From f73f8a03e176641ab22298838a5b986404ccf0f5 Mon Sep 17 00:00:00 2001 From: PGAN-MIS Date: Fri, 15 Sep 2023 08:03:54 +0800 Subject: [PATCH] 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()); }