From 01d454dccec7835b65d0fe718b0f61b8a3c92130 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Thu, 7 Sep 2023 13:54:47 +0800 Subject: [PATCH 1/8] fixed retain username and password in error login state --- lib/bloc/user/user_bloc.dart | 19 ++++++++++++------- lib/bloc/user/user_event.dart | 6 ++++-- lib/screens/profile/profile.dart | 2 +- lib/screens/unit2/basic-info/basic-info.dart | 19 +++++++++---------- lib/screens/unit2/login/login.dart | 10 +++++----- lib/sevices/roles/pass_check_services.dart | 6 ------ lib/utils/app_router.dart | 2 +- 7 files changed, 32 insertions(+), 32 deletions(-) diff --git a/lib/bloc/user/user_bloc.dart b/lib/bloc/user/user_bloc.dart index 3d0e250..3c80c9c 100644 --- a/lib/bloc/user/user_bloc.dart +++ b/lib/bloc/user/user_bloc.dart @@ -15,13 +15,14 @@ import '../../utils/scanner.dart'; import '../../utils/text_container.dart'; part 'user_event.dart'; part 'user_state.dart'; - class UserBloc extends Bloc { UserData? _userData; VersionInfo? _versionInfo; String? _apkVersion; bool save = false; String? uuid; + String? username; + String? password; List establishmentPointPersonAssignedAreas = []; UserBloc() : super(UserInitial()) { //// this event is called when opening the app to check if @@ -37,8 +38,8 @@ class UserBloc extends Bloc { String apkVersion = await getAppVersion(); _apkVersion = apkVersion; final String? saved = CREDENTIALS?.get('saved'); - final String? username = CREDENTIALS?.get('username'); - final String? password = CREDENTIALS?.get('password'); + username = CREDENTIALS?.get('username'); + password = CREDENTIALS?.get('password'); if (saved != null) { save = true; add(UserLogin(username: username, password: password)); @@ -46,8 +47,8 @@ class UserBloc extends Bloc { emit(VersionLoaded( versionInfo: _versionInfo, apkVersion: _apkVersion, - username: null, - password: null)); + username: event.username, + password: event.password)); } } catch (e) { emit(UserError( @@ -57,14 +58,18 @@ class UserBloc extends Bloc { }); ////Loading the current version of the app on((event, emit) { + username = event.username; + password = event.password; emit(VersionLoaded( versionInfo: _versionInfo, apkVersion: _apkVersion, - username: event.username, - password: event.password)); + username: username, + password: password)); }); ////userlogin on((event, emit) async { + username = event.username; + password = event.password; try { Map response = await AuthService.instance .webLogin(username: event.username, password: event.password); diff --git a/lib/bloc/user/user_event.dart b/lib/bloc/user/user_event.dart index 002410e..be22335 100644 --- a/lib/bloc/user/user_event.dart +++ b/lib/bloc/user/user_event.dart @@ -6,9 +6,11 @@ abstract class UserEvent extends Equatable { } class GetApkVersion extends UserEvent { - GetApkVersion(); + final String username; + final String password; + GetApkVersion({required this.password, required this.username}); @override - List get props => []; + List get props => [username,password]; } class UserLogin extends UserEvent { diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index ec1a721..9037fee 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -70,7 +70,7 @@ class ProfileInfo extends StatelessWidget { profileId = state.userData!.user!.login!.user!.profileId; token = state.userData!.user!.login!.token!; profile = state.userData!.employeeInfo!.profile!; - + return BlocConsumer( listener: ( context, diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index 9b1544b..85d6213 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -58,8 +58,8 @@ class BasicInfo extends StatelessWidget { width: 160, height: 160, decoration: BoxDecoration( - border: - Border.all(color: Colors.black26, width: 3), + border: Border.all( + color: Colors.black26, width: 3), shape: BoxShape.circle, image: DecorationImage( image: imageProvider, @@ -70,19 +70,18 @@ class BasicInfo extends StatelessWidget { const CircularProgressIndicator(), errorWidget: (context, url, error) => Container( - width: 160, + width: 160, height: 160, - decoration: BoxDecoration( - border: - Border.all(color: Colors.white, width: 3), + decoration: BoxDecoration( + border: Border.all( + color: Colors.white, width: 3), shape: BoxShape.circle, - ), - child: SvgPicture.asset( - 'assets/svgs/male.svg', + child: SvgPicture.asset( + 'assets/svgs/male.svg', + ), ), ), - ), ], ), ), diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index d828c89..a6f51ac 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -46,8 +46,9 @@ class _UniT2LoginState extends State { backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer(listener: (context, state) { - print(state); - if (state is UserLoggedIn || state is UuidLoaded || state is LoginErrorState) { + if (state is UserLoggedIn || + state is UuidLoaded || + state is LoginErrorState) { final progress = ProgressHUD.of(context); progress!.dismiss(); } @@ -94,7 +95,6 @@ class _UniT2LoginState extends State { })); } }, builder: (context, state) { - print(state); if (state is VersionLoaded) { return Builder(builder: (context) { if (state.versionInfo!.version != state.apkVersion) { @@ -355,7 +355,7 @@ class _UniT2LoginState extends State { onpressed: () { BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(GetApkVersion()); + .add(LoadVersion(username: username, password: password)); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); @@ -374,7 +374,7 @@ class _UniT2LoginState extends State { onpressed: () { BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(GetApkVersion()); + .add(LoadVersion(username: username, password: password)); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); diff --git a/lib/sevices/roles/pass_check_services.dart b/lib/sevices/roles/pass_check_services.dart index c74704f..b0a66e4 100644 --- a/lib/sevices/roles/pass_check_services.dart +++ b/lib/sevices/roles/pass_check_services.dart @@ -184,7 +184,6 @@ class PassCheckServices { if (otherInputs) { if (roleid == 41 || roleid == 13 || roleid == 17 || roleid == 22) { if (io == "i") { - print("1"); body = { "station_id": stationId, "temperature": temp, @@ -193,7 +192,6 @@ class PassCheckServices { "io": io }; } else { - print("2"); body = { "station_id": stationId, "destination": destination, @@ -203,7 +201,6 @@ class PassCheckServices { }; } } else { - print("3"); if (io == "i") { body = { "cp_id": cpId, @@ -213,7 +210,6 @@ class PassCheckServices { "io": io }; } else { - print("4"); body = { "cp_id": cpId, "destination": destination, @@ -224,7 +220,6 @@ class PassCheckServices { } } } else { - print("5"); if (roleid == 41 || roleid == 13 || roleid == 17 || roleid == 22) { body = { "station_id": stationId, @@ -233,7 +228,6 @@ class PassCheckServices { "io": io }; } else { - print("6"); body = { "cp_id": cpId, "temperature": temp, diff --git a/lib/utils/app_router.dart b/lib/utils/app_router.dart index 8b11ea5..f2c9b3b 100644 --- a/lib/utils/app_router.dart +++ b/lib/utils/app_router.dart @@ -27,7 +27,7 @@ class AppRouter { case '/': BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(GetApkVersion()); + .add(GetApkVersion(username: "",password: "")); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); From 749bd30fabb24ea2547d1850a5a72bc3a6bb4bbb Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Mon, 11 Sep 2023 11:34:42 +0800 Subject: [PATCH 2/8] flutter upgrade to latest version --- android/build.gradle | 2 +- .../assign_area/assign_area_bloc.dart | 42 ++++++ .../assign_area/assign_area_event.dart | 14 ++ .../assign_area/assign_area_state.dart | 28 ++++ lib/bloc/role/pass_check/pass_check_bloc.dart | 5 +- .../role/pass_check/pass_check_event.dart | 2 + .../role_assignment/role_assignment_bloc.dart | 20 ++- lib/model/profile/assigned_area.dart | 74 +++++++++ .../assign_area/assign_area_screen.dart | 12 ++ .../dashboard/superadmin_expanded_menu.dart | 141 +++++++++++++++--- .../unit2/homepage.dart/module-screen.dart | 67 +++++---- lib/screens/unit2/login/login.dart | 14 +- lib/sevices/roles/pass_check_services.dart | 6 +- .../assigned_area_services.dart | 42 ++++++ lib/utils/request.dart | 8 +- lib/utils/urls.dart | 13 +- pubspec.lock | 74 ++++----- pubspec.yaml | 10 +- 18 files changed, 453 insertions(+), 121 deletions(-) create mode 100644 lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart create mode 100644 lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart create mode 100644 lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart create mode 100644 lib/model/profile/assigned_area.dart create mode 100644 lib/screens/superadmin/assign_area/assign_area_screen.dart create mode 100644 lib/sevices/roles/rbac_operations/assigned_area_services.dart diff --git a/android/build.gradle b/android/build.gradle index dfce013..e06c40a 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -26,6 +26,6 @@ subprojects { project.evaluationDependsOn(':app') } -task clean(type: Delete) { +tasks.register("clean", Delete) { delete rootProject.buildDir } 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 new file mode 100644 index 0000000..df17578 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart @@ -0,0 +1,42 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/rbac/rbac_bloc.dart'; +import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart'; + +import '../../../../model/profile/assigned_area.dart'; +import '../../../../model/profile/basic_information/primary-information.dart'; +import '../../../../sevices/roles/rbac_operations/role_assignment_services.dart'; + +part 'assign_area_event.dart'; +part 'assign_area_state.dart'; + +class AssignAreaBloc extends Bloc { + AssignAreaBloc() : super(AssignAreaInitial()) { + String? fname; + String? lname; + String? fullname; + Profile? profile; + int id; + List userAssignedAreas = []; + on((event, emit) async { + emit(AssignAreaLoadingState()); + try { + profile = await RbacRoleAssignmentServices.instance.searchUser( + page: 1, name: event.firstname, lastname: event.lastname); + if (profile != null && profile!.id != null) { + fname = profile!.firstName; + lname = profile!.lastName; + fullname = profile!.lastName; + fullname = "${fname!} ${lname!}"; + id = profile!.webuserId!; + userAssignedAreas = await RbacAssignedAreaServices.instance.getAssignedArea(id: profile!.webuserId!); + emit(AssignedAreaLoadedState(userAssignedAreas: userAssignedAreas, fullname: fullname!)); + } else { + emit(UserNotExistError()); + } + } catch (e) { + emit(AssignAreaErorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart new file mode 100644 index 0000000..e60e372 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart @@ -0,0 +1,14 @@ +part of 'assign_area_bloc.dart'; + class AssignAreaEvent extends Equatable { + const AssignAreaEvent(); + + @override + List get props => []; +} + +class GetAssignArea extends AssignAreaEvent{ + final String firstname; + final String lastname; + const GetAssignArea({required this.firstname, required this.lastname}); + +} \ No newline at end of file diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart new file mode 100644 index 0000000..eab0be7 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart @@ -0,0 +1,28 @@ +part of 'assign_area_bloc.dart'; + +class AssignAreaState extends Equatable { + const AssignAreaState(); + + @override + List get props => []; +} + +class AssignedAreaLoadedState extends AssignAreaState{ + final List userAssignedAreas; + final String fullname; + const AssignedAreaLoadedState({required this.userAssignedAreas, required this.fullname}); + @override + List get props => [userAssignedAreas,fullname]; +} +class AssignAreaErorState extends AssignAreaState { + final String message; + const AssignAreaErorState({required this.message}); +} +class AssignAreaLoadingState extends AssignAreaState{ + +} + +class UserNotExistError extends AssignAreaState{ + +} +class AssignAreaInitial extends AssignAreaState {} diff --git a/lib/bloc/role/pass_check/pass_check_bloc.dart b/lib/bloc/role/pass_check/pass_check_bloc.dart index ca5be7f..00e7365 100644 --- a/lib/bloc/role/pass_check/pass_check_bloc.dart +++ b/lib/bloc/role/pass_check/pass_check_bloc.dart @@ -65,6 +65,7 @@ class PassCheckBloc extends Bloc { otherInputs: otherInputs!, passerId: uuid!, roleId: roleIdRoleName!.roleId, + roleName: roleIdRoleName!.roleName, stationId: stationId, temp: event.temp)); }); @@ -78,6 +79,7 @@ class PassCheckBloc extends Bloc { otherInputs: otherInputs!, passerId: uuid!, roleId: roleIdRoleName!.roleId, + roleName: roleIdRoleName!.roleName, stationId: stationId, temp: null)); }); @@ -123,6 +125,7 @@ class PassCheckBloc extends Bloc { otherInputs: otherInputs!, passerId: uuid!, roleId: roleIdRoleName!.roleId, + roleName: roleIdRoleName!.roleName, stationId: stationId, temp: null)); } @@ -152,7 +155,7 @@ class PassCheckBloc extends Bloc { stationId: event.stationId, cpId: event.cpId, otherInputs: event.otherInputs, - roleid: event.roleId); + roleIdRoleName: roleIdRoleName!); if (success) { Fluttertoast.showToast( msg: "SUCCESSFULLY SAVED", diff --git a/lib/bloc/role/pass_check/pass_check_event.dart b/lib/bloc/role/pass_check/pass_check_event.dart index f63ad23..0fe8365 100644 --- a/lib/bloc/role/pass_check/pass_check_event.dart +++ b/lib/bloc/role/pass_check/pass_check_event.dart @@ -44,6 +44,7 @@ class PerformPostLogs extends PassCheckEvent { final int? stationId; final String? destination; final double? temp; + final String roleName; final int roleId; const PerformPostLogs( {required this.checkerId, @@ -52,6 +53,7 @@ class PerformPostLogs extends PassCheckEvent { required this.io, required this.otherInputs, required this.passerId, + required this.roleName, required this.roleId, required this.stationId, required this.temp}); diff --git a/lib/bloc/role_assignment/role_assignment_bloc.dart b/lib/bloc/role_assignment/role_assignment_bloc.dart index 8f06a0d..5f401a7 100644 --- a/lib/bloc/role_assignment/role_assignment_bloc.dart +++ b/lib/bloc/role_assignment/role_assignment_bloc.dart @@ -1,5 +1,6 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; +import 'package:unit2/utils/text_container.dart'; import '../../model/profile/basic_information/primary-information.dart'; import '../../model/rbac/assigned_role.dart'; import '../../model/rbac/rbac.dart'; @@ -21,27 +22,24 @@ class RoleAssignmentBloc List roles = []; on((event, emit) async { emit(RoleAssignmentLoadingState()); - fname = event.firstname; - lname = event.lastname; - fullname = "${event.firstname} ${event.lastname}"; try { profile = await RbacRoleAssignmentServices.instance.searchUser( page: 1, name: event.firstname, lastname: event.lastname); - if (profile != null && profile?.id != null) { + if (profile != null && profile?.id != null) { + fname = profile!.firstName; + lname = profile!.lastName; + fullname = "${fname!} ${lname!}"; assignedRoles = await RbacRoleAssignmentServices.instance - .getAssignedRoles( - firstname: event.firstname, lastname: event.lastname); + .getAssignedRoles(firstname: fname!, lastname: lname!); - if (roles.isEmpty) { - roles = await RbacRoleServices.instance.getRbacRoles(); - } + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } emit(AssignedRoleLoaded( assignedRoles: assignedRoles, fullname: fullname!, roles: roles)); } else { emit(UserNotExistError()); } - - } catch (e) { emit(RoleAssignmentErrorState(message: e.toString())); } diff --git a/lib/model/profile/assigned_area.dart b/lib/model/profile/assigned_area.dart new file mode 100644 index 0000000..4d9f887 --- /dev/null +++ b/lib/model/profile/assigned_area.dart @@ -0,0 +1,74 @@ +import 'package:unit2/model/rbac/rbac.dart'; + +import '../roles/pass_check/assign_role_area_type.dart'; + +class UserAssignedArea { + final int id; + final AssignedRole? assignedRole; + final AssignRoleAreaType? assignedRoleAreaType; + final dynamic assignedArea; + + UserAssignedArea({ + required this.id, + required this.assignedRole, + required this.assignedRoleAreaType, + required this.assignedArea, + }); + + factory UserAssignedArea.fromJson(Map json) => UserAssignedArea( + id: json["id"], + assignedRole: json['assigned_role'] == null? null: AssignedRole.fromJson(json["assigned_role"]), + assignedRoleAreaType: json['assigned_role_area_type'] == null? null : AssignRoleAreaType.fromJson(json["assigned_role_area_type"]), + assignedArea: json["assigned_area"], + ); + + Map toJson() => { + "id": id, + "assigned_role": assignedRole?.toJson(), + "assigned_role_area_type": assignedRoleAreaType?.toJson(), + "assigned_area": assignedArea, + }; +} + +class AssignedRole { + final int id; + final RBAC? role; + final CreatedBy? user; + final DateTime? createdAt; + final DateTime? updatedAt; + final CreatedBy? createdBy; + final CreatedBy? updatedBy; + + AssignedRole({ + required this.id, + required this.role, + required this.user, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory AssignedRole.fromJson(Map json) => AssignedRole( + id: json["id"], + role: RBAC.fromJson(json["role"]), + user: CreatedBy.fromJson(json["user"]), + createdAt: DateTime.parse(json["created_at"]), + updatedAt: DateTime.parse(json["updated_at"]), + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: CreatedBy.fromJson(json["updated_by"]), + ); + + Map toJson() => { + "id": id, + "role": role?.toJson(), + "user": user?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "created_by": createdBy?.toJson(), + "updated_by": updatedBy?.toJson(), + }; +} + + + diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart new file mode 100644 index 0000000..4b0a84a --- /dev/null +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/src/widgets/framework.dart'; +import 'package:flutter/src/widgets/placeholder.dart'; + +class RbacAssignedAreaScreen extends StatelessWidget { + const RbacAssignedAreaScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Center(child: Text("dsadasdas"),); + } +} \ No newline at end of file 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 22afbe3..f00739f 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 @@ -4,6 +4,7 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/module/module_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; @@ -15,6 +16,7 @@ import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dar import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart'; import 'package:unit2/bloc/role_assignment/role_assignment_bloc.dart'; +import 'package:unit2/screens/superadmin/assign_area/assign_area_screen.dart'; 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'; @@ -49,6 +51,7 @@ class SuperAdminMenu extends StatelessWidget { @override Widget build(BuildContext context) { final roleAssignmentKey = GlobalKey(); + final areaKey = GlobalKey(); return AnimationConfiguration.staggeredGrid( position: index, columnCount: columnCount, @@ -74,12 +77,9 @@ class SuperAdminMenu extends StatelessWidget { object.moduleName == 'superadmin' ? CardLabel( icon: iconGenerator(name: object.object.name!), - title: - object.object.name!, + title: object.object.name!, ontap: () { - if (object.object.name == 'Role') { - Navigator.push(context, MaterialPageRoute( builder: (BuildContext context) { return BlocProvider( @@ -156,9 +156,7 @@ class SuperAdminMenu extends StatelessWidget { return BlocProvider( create: (context) => AgencyBloc()..add(GetAgencies()), - child: RbacAgencyScreen( - - ), + child: const RbacAgencyScreen(), ); })); } @@ -198,31 +196,125 @@ class SuperAdminMenu extends StatelessWidget { ); })); } - + if (object.object.name == 'Station') { Navigator.push(context, MaterialPageRoute( builder: (BuildContext context) { return BlocProvider( create: (context) => StationBloc() ..add(const GetStations(agencyId: 1)), - child: const RbacStationScreen( + child: const RbacStationScreen( agencyId: 1, ), ); })); } - if (object.object.name == 'Role Member') { - Navigator.of(context).pop(); + if (object.object.name == 'Area') { + Navigator.of(context).pop(); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Row( children: [ - const Expanded(child: Text("Search User")), - IconButton(onPressed: (){ - Navigator.pop(context); - }, icon: const Icon(Icons.close)) + const Expanded( + child: Text("Search User")), + IconButton( + onPressed: () { + Navigator.pop(context); + }, + icon: const Icon(Icons.close)) + ], + ), + content: FormBuilder( + key: areaKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "firstname", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + decoration: normalTextFieldStyle( + "First name", "first name"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + name: "lastname", + decoration: normalTextFieldStyle( + "Last name", "last tname"), + ), + const SizedBox( + height: 24, + ), + SizedBox( + height: 60, + width: double.maxFinite, + child: ElevatedButton( + onPressed: () { + if (areaKey.currentState! + .saveAndValidate()) { + String fname = + areaKey + .currentState! + .value['firstname']; + String lname = areaKey + .currentState! + .value['lastname']; + Navigator.of(context).pop(); + Navigator.push(context, + MaterialPageRoute(builder: + (BuildContext + context) { + return BlocProvider( + create: (context) => + AssignAreaBloc() + ..add( + GetAssignArea( + firstname: + fname, + lastname: + lname), + ), + child: + const RbacAssignedAreaScreen(), + ); + })); + } + }, + style: mainBtnStyle(primary, + Colors.transparent, second), + child: const Text("Submit"), + ), + ) + ], + )), + ); + }); + } + if (object.object.name == 'Role Member') { + Navigator.of(context).pop(); + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Row( + children: [ + const Expanded( + child: Text("Search User")), + IconButton( + onPressed: () { + Navigator.pop(context); + }, + icon: const Icon(Icons.close)) ], ), content: FormBuilder( @@ -262,7 +354,6 @@ class SuperAdminMenu extends StatelessWidget { if (roleAssignmentKey .currentState! .saveAndValidate()) { - String fname = roleAssignmentKey .currentState! @@ -271,19 +362,27 @@ class SuperAdminMenu extends StatelessWidget { roleAssignmentKey .currentState! .value['lastname']; - Navigator.of(context).pop(); + Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) { return BlocProvider( - create: (context) => - RoleAssignmentBloc() - ..add(GetAssignedRoles( + create: (context) => + RoleAssignmentBloc() + ..add( + GetAssignedRoles( firstname: fname, lastname: - lname),),child:RbacRoleAssignment(id:id,name: fname,lname: lname,) ,); + lname), + ), + child: RbacRoleAssignment( + id: id, + name: fname, + lname: lname, + ), + ); })); } }, diff --git a/lib/screens/unit2/homepage.dart/module-screen.dart b/lib/screens/unit2/homepage.dart/module-screen.dart index 5f2046f..f614ff0 100644 --- a/lib/screens/unit2/homepage.dart/module-screen.dart +++ b/lib/screens/unit2/homepage.dart/module-screen.dart @@ -20,8 +20,10 @@ class _MainScreenState extends State { List roles = []; List cards = []; int? userId; + DateTime? ctime; @override Widget build(BuildContext context) { + setState(() { cards.clear(); cards=[]; @@ -52,34 +54,49 @@ class _MainScreenState extends State { } } - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - leading: IconButton( - onPressed: () { - ZoomDrawer.of(context)!.toggle(); - }, - icon: const Icon( - Icons.menu, - color: Colors.white, - ), - ), - centerTitle: true, - title: const Text( - unit2ModuleScreen, - style: TextStyle( - fontSize: 18.0, - color: Colors.white, + return WillPopScope( + onWillPop: () { + DateTime now = DateTime.now(); + if (ctime == null || now.difference(ctime!) > const Duration(seconds: 2)) { + //add duration of press gap + ctime = now; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Press Again to Exit',textAlign: TextAlign.center,)) + ); + return Future.value(false); + } + + return Future.value(true); + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: primary, + leading: IconButton( + onPressed: () { + ZoomDrawer.of(context)!.toggle(); + }, + icon: const Icon( + Icons.menu, + color: Colors.white, + ), + ), + centerTitle: true, + title: const Text( + unit2ModuleScreen, + style: TextStyle( + fontSize: 18.0, + color: Colors.white, + ), ), ), + body: state.userData!.user!.login!.user!.roles!.isNotEmpty + ? DashBoard( + estPersonAssignedArea: state.estPersonAssignedArea, + userId: userId!, + cards: cards, + ) + : const NoModule(), ), - body: state.userData!.user!.login!.user!.roles!.isNotEmpty - ? DashBoard( - estPersonAssignedArea: state.estPersonAssignedArea, - userId: userId!, - cards: cards, - ) - : const NoModule(), ); } return Container(); diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index a6f51ac..d3cfc7c 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -37,10 +37,22 @@ class _UniT2LoginState extends State { bool _showPassword = true; String? password; String? username; + DateTime? ctime; @override Widget build(BuildContext context) { return WillPopScope( - onWillPop: pressAgainToExit, + onWillPop: () { + DateTime now = DateTime.now(); + if (ctime == null || now.difference(ctime!) > const Duration(seconds: 2)) { + ctime = now; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Press Again to Exit',textAlign: TextAlign.center,)) + ); + return Future.value(false); + } + + return Future.value(true); + }, child: Scaffold( body: ProgressHUD( backgroundColor: Colors.black87, diff --git a/lib/sevices/roles/pass_check_services.dart b/lib/sevices/roles/pass_check_services.dart index b0a66e4..12cd2a2 100644 --- a/lib/sevices/roles/pass_check_services.dart +++ b/lib/sevices/roles/pass_check_services.dart @@ -172,7 +172,7 @@ class PassCheckServices { double? temp, int? stationId, String? cpId, - required int roleid}) async { + required RoleIdRoleName roleIdRoleName}) async { String path = Url.instance.postLogs(); bool success; Map headers = { @@ -182,7 +182,7 @@ class PassCheckServices { }; Map body; if (otherInputs) { - if (roleid == 41 || roleid == 13 || roleid == 17 || roleid == 22) { + if (roleIdRoleName.roleName.toLowerCase() == "security guard" || roleIdRoleName.roleName.toLowerCase() == "qr code scanner") { if (io == "i") { body = { "station_id": stationId, @@ -220,7 +220,7 @@ class PassCheckServices { } } } else { - if (roleid == 41 || roleid == 13 || roleid == 17 || roleid == 22) { + if (roleIdRoleName.roleName.toLowerCase() == "security guard" || roleIdRoleName.roleName.toLowerCase() == "qr code scanner") { body = { "station_id": stationId, "passer": passerId, diff --git a/lib/sevices/roles/rbac_operations/assigned_area_services.dart b/lib/sevices/roles/rbac_operations/assigned_area_services.dart new file mode 100644 index 0000000..7bc2030 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/assigned_area_services.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; + +import 'package:unit2/model/profile/assigned_area.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"; + 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(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: param, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var assignedArea in data['data']) { + UserAssignedArea newArea = UserAssignedArea.fromJson(assignedArea); + userAssignedAreas.add(newArea); + } + } + } + } catch (e) { + throw e.toString(); + } + return userAssignedAreas; + } +} diff --git a/lib/utils/request.dart b/lib/utils/request.dart index 970fac6..562a9fb 100644 --- a/lib/utils/request.dart +++ b/lib/utils/request.dart @@ -19,7 +19,7 @@ class Request { Map? param}) async { Response response; try { - response = await get(Uri.https(host, path!, param), headers: headers) + response = await get(Uri.http(host, path!, param), headers: headers) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -61,7 +61,7 @@ class Request { Map? param}) async { Response response; try { - response = await post(Uri.https(host, path!, param), + response = await post(Uri.http(host, path!, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { @@ -104,7 +104,7 @@ class Request { required Map? param}) async { Response response; try { - response = await put(Uri.https(host, path, param), + response = await put(Uri.http(host, path, param), headers: headers, body: jsonEncode(body)); } on TimeoutException catch (_) { // Fluttertoast.showToast( @@ -188,7 +188,7 @@ class Request { required Map? param}) async { Response response; try { - response = await delete(Uri.https(host, path, param), + response = await delete(Uri.http(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 20385fe..2ec2083 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -5,8 +5,8 @@ class Url { String host() { // return '192.168.10.183:3000'; - return 'agusandelnorte.gov.ph'; - // return "192.168.10.219:3000"; + // return 'agusandelnorte.gov.ph'; + return "192.168.10.219:3000"; // return "192.168.10.241"; // return "192.168.10.221:3004"; // return "playweb.agusandelnorte.gov.ph"; @@ -14,8 +14,8 @@ class Url { } String prefixHost() { - return "https"; - // return "http"; + // return "https"; + return "http"; } String authentication() { @@ -26,7 +26,6 @@ class Url { return 'api/jobnet_app/profile/pds/'; } - String latestApk() { return "/api/system_app/apk_version/latest"; } @@ -320,6 +319,10 @@ class Url { return "/api/hrms_app/position_title/"; } + String getAssignedAreas() { + return "/api/account/auth/assigned_role_area"; + } + //// location utils path String getCounties() { return "/api/jobnet_app/countries/"; diff --git a/pubspec.lock b/pubspec.lock index 71599d5..a494f46 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -69,10 +69,10 @@ packages: dependency: transitive description: name: async - sha256: bfe67ef28df125b7dddcea62755991f807aa39a2492a23e1550161692950bbe0 + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted - version: "2.10.0" + version: "2.11.0" audioplayers: dependency: "direct main" description: @@ -277,10 +277,10 @@ packages: dependency: transitive description: name: characters - sha256: e6a326c8af69605aec75ed6c187d06b349707a27fbff8222ca9cc2cff167975c + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.3.0" checked_yaml: dependency: transitive description: @@ -309,10 +309,10 @@ packages: dependency: transitive description: name: collection - sha256: cfc915e6923fe5ce6e153b0723c753045de46de1b4d63771530504004a45fae0 + sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.17.2" convert: dependency: transitive description: @@ -369,14 +369,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" - device_frame: - dependency: transitive - description: - name: device_frame - sha256: afe76182aec178d171953d9b4a50a43c57c7cf3c77d8b09a48bf30c8fa04dd9d - url: "https://pub.dev" - source: hosted - version: "1.1.0" device_info: dependency: transitive description: @@ -409,14 +401,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.0" - device_preview: - dependency: "direct main" - description: - name: device_preview - sha256: "2f097bf31b929e15e6756dbe0ec1bcb63952ab9ed51c25dc5a2c722d2b21fdaf" - url: "https://pub.dev" - source: hosted - version: "1.1.0" dio: dependency: "direct main" description: @@ -685,14 +669,6 @@ packages: url: "https://pub.dev" source: hosted version: "8.6.1" - freezed_annotation: - dependency: transitive - description: - name: freezed_annotation - sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d - url: "https://pub.dev" - source: hosted - version: "2.4.1" frontend_server_client: dependency: transitive description: @@ -801,10 +777,10 @@ packages: dependency: "direct main" description: name: intl - sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" + sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" url: "https://pub.dev" source: hosted - version: "0.17.0" + version: "0.18.1" io: dependency: transitive description: @@ -889,26 +865,26 @@ packages: dependency: transitive description: name: matcher - sha256: "16db949ceee371e9b99d22f88fa3a73c4e59fd0afed0bd25fc336eb76c198b72" + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted - version: "0.12.13" + version: "0.12.16" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "0.5.0" meta: dependency: transitive description: name: meta - sha256: "6c268b42ed578a53088d834796959e4a1814b5e9e164f147f580a386e5decf42" + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted - version: "1.8.0" + version: "1.9.1" mime: dependency: transitive description: @@ -1001,10 +977,10 @@ packages: dependency: transitive description: name: path - sha256: db9d4f58c908a4ba5953fcee2ae317c94889433e5024c27ce74a37f94267945b + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted - version: "1.8.2" + version: "1.8.3" path_drawing: dependency: transitive description: @@ -1430,10 +1406,10 @@ packages: dependency: transitive description: name: source_span - sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.10.0" sqflite: dependency: transitive description: @@ -1574,10 +1550,10 @@ packages: dependency: transitive description: name: test_api - sha256: ad540f65f92caa91bf21dfc8ffb8c589d6e4dc0c2267818b4cc2792857706206 + sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" url: "https://pub.dev" source: hosted - version: "0.4.16" + version: "0.6.0" timing: dependency: transitive description: @@ -1690,6 +1666,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.2" + web: + dependency: transitive + description: + name: web + sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 + url: "https://pub.dev" + source: hosted + version: "0.1.4-beta" web_socket_channel: dependency: transitive description: @@ -1731,5 +1715,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">2.19.0 <3.0.0" + dart: ">=3.1.0-185.0.dev <4.0.0" flutter: ">=3.7.0" diff --git a/pubspec.yaml b/pubspec.yaml index 2f532b8..8d51f86 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -38,10 +38,9 @@ dependencies: flutter_custom_clippers: ^2.0.0 flutter_svg: ^1.1.6 flutter_form_builder: ^7.7.0 - form_builder_validators: ^8.4.0 + form_builder_validators: any fluttericon: ^2.0.0 fluttertoast: ^8.1.1 - device_preview: ^1.1.0 flutter_zoom_drawer: ^3.0.3 cached_network_image: ^3.2.3 auto_size_text: ^3.0.0 @@ -50,7 +49,7 @@ dependencies: toggle_switch: ^2.0.1 convex_bottom_bar: ^3.1.0+1 azlistview: ^2.0.0 - intl: ^0.17.0 + intl: ^0.18.1 date_time_picker: ^2.1.0 flutter_progress_hud: ^2.0.2 barcode_scan2: ^4.2.1 @@ -85,7 +84,7 @@ dependencies: flutter_speed_dial: ^6.2.0 im_stepper: ^1.0.1+1 shared_preferences: ^2.0.20 - multiselect: ^0.1.0 + multiselect: any multi_select_flutter: ^4.1.3 flutter_custom_selector: ^0.0.3 flutter_staggered_animations: ^1.1.1 @@ -98,6 +97,9 @@ dependencies: url_launcher: ^6.1.11 url_launcher_android: ^6.0.38 share_plus: ^7.1.0 + +dependency_overrides: + intl: ^0.18.0 From 8fea765258e3bd313759792663c33f8a87d856a5 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Wed, 13 Sep 2023 10:45:03 +0800 Subject: [PATCH 3/8] agency areaType selection --- lib/bloc/profile/profile_bloc.dart | 16 +- .../assign_area/assign_area_bloc.dart | 27 +- .../assign_area/assign_area_event.dart | 17 + .../assign_area/assign_area_state.dart | 8 + .../role_assignment/role_assignment_bloc.dart | 2 +- lib/bloc/user/user_bloc.dart | 2 + lib/main.dart | 2 +- lib/model/profile/assigned_area.dart | 4 - lib/model/rbac/assigned_role.dart | 30 +- .../edit_basic_info_modal.dart | 140 ++-- .../primary_information_screen.dart | 679 +++++++++++------- lib/screens/profile/profile.dart | 1 - .../assign_area/assign_area_screen.dart | 414 ++++++++++- .../role_assignment_screen.dart | 6 +- .../components/dashboard/dashboard.dart | 3 - .../dashboard/superadmin_expanded_menu.dart | 1 + lib/screens/unit2/login/login.dart | 2 +- .../est_point_person_role_member_screen.dart | 4 +- .../assigned_area_services.dart | 19 + lib/utils/urls.dart | 4 +- pubspec.lock | 16 + pubspec.yaml | 1 + 22 files changed, 1016 insertions(+), 382 deletions(-) diff --git a/lib/bloc/profile/profile_bloc.dart b/lib/bloc/profile/profile_bloc.dart index 2384265..a3cfc36 100644 --- a/lib/bloc/profile/profile_bloc.dart +++ b/lib/bloc/profile/profile_bloc.dart @@ -59,9 +59,18 @@ class ProfileBloc extends Bloc { } }); on((event, emit) { - currentProfileInformation = event.primaryBasicInformation; - emit(BasicInformationProfileLoaded( - primaryBasicInformation: event.primaryBasicInformation)); + if(currentProfileInformation != null){ + emit(BasicInformationProfileLoaded( + primaryBasicInformation: currentProfileInformation!)); + }else{ + currentProfileInformation = event.primaryBasicInformation; + emit(BasicInformationProfileLoaded( + primaryBasicInformation: currentProfileInformation!)); + } + + + + }); on((event, emit) { emit(BasicInformationProfileLoaded( @@ -132,6 +141,7 @@ class ProfileBloc extends Bloc { if (status['success']) { Profile profile = Profile.fromJson(status['data']); currentProfileInformation = profile; + emit(BasicProfileInfoEditedState(response: status)); } emit(BasicProfileInfoEditedState(response: status)); 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 df17578..0473081 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 @@ -29,8 +29,10 @@ class AssignAreaBloc extends Bloc { fullname = profile!.lastName; fullname = "${fname!} ${lname!}"; id = profile!.webuserId!; - userAssignedAreas = await RbacAssignedAreaServices.instance.getAssignedArea(id: profile!.webuserId!); - emit(AssignedAreaLoadedState(userAssignedAreas: userAssignedAreas, fullname: fullname!)); + userAssignedAreas = await RbacAssignedAreaServices.instance + .getAssignedArea(id: profile!.webuserId!); + emit(AssignedAreaLoadedState( + userAssignedAreas: userAssignedAreas, fullname: fullname!)); } else { emit(UserNotExistError()); } @@ -38,5 +40,26 @@ class AssignAreaBloc extends Bloc { emit(AssignAreaErorState(message: e.toString())); } }); + on((event, emit) async { + emit(AssignedAreaLoadedState( + userAssignedAreas: userAssignedAreas, fullname: fullname!)); + }); + on((event, emit) async { + emit(AssignAreaLoadingState()); + try { + bool success = await RbacRoleAssignmentServices.instance + .deleteAssignedRole(roleId: event.areaId); + if (success) { + emit(AssignedAreaDeletedState(success: success)); + } else { + emit(AssignedAreaDeletedState(success: success)); + } + } catch (e) { + emit(AssignAreaErorState(message: e.toString())); + } + }); + on((event, emit) { + emit(AssignAreaErorState(message: event.message)); + }); } } diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart index e60e372..0f97956 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart @@ -10,5 +10,22 @@ class GetAssignArea extends AssignAreaEvent{ final String firstname; final String lastname; const GetAssignArea({required this.firstname, required this.lastname}); + @override + List get props => [firstname,lastname]; +} +class DeleteAssignedArea extends AssignAreaEvent{ +final int areaId; +const DeleteAssignedArea({required this.areaId}); + @override + List get props => [areaId]; +} + +class LoadAssignedAreas extends AssignAreaEvent{ +} +class CallErrorState extends AssignAreaEvent{ + final String message; + const CallErrorState({required this.message}); + @override + List get props => [message]; } \ No newline at end of file diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart index eab0be7..255ad6d 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart @@ -17,6 +17,8 @@ class AssignedAreaLoadedState extends AssignAreaState{ class AssignAreaErorState extends AssignAreaState { final String message; const AssignAreaErorState({required this.message}); + @override + List get props => [message]; } class AssignAreaLoadingState extends AssignAreaState{ @@ -26,3 +28,9 @@ class UserNotExistError extends AssignAreaState{ } class AssignAreaInitial extends AssignAreaState {} +class AssignedAreaDeletedState extends AssignAreaState{ + final bool success; + const AssignedAreaDeletedState({required this.success}); + @override + List get props => [success]; +} \ No newline at end of file diff --git a/lib/bloc/role_assignment/role_assignment_bloc.dart b/lib/bloc/role_assignment/role_assignment_bloc.dart index 5f401a7..5734aa7 100644 --- a/lib/bloc/role_assignment/role_assignment_bloc.dart +++ b/lib/bloc/role_assignment/role_assignment_bloc.dart @@ -30,7 +30,7 @@ class RoleAssignmentBloc lname = profile!.lastName; fullname = "${fname!} ${lname!}"; assignedRoles = await RbacRoleAssignmentServices.instance - .getAssignedRoles(firstname: fname!, lastname: lname!); + .getAssignedRoles(firstname: event.firstname, lastname: event.lastname); if (roles.isEmpty) { roles = await RbacRoleServices.instance.getRbacRoles(); diff --git a/lib/bloc/user/user_bloc.dart b/lib/bloc/user/user_bloc.dart index 3c80c9c..475b451 100644 --- a/lib/bloc/user/user_bloc.dart +++ b/lib/bloc/user/user_bloc.dart @@ -40,6 +40,8 @@ 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) { save = true; add(UserLogin(username: username, password: password)); diff --git a/lib/main.dart b/lib/main.dart index d88fa6c..ecec407 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -36,7 +36,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { _appRouter = AppRouter(); final mediaQueryData = - MediaQueryData.fromWindow(WidgetsBinding.instance.window); + MediaQueryData.fromView(WidgetsBinding.instance.window); screenWidth = mediaQueryData.size.width; screenHeight = mediaQueryData.size.height; blockSizeHorizontal = screenWidth / 100; diff --git a/lib/model/profile/assigned_area.dart b/lib/model/profile/assigned_area.dart index 4d9f887..83be0b0 100644 --- a/lib/model/profile/assigned_area.dart +++ b/lib/model/profile/assigned_area.dart @@ -3,27 +3,23 @@ import 'package:unit2/model/rbac/rbac.dart'; import '../roles/pass_check/assign_role_area_type.dart'; class UserAssignedArea { - final int id; final AssignedRole? assignedRole; final AssignRoleAreaType? assignedRoleAreaType; final dynamic assignedArea; UserAssignedArea({ - required this.id, required this.assignedRole, required this.assignedRoleAreaType, required this.assignedArea, }); factory UserAssignedArea.fromJson(Map json) => UserAssignedArea( - id: json["id"], assignedRole: json['assigned_role'] == null? null: AssignedRole.fromJson(json["assigned_role"]), assignedRoleAreaType: json['assigned_role_area_type'] == null? null : AssignRoleAreaType.fromJson(json["assigned_role_area_type"]), assignedArea: json["assigned_area"], ); Map toJson() => { - "id": id, "assigned_role": assignedRole?.toJson(), "assigned_role_area_type": assignedRoleAreaType?.toJson(), "assigned_area": assignedArea, diff --git a/lib/model/rbac/assigned_role.dart b/lib/model/rbac/assigned_role.dart index 52a1b78..82dc3b2 100644 --- a/lib/model/rbac/assigned_role.dart +++ b/lib/model/rbac/assigned_role.dart @@ -87,13 +87,13 @@ class CreatedBy { class Role { final int id; - final String name; - final String slug; - final String shorthand; - final DateTime createdAt; - final DateTime updatedAt; - final CreatedBy createdBy; - final CreatedBy updatedBy; + final String? name; + final String? slug; + final String? shorthand; + final DateTime? createdAt; + final DateTime? updatedAt; + final CreatedBy? createdBy; + final CreatedBy? updatedBy; Role({ required this.id, @@ -111,10 +111,10 @@ class Role { name: json["name"], slug: json["slug"], shorthand: json["shorthand"], - createdAt: DateTime.parse(json["created_at"]), - updatedAt: DateTime.parse(json["updated_at"]), - createdBy: CreatedBy.fromJson(json["created_by"]), - updatedBy: CreatedBy.fromJson(json["updated_by"]), + 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: CreatedBy.fromJson(json["created_by"]), + updatedBy:json["updated_by"] == null?null: CreatedBy.fromJson(json["updated_by"]), ); Map toJson() => { @@ -122,9 +122,9 @@ class Role { "name": name, "slug": slug, "shorthand": shorthand, - "created_at": createdAt.toIso8601String(), - "updated_at": updatedAt.toIso8601String(), - "created_by": createdBy.toJson(), - "updated_by": updatedBy.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "created_by": createdBy?.toJson(), + "updated_by": updatedBy?.toJson(), }; } diff --git a/lib/screens/profile/components/basic_information/edit_basic_info_modal.dart b/lib/screens/profile/components/basic_information/edit_basic_info_modal.dart index 4a24280..d993f72 100644 --- a/lib/screens/profile/components/basic_information/edit_basic_info_modal.dart +++ b/lib/screens/profile/components/basic_information/edit_basic_info_modal.dart @@ -24,6 +24,7 @@ class EditBasicProfileInfoScreen extends StatefulWidget { State createState() => _EditBasicProfileInfoScreenState(); } + final bdayController = TextEditingController(); ProfileOtherInfo? selectedIndigency; ProfileOtherInfo? selectedEthnicity; @@ -36,13 +37,13 @@ String? selectedStatus; String? selectedExtension; final _formKey = GlobalKey(); - class _EditBasicProfileInfoScreenState extends State { - @override + @override void dispose() { super.dispose(); } + @override Widget build(BuildContext context) { return BlocBuilder( @@ -52,7 +53,8 @@ class _EditBasicProfileInfoScreenState selectedSex = state.sexes.firstWhere((element) => element.toLowerCase() == state.primaryInformation.sex!.toLowerCase()); - if (state.primaryInformation.bloodType != null && state.primaryInformation.bloodType != "N/A") { + if (state.primaryInformation.bloodType != null && + state.primaryInformation.bloodType != "N/A") { selectedBloodType = state.bloodTypes.firstWhere((element) => element.toLowerCase() == state.primaryInformation.bloodType?.toLowerCase()); @@ -99,9 +101,6 @@ class _EditBasicProfileInfoScreenState state.primaryInformation.disability!.toLowerCase()); } - - - return Container( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32), child: FormBuilder( @@ -116,9 +115,7 @@ class _EditBasicProfileInfoScreenState ), FormBuilderTextField( name: "lastname", - inputFormatters: [ - UpperCaseTextFormatter() - ], + inputFormatters: [UpperCaseTextFormatter()], initialValue: state.primaryInformation.lastName, decoration: normalTextFieldStyle("Last name *", ""), validator: FormBuilderValidators.required( @@ -129,9 +126,7 @@ class _EditBasicProfileInfoScreenState ), FormBuilderTextField( name: "firstname", - inputFormatters: [ - UpperCaseTextFormatter() - ], + inputFormatters: [UpperCaseTextFormatter()], initialValue: state.primaryInformation.firstName, decoration: normalTextFieldStyle("First name *", ""), validator: FormBuilderValidators.required( @@ -146,12 +141,12 @@ class _EditBasicProfileInfoScreenState Flexible( flex: 2, child: FormBuilderTextField( - inputFormatters: [ - UpperCaseTextFormatter() - ], + inputFormatters: [UpperCaseTextFormatter()], name: "middlename", - initialValue: state.primaryInformation.middleName??'', - decoration: normalTextFieldStyle("Middle name", ""), + initialValue: + state.primaryInformation.middleName ?? '', + decoration: + normalTextFieldStyle("Middle name", ""), ), ), const SizedBox( @@ -164,13 +159,11 @@ class _EditBasicProfileInfoScreenState value: selectedExtension, decoration: normalTextFieldStyle("Name Extension", ""), - items: state.extensions .map((element) => DropdownMenuItem( value: element, child: Text(element))) .toList(), onChanged: (e) { - selectedExtension = e; }, ), @@ -193,8 +186,9 @@ class _EditBasicProfileInfoScreenState errorText: "This field is required"), timeHintText: "Birthdate", decoration: - normalTextFieldStyle("Birthdate *", "*").copyWith( - prefixIcon: const Icon( + normalTextFieldStyle("Birthdate *", "*") + .copyWith( + prefixIcon: const Icon( Icons.date_range, color: Colors.black87, )), @@ -206,7 +200,7 @@ class _EditBasicProfileInfoScreenState const SizedBox( width: 10, ), - + ////sex Flexible( flex: 1, @@ -221,7 +215,7 @@ class _EditBasicProfileInfoScreenState value: element, child: Text(element))) .toList(), onChanged: (e) { - selectedSex= e; + selectedSex = e; }, ), ) @@ -238,9 +232,10 @@ class _EditBasicProfileInfoScreenState flex: 1, child: FormBuilderDropdown( initialValue: selectedBloodType, - validator: FormBuilderValidators.required( + validator: FormBuilderValidators.required( errorText: "This field is required"), - decoration: normalTextFieldStyle("Blood type *", ""), + decoration: + normalTextFieldStyle("Blood type *", ""), name: "bloodtype", items: state.bloodTypes .map((element) => DropdownMenuItem( @@ -259,8 +254,9 @@ class _EditBasicProfileInfoScreenState flex: 1, child: FormBuilderDropdown( initialValue: selectedStatus, - decoration: normalTextFieldStyle("Civil status *", ""), - validator: FormBuilderValidators.required( + decoration: + normalTextFieldStyle("Civil status *", ""), + validator: FormBuilderValidators.required( errorText: "This field is required"), name: "extension", items: state.civilStatus @@ -305,11 +301,12 @@ class _EditBasicProfileInfoScreenState flex: 1, child: FormBuilderTextField( name: "height", - validator: numericRequired, + validator: numericRequired, initialValue: state.primaryInformation.heightM .toString() .toString(), - decoration: normalTextFieldStyle("Height (Meter) *", ""), + decoration: normalTextFieldStyle( + "Height (Meter) *", ""), ), ), const SizedBox( @@ -317,13 +314,13 @@ class _EditBasicProfileInfoScreenState ), Flexible( flex: 1, - child: FormBuilderTextField( - validator: numericRequired, + validator: numericRequired, name: "weigth", - initialValue: - state.primaryInformation.weightKg!.toString(), - decoration: normalTextFieldStyle("Weight (Kg) *", ""), + initialValue: state.primaryInformation.weightKg! + .toString(), + decoration: + normalTextFieldStyle("Weight (Kg) *", ""), ), ), ]), @@ -338,7 +335,8 @@ class _EditBasicProfileInfoScreenState flex: 1, child: FormBuilderTextField( name: "prefix", - initialValue: state.primaryInformation.titlePrefix + initialValue: state + .primaryInformation.titlePrefix .toString() .toString(), decoration: normalTextFieldStyle( @@ -352,7 +350,8 @@ class _EditBasicProfileInfoScreenState flex: 1, child: FormBuilderTextField( name: "suffix", - initialValue: state.primaryInformation.titleSuffix, + initialValue: + state.primaryInformation.titleSuffix, decoration: normalTextFieldStyle( "Title Suffix", "PhD.,MD.,MS.,CE"), ), @@ -368,10 +367,11 @@ class _EditBasicProfileInfoScreenState ////Indigency Flexible( flex: 1, - child: DropdownButtonFormField( + child: DropdownButtonFormField( isExpanded: true, value: selectedIndigency, - decoration: normalTextFieldStyle("Indigency", ""), + decoration: + normalTextFieldStyle("Indigency", ""), items: state.indigenous .map((element) => DropdownMenuItem( @@ -392,7 +392,8 @@ class _EditBasicProfileInfoScreenState child: DropdownButtonFormField( isExpanded: true, value: selectedEthnicity, - decoration: normalTextFieldStyle("Ethnicity", ""), + decoration: + normalTextFieldStyle("Ethnicity", ""), items: state.ethnicity .map((element) => DropdownMenuItem( @@ -402,8 +403,7 @@ class _EditBasicProfileInfoScreenState onChanged: (e) { selectedEthnicity = e; print(selectedEthnicity!.name); - print(selectedEthnicity! - .id); + print(selectedEthnicity!.id); }, ), ), @@ -421,7 +421,8 @@ class _EditBasicProfileInfoScreenState child: DropdownButtonFormField( isExpanded: true, value: selectedReligion, - decoration: normalTextFieldStyle("Religion", ""), + decoration: + normalTextFieldStyle("Religion", ""), items: state.religion .map((element) => DropdownMenuItem( @@ -440,10 +441,10 @@ class _EditBasicProfileInfoScreenState Flexible( flex: 1, child: DropdownButtonFormField( - isExpanded: true, value: selectedDisability, - decoration: normalTextFieldStyle("Disability", ""), + decoration: + normalTextFieldStyle("Disability", ""), items: state.disability .map((element) => DropdownMenuItem( @@ -464,33 +465,36 @@ class _EditBasicProfileInfoScreenState width: double.infinity, height: 60, child: ElevatedButton( - style: - mainBtnStyle(primary, Colors.transparent, second), + style: mainBtnStyle( + primary, Colors.transparent, second), onPressed: () { if (_formKey.currentState!.saveAndValidate()) { String lastName = _formKey.currentState!.value['lastname']; String firstName = _formKey.currentState!.value['firstname']; - String? middleName = - _formKey.currentState?.value['middlename']; + String? middleName = _formKey + .currentState?.value['middlename']; String? pref = _formKey.currentState?.value['prefix']; - String suf = _formKey.currentState?.value['suffix']; + String suf = + _formKey.currentState?.value['suffix']; DateTime birthdate = DateTime.parse(bdayController.text); double? hM = - _formKey.currentState!.value['height'] == null + _formKey.currentState!.value['height'] == + null ? null - : double.tryParse( - _formKey.currentState?.value['height']); + : double.tryParse(_formKey + .currentState?.value['height']); double? wKg = - _formKey.currentState!.value['weigth'] == null + _formKey.currentState!.value['weigth'] == + null ? null - : double.tryParse( - _formKey.currentState?.value['weigth']); + : double.tryParse(_formKey + .currentState?.value['weigth']); Profile primaryInformation = Profile( - webuserId: null, + webuserId: null, id: state.primaryInformation.id, lastName: lastName, firstName: firstName, @@ -499,14 +503,21 @@ class _EditBasicProfileInfoScreenState sex: selectedSex, birthdate: birthdate, civilStatus: selectedStatus, - bloodType: selectedBloodType =="NONE"?null:selectedBloodType, + bloodType: selectedBloodType == "NONE" + ? null + : selectedBloodType, heightM: hM, weightKg: wKg, - photoPath: state.primaryInformation.photoPath, - esigPath: state.primaryInformation.esigPath, - maidenName: state.primaryInformation.maidenName, - deceased: state.primaryInformation.deceased, - uuidQrcode: state.primaryInformation.uuidQrcode, + photoPath: + state.primaryInformation.photoPath, + esigPath: + state.primaryInformation.esigPath, + maidenName: + state.primaryInformation.maidenName, + deceased: + state.primaryInformation.deceased, + uuidQrcode: + state.primaryInformation.uuidQrcode, titlePrefix: pref, titleSuffix: suf, showTitleId: @@ -525,7 +536,8 @@ class _EditBasicProfileInfoScreenState genderId: selectedGender?.id, indigencyId: selectedIndigency?.id, profileId: widget.profileId, - profileInformation: primaryInformation, + profileInformation: + primaryInformation, religionId: selectedReligion?.id, token: widget.token)); } @@ -540,7 +552,7 @@ class _EditBasicProfileInfoScreenState ), ); } - return Container(); + return Container(); }, ); } diff --git a/lib/screens/profile/components/basic_information/primary_information_screen.dart b/lib/screens/profile/components/basic_information/primary_information_screen.dart index 1927bb1..9816769 100644 --- a/lib/screens/profile/components/basic_information/primary_information_screen.dart +++ b/lib/screens/profile/components/basic_information/primary_information_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'; @@ -6,6 +5,8 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:intl/intl.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/profile/basic_information/primary-information.dart'; import 'package:unit2/screens/profile/components/basic_information/edit_basic_info_modal.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; @@ -30,6 +31,7 @@ class _PrimaryInfoState extends State { Widget build(BuildContext context) { bool enabled = false; DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); + Profile? profile; return Scaffold( appBar: AppBar( title: context.watch().state @@ -62,300 +64,421 @@ class _PrimaryInfoState extends State { padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is BasicPrimaryInformationLoadingState) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is BasicInformationProfileLoaded || - state is BasicInformationEditingState || - state is BasicPrimaryInformationErrorState || - state is BasicProfileInfoEditedState) { - final progress = ProgressHUD.of(context); - progress!.dismiss(); - } - if (state is BasicProfileInfoEditedState) { - if (state.response['success']) { - successAlert(context, "Updated Successfull!", - state.response['message'], () { - Navigator.of(context).pop(); - context.read().add(LoadBasicPrimaryInfo()); - }); - } else { - errorAlert(context, "Update Failed", - "Something went wrong. Please try again.", () { - Navigator.of(context).pop(); - context.read().add(LoadBasicPrimaryInfo()); - }); - } - } - }, + child: BlocBuilder( builder: (context, state) { - if (state is BasicInformationProfileLoaded) { - return Container( - padding: - const EdgeInsets.symmetric(vertical: 24, horizontal: 24), - child: Column( - children: [ - const SizedBox( - height: 28, - ), - FormBuilderTextField( - enabled: enabled, - name: lastname, - initialValue: state.primaryBasicInformation.lastName!, - decoration: normalTextFieldStyle("Last name", ""), - ), - const SizedBox( - height: 15, - ), - FormBuilderTextField( - enabled: enabled, - name: firstname, - initialValue: state.primaryBasicInformation.firstName!, - decoration: normalTextFieldStyle("First name", ""), - ), - const SizedBox( - height: 15, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 2, - child: FormBuilderTextField( - enabled: enabled, - name: middlename, - initialValue: state.primaryBasicInformation.middleName??'' - , - decoration: - normalTextFieldStyle("Middle name", ""), + if (state is UserLoggedIn) { + state.userData?.employeeInfo?.profile = profile; + return BlocConsumer( + listener: (context, state) { + if (state is BasicPrimaryInformationLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is BasicInformationProfileLoaded || + state is BasicInformationEditingState || + state is BasicPrimaryInformationErrorState || + state is BasicProfileInfoEditedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + if (state is BasicProfileInfoEditedState) { + profile = Profile.fromJson(state.response['data']); + if (state.response['success']) { + successAlert(context, "Updated Successfull!", + state.response['message'], () { + Navigator.of(context).pop(); + context + .read() + .add(LoadBasicPrimaryInfo()); + }); + } else { + errorAlert(context, "Update Failed", + "Something went wrong. Please try again.", () { + Navigator.of(context).pop(); + context + .read() + .add(LoadBasicPrimaryInfo()); + }); + } + } + }, + builder: (context, state) { + if (state is BasicInformationProfileLoaded) { + profile = state.primaryBasicInformation; + return Container( + padding: const EdgeInsets.symmetric( + vertical: 24, horizontal: 24), + child: Column( + children: [ + const SizedBox( + height: 28, ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: extensionName, - initialValue: state.primaryBasicInformation - .nameExtension ??= 'N/A', - decoration: - normalTextFieldStyle("Name extension", ""), - ), - ) - ]), - ), - const SizedBox( - height: 15, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: extensionName, - initialValue: dteFormat2.format( - state.primaryBasicInformation.birthdate!), - decoration: - normalTextFieldStyle("Birth date", ""), - ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: sex, - initialValue: state.primaryBasicInformation.sex!, - decoration: normalTextFieldStyle("Sex", ""), - ), - ) - ]), - ), - const SizedBox( - height: 15, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: "bloodType", + FormBuilderTextField( + enabled: false, + name: lastname, initialValue: - state.primaryBasicInformation.bloodType!, - decoration: - normalTextFieldStyle("Blood type", ""), + state.primaryBasicInformation.lastName!, + style: const TextStyle(color: Colors.black), + decoration: normalTextFieldStyle("Last name", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: + const TextStyle(color: Colors.black)), ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( + const SizedBox( + height: 15, + ), + FormBuilderTextField( enabled: enabled, - name: "civilStatus", + name: firstname, initialValue: - state.primaryBasicInformation.civilStatus!, - decoration: - normalTextFieldStyle("Civil Status", ""), + state.primaryBasicInformation.firstName!, + style: const TextStyle(color: Colors.black), + decoration: normalTextFieldStyle("First name", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: + const TextStyle(color: Colors.black)), ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: "gender", - initialValue: state - .primaryBasicInformation.gender ??= "N/A", - decoration: normalTextFieldStyle("Gender", ""), + const SizedBox( + height: 15, ), - ), - ]), - ), - const SizedBox( - height: 15, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 1, - child: FormBuilderTextField( - maxLines: 2, - enabled: enabled, - name: height, - initialValue: state - .primaryBasicInformation.heightM! - .toString(), - decoration: normalTextFieldStyle("Height", ""), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 2, + child: FormBuilderTextField( + enabled: enabled, + name: middlename, + initialValue: state.primaryBasicInformation + .middleName ?? + '', + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Middle name", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: extensionName, + initialValue: state.primaryBasicInformation + .nameExtension ??= 'N/A', + style: const TextStyle(color: Colors.black), + decoration: normalTextFieldStyle( + "Name extension", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ) + ]), ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: width, - initialValue: state - .primaryBasicInformation.weightKg! - .toString(), - decoration: normalTextFieldStyle("Weight", ""), + const SizedBox( + height: 15, ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: prefixSuffix, - initialValue: - "${state.primaryBasicInformation.titlePrefix ??= "NA"} | ${state.primaryBasicInformation.titleSuffix ??= "N/A"}", - decoration: normalTextFieldStyle( - "Title Prefix and Suffix", ""), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: extensionName, + initialValue: dteFormat2.format(state + .primaryBasicInformation.birthdate!), + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Birth date", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: sex, + initialValue: + state.primaryBasicInformation.sex!, + style: const TextStyle(color: Colors.black), + decoration: normalTextFieldStyle("Sex", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ) + ]), ), - ), - ]), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 1, - child: FormBuilderTextField( - maxLines: 2, - enabled: enabled, - name: height, - initialValue: state.primaryBasicInformation.ip ??= - "N/A", - decoration: - normalTextFieldStyle("Indigenous", ""), + const SizedBox( + height: 15, ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - enabled: enabled, - name: width, - initialValue: state - .primaryBasicInformation.ethnicity ??= "N/A", - decoration: normalTextFieldStyle("Ethnicity", ""), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: "bloodType", + initialValue: state + .primaryBasicInformation.bloodType!, + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Blood type", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: "civilStatus", + initialValue: state + .primaryBasicInformation.civilStatus!, + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Civil Status", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: "gender", + initialValue: state.primaryBasicInformation + .gender ??= "N/A", + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Gender", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + ]), ), - ), - ]), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: screenWidth, - child: Row(children: [ - Flexible( - flex: 1, - child: FormBuilderTextField( - maxLines: 2, - enabled: enabled, - name: height, - initialValue: state - .primaryBasicInformation.religion ??= "N/A", - decoration: normalTextFieldStyle("Religion", ""), + const SizedBox( + height: 15, ), - ), - const SizedBox( - width: 10, - ), - Flexible( - flex: 1, - child: FormBuilderTextField( - maxLines: 2, - enabled: enabled, - name: width, - initialValue: state - .primaryBasicInformation.disability ??= "N/A", - decoration: - normalTextFieldStyle("Disability", ""), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + maxLines: 2, + enabled: enabled, + name: height, + initialValue: state + .primaryBasicInformation.heightM! + .toString(), + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Height", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: width, + initialValue: state + .primaryBasicInformation.weightKg! + .toString(), + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Weight", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: prefixSuffix, + initialValue: + "${state.primaryBasicInformation.titlePrefix ??= "NA"} | ${state.primaryBasicInformation.titleSuffix ??= "N/A"}", + style: const TextStyle(color: Colors.black), + decoration: normalTextFieldStyle( + "Title Prefix and Suffix", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + ]), ), - ), - ]), - ), - ], - ), + const SizedBox( + height: 12, + ), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + maxLines: 2, + enabled: enabled, + name: height, + initialValue: state + .primaryBasicInformation.ip ??= "N/A", + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Indigenous", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + enabled: enabled, + name: width, + initialValue: state.primaryBasicInformation + .ethnicity ??= "N/A", + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Ethnicity", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + ]), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: screenWidth, + child: Row(children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + maxLines: 2, + enabled: enabled, + name: height, + initialValue: state.primaryBasicInformation + .religion ??= "N/A", + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Religion", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + const SizedBox( + width: 10, + ), + Flexible( + flex: 1, + child: FormBuilderTextField( + maxLines: 2, + enabled: enabled, + name: width, + initialValue: state.primaryBasicInformation + .disability ??= "N/A", + style: const TextStyle(color: Colors.black), + decoration: + normalTextFieldStyle("Disability", "") + .copyWith( + disabledBorder: + const OutlineInputBorder(), + labelStyle: const TextStyle( + color: Colors.black)), + ), + ), + ]), + ), + ], + ), + ); + } + if (state is BasicPrimaryInformationErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context + .read() + .add(LoadBasicPrimaryInfo()); + }); + } + if (state is BasicInformationEditingState) { + return EditBasicProfileInfoScreen( + profileId: widget.profileId, token: widget.token); + } + return Container(); + }, ); } - if (state is BasicPrimaryInformationErrorState) { - return SomethingWentWrong( - message: state.message, - onpressed: () { - context.read().add(LoadBasicPrimaryInfo()); - }); - } - if (state is BasicInformationEditingState) { - return EditBasicProfileInfoScreen( - profileId: widget.profileId, token: widget.token); - } return Container(); }, ), diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index 9037fee..a8cd223 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -70,7 +70,6 @@ class ProfileInfo extends StatelessWidget { profileId = state.userData!.user!.login!.user!.profileId; token = state.userData!.user!.login!.token!; profile = state.userData!.employeeInfo!.profile!; - return BlocConsumer( listener: ( context, diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index 4b0a84a..6291eb9 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -1,12 +1,422 @@ +import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.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:fluttericon/font_awesome5_icons.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart'; +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/login_data/user_info/assigned_area.dart'; +import 'package:unit2/model/profile/assigned_area.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/model/utils/agency.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/utils/formatters.dart'; +import 'package:unit2/utils/global_context.dart'; +import 'package:unit2/utils/profile_utilities.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/empty_data.dart'; class RbacAssignedAreaScreen extends StatelessWidget { const RbacAssignedAreaScreen({super.key}); @override Widget build(BuildContext context) { - return Center(child: Text("dsadasdas"),); + Map> assignedAreas = {}; + final formKey = GlobalKey(); + List roles = []; + bool async = false; + List userAssignedAreas = []; + final bloc = BlocProvider.of(context); + RBAC? selectedRole; + String? areaType; + List agencies = []; + FocusNode agencyFocusNode = FocusNode(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + centerTitle: true, + title: const Text("Assigned Area"), + actions: [ + AddLeading(onPressed: () { + roles.clear(); + for (var area in userAssignedAreas) { + roles.add(area.assignedRole!.role!); + } + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: StatefulBuilder(builder: (context, setState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Select Role", "Select Role"), + name: 'role', + items: roles.map>((e) { + return DropdownMenuItem( + value: e, + child: Text(e.name!), + onTap: () async { + setState(() { + async = true; + }); + //// barangay + if (e.name!.toLowerCase() == "barangay chairperson" || + e.name!.toLowerCase() == + "barangay councilor" || + e.name!.toLowerCase() == + "barangay nurse" || + e.name!.toLowerCase() == + "health officer in-charge" || + e.name!.toLowerCase() == + "health monitoring in-charge" || + e.name!.toLowerCase() == + "health nurse") { + ////=========== + //// purok + } else if (e.name!.toLowerCase() == + "purok president") { + ////=============== + //// station + } else if (e.name!.toLowerCase() == "qr code scanner" || + e.name!.toLowerCase() == + "security guard" || + e.name!.toLowerCase() == + "checkpoint in-charge" || + e.name!.toLowerCase() == + 'office/branch chief' || + e.name!.toLowerCase() == + "process server") { + //// agency + } else if (e.name!.toLowerCase() == + "establishment point-person" || + e.name!.toLowerCase() == + 'registration in-charge' || + e.name!.toLowerCase() == + "provincial/city drrm officer in-charge") { + try { + areaType = "agency"; + agencies = await ProfileUtilities + .instance + .getAgecies(); + } catch (e) { + bloc.add(CallErrorState( + message: e.toString())); + } + setState(() { + async = false; + }); + } + }, + ); + }).toList(), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 75, + width: double.maxFinite, + child: ModalProgressHUD( + inAsyncCall: async, + child: SizedBox( + child: areaType == "agency" + ? SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + focusNode: agencyFocusNode, + itemHeight: 100, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem( + agency.name!, + item: agency, + child: ListTile( + title: + AutoSizeText( + agency.name! + .toUpperCase(), + minFontSize: + 12, + ), + subtitle: Text(agency + .privateEntity == + true + ? "Private" + : agency.privateEntity == + false + ? "Government" + : ""), + ))) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: + normalTextFieldStyle( + "Agency *", "") + .copyWith( + suffixIcon: + GestureDetector( + onTap: () => agencyFocusNode + .unfocus(), + child: const Icon( + Icons.arrow_drop_down, + ), + )), + ////agency suggestion tap + onSuggestionTap: (agency) { + setState(() { + agencyFocusNode.unfocus(); + }); + }, + emptyWidget: const Text( + "No Result Found..")) + : areaType == "station"?Container():Container()))), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ); + }), + )); + }); + }) + ], + ), + 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) { + return BlocConsumer( + listener: (context, state) { + if (state is AssignAreaLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is AssignAreaErorState || + state is AssignedAreaLoadedState || + state is UserNotExistError || + state is AssignedAreaDeletedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is AssignedAreaDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Role Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedAreas()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedAreas()); + }); + } + } + }, + builder: (context, state) { + if (state is AssignedAreaLoadedState) { + assignedAreas = {}; + userAssignedAreas = state.userAssignedAreas; + if (state.userAssignedAreas.isNotEmpty) { + for (var roleMod in state.userAssignedAreas) { + assignedAreas.addAll({ + roleMod.assignedRole!.role!.name!.toLowerCase(): [] + }); + String areaType = roleMod + .assignedRoleAreaType!.areaTypeName + .toLowerCase(); + for (var area in roleMod.assignedArea) { + if (areaType == 'baranggay') { + assignedAreas[roleMod.assignedRole!.role!.name! + .toLowerCase()]! + .add(Content( + id: area['id'], + name: area['area']['brgydesc'])); + } else if (areaType == 'purok') { + assignedAreas[roleMod.assignedRole!.role!.name! + .toLowerCase()]! + .add(Content( + id: area['id'], + name: area['area']['purokdesc'])); + } else if (areaType == 'station') { + assignedAreas[roleMod.assignedRole!.role!.name! + .toLowerCase()]! + .add(Content( + id: area['id'], + name: area['area']["station_name"])); + } else if (areaType == 'agency') { + assignedAreas[roleMod.assignedRole!.role!.name! + .toLowerCase()]! + .add(Content( + id: area['id'], + name: area['area']['name'])); + } + } + } + } + if (state.userAssignedAreas.isNotEmpty) { + return Column( + children: [ + ListTile( + tileColor: second, + leading: const Icon( + FontAwesome5.user_alt, + color: Colors.white, + ), + title: Text(state.fullname.toUpperCase(), + style: Theme.of(context) + .textTheme + .titleLarge! + .copyWith(color: Colors.white)), + subtitle: Text("Person full name", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white)), + ), + Expanded( + child: GroupListView( + sectionsCount: assignedAreas.keys.toList().length, + countOfItemInSection: (int section) { + return assignedAreas.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( + DeleteAssignedArea( + areaId: assignedAreas.values + .toList()[index.section] + [index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + title: Row( + children: [ + Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white)), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + assignedAreas.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( + assignedAreas.keys + .toList()[section] + .toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, + fontWeight: FontWeight.bold), + ), + ); + }, + ), + ), + ], + ); + } else { + return EmptyData( + message: + "No Assigned Area available for ${state.fullname}. Please click + to add."); + } + } + if (state is AssignAreaErorState) { + print("error state"); + } + if (state is UserNotExistError) { + return const Center( + child: Text("User Not Exsit"), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ), + ), + ); } -} \ No newline at end of file +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} 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 93ec3ed..b09f086 100644 --- a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart +++ b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart @@ -213,7 +213,7 @@ class RbacRoleAssignment extends StatelessWidget { Flexible( child: Text( state.assignedRoles[index].role! - .name, + .name!, style: Theme.of(context) .textTheme .titleMedium! @@ -262,8 +262,8 @@ class RbacRoleAssignment extends StatelessWidget { ], ); } else { - return const EmptyData( - message: "No Role available. Please click + to add."); + return EmptyData( + message: "No Role available for ${state.fullname}. Please click + to add."); } } if (state is RoleAssignmentErrorState) { diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart index eb7ffb4..5098a1f 100644 --- a/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart +++ b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart @@ -76,9 +76,6 @@ class _DashBoardState extends State { tempUnit2Cards = unit2Cards.sublist(0, 4); } - superadminCards.forEach((el) { - print(el.object.name); - }); return Container( padding: 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 f00739f..cda98a5 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 @@ -209,6 +209,7 @@ class SuperAdminMenu extends StatelessWidget { ); })); } + //////////////////////////////// if (object.object.name == 'Area') { Navigator.of(context).pop(); showDialog( diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index d3cfc7c..69c96c2 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -393,7 +393,7 @@ class _UniT2LoginState extends State { }, ); } - return Container(); + return const UniTSplashScreen(); }), ), ), diff --git a/lib/screens/unit2/roles/establishment_point_person/est_point_person_role_member_screen.dart b/lib/screens/unit2/roles/establishment_point_person/est_point_person_role_member_screen.dart index 185c62d..262fd50 100644 --- a/lib/screens/unit2/roles/establishment_point_person/est_point_person_role_member_screen.dart +++ b/lib/screens/unit2/roles/establishment_point_person/est_point_person_role_member_screen.dart @@ -158,11 +158,11 @@ class EstPointPersonRoleAssignmentScreen extends StatelessWidget { if (!assignedRoles.keys.contains(fullName)) { assignedRoles.addAll({fullName: []}); assignedRoles[fullName]!.add(Content( - id: assignedRole.id!, name: assignedRole.role!.name)); + id: assignedRole.id!, name: assignedRole.role!.name!)); } else { assignedRoles[fullName]!.add(Content( id: assignedRole.id!, - name: assignedRole.role!.name)); + name: assignedRole.role!.name!)); } } } diff --git a/lib/sevices/roles/rbac_operations/assigned_area_services.dart b/lib/sevices/roles/rbac_operations/assigned_area_services.dart index 7bc2030..c2eda76 100644 --- a/lib/sevices/roles/rbac_operations/assigned_area_services.dart +++ b/lib/sevices/roles/rbac_operations/assigned_area_services.dart @@ -39,4 +39,23 @@ class RbacAssignedAreaServices { } return userAssignedAreas; } + 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: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } } diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 2ec2083..3cecbe6 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -14,8 +14,8 @@ class Url { } String prefixHost() { - // return "https"; - return "http"; + return "https"; + // return "http"; } String authentication() { diff --git a/pubspec.lock b/pubspec.lock index a494f46..a6d51ca 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -25,6 +25,14 @@ packages: 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" app_popup_menu: dependency: "direct main" description: @@ -973,6 +981,14 @@ 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: diff --git a/pubspec.yaml b/pubspec.yaml index 8d51f86..c103c45 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -97,6 +97,7 @@ dependencies: url_launcher: ^6.1.11 url_launcher_android: ^6.0.38 share_plus: ^7.1.0 + animated_splash_screen: ^1.3.0 dependency_overrides: intl: ^0.18.0 From f73f8a03e176641ab22298838a5b986404ccf0f5 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Fri, 15 Sep 2023 08:03:54 +0800 Subject: [PATCH 4/8] role area assignment done but need ui enhancement and refactoring --- .../assign_area/assign_area_bloc.dart | 37 +- .../assign_area/assign_area_event.dart | 46 +- .../assign_area/assign_area_state.dart | 14 +- lib/model/profile/assigned_area.dart | 40 +- lib/model/rbac/assigned_role.dart | 50 +- .../assign_area/assign_area_screen.dart | 573 +++++++++++++++--- .../assigned_area_services.dart | 28 + lib/utils/location_utilities.dart | 4 +- 8 files changed, 605 insertions(+), 187 deletions(-) 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 0473081..10c7aff 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 @@ -1,12 +1,11 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; -import 'package:unit2/bloc/rbac/rbac_bloc.dart'; +import 'package:unit2/model/rbac/assigned_role.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart'; - import '../../../../model/profile/assigned_area.dart'; import '../../../../model/profile/basic_information/primary-information.dart'; import '../../../../sevices/roles/rbac_operations/role_assignment_services.dart'; - part 'assign_area_event.dart'; part 'assign_area_state.dart'; @@ -18,6 +17,8 @@ class AssignAreaBloc extends Bloc { Profile? profile; int id; List userAssignedAreas = []; + List assignedRoles = []; + List roles = []; on((event, emit) async { emit(AssignAreaLoadingState()); try { @@ -31,24 +32,46 @@ class AssignAreaBloc extends Bloc { id = profile!.webuserId!; userAssignedAreas = await RbacAssignedAreaServices.instance .getAssignedArea(id: profile!.webuserId!); + + assignedRoles = await RbacRoleAssignmentServices.instance + .getAssignedRoles( + firstname: event.firstname, lastname: event.lastname); + + for (var role in assignedRoles) { + roles.add(role.role!); + } emit(AssignedAreaLoadedState( - userAssignedAreas: userAssignedAreas, fullname: fullname!)); + userAssignedAreas: userAssignedAreas, fullname: fullname!,roles: roles,userId: id)); } else { + id = 0; emit(UserNotExistError()); } } catch (e) { emit(AssignAreaErorState(message: e.toString())); } }); + on((event,emit)async{ + try{ + emit(AssignAreaLoadingState()); + Map response = await RbacAssignedAreaServices.instance.add(userId: event.userId, roleId: event.roleId, areaTypeId: event.areaTypeId, areaId: event.areaId); + if(response["success"]){ + emit(AssignAreaAddedState(response: response)); + }else{ + emit(AssignAreaAddedState(response: response)); + } + }catch(e){ + emit(AssignAreaErorState(message: e.toString())); + } + }); on((event, emit) async { emit(AssignedAreaLoadedState( - userAssignedAreas: userAssignedAreas, fullname: fullname!)); + userAssignedAreas: userAssignedAreas, fullname: fullname!,roles: roles,userId: event.userId)); }); on((event, emit) async { emit(AssignAreaLoadingState()); try { - bool success = await RbacRoleAssignmentServices.instance - .deleteAssignedRole(roleId: event.areaId); + bool success = await RbacAssignedAreaServices.instance + .deleteAssignedArea(areaId: event.areaId); if (success) { emit(AssignedAreaDeletedState(success: success)); } else { diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart index 0f97956..3c3817d 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart @@ -1,31 +1,51 @@ part of 'assign_area_bloc.dart'; - class AssignAreaEvent extends Equatable { + +class AssignAreaEvent extends Equatable { const AssignAreaEvent(); @override List get props => []; } -class GetAssignArea extends AssignAreaEvent{ +class GetAssignArea extends AssignAreaEvent { final String firstname; final String lastname; const GetAssignArea({required this.firstname, required this.lastname}); - @override - List get props => [firstname,lastname]; + @override + List get props => [firstname, lastname]; } -class DeleteAssignedArea extends AssignAreaEvent{ -final int areaId; -const DeleteAssignedArea({required this.areaId}); - @override + +class DeleteAssignedArea extends AssignAreaEvent { + final int areaId; + const DeleteAssignedArea({required this.areaId}); + @override List get props => [areaId]; } -class LoadAssignedAreas extends AssignAreaEvent{ - +class LoadAssignedAreas extends AssignAreaEvent { + final int userId; + const LoadAssignedAreas({required this.userId}); + @override + List get props => [userId]; } -class CallErrorState extends AssignAreaEvent{ + +class CallErrorState extends AssignAreaEvent { final String message; const CallErrorState({required this.message}); - @override + @override List get props => [message]; -} \ No newline at end of file +} + +class AddAssignArea extends AssignAreaEvent { + final int userId; + final int roleId; + final int areaTypeId; + final String areaId; + const AddAssignArea( + {required this.areaId, + required this.areaTypeId, + required this.roleId, + required this.userId}); + @override + List get props => [userId, roleId, areaTypeId, areaId]; +} diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart index 255ad6d..e1f4ab6 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_state.dart @@ -9,10 +9,12 @@ class AssignAreaState extends Equatable { class AssignedAreaLoadedState extends AssignAreaState{ final List userAssignedAreas; + final List roles; final String fullname; - const AssignedAreaLoadedState({required this.userAssignedAreas, required this.fullname}); + final int userId; + const AssignedAreaLoadedState({required this.userAssignedAreas, required this.fullname, required this.roles, required this.userId}); @override - List get props => [userAssignedAreas,fullname]; + List get props => [userAssignedAreas,fullname,roles]; } class AssignAreaErorState extends AssignAreaState { final String message; @@ -33,4 +35,10 @@ class AssignedAreaDeletedState extends AssignAreaState{ const AssignedAreaDeletedState({required this.success}); @override List get props => [success]; -} \ No newline at end of file +} +class AssignAreaAddedState extends AssignAreaState { + final Map response; + const AssignAreaAddedState({required this.response}); + @override + List get props => [response]; +} diff --git a/lib/model/profile/assigned_area.dart b/lib/model/profile/assigned_area.dart index 83be0b0..e4424b2 100644 --- a/lib/model/profile/assigned_area.dart +++ b/lib/model/profile/assigned_area.dart @@ -1,3 +1,4 @@ +import 'package:unit2/model/rbac/assigned_role.dart'; import 'package:unit2/model/rbac/rbac.dart'; import '../roles/pass_check/assign_role_area_type.dart'; @@ -26,45 +27,6 @@ class UserAssignedArea { }; } -class AssignedRole { - final int id; - final RBAC? role; - final CreatedBy? user; - final DateTime? createdAt; - final DateTime? updatedAt; - final CreatedBy? createdBy; - final CreatedBy? updatedBy; - - AssignedRole({ - required this.id, - required this.role, - required this.user, - required this.createdAt, - required this.updatedAt, - required this.createdBy, - required this.updatedBy, - }); - - factory AssignedRole.fromJson(Map json) => AssignedRole( - id: json["id"], - role: RBAC.fromJson(json["role"]), - user: CreatedBy.fromJson(json["user"]), - createdAt: DateTime.parse(json["created_at"]), - updatedAt: DateTime.parse(json["updated_at"]), - createdBy: CreatedBy.fromJson(json["created_by"]), - updatedBy: CreatedBy.fromJson(json["updated_by"]), - ); - - Map toJson() => { - "id": id, - "role": role?.toJson(), - "user": user?.toJson(), - "created_at": createdAt?.toIso8601String(), - "updated_at": updatedAt?.toIso8601String(), - "created_by": createdBy?.toJson(), - "updated_by": updatedBy?.toJson(), - }; -} diff --git a/lib/model/rbac/assigned_role.dart b/lib/model/rbac/assigned_role.dart index 82dc3b2..ca688e1 100644 --- a/lib/model/rbac/assigned_role.dart +++ b/lib/model/rbac/assigned_role.dart @@ -5,13 +5,15 @@ import 'package:meta/meta.dart'; import 'dart:convert'; +import 'package:unit2/model/rbac/rbac.dart'; + AssignedRole assignedRoleFromJson(String str) => AssignedRole.fromJson(json.decode(str)); String assignedRoleToJson(AssignedRole data) => json.encode(data.toJson()); class AssignedRole { final int? id; - final Role? role; + final RBAC? role; final CreatedBy? user; final DateTime? createdAt; final DateTime? updatedAt; @@ -30,7 +32,7 @@ class AssignedRole { factory AssignedRole.fromJson(Map json) => AssignedRole( id: json["id"], - role: json['role'] == null?null: Role.fromJson(json["role"]), + role: json['role'] == null?null: RBAC.fromJson(json["role"]), user: json['role'] == null?null: CreatedBy.fromJson(json["user"]), createdAt:json["created_at"] == null?null: DateTime.parse(json["created_at"]), updatedAt: json["updated_at"] == null?null: DateTime.parse(json["updated_at"]), @@ -84,47 +86,3 @@ class CreatedBy { "is_active": isActive, }; } - -class Role { - final int id; - final String? name; - final String? slug; - final String? shorthand; - final DateTime? createdAt; - final DateTime? updatedAt; - final CreatedBy? createdBy; - final CreatedBy? 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: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: CreatedBy.fromJson(json["created_by"]), - updatedBy:json["updated_by"] == null?null: CreatedBy.fromJson(json["updated_by"]), - ); - - Map toJson() => { - "id": id, - "name": name, - "slug": slug, - "shorthand": shorthand, - "created_at": createdAt?.toIso8601String(), - "updated_at": updatedAt?.toIso8601String(), - "created_by": createdBy?.toJson(), - "updated_by": updatedBy?.toJson(), - }; -} diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index 6291eb9..9f210f4 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -13,35 +13,68 @@ import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:searchfield/searchfield.dart'; import 'package:unit2/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart'; import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/location/city.dart'; +import 'package:unit2/model/location/provinces.dart'; +import 'package:unit2/model/location/region.dart'; import 'package:unit2/model/login_data/user_info/assigned_area.dart'; import 'package:unit2/model/profile/assigned_area.dart'; import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/model/rbac/rbac_station.dart'; +import 'package:unit2/model/roles/pass_check/agency_area_type.dart'; +import 'package:unit2/model/roles/pass_check/station_assign_area.dart'; import 'package:unit2/model/utils/agency.dart'; +import 'package:unit2/model/utils/category.dart'; +import 'package:unit2/sevices/roles/rbac_operations/station_services.dart'; +import 'package:unit2/test_data.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/utils/formatters.dart'; import 'package:unit2/utils/global_context.dart'; +import 'package:unit2/utils/location_utilities.dart'; import 'package:unit2/utils/profile_utilities.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/empty_data.dart'; +import 'package:unit2/widgets/error_state.dart'; -class RbacAssignedAreaScreen extends StatelessWidget { +class RbacAssignedAreaScreen extends StatefulWidget { const RbacAssignedAreaScreen({super.key}); + @override + State createState() => _RbacAssignedAreaScreenState(); +} + +class _RbacAssignedAreaScreenState extends State { @override Widget build(BuildContext context) { Map> assignedAreas = {}; final formKey = GlobalKey(); List roles = []; - bool async = false; + bool agencyAsyncCall = false; + bool stationAsyncCall = false; + bool provinceAsyncCall = false; + bool cityAsyncCall = false; + bool barangayAsyncCall = false; List userAssignedAreas = []; final bloc = BlocProvider.of(context); - RBAC? selectedRole; + int? areaTypeId; + int? roleId; + int? userId; + String? areaId; String? areaType; List agencies = []; + List stations = []; FocusNode agencyFocusNode = FocusNode(); + final agencyController = TextEditingController( + text: "PROVINCIAL GOVERNMENT OF AGUSAN DEL NORTE"); + List provinces = []; + List cities = []; + List barangays = []; + Province? selectedProvince; + CityMunicipality? selectedMunicipality; + Barangay? selectedBarangay; return Scaffold( appBar: AppBar( backgroundColor: primary, @@ -49,13 +82,11 @@ class RbacAssignedAreaScreen extends StatelessWidget { title: const Text("Assigned Area"), actions: [ AddLeading(onPressed: () { - roles.clear(); - for (var area in userAssignedAreas) { - roles.add(area.assignedRole!.role!); - } showDialog( context: context, builder: (BuildContext context) { + areaType = null; + return AlertDialog( title: const Text("Add New Role"), content: FormBuilder( @@ -73,9 +104,7 @@ class RbacAssignedAreaScreen extends StatelessWidget { value: e, child: Text(e.name!), onTap: () async { - setState(() { - async = true; - }); + roleId = e.id; //// barangay if (e.name!.toLowerCase() == "barangay chairperson" || e.name!.toLowerCase() == @@ -88,11 +117,41 @@ class RbacAssignedAreaScreen extends StatelessWidget { "health monitoring in-charge" || e.name!.toLowerCase() == "health nurse") { + try { + areaType = "barangay"; + areaTypeId = 1; + setState(() { + provinceAsyncCall = true; + }); + provinces = await LocationUtils + .instance + .getProvinces(regionCode: "16"); + setState(() { + provinceAsyncCall = false; + cityAsyncCall = true; + }); + cities = await LocationUtils.instance + .getCities( + code: provinces[0].code!); + setState(() { + cityAsyncCall = false; + barangayAsyncCall = true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: cities[0].code!); + setState(() { + barangayAsyncCall = false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e.toString())); + } ////=========== //// purok } else if (e.name!.toLowerCase() == "purok president") { - ////=============== //// station } else if (e.name!.toLowerCase() == "qr code scanner" || e.name!.toLowerCase() == @@ -103,15 +162,44 @@ class RbacAssignedAreaScreen extends StatelessWidget { 'office/branch chief' || e.name!.toLowerCase() == "process server") { - //// agency + try { + areaType = "station"; + areaId = "4"; + setState(() { + agencyAsyncCall = true; + }); + agencies = await ProfileUtilities + .instance + .getAgecies(); + setState(() { + agencyAsyncCall = false; + stationAsyncCall = true; + }); + stations = await RbacStationServices + .instance + .getStations(agencyId: "1"); + setState(() { + stationAsyncCall = false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e.toString())); + } + + //// agency------------------------------- } else if (e.name!.toLowerCase() == "establishment point-person" || e.name!.toLowerCase() == 'registration in-charge' || e.name!.toLowerCase() == "provincial/city drrm officer in-charge") { + areaType = "agency"; + areaTypeId = 3; try { - areaType = "agency"; + setState(() { + agencyAsyncCall = true; + }); + agencies = await ProfileUtilities .instance .getAgecies(); @@ -120,7 +208,7 @@ class RbacAssignedAreaScreen extends StatelessWidget { message: e.toString())); } setState(() { - async = false; + agencyAsyncCall = false; }); } }, @@ -130,67 +218,362 @@ class RbacAssignedAreaScreen extends StatelessWidget { const SizedBox( height: 12, ), - SizedBox( - height: 75, - width: double.maxFinite, - child: ModalProgressHUD( - inAsyncCall: async, - child: SizedBox( - child: areaType == "agency" - ? SearchField( - inputFormatters: [ - UpperCaseTextFormatter() - ], - focusNode: agencyFocusNode, - itemHeight: 100, - suggestions: agencies - .map((Agency agency) => - SearchFieldListItem( - agency.name!, - item: agency, - child: ListTile( - title: - AutoSizeText( - agency.name! - .toUpperCase(), - minFontSize: - 12, - ), - subtitle: Text(agency - .privateEntity == - true - ? "Private" - : agency.privateEntity == - false - ? "Government" - : ""), - ))) - .toList(), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), - searchInputDecoration: - normalTextFieldStyle( - "Agency *", "") - .copyWith( - suffixIcon: - GestureDetector( - onTap: () => agencyFocusNode - .unfocus(), - child: const Icon( - Icons.arrow_drop_down, + areaType == "agency" + ? SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + focusNode: agencyFocusNode, + itemHeight: 100, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem( + agency.name!, + item: agency, + child: ListTile( + title: + AutoSizeText( + agency.name! + .toUpperCase(), + minFontSize: + 12, ), - )), - ////agency suggestion tap - onSuggestionTap: (agency) { - setState(() { - agencyFocusNode.unfocus(); - }); - }, - emptyWidget: const Text( - "No Result Found..")) - : areaType == "station"?Container():Container()))), + subtitle: Text(agency + .privateEntity == + true + ? "Private" + : agency.privateEntity == + false + ? "Government" + : ""), + ))) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: + normalTextFieldStyle( + "Agency *", "") + .copyWith( + suffixIcon: + GestureDetector( + onTap: () => agencyFocusNode + .unfocus(), + child: const Icon( + Icons.arrow_drop_down, + ), + )), + ////agency suggestion tap + onSuggestionTap: (agency) { + setState(() { + areaId = agency.item!.id + .toString(); + agencyFocusNode.unfocus(); + }); + }, + emptyWidget: const Text( + "No Result Found..")) + //// station ------------------------------------------------ + : areaType == "station" + ? SizedBox( + height: 200, + child: Flexible( + child: Column( + children: [ + Expanded( + child: SizedBox( + height: 100, + child: ModalProgressHUD( + inAsyncCall: agencyAsyncCall, + child: SearchField( + controller: + agencyController, + inputFormatters: [ + UpperCaseTextFormatter() + ], + focusNode: + agencyFocusNode, + itemHeight: 100, + suggestions: + agencies + .map((Agency agency) => SearchFieldListItem( + agency + .name!, + item: + agency, + child: + ListTile( + title: AutoSizeText( + agency.name!.toUpperCase(), + minFontSize: 12, + ), + subtitle: Text(agency.privateEntity == true + ? "Private" + : agency.privateEntity == false + ? "Government" + : ""), + ))) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: normalTextFieldStyle( + "Agency *", + "") + .copyWith( + suffixIcon: + GestureDetector( + onTap: () => + agencyFocusNode + .unfocus(), + child: + const Icon( + Icons + .arrow_drop_down, + ), + )), + ////agency suggestion tap + onSuggestionTap: + (agency) { + setState(() { + agencyFocusNode + .unfocus(); + }); + }, + emptyWidget: + const Text( + "No Result Found..")), + ), + ), + ), + const SizedBox( + height: 12, + ), + Expanded( + child: SizedBox( + height: 75, + child: + ModalProgressHUD( + color: Colors + .transparent, + inAsyncCall: + stationAsyncCall, + child: FormBuilderDropdown< + RbacStation>( + decoration: normalTextFieldStyle( + "Station", + "Station"), + name: + "parent-stations", + items: stations + .isEmpty + ? [] + : stations + .map( + (e) { + return DropdownMenuItem( + value: + e, + child: + Text(e.stationName!), + ); + }).toList(), + onChanged: + (RbacStation? + e) {}, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + ), + ) + ], + ), + ), + ) + //// barangay ------------------------------------------------------------ + : areaType == 'barangay' + ? SizedBox( + height: 300, + child: Column( + children: [ + //// PROVINCE DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors + .transparent, + inAsyncCall: + provinceAsyncCall, + child: DropdownButtonFormField< + Province?>( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: (value) => value == + null + ? 'required' + : null, + isExpanded: + true, + // value: selectedProvince, + onChanged: + (Province? + province) async { + setState( + () { + selectedProvince = + province; + cityAsyncCall = + true; + }); + cities = await LocationUtils + .instance + .getCities(code: provinces[0].code!); + setState( + () { + cityAsyncCall = + false; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay(code: cities[0].code!); + setState( + () { + barangayAsyncCall = + false; + }); + }, + items: provinces + .isEmpty + ? [] + : provinces.map>((Province + province) { + return DropdownMenuItem( + value: province, + child: FittedBox( + child: Text(province.description!), + )); + }).toList(), + decoration: normalTextFieldStyle( + "Province*", + "Province")), + ), + ), + ), + //// CITIES DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors + .white, + inAsyncCall: + cityAsyncCall, + child: DropdownButtonFormField< + CityMunicipality>( + validator: FormBuilderValidators.required( + errorText: + "This field is required"), + isExpanded: + true, + onChanged: + (CityMunicipality? + city) async { + setState( + () { + selectedMunicipality = + city; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality!.code!); + setState( + () { + barangayAsyncCall = + false; + }); + }, + decoration: normalTextFieldStyle( + "Municipality*", + "Municipality"), + // value: selectedMunicipality, + items: cities + .isEmpty + ? [] + : cities.map< + DropdownMenuItem< + CityMunicipality>>((CityMunicipality + c) { + return DropdownMenuItem( + value: c, + child: Text(c.description!)); + }).toList(), + ), + ), + ), + ), + ////Barangay + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors + .white, + inAsyncCall: + barangayAsyncCall, + child: DropdownButtonFormField< + Barangay>( + isExpanded: + true, + onChanged: + (Barangay? + baragay) { + areaId = + baragay! + .code; + }, + decoration: normalTextFieldStyle( + "Barangay*", + "Barangay"), + // value: selectedBarangay, + validator: FormBuilderValidators.required( + errorText: + "This field is required"), + items: barangays + .isEmpty + ? [] + : barangays.map< + DropdownMenuItem< + Barangay>>((Barangay + barangay) { + return DropdownMenuItem( + value: barangay, + child: Text(barangay.description!)); + }).toList(), + ), + ), + ), + ), + ], + )) + : Container(), + const SizedBox( + height: 25, + ), SizedBox( width: double.infinity, height: 50, @@ -200,6 +583,11 @@ class RbacAssignedAreaScreen extends StatelessWidget { onPressed: () { if (formKey.currentState! .saveAndValidate()) { + bloc.add(AddAssignArea( + areaId: areaId!, + areaTypeId: areaTypeId!, + roleId: roleId!, + userId: userId!)); Navigator.pop(context); } }, @@ -228,7 +616,8 @@ class RbacAssignedAreaScreen extends StatelessWidget { if (state is AssignAreaErorState || state is AssignedAreaLoadedState || state is UserNotExistError || - state is AssignedAreaDeletedState) { + state is AssignedAreaDeletedState || + state is AssignAreaAddedState) { final progress = ProgressHUD.of(context); progress!.dismiss(); } @@ -239,14 +628,39 @@ class RbacAssignedAreaScreen extends StatelessWidget { successAlert(context, "Delete Successfull!", "Role Module Deleted Successfully", () { Navigator.of(context).pop(); - context.read().add(LoadAssignedAreas()); + context + .read() + .add(LoadAssignedAreas(userId: userId!)); }); } else { errorAlert( context, "Delete Failed", "Role Module Delete Failed", () { Navigator.of(context).pop(); - context.read().add(LoadAssignedAreas()); + context + .read() + .add(LoadAssignedAreas(userId: userId!)); + }); + } + } + + ////Added State + if (state is AssignAreaAddedState) { + if (state.response['success']) { + successAlert(context, "Adding Successfull!", + state.response['message'], () { + Navigator.of(context).pop(); + context + .read() + .add(LoadAssignedAreas(userId: userId!)); + }); + } else { + errorAlert(context, "Adding Failed", + "Something went wrong. Please try again.", () { + Navigator.of(context).pop(); + context + .read() + .add(LoadAssignedAreas(userId: userId!)); }); } } @@ -254,6 +668,8 @@ class RbacAssignedAreaScreen extends StatelessWidget { builder: (context, state) { if (state is AssignedAreaLoadedState) { assignedAreas = {}; + roles = state.roles; + userId = state.userId; userAssignedAreas = state.userAssignedAreas; if (state.userAssignedAreas.isNotEmpty) { for (var roleMod in state.userAssignedAreas) { @@ -396,7 +812,8 @@ class RbacAssignedAreaScreen extends StatelessWidget { } } if (state is AssignAreaErorState) { - print("error state"); + return SomethingWentWrong( + message: state.message, onpressed: () {}); } if (state is UserNotExistError) { return const Center( diff --git a/lib/sevices/roles/rbac_operations/assigned_area_services.dart b/lib/sevices/roles/rbac_operations/assigned_area_services.dart index c2eda76..7dd4962 100644 --- a/lib/sevices/roles/rbac_operations/assigned_area_services.dart +++ b/lib/sevices/roles/rbac_operations/assigned_area_services.dart @@ -52,10 +52,38 @@ class RbacAssignedAreaServices { .deleteRequest(path: path, headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; + }else{ + success = false; } } catch (e) { throw e.toString(); } 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 = {}; + Map body = { + "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); + responseStatus = data; + } else { + responseStatus.addAll({'success': false}); + } + }catch(e){ + throw e.toString(); + } + return responseStatus; + } } diff --git a/lib/utils/location_utilities.dart b/lib/utils/location_utilities.dart index e52c10b..87fa959 100644 --- a/lib/utils/location_utilities.dart +++ b/lib/utils/location_utilities.dart @@ -70,13 +70,15 @@ class LocationUtils { try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); - Map data = jsonDecode(response.body); + if(response.statusCode == 200){ + Map data = jsonDecode(response.body); if (data['data'] != null) { data['data'].forEach((var province) { Province newProvince = Province.fromJson(province); provinces.add(newProvince); }); } + } } catch (e) { throw (e.toString()); } From 6dd9216af7ef3129e7b3cc76d715a7f3ea048265 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Tue, 19 Sep 2023 11:35:31 +0800 Subject: [PATCH 5/8] assign area using purok --- lib/main.dart | 2 +- lib/model/location/purok.dart | 36 + .../roles/pass_check/purok_assign_area.dart | 6 +- .../assign_area/assign_area_screen.dart | 771 ++++++++++++------ lib/screens/unit2/login/login.dart | 2 +- lib/sevices/roles/pass_check_services.dart | 4 +- lib/utils/location_utilities.dart | 134 +-- lib/utils/urls.dart | 3 + 8 files changed, 669 insertions(+), 289 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index ecec407..d88fa6c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -36,7 +36,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { _appRouter = AppRouter(); final mediaQueryData = - MediaQueryData.fromView(WidgetsBinding.instance.window); + MediaQueryData.fromWindow(WidgetsBinding.instance.window); screenWidth = mediaQueryData.size.width; screenHeight = mediaQueryData.size.height; blockSizeHorizontal = screenWidth / 100; diff --git a/lib/model/location/purok.dart b/lib/model/location/purok.dart index e69de29..d32dbf4 100644 --- a/lib/model/location/purok.dart +++ b/lib/model/location/purok.dart @@ -0,0 +1,36 @@ +// To parse this JSON data, do +// +// final purok = purokFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +import 'package:unit2/model/location/barangay.dart'; + +Purok purokFromJson(String str) => Purok.fromJson(json.decode(str)); + +String purokToJson(Purok data) => json.encode(data.toJson()); + +class Purok { + final String code; + final String description; + final Barangay barangay; + + Purok({ + required this.code, + required this.description, + required this.barangay, + }); + + factory Purok.fromJson(Map json) => Purok( + code: json["code"], + description: json["description"], + barangay: Barangay.fromJson(json["barangay"]), + ); + + Map toJson() => { + "code": code, + "description": description, + "barangay": barangay.toJson(), + }; +} diff --git a/lib/model/roles/pass_check/purok_assign_area.dart b/lib/model/roles/pass_check/purok_assign_area.dart index 883086f..7839854 100644 --- a/lib/model/roles/pass_check/purok_assign_area.dart +++ b/lib/model/roles/pass_check/purok_assign_area.dart @@ -2,7 +2,7 @@ import 'barangay_assign_area.dart'; -class Purok { +class PassCheckPurok { final String? purokid; final String? purokdesc; final BaragayAssignArea? brgy; @@ -10,7 +10,7 @@ class Purok { final bool? writelock; final dynamic recordsignature; - Purok({ + PassCheckPurok({ required this.purokid, required this.purokdesc, required this.brgy, @@ -19,7 +19,7 @@ class Purok { required this.recordsignature, }); - factory Purok.fromJson(Map json) => Purok( + factory PassCheckPurok.fromJson(Map json) => PassCheckPurok( purokid: json["purokid"], purokdesc: json["purokdesc"], brgy: json["brgy"]==null?null:BaragayAssignArea.fromJson(json["brgy"]), diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index 9f210f4..c4a3247 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -16,12 +16,14 @@ import 'package:unit2/bloc/user/user_bloc.dart'; import 'package:unit2/model/location/barangay.dart'; import 'package:unit2/model/location/city.dart'; import 'package:unit2/model/location/provinces.dart'; +import 'package:unit2/model/location/purok.dart'; import 'package:unit2/model/location/region.dart'; import 'package:unit2/model/login_data/user_info/assigned_area.dart'; import 'package:unit2/model/profile/assigned_area.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; import 'package:unit2/model/roles/pass_check/agency_area_type.dart'; +import 'package:unit2/model/roles/pass_check/purok_assign_area.dart'; import 'package:unit2/model/roles/pass_check/station_assign_area.dart'; import 'package:unit2/model/utils/agency.dart'; import 'package:unit2/model/utils/category.dart'; @@ -57,6 +59,7 @@ class _RbacAssignedAreaScreenState extends State { bool provinceAsyncCall = false; bool cityAsyncCall = false; bool barangayAsyncCall = false; + bool purokAsyncCall = false; List userAssignedAreas = []; final bloc = BlocProvider.of(context); int? areaTypeId; @@ -72,6 +75,7 @@ class _RbacAssignedAreaScreenState extends State { List provinces = []; List cities = []; List barangays = []; + List puroks = []; Province? selectedProvince; CityMunicipality? selectedMunicipality; Barangay? selectedBarangay; @@ -119,7 +123,7 @@ class _RbacAssignedAreaScreenState extends State { "health nurse") { try { areaType = "barangay"; - areaTypeId = 1; + areaTypeId = 1; setState(() { provinceAsyncCall = true; }); @@ -152,6 +156,44 @@ class _RbacAssignedAreaScreenState extends State { //// purok } else if (e.name!.toLowerCase() == "purok president") { + try { + areaType = "purok"; + areaTypeId = 2; + setState(() { + provinceAsyncCall = true; + }); + provinces = await LocationUtils + .instance + .getProvinces(regionCode: "16"); + setState(() { + provinceAsyncCall = false; + cityAsyncCall = true; + }); + cities = await LocationUtils.instance + .getCities( + code: provinces[0].code!); + setState(() { + cityAsyncCall = false; + barangayAsyncCall = true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: cities[0].code!); + setState(() { + barangayAsyncCall = false; + purokAsyncCall = true; + }); + puroks = await LocationUtils.instance + .getPurok( + barangay: barangays[0].code!); + setState(() { + purokAsyncCall = false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e.toString())); + } //// station } else if (e.name!.toLowerCase() == "qr code scanner" || e.name!.toLowerCase() == @@ -164,7 +206,7 @@ class _RbacAssignedAreaScreenState extends State { "process server") { try { areaType = "station"; - areaId = "4"; + areaId = "4"; setState(() { agencyAsyncCall = true; }); @@ -185,7 +227,6 @@ class _RbacAssignedAreaScreenState extends State { bloc.add(CallErrorState( message: e.toString())); } - //// agency------------------------------- } else if (e.name!.toLowerCase() == "establishment point-person" || @@ -227,16 +268,13 @@ class _RbacAssignedAreaScreenState extends State { itemHeight: 100, suggestions: agencies .map((Agency agency) => - SearchFieldListItem( - agency.name!, + SearchFieldListItem(agency.name!, item: agency, child: ListTile( - title: - AutoSizeText( + title: AutoSizeText( agency.name! .toUpperCase(), - minFontSize: - 12, + minFontSize: 12, ), subtitle: Text(agency .privateEntity == @@ -248,18 +286,13 @@ class _RbacAssignedAreaScreenState extends State { : ""), ))) .toList(), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), searchInputDecoration: - normalTextFieldStyle( - "Agency *", "") + normalTextFieldStyle("Agency *", "") .copyWith( - suffixIcon: - GestureDetector( - onTap: () => agencyFocusNode - .unfocus(), + suffixIcon: GestureDetector( + onTap: () => agencyFocusNode.unfocus(), child: const Icon( Icons.arrow_drop_down, ), @@ -267,17 +300,16 @@ class _RbacAssignedAreaScreenState extends State { ////agency suggestion tap onSuggestionTap: (agency) { setState(() { - areaId = agency.item!.id - .toString(); + areaId = agency.item!.id.toString(); agencyFocusNode.unfocus(); }); }, - emptyWidget: const Text( - "No Result Found..")) + emptyWidget: + const Text("No Result Found..")) //// station ------------------------------------------------ : areaType == "station" ? SizedBox( - height: 200, + height: 200, child: Flexible( child: Column( children: [ @@ -285,7 +317,8 @@ class _RbacAssignedAreaScreenState extends State { child: SizedBox( height: 100, child: ModalProgressHUD( - inAsyncCall: agencyAsyncCall, + inAsyncCall: + agencyAsyncCall, child: SearchField( controller: agencyController, @@ -295,41 +328,48 @@ class _RbacAssignedAreaScreenState extends State { focusNode: agencyFocusNode, itemHeight: 100, - suggestions: - agencies - .map((Agency agency) => SearchFieldListItem( + suggestions: agencies + .map((Agency + agency) => + SearchFieldListItem( agency .name!, item: agency, child: ListTile( - title: AutoSizeText( - agency.name!.toUpperCase(), - minFontSize: 12, + title: + AutoSizeText( + agency + .name! + .toUpperCase(), + minFontSize: + 12, ), - subtitle: Text(agency.privateEntity == true + subtitle: Text(agency.privateEntity == + true ? "Private" : agency.privateEntity == false ? "Government" : ""), ))) - .toList(), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), - searchInputDecoration: normalTextFieldStyle( - "Agency *", - "") - .copyWith( - suffixIcon: - GestureDetector( + .toList(), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: + normalTextFieldStyle( + "Agency *", + "") + .copyWith( + suffixIcon: + GestureDetector( onTap: () => agencyFocusNode .unfocus(), - child: - const Icon( + child: const Icon( Icons .arrow_drop_down, ), @@ -342,9 +382,8 @@ class _RbacAssignedAreaScreenState extends State { .unfocus(); }); }, - emptyWidget: - const Text( - "No Result Found..")), + emptyWidget: const Text( + "No Result Found..")), ), ), ), @@ -354,39 +393,34 @@ class _RbacAssignedAreaScreenState extends State { Expanded( child: SizedBox( height: 75, - child: - ModalProgressHUD( - color: Colors - .transparent, + child: ModalProgressHUD( + color: Colors.transparent, inAsyncCall: stationAsyncCall, - child: FormBuilderDropdown< - RbacStation>( - decoration: normalTextFieldStyle( - "Station", - "Station"), - name: - "parent-stations", - items: stations - .isEmpty + child: + FormBuilderDropdown< + RbacStation>( + decoration: + normalTextFieldStyle( + "Station", + "Station"), + name: "parent-stations", + items: stations.isEmpty ? [] - : stations - .map( - (e) { + : stations.map((e) { return DropdownMenuItem( - value: - e, - child: - Text(e.stationName!), + value: e, + child: Text(e + .stationName!), ); }).toList(), onChanged: - (RbacStation? - e) {}, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + (RbacStation? e) {}, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), ), ), ), @@ -398,179 +432,460 @@ class _RbacAssignedAreaScreenState extends State { //// barangay ------------------------------------------------------------ : areaType == 'barangay' ? SizedBox( - height: 300, + height: 300, child: Column( - children: [ - //// PROVINCE DROPDOWN - Expanded( - child: SizedBox( - height: 60, - child: - ModalProgressHUD( - color: Colors - .transparent, - inAsyncCall: - provinceAsyncCall, - child: DropdownButtonFormField< - Province?>( - autovalidateMode: - AutovalidateMode - .onUserInteraction, - validator: (value) => value == - null - ? 'required' - : null, - isExpanded: - true, - // value: selectedProvince, + children: [ + //// PROVINCE DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: ModalProgressHUD( + color: + Colors.transparent, + inAsyncCall: + provinceAsyncCall, + child: DropdownButtonFormField< + Province?>( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, + // value: selectedProvince, + onChanged: (Province? + province) async { + setState(() { + selectedProvince = + province; + cityAsyncCall = + true; + }); + cities = await LocationUtils + .instance + .getCities( + code: provinces[ + 0] + .code!); + setState(() { + cityAsyncCall = + false; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: cities[ + 0] + .code!); + setState(() { + barangayAsyncCall = + false; + }); + }, + items: provinces + .isEmpty + ? [] + : provinces.map< + DropdownMenuItem< + Province>>((Province + province) { + return DropdownMenuItem( + value: + province, + child: + FittedBox( + child: + Text(province.description!), + )); + }).toList(), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), + ), + ), + ), + //// CITIES DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: + cityAsyncCall, + child: + DropdownButtonFormField< + CityMunicipality>( + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, onChanged: - (Province? - province) async { - setState( - () { - selectedProvince = - province; - cityAsyncCall = - true; - }); - cities = await LocationUtils - .instance - .getCities(code: provinces[0].code!); - setState( - () { - cityAsyncCall = - false; + (CityMunicipality? + city) async { + setState(() { + selectedMunicipality = + city; barangayAsyncCall = true; }); barangays = await LocationUtils .instance - .getBarangay(code: cities[0].code!); - setState( - () { + .getBarangay( + code: selectedMunicipality! + .code!); + setState(() { barangayAsyncCall = false; }); }, - items: provinces + decoration: + normalTextFieldStyle( + "Municipality*", + "Municipality"), + // value: selectedMunicipality, + items: cities.isEmpty + ? [] + : cities.map< + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { + return DropdownMenuItem( + value: c, + child: Text( + c.description!)); + }).toList(), + ), + ), + ), + ), + ////Barangay + Expanded( + child: SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: + barangayAsyncCall, + child: + DropdownButtonFormField< + Barangay>( + isExpanded: true, + onChanged: (Barangay? + baragay) { + areaId = + baragay!.code; + }, + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), + // value: selectedBarangay, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + items: barangays .isEmpty ? [] - : provinces.map>((Province - province) { + : barangays.map< + DropdownMenuItem< + Barangay>>((Barangay + barangay) { return DropdownMenuItem( - value: province, - child: FittedBox( - child: Text(province.description!), - )); + value: + barangay, + child: Text( + barangay + .description!)); }).toList(), - decoration: normalTextFieldStyle( - "Province*", - "Province")), - ), - ), - ), - //// CITIES DROPDOWN - Expanded( - child: SizedBox( - height: 60, - child: - ModalProgressHUD( - color: Colors - .white, - inAsyncCall: - cityAsyncCall, - child: DropdownButtonFormField< - CityMunicipality>( - validator: FormBuilderValidators.required( - errorText: - "This field is required"), - isExpanded: - true, - onChanged: - (CityMunicipality? - city) async { - setState( - () { - selectedMunicipality = - city; - barangayAsyncCall = - true; - }); - barangays = await LocationUtils - .instance - .getBarangay( - code: selectedMunicipality!.code!); - setState( - () { - barangayAsyncCall = - false; - }); - }, - decoration: normalTextFieldStyle( - "Municipality*", - "Municipality"), - // value: selectedMunicipality, - items: cities - .isEmpty - ? [] - : cities.map< - DropdownMenuItem< - CityMunicipality>>((CityMunicipality - c) { - return DropdownMenuItem( - value: c, - child: Text(c.description!)); - }).toList(), + ), ), ), ), - ), - ////Barangay - Expanded( - child: SizedBox( - height: 60, - child: - ModalProgressHUD( - color: Colors - .white, - inAsyncCall: - barangayAsyncCall, - child: DropdownButtonFormField< - Barangay>( - isExpanded: - true, - onChanged: - (Barangay? - baragay) { - areaId = - baragay! - .code; - }, - decoration: normalTextFieldStyle( - "Barangay*", - "Barangay"), - // value: selectedBarangay, - validator: FormBuilderValidators.required( - errorText: - "This field is required"), - items: barangays - .isEmpty - ? [] - : barangays.map< - DropdownMenuItem< - Barangay>>((Barangay - barangay) { - return DropdownMenuItem( - value: barangay, - child: Text(barangay.description!)); - }).toList(), + ], + )) + : //// Purok ------------------------------------------------------------ + areaType == 'purok' + ? SizedBox( + height: 300, + child: Column( + children: [ + //// PROVINCE DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors + .transparent, + inAsyncCall: + provinceAsyncCall, + child: DropdownButtonFormField< + Province?>( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: + true, + // value: selectedProvince, + onChanged: + (Province? + province) async { + setState(() { + selectedProvince = + province; + cityAsyncCall = + true; + }); + cities = await LocationUtils + .instance + .getCities( + code: + provinces[0].code!); + setState(() { + cityAsyncCall = + false; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: + cities[0].code!); + setState(() { + barangayAsyncCall = + false; + purokAsyncCall = + true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + setState(() { + purokAsyncCall = + false; + }); + }, + items: provinces + .isEmpty + ? [] + : provinces.map< + DropdownMenuItem< + Province>>((Province + province) { + return DropdownMenuItem( + value: + province, + child: + FittedBox( + child: Text(province.description!), + )); + }).toList(), + decoration: normalTextFieldStyle( + "Province*", + "Province")), + ), + ), ), - ), - ), - ), - ], - )) - : Container(), + //// CITIES DROPDOWN + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors.white, + inAsyncCall: + cityAsyncCall, + child: DropdownButtonFormField< + CityMunicipality>( + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, + onChanged: + (CityMunicipality? + city) async { + setState(() { + selectedMunicipality = + city; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality! + .code!); + setState(() { + barangayAsyncCall = + false; + purokAsyncCall = true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + + setState((){ + purokAsyncCall = false; + }); + }, + + decoration: normalTextFieldStyle( + "Municipality*", + "Municipality"), + // value: selectedMunicipality, + items: cities + .isEmpty + ? [] + : cities.map< + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { + return DropdownMenuItem( + value: + c, + child: + Text(c.description!)); + }).toList(), + ), + ), + ), + ), + ////Barangay + Expanded( + + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors.white, + inAsyncCall: + barangayAsyncCall, + child: + DropdownButtonFormField< + Barangay>( + + isExpanded: true, + onChanged: + (Barangay? + baragay)async { + areaId = + baragay! + .code; + + setState((){ + purokAsyncCall= true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + setState((){ + purokAsyncCall = false; + }); + }, + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), + // value: selectedBarangay, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + + + items: barangays + .isEmpty + ? [] + : barangays.map< + DropdownMenuItem< + Barangay>>((Barangay + barangay) { + return DropdownMenuItem( + value: + barangay, + child: + Text(barangay.description!)); + }).toList(), + + + ), + ), + ), + ), + const SizedBox( + height: 12, + ), + ////Purok + Expanded( + child: SizedBox( + height: 60, + child: + ModalProgressHUD( + color: Colors.white, + inAsyncCall: + purokAsyncCall, + child: + DropdownButtonFormField< + Purok>( + isExpanded: true, + onChanged: + (Purok? + purok) { + areaId = + purok!.code; + }, + decoration: + normalTextFieldStyle( + "Purok*", + "Parangay"), + // value: selectedBarangay, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + items: puroks + .isEmpty + ? [] + : puroks.map< + DropdownMenuItem< + Purok>>((Purok + purok) { + return DropdownMenuItem( + value: + purok, + child: + Text(purok.description)); + }).toList(), + ), + ), + ), + ), + ], + )) + : Container(), const SizedBox( height: 25, ), diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index 69c96c2..a9cbcd2 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -109,7 +109,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?.version != state.apkVersion) { return SizedBox( child: SingleChildScrollView( child: Stack( diff --git a/lib/sevices/roles/pass_check_services.dart b/lib/sevices/roles/pass_check_services.dart index 12cd2a2..063118a 100644 --- a/lib/sevices/roles/pass_check_services.dart +++ b/lib/sevices/roles/pass_check_services.dart @@ -116,9 +116,9 @@ class PassCheckServices { } ////PUROK if (assignRoleAreaType.areaTypeName.toLowerCase() == 'purok') { - List assignedArea = []; + List assignedArea = []; data['data'][0]['assigned_area'].forEach((var element) { - Purok purok = Purok.fromJson(element['area']); + PassCheckPurok purok = PassCheckPurok.fromJson(element['area']); assignedArea.add(purok); }); statusResponse = assignedArea; diff --git a/lib/utils/location_utilities.dart b/lib/utils/location_utilities.dart index 87fa959..98f1b4f 100644 --- a/lib/utils/location_utilities.dart +++ b/lib/utils/location_utilities.dart @@ -6,6 +6,7 @@ import 'package:unit2/model/location/city.dart'; import 'package:unit2/model/location/country.dart'; import 'package:http/http.dart' as http; import 'package:unit2/model/location/provinces.dart'; +import 'package:unit2/model/location/purok.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; @@ -23,20 +24,20 @@ class LocationUtils { List countries = []; String path = Url.instance.getCounties(); - try{ - http.Response response = await Request.instance - .getRequest(path: path, param: {}, headers: headers); - if (response.statusCode == 200) { - Map data = jsonDecode(response.body); - if (data['data'] != null) { - data['data'].forEach((var country) { - Country newCOuntry = Country.fromJson(country); - countries.add(newCOuntry); - }); + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var country) { + Country newCOuntry = Country.fromJson(country); + countries.add(newCOuntry); + }); + } } - } - }catch(e){ - throw(e.toString()); + } catch (e) { + throw (e.toString()); } return countries; } @@ -45,20 +46,20 @@ class LocationUtils { List regions = []; String path = Url.instance.getRegions(); - try{ - http.Response response = await Request.instance - .getRequest(path: path, param: {}, headers: headers); - if (response.statusCode == 200) { - Map data = jsonDecode(response.body); - if (data['data'] != null) { - data['data'].forEach((var region) { - Region newRegion = Region.fromJson(region); - regions.add(newRegion); - }); + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var region) { + Region newRegion = Region.fromJson(region); + regions.add(newRegion); + }); + } } - } - }catch(e){ - throw(e.toString()); + } catch (e) { + throw (e.toString()); } return regions; } @@ -70,15 +71,15 @@ class LocationUtils { try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); - if(response.statusCode == 200){ + if (response.statusCode == 200) { Map data = jsonDecode(response.body); - if (data['data'] != null) { - data['data'].forEach((var province) { - Province newProvince = Province.fromJson(province); - provinces.add(newProvince); - }); + if (data['data'] != null) { + data['data'].forEach((var province) { + Province newProvince = Province.fromJson(province); + provinces.add(newProvince); + }); + } } - } } catch (e) { throw (e.toString()); } @@ -91,12 +92,14 @@ class LocationUtils { try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); - Map data = jsonDecode(response.body); - if (data['data'] != null) { - data['data'].forEach((var city) { - CityMunicipality cityMun = CityMunicipality.fromJson(city); - cities.add(cityMun); - }); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var city) { + CityMunicipality cityMun = CityMunicipality.fromJson(city); + cities.add(cityMun); + }); + } } } catch (e) { throw (e.toString()); @@ -104,41 +107,64 @@ class LocationUtils { return cities; } - Future> getBarangay({required String code}) async { + Future> getBarangay({required String code}) async { List barangays = []; String path = Url.instance.getBarangays() + code; try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); - Map data = jsonDecode(response.body); - if (data['data'] != null) { - data['data'].forEach((var city) { - Barangay barangay = Barangay.fromJson(city); - barangays.add(barangay); - }); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var city) { + Barangay barangay = Barangay.fromJson(city); + barangays.add(barangay); + }); + } } } catch (e) { throw (e.toString()); } return barangays; } - Future>getAddressCategory()async{ + + Future> getPurok({required String barangay}) async { + List puroks = []; + String path = Url.instance.getPurok() + barangay; + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var purok) { + Purok newPurok = Purok.fromJson(purok); + puroks.add(newPurok); + }); + } + } + } catch (e) { + throw (e.toString()); + } + return puroks; + } + + Future> getAddressCategory() async { List categories = []; String path = Url.instance.getAddressCategory(); - try{ - http.Response response = await Request.instance.getRequest(path: path,param: {},headers:headers ); + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); Map data = jsonDecode(response.body); - if(data['data'] != null){ - data['data'].forEach((var cat){ + if (data['data'] != null) { + data['data'].forEach((var cat) { categories.add(AddressCategory.fromJson(cat)); }); } categories; return categories; - }catch(e){ + } catch (e) { throw e.toString(); } } - - } diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 3cecbe6..6a88218 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -343,6 +343,9 @@ class Url { String getBarangays() { return "/api/web_app/location/barangay/"; } + String getPurok(){ + return "/api/web_app/location/purok/"; + } String getAddressCategory() { return "/api/jobnet_app/address_categories/"; From 6a42e52d87437035c4815f9bfb98e996e1918a53 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Wed, 20 Sep 2023 09:35:34 +0800 Subject: [PATCH 6/8] assign area barangay area type add response with bloc --- .../assign_area/assign_area_bloc.dart | 82 +++++++++++-- .../assign_area/assign_area_event.dart | 1 + lib/model/location/barangay2.dart | 41 +++++++ lib/model/profile/assigned_area.dart | 2 +- .../assign_area/assign_area_screen.dart | 109 +++++++++--------- 5 files changed, 165 insertions(+), 70 deletions(-) create mode 100644 lib/model/location/barangay2.dart 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 10c7aff..367d466 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 @@ -1,8 +1,10 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; +import 'package:unit2/model/location/barangay.dart'; import 'package:unit2/model/rbac/assigned_role.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart'; +import '../../../../model/location/barangay2.dart'; import '../../../../model/profile/assigned_area.dart'; import '../../../../model/profile/basic_information/primary-information.dart'; import '../../../../sevices/roles/rbac_operations/role_assignment_services.dart'; @@ -41,7 +43,10 @@ class AssignAreaBloc extends Bloc { roles.add(role.role!); } emit(AssignedAreaLoadedState( - userAssignedAreas: userAssignedAreas, fullname: fullname!,roles: roles,userId: id)); + userAssignedAreas: userAssignedAreas, + fullname: fullname!, + roles: roles, + userId: id)); } else { id = 0; emit(UserNotExistError()); @@ -50,22 +55,70 @@ class AssignAreaBloc extends Bloc { emit(AssignAreaErorState(message: e.toString())); } }); - on((event,emit)async{ - try{ - emit(AssignAreaLoadingState()); - Map response = await RbacAssignedAreaServices.instance.add(userId: event.userId, roleId: event.roleId, areaTypeId: event.areaTypeId, areaId: event.areaId); - if(response["success"]){ - emit(AssignAreaAddedState(response: response)); - }else{ - emit(AssignAreaAddedState(response: response)); + on((event, emit) async { + // try { + emit(AssignAreaLoadingState()); + Map response = await RbacAssignedAreaServices.instance + .add( + userId: event.userId, + roleId: event.roleId, + areaTypeId: event.areaTypeId, + areaId: event.areaId); + if (response["success"]) { + UserAssignedArea newAssignArea = userAssignedAreas.firstWhere( + (element) => + element.assignedRole!.role!.id == event.roleId && + element.assignedRole!.user!.id == event.userId); + userAssignedAreas.removeWhere((element) => + element.assignedRole!.role!.id == event.roleId && + element.assignedRole!.user!.id == event.userId); + ////barangay + if (event.areaTypeId == 1) { + List newAreas = []; + for (var area in response['data']) { + for (var assignedArea in area['assigned_area']) { + var newArea = {}; + newArea.addAll({"id": assignedArea['id']}); + newArea.addAll({'isactive': assignedArea['isactive']}); + + Barangay2 newBarangay = Barangay2.fromJson(assignedArea['area']); + + newArea.addAll({ + 'area': { + "brgycode": newBarangay.brgycode, + "brgydesc": newBarangay.brgydesc, + "citymuncode": newBarangay.citymuncode + } + }); + + newAreas.add(newArea); + } + } + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); + //// purok } - }catch(e){ - emit(AssignAreaErorState(message: e.toString())); + if (event.areaTypeId == 2) { + //// station + } + if (event.areaTypeId == 4) { + ////agency + } + if (event.areaTypeId == 3) {} + emit(AssignAreaAddedState(response: response)); + } else { + emit(AssignAreaAddedState(response: response)); } + // } catch (e) { + // emit(AssignAreaErorState(message: e.toString())); + // } }); on((event, emit) async { emit(AssignedAreaLoadedState( - userAssignedAreas: userAssignedAreas, fullname: fullname!,roles: roles,userId: event.userId)); + userAssignedAreas: userAssignedAreas, + fullname: fullname!, + roles: roles, + userId: event.userId)); }); on((event, emit) async { emit(AssignAreaLoadingState()); @@ -73,6 +126,11 @@ class AssignAreaBloc extends Bloc { bool success = await RbacAssignedAreaServices.instance .deleteAssignedArea(areaId: event.areaId); if (success) { + for (var area in userAssignedAreas) { + area.assignedArea.removeWhere((var a) { + return a['id'] == event.areaId; + }); + } emit(AssignedAreaDeletedState(success: success)); } else { emit(AssignedAreaDeletedState(success: success)); diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart index 3c3817d..6cee9b0 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_event.dart @@ -41,6 +41,7 @@ class AddAssignArea extends AssignAreaEvent { final int roleId; final int areaTypeId; final String areaId; + const AddAssignArea( {required this.areaId, required this.areaTypeId, diff --git a/lib/model/location/barangay2.dart b/lib/model/location/barangay2.dart new file mode 100644 index 0000000..76667bf --- /dev/null +++ b/lib/model/location/barangay2.dart @@ -0,0 +1,41 @@ +// To parse this JSON data, do +// +// final barangay = barangayFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +import 'city.dart'; +import 'provinces.dart'; + +Barangay2 barangayFromJson(String str) => Barangay2.fromJson(json.decode(str)); + +String barangayToJson(Barangay2 data) => json.encode(data.toJson()); + +class Barangay2 { + Barangay2({ + required this.brgycode, + required this.brgydesc, + required this.citymuncode, + }); + + final String? brgycode; + final String? brgydesc; + final String? citymuncode; + + factory Barangay2.fromJson(Map json) => Barangay2( + brgycode: json["brgycode"], + brgydesc: json["brgydesc"], + citymuncode: json['citymuncode'] + ); + + Map toJson() => { + "brgycode": brgycode, + "brgydesc": brgydesc, + "citymuncode": citymuncode + }; +} + + + + diff --git a/lib/model/profile/assigned_area.dart b/lib/model/profile/assigned_area.dart index e4424b2..d2d9307 100644 --- a/lib/model/profile/assigned_area.dart +++ b/lib/model/profile/assigned_area.dart @@ -6,7 +6,7 @@ import '../roles/pass_check/assign_role_area_type.dart'; class UserAssignedArea { final AssignedRole? assignedRole; final AssignRoleAreaType? assignedRoleAreaType; - final dynamic assignedArea; + dynamic assignedArea; UserAssignedArea({ required this.assignedRole, diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index c4a3247..0c8699d 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -1,7 +1,5 @@ import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/placeholder.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'; @@ -17,24 +15,15 @@ import 'package:unit2/model/location/barangay.dart'; import 'package:unit2/model/location/city.dart'; import 'package:unit2/model/location/provinces.dart'; import 'package:unit2/model/location/purok.dart'; -import 'package:unit2/model/location/region.dart'; -import 'package:unit2/model/login_data/user_info/assigned_area.dart'; -import 'package:unit2/model/profile/assigned_area.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; -import 'package:unit2/model/roles/pass_check/agency_area_type.dart'; -import 'package:unit2/model/roles/pass_check/purok_assign_area.dart'; -import 'package:unit2/model/roles/pass_check/station_assign_area.dart'; import 'package:unit2/model/utils/agency.dart'; -import 'package:unit2/model/utils/category.dart'; import 'package:unit2/sevices/roles/rbac_operations/station_services.dart'; -import 'package:unit2/test_data.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/utils/formatters.dart'; -import 'package:unit2/utils/global_context.dart'; import 'package:unit2/utils/location_utilities.dart'; import 'package:unit2/utils/profile_utilities.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; @@ -60,7 +49,6 @@ class _RbacAssignedAreaScreenState extends State { bool cityAsyncCall = false; bool barangayAsyncCall = false; bool purokAsyncCall = false; - List userAssignedAreas = []; final bloc = BlocProvider.of(context); int? areaTypeId; int? roleId; @@ -76,9 +64,7 @@ class _RbacAssignedAreaScreenState extends State { List cities = []; List barangays = []; List puroks = []; - Province? selectedProvince; CityMunicipality? selectedMunicipality; - Barangay? selectedBarangay; return Scaffold( appBar: AppBar( backgroundColor: primary, @@ -152,7 +138,7 @@ class _RbacAssignedAreaScreenState extends State { bloc.add(CallErrorState( message: e.toString())); } - ////=========== + //// purok } else if (e.name!.toLowerCase() == "purok president") { @@ -206,7 +192,7 @@ class _RbacAssignedAreaScreenState extends State { "process server") { try { areaType = "station"; - areaId = "4"; + areaTypeId = 4; setState(() { agencyAsyncCall = true; }); @@ -376,10 +362,23 @@ class _RbacAssignedAreaScreenState extends State { )), ////agency suggestion tap onSuggestionTap: - (agency) { + (agency) async { setState(() { - agencyFocusNode - .unfocus(); + stationAsyncCall = + true; + }); + stations = await RbacStationServices + .instance + .getStations( + agencyId: agency + .item! + .id + .toString()); + agencyFocusNode + .unfocus(); + setState(() { + stationAsyncCall = + false; }); }, emptyWidget: const Text( @@ -415,7 +414,9 @@ class _RbacAssignedAreaScreenState extends State { ); }).toList(), onChanged: - (RbacStation? e) {}, + (RbacStation? e) { + areaId = e!.code; + }, validator: FormBuilderValidators .required( @@ -458,8 +459,6 @@ class _RbacAssignedAreaScreenState extends State { onChanged: (Province? province) async { setState(() { - selectedProvince = - province; cityAsyncCall = true; }); @@ -645,8 +644,7 @@ class _RbacAssignedAreaScreenState extends State { (Province? province) async { setState(() { - selectedProvince = - province; + province; cityAsyncCall = true; }); @@ -736,19 +734,21 @@ class _RbacAssignedAreaScreenState extends State { setState(() { barangayAsyncCall = false; - purokAsyncCall = true; + purokAsyncCall = + true; }); - puroks = await LocationUtils - .instance - .getPurok( - barangay: - barangays[0].code!); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); - setState((){ - purokAsyncCall = false; - }); + setState(() { + purokAsyncCall = + false; + }); }, - + decoration: normalTextFieldStyle( "Municipality*", "Municipality"), @@ -773,7 +773,6 @@ class _RbacAssignedAreaScreenState extends State { ), ////Barangay Expanded( - child: SizedBox( height: 60, child: @@ -784,25 +783,25 @@ class _RbacAssignedAreaScreenState extends State { child: DropdownButtonFormField< Barangay>( - isExpanded: true, - onChanged: - (Barangay? - baragay)async { + onChanged: (Barangay? + baragay) async { areaId = baragay! .code; - setState((){ - purokAsyncCall= true; + setState(() { + purokAsyncCall = + true; }); - puroks = await LocationUtils - .instance - .getPurok( - barangay: - barangays[0].code!); - setState((){ - purokAsyncCall = false; + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + setState(() { + purokAsyncCall = + false; }); }, decoration: @@ -815,7 +814,6 @@ class _RbacAssignedAreaScreenState extends State { errorText: "This field is required"), - items: barangays .isEmpty ? [] @@ -829,8 +827,6 @@ class _RbacAssignedAreaScreenState extends State { child: Text(barangay.description!)); }).toList(), - - ), ), ), @@ -838,7 +834,7 @@ class _RbacAssignedAreaScreenState extends State { const SizedBox( height: 12, ), - ////Purok + ////Purok Expanded( child: SizedBox( height: 60, @@ -851,11 +847,10 @@ class _RbacAssignedAreaScreenState extends State { DropdownButtonFormField< Purok>( isExpanded: true, - onChanged: - (Purok? - purok) { + onChanged: (Purok? + purok) { areaId = - purok!.code; + purok!.code; }, decoration: normalTextFieldStyle( @@ -985,7 +980,7 @@ class _RbacAssignedAreaScreenState extends State { assignedAreas = {}; roles = state.roles; userId = state.userId; - userAssignedAreas = state.userAssignedAreas; + if (state.userAssignedAreas.isNotEmpty) { for (var roleMod in state.userAssignedAreas) { assignedAreas.addAll({ From b46022c167fcf1659437d707b370c8c3d5ddf595 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Wed, 20 Sep 2023 14:10:44 +0800 Subject: [PATCH 7/8] role area assignment done. just need testing --- .../assign_area/assign_area_bloc.dart | 113 ++++- lib/model/location/purok2.dart | 39 ++ .../assign_area/assign_area_screen.dart | 447 ++++++++++-------- .../dashboard/superadmin_expanded_menu.dart | 2 +- 4 files changed, 409 insertions(+), 192 deletions(-) create mode 100644 lib/model/location/purok2.dart 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 367d466..455607c 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 @@ -1,8 +1,10 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; -import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/location/purok2.dart'; import 'package:unit2/model/rbac/assigned_role.dart'; import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/model/rbac/rbac_station.dart'; +import 'package:unit2/model/utils/agency.dart'; import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart'; import '../../../../model/location/barangay2.dart'; import '../../../../model/profile/assigned_area.dart'; @@ -99,12 +101,115 @@ class AssignAreaBloc extends Bloc { //// purok } if (event.areaTypeId == 2) { - //// station + List newAreas = []; + for (var area in response['data']) { + for (var assignedArea in area['assigned_area']) { + var newArea = {}; + newArea.addAll({"id": assignedArea['id']}); + newArea.addAll({'isactive': assignedArea['isactive']}); + Purok2 newPurok = Purok2.fromJson(assignedArea['area']); + newArea.addAll({ + 'area': { + "purokid": newPurok.purokid, + "purokdesc": newPurok.purokdesc, + "brgy": { + "brgycode": newPurok.brgy?.brgycode, + "brgydesc": newPurok.brgy?.brgydesc, + "citymuncode": newPurok.brgy?.citymuncode, + }, + "purok_leader": newPurok.purokLeader, + "writelock": newPurok.writelock, + "recordsignature": newPurok.recordsignature + } + }); + newAreas.add(newArea); + } + } + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } + ////statiom if (event.areaTypeId == 4) { - ////agency + List newAreas = []; + for (var area in response['data']) { + for (var assignedArea in area['assigned_area']) { + var newArea = {}; + newArea.addAll({"id": assignedArea['id']}); + newArea.addAll({'isactive': assignedArea['isactive']}); + RbacStation newStation = + RbacStation.fromJson(assignedArea['area']); + newArea.addAll({ + "area": { + "id": newStation.id, + "station_name": newStation.stationName, + "station_type": { + "id": newStation.stationType?.id, + "type_name": newStation.stationType?.typeName, + "color": newStation.stationType?.color, + "order": newStation.stationType?.order, + "is_active": newStation.stationType?.isActive, + "group": null + }, + "hierarchy_order_no": newStation.hierarchyOrderNo, + "head_position": newStation.headPosition, + "government_agency": { + "agencyid": newStation.governmentAgency?.agencycatid, + "agencyname": newStation.governmentAgency?.agencyname, + "agencycatid": newStation.governmentAgency?.agencycatid, + "private_entity": + newStation.governmentAgency?.privateEntity, + "contactinfoid": newStation.governmentAgency?.contactinfoid + }, + "acronym": newStation.acronym, + "parent_station": newStation.parentStation, + "code": newStation.code, + "fullcode": newStation.fullcode, + "child_station_info": newStation.childStationInfo, + "islocation_under_parent": newStation.islocationUnderParent, + "main_parent_station": newStation.mainParentStation, + "description": newStation.description, + "ishospital": newStation.ishospital, + "isactive": newStation.isactive, + "selling_station": newStation.sellingStation + } + }); + newAreas.add(newArea); + } + } + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); + } + ////agency + if (event.areaTypeId == 3) { + List newAreas = []; + for (var area in response['data']) { + for (var assignedArea in area['assigned_area']) { + var newArea = {}; + newArea.addAll({"id": assignedArea['id']}); + newArea.addAll({'isactive': assignedArea['isactive']}); + Agency newAgency = Agency.fromJson(assignedArea['area']); + newArea.addAll({ + "area": { + "id": newAgency.id, + "name": newAgency.name, + "category": { + "id": newAgency.category?.id, + "industry_class": { + "id": newAgency.category?.industryClass?.id, + "name": newAgency.category?.industryClass?.name, + "description": + newAgency.category?.industryClass?.description + } + }, + "private_entity": newAgency.privateEntity, + } + }); + newAreas.add(newArea); + } + } + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } - if (event.areaTypeId == 3) {} emit(AssignAreaAddedState(response: response)); } else { emit(AssignAreaAddedState(response: response)); diff --git a/lib/model/location/purok2.dart b/lib/model/location/purok2.dart new file mode 100644 index 0000000..bac74f1 --- /dev/null +++ b/lib/model/location/purok2.dart @@ -0,0 +1,39 @@ + + +import 'package:unit2/model/location/barangay2.dart'; + +class Purok2 { + final String purokid; + final String purokdesc; + final Barangay2? brgy; + final dynamic purokLeader; + final bool writelock; + final dynamic recordsignature; + + Purok2({ + required this.purokid, + required this.purokdesc, + required this.brgy, + required this.purokLeader, + required this.writelock, + required this.recordsignature, + }); + + factory Purok2.fromJson(Map json) => Purok2( + purokid: json["purokid"], + purokdesc: json["purokdesc"], + brgy: json['brgy'] == null?null: Barangay2.fromJson(json["brgy"]), + purokLeader: json["purok_leader"], + writelock: json["writelock"], + recordsignature: json["recordsignature"], + ); + + Map toJson() => { + "purokid": purokid, + "purokdesc": purokdesc, + "brgy": brgy?.toJson(), + "purok_leader": purokLeader, + "writelock": writelock, + "recordsignature": recordsignature, + }; +} diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index 0c8699d..674b722 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -31,7 +31,11 @@ import 'package:unit2/widgets/empty_data.dart'; import 'package:unit2/widgets/error_state.dart'; class RbacAssignedAreaScreen extends StatefulWidget { - const RbacAssignedAreaScreen({super.key}); + final int id; + final String fname; + final String lname; + const RbacAssignedAreaScreen( + {super.key, required this.fname, required this.id, required this.lname}); @override State createState() => _RbacAssignedAreaScreenState(); @@ -246,63 +250,79 @@ class _RbacAssignedAreaScreenState extends State { height: 12, ), areaType == "agency" - ? SearchField( - inputFormatters: [ - UpperCaseTextFormatter() - ], - focusNode: agencyFocusNode, - itemHeight: 100, - suggestions: agencies - .map((Agency agency) => - SearchFieldListItem(agency.name!, - item: agency, - child: ListTile( - title: AutoSizeText( - agency.name! - .toUpperCase(), - minFontSize: 12, - ), - subtitle: Text(agency - .privateEntity == - true - ? "Private" - : agency.privateEntity == - false - ? "Government" - : ""), - ))) - .toList(), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - searchInputDecoration: - normalTextFieldStyle("Agency *", "") - .copyWith( - suffixIcon: GestureDetector( - onTap: () => agencyFocusNode.unfocus(), - child: const Icon( - Icons.arrow_drop_down, - ), - )), - ////agency suggestion tap - onSuggestionTap: (agency) { - setState(() { - areaId = agency.item!.id.toString(); - agencyFocusNode.unfocus(); - }); - }, - emptyWidget: - const Text("No Result Found..")) + ? SizedBox( + height: 70, + child: ModalProgressHUD( + color: Colors.transparent, + inAsyncCall: agencyAsyncCall, + child: SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + focusNode: agencyFocusNode, + itemHeight: 100, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem( + agency.name!, + item: agency, + child: ListTile( + title: AutoSizeText( + agency.name! + .toUpperCase(), + minFontSize: 12, + ), + subtitle: Text(agency + .privateEntity == + true + ? "Private" + : agency.privateEntity == + false + ? "Government" + : ""), + ))) + .toList(), + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + searchInputDecoration: + normalTextFieldStyle( + "Agency *", "") + .copyWith( + suffixIcon: + GestureDetector( + onTap: () => + agencyFocusNode.unfocus(), + child: const Icon( + Icons.arrow_drop_down, + ), + )), + ////agency suggestion tap + onSuggestionTap: (agency) { + setState(() { + areaId = + agency.item!.id.toString(); + + agencyFocusNode.unfocus(); + }); + }, + emptyWidget: const Text( + "No Result Found..")), + ), + ) //// station ------------------------------------------------ : areaType == "station" ? SizedBox( - height: 200, + height: 140, child: Flexible( child: Column( children: [ Expanded( child: SizedBox( - height: 100, + height: 75, child: ModalProgressHUD( + color: Colors.transparent, inAsyncCall: agencyAsyncCall, child: SearchField( @@ -313,7 +333,7 @@ class _RbacAssignedAreaScreenState extends State { ], focusNode: agencyFocusNode, - itemHeight: 100, + itemHeight: 75, suggestions: agencies .map((Agency agency) => @@ -367,28 +387,34 @@ class _RbacAssignedAreaScreenState extends State { stationAsyncCall = true; }); - stations = await RbacStationServices - .instance - .getStations( - agencyId: agency - .item! - .id - .toString()); - agencyFocusNode - .unfocus(); - setState(() { - stationAsyncCall = - false; - }); + try { + stations = await RbacStationServices + .instance + .getStations( + agencyId: agency + .item! + .id + .toString()); + agencyFocusNode + .unfocus(); + setState(() { + stationAsyncCall = + false; + }); + } catch (e) { + bloc.add( + CallErrorState( + message: e + .toString())); + } }, emptyWidget: const Text( "No Result Found..")), ), ), ), - const SizedBox( - height: 12, - ), + + ///Stations Expanded( child: SizedBox( height: 75, @@ -415,7 +441,8 @@ class _RbacAssignedAreaScreenState extends State { }).toList(), onChanged: (RbacStation? e) { - areaId = e!.code; + areaId = + e!.id.toString(); }, validator: FormBuilderValidators @@ -433,7 +460,7 @@ class _RbacAssignedAreaScreenState extends State { //// barangay ------------------------------------------------------------ : areaType == 'barangay' ? SizedBox( - height: 300, + height: 180, child: Column( children: [ //// PROVINCE DROPDOWN @@ -458,32 +485,36 @@ class _RbacAssignedAreaScreenState extends State { // value: selectedProvince, onChanged: (Province? province) async { - setState(() { - cityAsyncCall = - true; - }); - cities = await LocationUtils - .instance - .getCities( - code: provinces[ - 0] - .code!); - setState(() { - cityAsyncCall = - false; - barangayAsyncCall = - true; - }); - barangays = await LocationUtils - .instance - .getBarangay( - code: cities[ - 0] - .code!); - setState(() { - barangayAsyncCall = - false; - }); + try { + setState(() { + cityAsyncCall = + true; + }); + cities = await LocationUtils + .instance + .getCities( + code: provinces[0] + .code!); + setState(() { + cityAsyncCall = + false; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: cities[0] + .code!); + setState(() { + barangayAsyncCall = + false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e + .toString())); + } }, items: provinces .isEmpty @@ -509,6 +540,7 @@ class _RbacAssignedAreaScreenState extends State { ), ), //// CITIES DROPDOWN + Expanded( child: SizedBox( height: 60, @@ -528,21 +560,28 @@ class _RbacAssignedAreaScreenState extends State { onChanged: (CityMunicipality? city) async { - setState(() { - selectedMunicipality = - city; - barangayAsyncCall = - true; - }); - barangays = await LocationUtils - .instance - .getBarangay( - code: selectedMunicipality! - .code!); - setState(() { - barangayAsyncCall = - false; - }); + try { + setState(() { + selectedMunicipality = + city; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality! + .code!); + setState(() { + barangayAsyncCall = + false; + }); + } catch (e) { + bloc.add( + CallErrorState( + message: e + .toString())); + } }, decoration: normalTextFieldStyle( @@ -566,6 +605,7 @@ class _RbacAssignedAreaScreenState extends State { ), ), ////Barangay + Expanded( child: SizedBox( height: 60, @@ -615,7 +655,7 @@ class _RbacAssignedAreaScreenState extends State { : //// Purok ------------------------------------------------------------ areaType == 'purok' ? SizedBox( - height: 300, + height: 200, child: Column( children: [ //// PROVINCE DROPDOWN @@ -643,42 +683,52 @@ class _RbacAssignedAreaScreenState extends State { onChanged: (Province? province) async { - setState(() { - province; - cityAsyncCall = - true; - }); - cities = await LocationUtils - .instance - .getCities( - code: - provinces[0].code!); - setState(() { - cityAsyncCall = - false; - barangayAsyncCall = - true; - }); - barangays = await LocationUtils - .instance - .getBarangay( - code: - cities[0].code!); - setState(() { - barangayAsyncCall = - false; - purokAsyncCall = - true; - }); - puroks = await LocationUtils - .instance - .getPurok( - barangay: - barangays[0].code!); - setState(() { - purokAsyncCall = - false; - }); + try { + setState( + () { + province; + cityAsyncCall = + true; + }); + cities = await LocationUtils + .instance + .getCities( + code: + provinces[0].code!); + setState( + () { + cityAsyncCall = + false; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: + cities[0].code!); + setState( + () { + barangayAsyncCall = + false; + purokAsyncCall = + true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + setState( + () { + purokAsyncCall = + false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: + e.toString())); + } }, items: provinces .isEmpty @@ -701,6 +751,9 @@ class _RbacAssignedAreaScreenState extends State { ), ), ), + const SizedBox( + height: 12, + ), //// CITIES DROPDOWN Expanded( child: SizedBox( @@ -720,33 +773,39 @@ class _RbacAssignedAreaScreenState extends State { onChanged: (CityMunicipality? city) async { - setState(() { - selectedMunicipality = - city; - barangayAsyncCall = - true; - }); - barangays = await LocationUtils - .instance - .getBarangay( - code: selectedMunicipality! - .code!); - setState(() { - barangayAsyncCall = - false; - purokAsyncCall = - true; - }); - puroks = await LocationUtils - .instance - .getPurok( - barangay: - barangays[0].code!); + try { + setState(() { + selectedMunicipality = + city; + barangayAsyncCall = + true; + }); + barangays = await LocationUtils + .instance + .getBarangay( + code: + selectedMunicipality!.code!); + setState(() { + barangayAsyncCall = + false; + purokAsyncCall = + true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); - setState(() { - purokAsyncCall = - false; - }); + setState(() { + purokAsyncCall = + false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e + .toString())); + } }, decoration: normalTextFieldStyle( @@ -772,6 +831,9 @@ class _RbacAssignedAreaScreenState extends State { ), ), ////Barangay + const SizedBox( + height: 12, + ), Expanded( child: SizedBox( height: 60, @@ -789,20 +851,25 @@ class _RbacAssignedAreaScreenState extends State { areaId = baragay! .code; - - setState(() { - purokAsyncCall = - true; - }); - puroks = await LocationUtils - .instance - .getPurok( - barangay: - barangays[0].code!); - setState(() { - purokAsyncCall = - false; - }); + try { + setState(() { + purokAsyncCall = + true; + }); + puroks = await LocationUtils + .instance + .getPurok( + barangay: + barangays[0].code!); + setState(() { + purokAsyncCall = + false; + }); + } catch (e) { + bloc.add(CallErrorState( + message: e + .toString())); + } }, decoration: normalTextFieldStyle( @@ -1123,7 +1190,13 @@ class _RbacAssignedAreaScreenState extends State { } if (state is AssignAreaErorState) { return SomethingWentWrong( - message: state.message, onpressed: () {}); + message: state.message, + onpressed: () { + context.read().add(GetAssignArea( + firstname: widget.fname, + lastname: widget.lname, + )); + }); } if (state is UserNotExistError) { return const Center( 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 cda98a5..bb638b9 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 @@ -286,7 +286,7 @@ class SuperAdminMenu extends StatelessWidget { lname), ), child: - const RbacAssignedAreaScreen(), + RbacAssignedAreaScreen(lname: lname,fname: fname,id: id,), ); })); } From 106cc71362a854cb5b63c133dc095dbfbc6b0b52 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Fri, 22 Sep 2023 16:07:13 +0800 Subject: [PATCH 8/8] fixed bugs for assigned area --- lib/bloc/profile/profile_bloc.dart | 27 ++--- .../assign_area/assign_area_bloc.dart | 54 +++++++--- lib/model/profile/assigned_area.dart | 4 +- .../primary_information_screen.dart | 1 - lib/screens/profile/profile.dart | 8 +- .../superadmin/agency/agency_screen.dart | 39 ++++---- .../assign_area/assign_area_screen.dart | 4 +- lib/screens/unit2/basic-info/basic-info.dart | 99 ++++++++++--------- .../dashboard/dashboard_icon_generator.dart | 8 +- .../homepage.dart/components/menu-screen.dart | 4 +- lib/screens/unit2/login/login.dart | 3 +- lib/utils/app_router.dart | 2 +- lib/utils/global.dart | 10 +- 13 files changed, 151 insertions(+), 112 deletions(-) diff --git a/lib/bloc/profile/profile_bloc.dart b/lib/bloc/profile/profile_bloc.dart index a3cfc36..6600285 100644 --- a/lib/bloc/profile/profile_bloc.dart +++ b/lib/bloc/profile/profile_bloc.dart @@ -6,6 +6,7 @@ import 'package:unit2/sevices/profile/profile_service.dart'; import '../../model/profile/basic_information/primary-information.dart'; import '../../screens/profile/components/basic_information/profile_other_info.dart'; +import '../../utils/global.dart'; part 'profile_event.dart'; part 'profile_state.dart'; @@ -52,29 +53,24 @@ class ProfileBloc extends Bloc { .getProfile(event.token, event.userID); globalProfileInformation = profileInformation; } - emit(ProfileLoaded(profileInformation: globalProfileInformation!)); } catch (e) { emit(ProfileErrorState(mesage: e.toString())); } }); on((event, emit) { - if(currentProfileInformation != null){ - emit(BasicInformationProfileLoaded( - primaryBasicInformation: currentProfileInformation!)); - }else{ + if (globalCurrentProfile != null) { + emit(BasicInformationProfileLoaded( + primaryBasicInformation: globalCurrentProfile!)); + } else { currentProfileInformation = event.primaryBasicInformation; - emit(BasicInformationProfileLoaded( - primaryBasicInformation: currentProfileInformation!)); + emit(BasicInformationProfileLoaded( + primaryBasicInformation: currentProfileInformation!)); } - - - - }); on((event, emit) { emit(BasicInformationProfileLoaded( - primaryBasicInformation: currentProfileInformation!)); + primaryBasicInformation: globalCurrentProfile!)); }); on((event, emit) async { try { @@ -141,7 +137,12 @@ class ProfileBloc extends Bloc { if (status['success']) { Profile profile = Profile.fromJson(status['data']); currentProfileInformation = profile; - + globalCurrentProfile = profile; + globalFistname = profile.firstName; + globalLastname = profile.lastName; + globalBday = profile.birthdate; + globalSex = profile.sex; + emit(BasicProfileInfoEditedState(response: status)); } emit(BasicProfileInfoEditedState(response: status)); 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 455607c..b302617 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 @@ -1,9 +1,11 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/role_assignment/role_assignment_bloc.dart'; import 'package:unit2/model/location/purok2.dart'; import 'package:unit2/model/rbac/assigned_role.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; +import 'package:unit2/model/roles/pass_check/assign_role_area_type.dart'; import 'package:unit2/model/utils/agency.dart'; import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart'; import '../../../../model/location/barangay2.dart'; @@ -67,13 +69,35 @@ class AssignAreaBloc extends Bloc { areaTypeId: event.areaTypeId, areaId: event.areaId); if (response["success"]) { - UserAssignedArea newAssignArea = userAssignedAreas.firstWhere( - (element) => - element.assignedRole!.role!.id == event.roleId && - element.assignedRole!.user!.id == event.userId); - userAssignedAreas.removeWhere((element) => - element.assignedRole!.role!.id == event.roleId && - element.assignedRole!.user!.id == event.userId); + UserAssignedArea? newAssignArea; + for (var userArea in userAssignedAreas) { + if (userArea.assignedRole?.role?.id == event.roleId && + userArea.assignedRole?.user?.id == event.userId) { + newAssignArea = userArea; + 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 && + element.assignedRole!.user!.id == event.userId); + } + + AssignedRole newAssignedRole = + AssignedRole.fromJson(response['data'][0]['assigned_role']); + AssignRoleAreaType newAssignRoleType = AssignRoleAreaType.fromJson( + response['data'][0]['assigned_role_area_type']); + UserAssignedArea temp = UserAssignedArea( + assignedRole: newAssignedRole, + assignedRoleAreaType: newAssignRoleType, + assignedArea: []); + newAssignArea = temp; + ////barangay if (event.areaTypeId == 1) { List newAreas = []; @@ -96,8 +120,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) { @@ -125,8 +149,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) { @@ -176,8 +200,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) { @@ -207,8 +231,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea); + newAssignArea?.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea!); } emit(AssignAreaAddedState(response: response)); } else { diff --git a/lib/model/profile/assigned_area.dart b/lib/model/profile/assigned_area.dart index d2d9307..88bc82e 100644 --- a/lib/model/profile/assigned_area.dart +++ b/lib/model/profile/assigned_area.dart @@ -4,8 +4,8 @@ import 'package:unit2/model/rbac/rbac.dart'; import '../roles/pass_check/assign_role_area_type.dart'; class UserAssignedArea { - final AssignedRole? assignedRole; - final AssignRoleAreaType? assignedRoleAreaType; + AssignedRole? assignedRole; + AssignRoleAreaType? assignedRoleAreaType; dynamic assignedArea; UserAssignedArea({ diff --git a/lib/screens/profile/components/basic_information/primary_information_screen.dart b/lib/screens/profile/components/basic_information/primary_information_screen.dart index 9816769..15b2fd1 100644 --- a/lib/screens/profile/components/basic_information/primary_information_screen.dart +++ b/lib/screens/profile/components/basic_information/primary_information_screen.dart @@ -67,7 +67,6 @@ class _PrimaryInfoState extends State { child: BlocBuilder( builder: (context, state) { if (state is UserLoggedIn) { - state.userData?.employeeInfo?.profile = profile; return BlocConsumer( listener: (context, state) { if (state is BasicPrimaryInformationLoadingState) { diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index a8cd223..fe9d5a4 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -30,6 +30,7 @@ import 'package:unit2/screens/profile/components/references_screen.dart'; import 'package:unit2/screens/profile/components/work_history_screen.dart'; import 'package:unit2/screens/profile/components/voluntary_works_screen.dart'; import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../bloc/profile/eligibility/eligibility_bloc.dart'; import '../../bloc/profile/family/family_bloc.dart'; @@ -69,7 +70,12 @@ class ProfileInfo extends StatelessWidget { if (state is UserLoggedIn) { profileId = state.userData!.user!.login!.user!.profileId; token = state.userData!.user!.login!.token!; - profile = state.userData!.employeeInfo!.profile!; + if (globalCurrentProfile == null) { + profile = state.userData!.employeeInfo!.profile!; + } else { + profile = globalCurrentProfile!; + } + print(profile.lastName); return BlocConsumer( listener: ( context, diff --git a/lib/screens/superadmin/agency/agency_screen.dart b/lib/screens/superadmin/agency/agency_screen.dart index 0640b76..57c88dc 100644 --- a/lib/screens/superadmin/agency/agency_screen.dart +++ b/lib/screens/superadmin/agency/agency_screen.dart @@ -172,7 +172,6 @@ class RbacAgencyScreen extends StatelessWidget { indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer( listener: (context, state) { - print(state); if (state is AgencyLoadingState) { final progress = ProgressHUD.of(context); progress!.showWithText("Please wait..."); @@ -235,26 +234,25 @@ class RbacAgencyScreen extends StatelessWidget { decoration: box1(), padding: const EdgeInsets.symmetric( horizontal: 12, vertical: 8), - child: Expanded( - child: Row( + child: Row( children: [ - CircleAvatar( - child: Text('${index + 1}'), - ), - const SizedBox( - width: 12, - ), - Flexible( - child: Text(state.agencies[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ), + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Flexible( + child: Text(state.agencies[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), ], - )), + ), ), const SizedBox( height: 5, @@ -266,8 +264,7 @@ class RbacAgencyScreen extends StatelessWidget { return const EmptyData( message: "No Object available. Please click + to add."); } - } - if (state is AgencyErrorState) { + }if (state is AgencyErrorState) { return SomethingWentWrong( message: state.message, onpressed: () { diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index 674b722..c9fcd6d 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -960,11 +960,13 @@ class _RbacAssignedAreaScreenState extends State { onPressed: () { if (formKey.currentState! .saveAndValidate()) { - bloc.add(AddAssignArea( + if(areaId !=null){ + bloc.add(AddAssignArea( areaId: areaId!, areaTypeId: areaTypeId!, roleId: roleId!, userId: userId!)); + } Navigator.pop(context); } }, diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index 85d6213..04d594b 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -46,45 +46,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,14 +137,15 @@ class BuildInformation extends StatelessWidget { @override Widget build(BuildContext context) { DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); - final String firstName = - userData.user!.login!.user!.firstName!.toUpperCase(); - final String lastname = userData.user!.login!.user!.lastName!.toUpperCase(); - final String? middlename = userData.employeeInfo == null - ? '' - : userData.employeeInfo!.profile?.middleName?.toUpperCase(); - final String sex = userData.employeeInfo!.profile!.sex!.toUpperCase(); - final DateTime? bday = userData.employeeInfo!.profile!.birthdate; + globalFistname = globalFistname ?? userData.user!.login!.user!.firstName!.toUpperCase(); + globalLastname =globalLastname ?? userData.user!.login!.user!.lastName!.toUpperCase(); + globalMiddleName = globalMiddleName == null + ? (userData.employeeInfo == null + ? '' + : userData.employeeInfo!.profile?.middleName?.toUpperCase()) + : ''; + globalSex = globalSex ?? userData.employeeInfo!.profile!.sex!.toUpperCase(); + globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate; final uuid = userData.employeeInfo!.uuid; return Container( padding: const EdgeInsets.symmetric(horizontal: 25), @@ -155,7 +156,7 @@ class BuildInformation extends StatelessWidget { height: 25, ), Text( - "$firstName ${middlename ?? ''} $lastname", + "$globalFistname ${globalMiddleName ?? ''} $globalLastname", textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -166,7 +167,7 @@ class BuildInformation extends StatelessWidget { height: 10, ), Text( - "${dteFormat2.format(bday!)} | $sex", + "${dteFormat2.format(globalBday!)} | $sex", style: Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 18), ), diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart index ff8e816..c5662c9 100644 --- a/lib/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart +++ b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart @@ -24,11 +24,15 @@ IconData? iconGenerator({required String name}) { return FontAwesome.box; } else if (name.toLowerCase() == 'permission') { return FontAwesome5.door_open; - } else if (name.toLowerCase() == 'station') { + } else if (name.toLowerCase() == 'permission assignment') { + return Icons.assignment_ind; + } + + else if (name.toLowerCase() == 'station') { return ModernPictograms.home; } else if (name.toLowerCase() == 'purok') { return WebSymbols.list_numbered; - } else if (name.toLowerCase() == 'barangay') { + } else if (name.toLowerCase() == 'baranggay') { return Maki.industrial_building; } else if (name.toLowerCase() == 'role module') { return FontAwesome5.person_booth; diff --git a/lib/screens/unit2/homepage.dart/components/menu-screen.dart b/lib/screens/unit2/homepage.dart/components/menu-screen.dart index 0b712e3..fe13218 100644 --- a/lib/screens/unit2/homepage.dart/components/menu-screen.dart +++ b/lib/screens/unit2/homepage.dart/components/menu-screen.dart @@ -17,9 +17,9 @@ class MenuScreen extends StatefulWidget { class _MenuScreenState extends State { @override Widget build(BuildContext context) { - final String firstName = + final String firstName =globalFistname?? widget.userData!.user!.login!.user!.firstName!.toUpperCase(); - final String lastname = + final String lastname = globalLastname?? widget.userData!.user!.login!.user!.lastName!.toUpperCase(); return Drawer( child: SizedBox( diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index a9cbcd2..d11a2f4 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -22,7 +22,6 @@ import '../../../theme-data.dart/colors.dart'; import '../../../theme-data.dart/form-style.dart'; import '../../../theme-data.dart/btn-style.dart'; import './components/login-via-qr-label.dart'; -import './functions/press-again-to-exit.dart'; class UniT2Login extends StatefulWidget { const UniT2Login({super.key}); @@ -393,7 +392,7 @@ class _UniT2LoginState extends State { }, ); } - return const UniTSplashScreen(); + return Container(); }), ), ), diff --git a/lib/utils/app_router.dart b/lib/utils/app_router.dart index f2c9b3b..163aaf2 100644 --- a/lib/utils/app_router.dart +++ b/lib/utils/app_router.dart @@ -27,7 +27,7 @@ class AppRouter { case '/': BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(GetApkVersion(username: "",password: "")); + .add(GetApkVersion(username: "", password: "")); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); diff --git a/lib/utils/global.dart b/lib/utils/global.dart index 0b427f7..adb63a6 100644 --- a/lib/utils/global.dart +++ b/lib/utils/global.dart @@ -1,5 +1,7 @@ import 'package:hive/hive.dart'; +import '../model/profile/basic_information/primary-information.dart'; + double screenWidth = 0; double screenHeight = 0; double blockSizeHorizontal = 0; @@ -11,8 +13,12 @@ double safeBlockVertical = 0; const xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; const xClientSecret = "unitcYqAN7GGalyz"; - - + String? globalFistname; + String? globalLastname; + String? globalMiddleName; + DateTime? globalBday; + String? globalSex; +Profile? globalCurrentProfile; //// hive boxes Box? CREDENTIALS;