diff --git a/lib/bloc/passo/barangay/barangay_bloc.dart b/lib/bloc/passo/barangay/barangay_bloc.dart new file mode 100644 index 0000000..f8ae3e7 --- /dev/null +++ b/lib/bloc/passo/barangay/barangay_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/sevices/passo/barangay.dart'; + +part 'barangay_event.dart'; +part 'barangay_state.dart'; + +class BarangayBloc extends Bloc { + BarangayBloc() : super(BarangayInitial()) { + on((event, emit) async { + emit(BarangayLoading()); + try { + final barangay = await BarangayServices.instance.fetch(event.id); + emit(BarangayLoaded(barangay)); + } catch (e) { + emit(BarangayErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/barangay/barangay_event.dart b/lib/bloc/passo/barangay/barangay_event.dart new file mode 100644 index 0000000..5012e1a --- /dev/null +++ b/lib/bloc/passo/barangay/barangay_event.dart @@ -0,0 +1,17 @@ +part of 'barangay_bloc.dart'; + +abstract class BarangayEvent extends Equatable { + const BarangayEvent(); + + @override + List get props => []; +} + +class LoadBarangay extends BarangayEvent { + final String id; + + const LoadBarangay({required this.id}); + + @override + List get props => [id]; +} diff --git a/lib/bloc/passo/barangay/barangay_state.dart b/lib/bloc/passo/barangay/barangay_state.dart new file mode 100644 index 0000000..bc36c1b --- /dev/null +++ b/lib/bloc/passo/barangay/barangay_state.dart @@ -0,0 +1,28 @@ +part of 'barangay_bloc.dart'; + +abstract class BarangayState extends Equatable { + const BarangayState(); + + @override + List get props => []; +} + +class BarangayInitial extends BarangayState {} + +class BarangayLoading extends BarangayState {} + +class BarangayLoaded extends BarangayState { + BarangayLoaded(this.brgy); + final List brgy; + + @override + List get props => [brgy]; +} + +class BarangayErrorState extends BarangayState { + BarangayErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/additional_item/additional_item_bloc.dart b/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart similarity index 89% rename from lib/bloc/passo/additional_item/additional_item_bloc.dart rename to lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart index ad9c4ca..167c65e 100644 --- a/lib/bloc/passo/additional_item/additional_item_bloc.dart +++ b/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart @@ -27,8 +27,8 @@ class AdditionalItemBloc } }); on((event, emit) async { - http.Response response = (await AdditionalItemsServices.instance - .postAdditionalItems(event.items))!; + http.Response response = + (await AdditionalItemsServices.instance.add(event.items))!; print(response.body); if (response.statusCode == 201) { @@ -43,8 +43,8 @@ class AdditionalItemBloc }); on((event, emit) async { print(event.id); - http.Response response = (await AdditionalItemsServices.instance - .removeAdditionalItems(event.id)); + http.Response response = + (await AdditionalItemsServices.instance.remove(event.id)); print(response.statusCode); if (response.statusCode == 200) { globalAdditionalItems diff --git a/lib/bloc/passo/additional_item/additional_item_event.dart b/lib/bloc/passo/bulding/additional_item/additional_item_event.dart similarity index 100% rename from lib/bloc/passo/additional_item/additional_item_event.dart rename to lib/bloc/passo/bulding/additional_item/additional_item_event.dart diff --git a/lib/bloc/passo/additional_item/additional_item_state.dart b/lib/bloc/passo/bulding/additional_item/additional_item_state.dart similarity index 100% rename from lib/bloc/passo/additional_item/additional_item_state.dart rename to lib/bloc/passo/bulding/additional_item/additional_item_state.dart diff --git a/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart new file mode 100644 index 0000000..7d243c4 --- /dev/null +++ b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart @@ -0,0 +1,63 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/sevices/passo/building/additional_items_services.dart'; +part 'additional_items_edit_event.dart'; +part 'additional_items_edit_state.dart'; + +class AdditionalItemsEditBloc + extends Bloc { + AdditionalItemsEditBloc() : super(AdditionalItemsEditInitial()) { + List globalAdditionalItemsEdit = []; + on((event, emit) async { + if (globalAdditionalItemsEdit.isEmpty) { + emit(AdditionalItemsEditLoading()); + try { + final additionalItems = + await AdditionalItemsServices.instance.fetch(event.id); + + globalAdditionalItemsEdit + .addAll(additionalItems); // Append fetched data + emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit)); + } catch (e) { + emit(AdditionalItemsEditErrorState(e.toString())); + } + } else { + emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit)); + } + }); + + on((event, emit) async { + http.Response response = + (await AdditionalItemsServices.instance.add(event.items))!; + print(response.statusCode); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + AdditionalItems newAdditional = + AdditionalItems.fromJson(jsonResponse['data']); + print(jsonResponse['data']); + globalAdditionalItemsEdit.add(newAdditional); + + emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit)); + } + }); + on((event, emit) async { + emit(ShowAddItemsScreenEdit()); + }); + on((event, emit) async { + print(event.id); + http.Response response = + (await AdditionalItemsServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + globalAdditionalItemsEdit + .removeWhere(((AdditionalItems element) => element.id == event.id)); + emit(AdditionalItemsEditDeletedState(success: true)); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_event.dart b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_event.dart new file mode 100644 index 0000000..8b34fd0 --- /dev/null +++ b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_event.dart @@ -0,0 +1,38 @@ +part of 'additional_items_edit_bloc.dart'; + +abstract class AdditionalItemsEditEvent extends Equatable { + const AdditionalItemsEditEvent(); + + @override + List get props => []; +} + +class LoadAdditionalItemsEdit extends AdditionalItemsEditEvent { + final List items; + final int? id; + + const LoadAdditionalItemsEdit({required this.items, this.id}); + + @override + List get props => [items]; +} + +class AddAdditionalItemsEdit extends AdditionalItemsEditEvent { + final AdditionalItems items; + + const AddAdditionalItemsEdit({required this.items}); + + @override + List get props => [items]; +} + +class ShowAdditionalItemsEdit extends AdditionalItemsEditEvent {} + +class DeleteAdditionalItemsEdit extends AdditionalItemsEditEvent { + final int id; + + const DeleteAdditionalItemsEdit({required this.id}); + + @override + List get props => [id]; +} diff --git a/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_state.dart b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_state.dart new file mode 100644 index 0000000..4016b98 --- /dev/null +++ b/lib/bloc/passo/bulding/additional_items_edit/additional_items_edit_state.dart @@ -0,0 +1,37 @@ +part of 'additional_items_edit_bloc.dart'; + +abstract class AdditionalItemsEditState extends Equatable { + const AdditionalItemsEditState(); + + @override + List get props => []; +} + +class AdditionalItemsEditInitial extends AdditionalItemsEditState {} + +class AdditionalItemsEditLoading extends AdditionalItemsEditState {} + +class AdditionalItemsEditLoaded extends AdditionalItemsEditState { + const AdditionalItemsEditLoaded(this.items); + final List items; + + @override + List get props => [items]; +} + +class AdditionalItemsEditErrorState extends AdditionalItemsEditState { + const AdditionalItemsEditErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class ShowAddItemsScreenEdit extends AdditionalItemsEditState {} + +class AdditionalItemsEditDeletedState extends AdditionalItemsEditState { + final bool success; + const AdditionalItemsEditDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/class_components/class_components_bloc.dart b/lib/bloc/passo/bulding/class_components/class_components_bloc.dart similarity index 89% rename from lib/bloc/passo/class_components/class_components_bloc.dart rename to lib/bloc/passo/bulding/class_components/class_components_bloc.dart index b3d9c52..084c0e3 100644 --- a/lib/bloc/passo/class_components/class_components_bloc.dart +++ b/lib/bloc/passo/bulding/class_components/class_components_bloc.dart @@ -12,7 +12,7 @@ class ClassComponentsBloc on((event, emit) async { emit(ClassComponentLoading()); try { - final classs = await ClassComponentService.instance.getClassComponent(); + final classs = await ClassComponentService.instance.fetch(); emit(ClassComponentLoaded(classs)); } catch (e) { emit(ClassComponentErrorState(e.toString())); diff --git a/lib/bloc/passo/class_components/class_components_event.dart b/lib/bloc/passo/bulding/class_components/class_components_event.dart similarity index 100% rename from lib/bloc/passo/class_components/class_components_event.dart rename to lib/bloc/passo/bulding/class_components/class_components_event.dart diff --git a/lib/bloc/passo/class_components/class_components_state.dart b/lib/bloc/passo/bulding/class_components/class_components_state.dart similarity index 100% rename from lib/bloc/passo/class_components/class_components_state.dart rename to lib/bloc/passo/bulding/class_components/class_components_state.dart diff --git a/lib/bloc/passo/bulding/general_description/general_description_bloc.dart b/lib/bloc/passo/bulding/general_description/general_description_bloc.dart new file mode 100644 index 0000000..0e0b213 --- /dev/null +++ b/lib/bloc/passo/bulding/general_description/general_description_bloc.dart @@ -0,0 +1,23 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/sevices/passo/building/general_description_services.dart'; + +part 'general_description_event.dart'; +part 'general_description_state.dart'; + +class GeneralDescriptionBloc + extends Bloc { + GeneralDescriptionBloc() : super(GenDescLoading()) { + on((event, emit) async { + emit(GenDescLoading()); + try { + final gendesc = + await GeneralDescriptionServices.instance.fetch(event.id); + emit(GenDescLoaded(gendesc)); + } catch (e) { + emit(GenDescErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/general_description/general_description_event.dart b/lib/bloc/passo/bulding/general_description/general_description_event.dart new file mode 100644 index 0000000..91cf288 --- /dev/null +++ b/lib/bloc/passo/bulding/general_description/general_description_event.dart @@ -0,0 +1,27 @@ +part of 'general_description_bloc.dart'; + +abstract class GeneralDescriptionEvent extends Equatable { + const GeneralDescriptionEvent(); + + @override + List get props => []; +} + +class LoadGenDesc extends GeneralDescriptionEvent { + final GeneralDesc gendesc; + final int? id; + + const LoadGenDesc({required this.gendesc, required this.id}); + + @override + List get props => [gendesc]; +} + +class UpdateGenDesc extends GeneralDescriptionEvent { + final GeneralDesc gendesc; + + const UpdateGenDesc(this.gendesc); + + @override + List get props => [gendesc]; +} diff --git a/lib/bloc/passo/bulding/general_description/general_description_state.dart b/lib/bloc/passo/bulding/general_description/general_description_state.dart new file mode 100644 index 0000000..9fb075a --- /dev/null +++ b/lib/bloc/passo/bulding/general_description/general_description_state.dart @@ -0,0 +1,26 @@ +part of 'general_description_bloc.dart'; + +abstract class GeneralDescriptionState extends Equatable { + const GeneralDescriptionState(); + + @override + List get props => []; +} + +class GenDescLoading extends GeneralDescriptionState {} + +class GenDescLoaded extends GeneralDescriptionState { + GenDescLoaded(this.gendesc); + final GeneralDesc gendesc; + + @override + List get props => [gendesc]; +} + +class GenDescErrorState extends GeneralDescriptionState { + GenDescErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/bulding/landref/landref_bloc.dart b/lib/bloc/passo/bulding/landref/landref_bloc.dart new file mode 100644 index 0000000..99fcc1b --- /dev/null +++ b/lib/bloc/passo/bulding/landref/landref_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/sevices/passo/building/landref_services.dart'; + +part 'landref_event.dart'; +part 'landref_state.dart'; + +class LandrefBloc extends Bloc { + LandrefBloc() : super(LandrefLoading()) { + on((event, emit) async { + emit(LandrefLoading()); + try { + final landRef = await LandRefServices.instance.fetch(event.id); + emit(LandrefLoaded(landRef)); + } catch (e) { + emit(LandrefErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/landref/landref_event.dart b/lib/bloc/passo/bulding/landref/landref_event.dart new file mode 100644 index 0000000..aaf2e78 --- /dev/null +++ b/lib/bloc/passo/bulding/landref/landref_event.dart @@ -0,0 +1,27 @@ +part of 'landref_bloc.dart'; + +abstract class LandrefEvent extends Equatable { + const LandrefEvent(); + + @override + List get props => []; +} + +class LoadLandref extends LandrefEvent { + final LandRef landRef; + final int? id; + + const LoadLandref({required this.landRef, required this.id}); + + @override + List get props => [landRef]; +} + +class UpdateLandref extends LandrefEvent { + final LandRef landRef; + + const UpdateLandref(this.landRef); + + @override + List get props => [landRef]; +} diff --git a/lib/bloc/passo/bulding/landref/landref_state.dart b/lib/bloc/passo/bulding/landref/landref_state.dart new file mode 100644 index 0000000..0832733 --- /dev/null +++ b/lib/bloc/passo/bulding/landref/landref_state.dart @@ -0,0 +1,26 @@ +part of 'landref_bloc.dart'; + +abstract class LandrefState extends Equatable { + const LandrefState(); + + @override + List get props => []; +} + +class LandrefLoading extends LandrefState {} + +class LandrefLoaded extends LandrefState { + LandrefLoaded(this.landRef); + final LandRef landRef; + + @override + List get props => [landRef]; +} + +class LandrefErrorState extends LandrefState { + LandrefErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/bulding/location/location_bloc.dart b/lib/bloc/passo/bulding/location/location_bloc.dart new file mode 100644 index 0000000..20aff1b --- /dev/null +++ b/lib/bloc/passo/bulding/location/location_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/sevices/passo/building/location_landref_services.dart'; + +part 'location_event.dart'; +part 'location_state.dart'; + +class LocationBloc extends Bloc { + LocationBloc() : super(LocationLoading()) { + on((event, emit) async { + emit(LocationLoading()); + try { + final bldgloc = await LocationLandrefServices.instance.fetch(event.id); + emit(LocationLoaded(bldgloc)); + } catch (e) { + emit(LocationErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/location/location_event.dart b/lib/bloc/passo/bulding/location/location_event.dart new file mode 100644 index 0000000..008f6db --- /dev/null +++ b/lib/bloc/passo/bulding/location/location_event.dart @@ -0,0 +1,27 @@ +part of 'location_bloc.dart'; + +abstract class LocationEvent extends Equatable { + const LocationEvent(); + + @override + List get props => []; +} + +class LoadLocation extends LocationEvent { + final BldgLoc bldgloc; + final int? id; + + const LoadLocation({required this.bldgloc, required this.id}); + + @override + List get props => [bldgloc]; +} + +class UpdateLocation extends LocationEvent { + final BldgLoc bldgloc; + + const UpdateLocation(this.bldgloc); + + @override + List get props => [bldgloc]; +} diff --git a/lib/bloc/passo/bulding/location/location_state.dart b/lib/bloc/passo/bulding/location/location_state.dart new file mode 100644 index 0000000..8281995 --- /dev/null +++ b/lib/bloc/passo/bulding/location/location_state.dart @@ -0,0 +1,26 @@ +part of 'location_bloc.dart'; + +abstract class LocationState extends Equatable { + const LocationState(); + + @override + List get props => []; +} + +class LocationLoading extends LocationState {} + +class LocationLoaded extends LocationState { + LocationLoaded(this.bldgloc); + final BldgLoc bldgloc; + + @override + List get props => [bldgloc]; +} + +class LocationErrorState extends LocationState { + LocationErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/property_appraisal/property_appraisal_bloc.dart b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart similarity index 79% rename from lib/bloc/passo/property_appraisal/property_appraisal_bloc.dart rename to lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart index 55c2d3d..e7953c2 100644 --- a/lib/bloc/passo/property_appraisal/property_appraisal_bloc.dart +++ b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart @@ -17,10 +17,7 @@ class PropertyAppraisalBloc on((event, emit) async { emit(PropertyAppraisalLoading()); try { - final tempID = await SharedPreferences.getInstance(); - - final appraisal = await PropertyAppraisalServices.instance - .getPropertyAppraisal(tempID.getInt('tempid')); + final appraisal = await PropertyAppraisalServices.instance.fetch(); emit(PropertyAppraisalLoaded(appraisal)); } catch (e) { @@ -28,17 +25,20 @@ class PropertyAppraisalBloc } }); on((event, emit) async { + final tempID = await SharedPreferences.getInstance(); + http.Response response = (await PropertyAppraisalServices.instance - .postPropertyAppraisal(event.appraisal))!; + .update(event.appraisal, tempID.getInt('tempid')! - 1))!; if (response.statusCode == 201) { var jsonResponse = jsonDecode(response.body); PropertyAppraisal newAppraisal = PropertyAppraisal.fromJson(jsonResponse['data']); - print(jsonResponse['data']); - globalPropertyAppraisal.add(newAppraisal); + print("PA"); + print(newAppraisal); + print(response.statusCode); - emit(PropertyAppraisalLoaded(globalPropertyAppraisal)); + emit(PropertyAppraisalLoaded(newAppraisal)); } }); } diff --git a/lib/bloc/passo/property_appraisal/property_appraisal_event.dart b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_event.dart similarity index 80% rename from lib/bloc/passo/property_appraisal/property_appraisal_event.dart rename to lib/bloc/passo/bulding/property_appraisal/property_appraisal_event.dart index c37835d..8eda5e3 100644 --- a/lib/bloc/passo/property_appraisal/property_appraisal_event.dart +++ b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_event.dart @@ -8,9 +8,9 @@ abstract class PropertyAppraisalEvent extends Equatable { } class LoadPropertyAppraisal extends PropertyAppraisalEvent { - final List appraisal; + final PropertyAppraisal appraisal; - const LoadPropertyAppraisal({this.appraisal = const []}); + const LoadPropertyAppraisal({required this.appraisal}); @override List get props => [appraisal]; diff --git a/lib/bloc/passo/property_appraisal/property_appraisal_state.dart b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_state.dart similarity index 93% rename from lib/bloc/passo/property_appraisal/property_appraisal_state.dart rename to lib/bloc/passo/bulding/property_appraisal/property_appraisal_state.dart index a2e3a77..2010d45 100644 --- a/lib/bloc/passo/property_appraisal/property_appraisal_state.dart +++ b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_state.dart @@ -13,7 +13,7 @@ class PropertyAppraisalLoading extends PropertyAppraisalState {} class PropertyAppraisalLoaded extends PropertyAppraisalState { PropertyAppraisalLoaded(this.appraisal); - final List appraisal; + final PropertyAppraisal appraisal; @override List get props => [appraisal]; diff --git a/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart new file mode 100644 index 0000000..33e6443 --- /dev/null +++ b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart @@ -0,0 +1,40 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/property_appraisal_edit.dart'; +import 'package:unit2/sevices/passo/building/property_appraisal_services.dart'; +import 'package:http/http.dart' as http; + +part 'property_appraisal_edit_event.dart'; +part 'property_appraisal_edit_state.dart'; + +class PropertyAppraisalEditBloc + extends Bloc { + PropertyAppraisalEditBloc() : super(PropertyAppraisalEditLoading()) { + on((event, emit) async { + emit(PropertyAppraisalEditLoading()); + try { + final appraisalEdit = + await PropertyAppraisalServices.instance.fetchEdit(event.id); + emit(PropertyAppraisalEditLoaded(appraisalEdit)); + } catch (e) { + emit(PropertyAppraisalEditErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = (await PropertyAppraisalServices.instance + .updateAppraisal(event.appraisalEdit!, event.id))!; + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + PropertyAppraisalEdit newAppraisal = + PropertyAppraisalEdit.fromJson(jsonResponse['data']); + print(response.statusCode); + emit(PropertyAppraisalEditLoaded(newAppraisal)); + + // emit(PropertyAppraisalLoaded(globalPropertyAppraisal)); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_event.dart b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_event.dart new file mode 100644 index 0000000..c1b5d75 --- /dev/null +++ b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_event.dart @@ -0,0 +1,28 @@ +part of 'property_appraisal_edit_bloc.dart'; + +abstract class PropertyAppraisalEditEvent extends Equatable { + const PropertyAppraisalEditEvent(); + + @override + List get props => []; +} + +class LoadPropertyAppraisalEdit extends PropertyAppraisalEditEvent { + final PropertyAppraisalEdit appraisalEdit; + final int? id; + + const LoadPropertyAppraisalEdit( + {required this.appraisalEdit, required this.id}); + + @override + List get props => [appraisalEdit]; +} + +class UpdatePropertyAppraisalEdit extends PropertyAppraisalEditEvent { + final PropertyAppraisalEdit? appraisalEdit; + final int? id; + const UpdatePropertyAppraisalEdit({this.appraisalEdit, required this.id}); + + @override + List get props => [appraisalEdit!]; +} diff --git a/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_state.dart b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_state.dart new file mode 100644 index 0000000..c6b812e --- /dev/null +++ b/lib/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_state.dart @@ -0,0 +1,26 @@ +part of 'property_appraisal_edit_bloc.dart'; + +abstract class PropertyAppraisalEditState extends Equatable { + const PropertyAppraisalEditState(); + + @override + List get props => []; +} + +class PropertyAppraisalEditLoading extends PropertyAppraisalEditState {} + +class PropertyAppraisalEditLoaded extends PropertyAppraisalEditState { + PropertyAppraisalEditLoaded(this.appraisalEdit); + final PropertyAppraisalEdit appraisalEdit; + + @override + List get props => [appraisalEdit]; +} + +class PropertyAppraisalEditErrorState extends PropertyAppraisalEditState { + PropertyAppraisalEditErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/property_assessment/property_assessment_bloc.dart b/lib/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart similarity index 88% rename from lib/bloc/passo/property_assessment/property_assessment_bloc.dart rename to lib/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart index ee73086..9bf078b 100644 --- a/lib/bloc/passo/property_assessment/property_assessment_bloc.dart +++ b/lib/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart @@ -20,7 +20,7 @@ class PropertyAssessmentBloc final tempID = await SharedPreferences.getInstance(); final assessments = await PropertyAssessmentServices.instance - .getPropertyAssessment(tempID.getInt('tempid')! + 1); + .fetch(tempID.getInt('tempid')! + 1); emit(PropertyAssessmentLoaded(assessments)); } catch (e) { @@ -28,8 +28,8 @@ class PropertyAssessmentBloc } }); on((event, emit) async { - http.Response response = (await PropertyAssessmentServices.instance - .postPropertyAssessment(event.assessments))!; + http.Response response = + (await PropertyAssessmentServices.instance.add(event.assessments))!; print('Assessment'); print(response.statusCode); print(response.body); @@ -47,7 +47,7 @@ class PropertyAssessmentBloc final tempID = await SharedPreferences.getInstance(); final tempID2 = tempID.getInt('tempid')! - 1; http.Response response = (await PropertyAssessmentServices.instance - .propertyAssessmentPutInfo(event.assessment, tempID2))!; + .update(event.assessment, tempID2))!; print('assessment'); print(response.statusCode); print(response.body); diff --git a/lib/bloc/passo/property_assessment/property_assessment_event.dart b/lib/bloc/passo/bulding/property_assessment/property_assessment_event.dart similarity index 100% rename from lib/bloc/passo/property_assessment/property_assessment_event.dart rename to lib/bloc/passo/bulding/property_assessment/property_assessment_event.dart diff --git a/lib/bloc/passo/property_assessment/property_assessment_state.dart b/lib/bloc/passo/bulding/property_assessment/property_assessment_state.dart similarity index 100% rename from lib/bloc/passo/property_assessment/property_assessment_state.dart rename to lib/bloc/passo/bulding/property_assessment/property_assessment_state.dart diff --git a/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart new file mode 100644 index 0000000..517d0fb --- /dev/null +++ b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart @@ -0,0 +1,61 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/sevices/passo/building/property_assessment_services.dart'; +part 'property_assessment_edit_event.dart'; +part 'property_assessment_edit_state.dart'; + +class PropertyAssessmentEditBloc + extends Bloc { + PropertyAssessmentEdit globalPropertyAssessmentEdit; + PropertyAssessmentEditBloc() + : globalPropertyAssessmentEdit = PropertyAssessmentEdit(), + super(PropertyAssessmentEditInitial()) { + on((event, emit) async { + emit(PropertyAssessmentEditLoading()); + try { + final tempID = await SharedPreferences.getInstance(); + + final assessments = + await PropertyAssessmentServices.instance.fetchEdit(event.id); + + emit(PropertyAssessmentEditLoaded(assessments)); + } catch (e) { + emit(PropertyAssessmentEditErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = (await PropertyAssessmentServices.instance + .addEdit(event.assessmentsEdit))!; + print('Assessment'); + print(response.statusCode); + print(response.body); + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + PropertyAssessmentEdit newAssessment = + PropertyAssessmentEdit.fromJson(jsonResponse['data']); + + globalPropertyAssessmentEdit = newAssessment; + + emit(PropertyAssessmentEditLoaded(globalPropertyAssessmentEdit)); + } + }); + on((event, emit) async { + final tempID = await SharedPreferences.getInstance(); + final tempID2 = tempID.getInt('tempid')! - 1; + http.Response response = (await PropertyAssessmentServices.instance + .updateEdit(event.assessmentsEdit, tempID2))!; + print('assessment'); + print(response.statusCode); + print(response.body); + // if (response.statusCode == 201) { + // final faas = await PropertyInfoRepository.getUsers(); + // emit(FaasLoaded(faas)); + // } + }); + } +} diff --git a/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_event.dart b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_event.dart new file mode 100644 index 0000000..4d478f4 --- /dev/null +++ b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_event.dart @@ -0,0 +1,39 @@ +part of 'property_assessment_edit_bloc.dart'; + +abstract class PropertyAssessmentEditEvent extends Equatable { + const PropertyAssessmentEditEvent(); + + @override + List get props => []; +} + +class LoadPropertyAssessmentEdit extends PropertyAssessmentEditEvent { + final PropertyAssessmentEdit assessmentsEdit; + final int? id; + + const LoadPropertyAssessmentEdit( + {required this.assessmentsEdit, required this.id}); + + @override + List get props => [assessmentsEdit]; +} + +class AddPropertyAssessmentEdit extends PropertyAssessmentEditEvent { + final PropertyAssessmentEdit assessmentsEdit; + + const AddPropertyAssessmentEdit({required this.assessmentsEdit}); + + @override + List get props => [assessmentsEdit]; +} + +class UpdatePropertyAssessmentEdit extends PropertyAssessmentEditEvent { + // ignore: non_constant_identifier_names + final PropertyAssessmentEdit assessmentsEdit; + + // ignore: non_constant_identifier_names + const UpdatePropertyAssessmentEdit({required this.assessmentsEdit}); + + @override + List get props => [assessmentsEdit]; +} diff --git a/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_state.dart b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_state.dart new file mode 100644 index 0000000..70d41a8 --- /dev/null +++ b/lib/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_state.dart @@ -0,0 +1,28 @@ +part of 'property_assessment_edit_bloc.dart'; + +abstract class PropertyAssessmentEditState extends Equatable { + const PropertyAssessmentEditState(); + + @override + List get props => []; +} + +class PropertyAssessmentEditInitial extends PropertyAssessmentEditState {} + +class PropertyAssessmentEditLoading extends PropertyAssessmentEditState {} + +class PropertyAssessmentEditLoaded extends PropertyAssessmentEditState { + PropertyAssessmentEditLoaded(this.assessmentsEdit); + final PropertyAssessmentEdit assessmentsEdit; + + @override + List get props => [assessmentsEdit]; +} + +class PropertyAssessmentEditErrorState extends PropertyAssessmentEditState { + PropertyAssessmentEditErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/bulding/property_info/property_info_bloc.dart b/lib/bloc/passo/bulding/property_info/property_info_bloc.dart new file mode 100644 index 0000000..37a75b9 --- /dev/null +++ b/lib/bloc/passo/bulding/property_info/property_info_bloc.dart @@ -0,0 +1,112 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/sevices/passo/building/general_description_services.dart'; +import 'package:unit2/sevices/passo/building/property_info_services.dart'; +import 'package:http/http.dart' as http; + +import 'package:unit2/sevices/passo/building/structural_material_services.dart'; + +part 'property_info_event.dart'; +part 'property_info_state.dart'; + +class PropertyInfoBloc extends Bloc { + PropertyInfoBloc() : super(PropertyInfoLoading()) { + on((event, emit) async { + emit(PropertyInfoLoading()); + try { + final property_info = await PropertyInfoService.instance.fetch(); + emit(PropertyInfoLoaded(property_info)); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + }); + on((event, emit) async { + final state = this.state; + try { + http.Response response = + (await PropertyInfoService.instance.add(event.property_info))!; + print(response.body); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + final tempID = await SharedPreferences.getInstance(); + print(jsonResponse['data']); + await tempID.setInt('tempid', jsonResponse['data']['id'] + 1); + final faas = await PropertyInfoService.instance.fetch(); + emit(PropertyInfoLoaded(faas)); + } + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + }); + on(((event, emit) async { + final state = this.state; + try { + http.Response response = (await PropertyInfoService.instance + .update(event.property_info, event.property_info.id))!; + print('property_info'); + print(response.body); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + })); + on(((event, emit) async { + final state = this.state; + try { + http.Response response = (await PropertyInfoService.instance + .updateBldg(event.bldg_loc, event.bldg_loc.id))!; + print('bldgLoc'); + print(response.statusCode); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + })); + on( + (event, emit) async { + final state = this.state; + try { + http.Response response = (await PropertyInfoService.instance + .updateLandRef(event.land_ref, event.land_ref.id))!; + print('landref'); + print(response.body); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + }, + ); + + on((event, emit) async { + final state = this.state; + try { + http.Response response = (await PropertyInfoService.instance + .updateGenDesc(event.gen_desc, event.gen_desc.id))!; + print('genDesc'); + print(response.body); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + }); + + on((event, emit) async { + final state = this.state; + try { + final tempID = await SharedPreferences.getInstance(); + print(tempID.getInt('tempid')! - 1); + http.Response response = (await StrucMaterialServices.instance + .update(event.data, event.data.id))!; + print('struc Material'); + print(response.body); + } catch (e) { + emit(PropertyInfoErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/property_info/property_info_event.dart b/lib/bloc/passo/bulding/property_info/property_info_event.dart similarity index 60% rename from lib/bloc/passo/property_info/property_info_event.dart rename to lib/bloc/passo/bulding/property_info/property_info_event.dart index 4356438..0b678c8 100644 --- a/lib/bloc/passo/property_info/property_info_event.dart +++ b/lib/bloc/passo/bulding/property_info/property_info_event.dart @@ -25,6 +25,17 @@ class AddPropertyInfo extends PropertyInfoEvent { List get props => [property_info]; } +class UpdatPropertyInfo extends PropertyInfoEvent { + // ignore: non_constant_identifier_names + final PropertyInfo property_info; + + // ignore: non_constant_identifier_names + const UpdatPropertyInfo({required this.property_info}); + + @override + List get props => [property_info]; +} + class UpdateBldgLoc extends PropertyInfoEvent { // ignore: non_constant_identifier_names final BldgLoc bldg_loc; @@ -45,11 +56,20 @@ class UpdateLandRef extends PropertyInfoEvent { List get props => [land_ref]; } -// class UpdateGeneralDesc extends PropertyInfoEvent { -// final GeneralDesc gen_desc; +class UpdateGeneralDesc extends PropertyInfoEvent { + final GeneralDesc gen_desc; -// const UpdateGeneralDesc({required this.gen_desc}); + const UpdateGeneralDesc({required this.gen_desc}); -// @override -// List get props => [gen_desc]; -// } \ No newline at end of file + @override + List get props => [gen_desc]; +} + +class UpdateStrucMaterials extends PropertyInfoEvent { + final StructureMaterialsII data; + + const UpdateStrucMaterials({required this.data}); + + @override + List get props => [data]; +} diff --git a/lib/bloc/passo/property_info/property_info_state.dart b/lib/bloc/passo/bulding/property_info/property_info_state.dart similarity index 100% rename from lib/bloc/passo/property_info/property_info_state.dart rename to lib/bloc/passo/bulding/property_info/property_info_state.dart diff --git a/lib/bloc/passo/bulding/structural_material/structural_material_bloc.dart b/lib/bloc/passo/bulding/structural_material/structural_material_bloc.dart new file mode 100644 index 0000000..4d58461 --- /dev/null +++ b/lib/bloc/passo/bulding/structural_material/structural_material_bloc.dart @@ -0,0 +1,23 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/model/passo/structureMaterial.dart'; +import 'package:unit2/sevices/passo/building/structural_material_services.dart'; + +part 'structural_material_event.dart'; +part 'structural_material_state.dart'; + +class StructuralMaterialBloc + extends Bloc { + StructuralMaterialBloc() : super(StructuralMaterialInitial()) { + on((event, emit) async { + emit(StructuralMaterialsLoading()); + try { + final structure = await StrucMaterialServices.instance.fetch(event.id); + emit(StructuralMaterialsLoaded(structure)); + } catch (e) { + emit(StructuralMaterialsErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/bulding/structural_material/structural_material_event.dart b/lib/bloc/passo/bulding/structural_material/structural_material_event.dart new file mode 100644 index 0000000..f54301a --- /dev/null +++ b/lib/bloc/passo/bulding/structural_material/structural_material_event.dart @@ -0,0 +1,18 @@ +part of 'structural_material_bloc.dart'; + +class StructuralMaterialEvent extends Equatable { + const StructuralMaterialEvent(); + + @override + List get props => []; +} + +class LoadStructuralMaterial extends StructuralMaterialEvent { + final StructureMaterials structure; + final int? id; + + const LoadStructuralMaterial({required this.structure, required this.id}); + + @override + List get props => [structure]; +} diff --git a/lib/bloc/passo/bulding/structural_material/structural_material_state.dart b/lib/bloc/passo/bulding/structural_material/structural_material_state.dart new file mode 100644 index 0000000..b5c0609 --- /dev/null +++ b/lib/bloc/passo/bulding/structural_material/structural_material_state.dart @@ -0,0 +1,28 @@ +part of 'structural_material_bloc.dart'; + +class StructuralMaterialState extends Equatable { + const StructuralMaterialState(); + + @override + List get props => []; +} + +class StructuralMaterialInitial extends StructuralMaterialState {} + +class StructuralMaterialsLoading extends StructuralMaterialState {} + +class StructuralMaterialsLoaded extends StructuralMaterialState { + const StructuralMaterialsLoaded(this.structure); + final StructureMaterials structure; + + @override + List get props => [structure]; +} + +class StructuralMaterialsErrorState extends StructuralMaterialState { + const StructuralMaterialsErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/unit_construct/unit_construct_bloc.dart b/lib/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart similarity index 89% rename from lib/bloc/passo/unit_construct/unit_construct_bloc.dart rename to lib/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart index 8112eb3..02f0650 100644 --- a/lib/bloc/passo/unit_construct/unit_construct_bloc.dart +++ b/lib/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart @@ -11,7 +11,7 @@ class UnitConstructBloc extends Bloc { on((event, emit) async { emit(UnitConstructLoading()); try { - final unit = await UnitConstructService.instance.getUnitConstruct(); + final unit = await UnitConstructService.instance.fetch(); emit(UnitConstructLoaded(unit)); } catch (e) { emit(UnitConstructErrorState(e.toString())); diff --git a/lib/bloc/passo/unit_construct/unit_construct_event.dart b/lib/bloc/passo/bulding/unit_construct/unit_construct_event.dart similarity index 100% rename from lib/bloc/passo/unit_construct/unit_construct_event.dart rename to lib/bloc/passo/bulding/unit_construct/unit_construct_event.dart diff --git a/lib/bloc/passo/unit_construct/unit_construct_state.dart b/lib/bloc/passo/bulding/unit_construct/unit_construct_state.dart similarity index 100% rename from lib/bloc/passo/unit_construct/unit_construct_state.dart rename to lib/bloc/passo/bulding/unit_construct/unit_construct_state.dart diff --git a/lib/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart b/lib/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart new file mode 100644 index 0000000..b542dbf --- /dev/null +++ b/lib/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart @@ -0,0 +1,60 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/sevices/passo/land/land_appraisal.dart'; +part 'land_appraisal_event.dart'; +part 'land_appraisal_state.dart'; + +class LandAppraisalBloc extends Bloc { + LandAppraisalBloc() : super(LandAppraisalLoading()) { + List globalLandAppraisal = []; + on((event, emit) async { + emit(LandAppraisalLoading()); + try { + final tempID = await SharedPreferences.getInstance(); + print(tempID.getInt('landid')); + final additionalItems = + await LandAppraisalServices.instance.fetch(tempID.getInt('tempid')); + + globalLandAppraisal + .addAll(additionalItems); // Append all items to the list + emit(LandAppraisalLoaded(globalLandAppraisal)); + } catch (e) { + emit(LandAppraisalErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = + (await LandAppraisalServices.instance.add(event.land_appr))!; + print(response.body); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + LandAppr newAdditional = LandAppr.fromJson(jsonResponse['data']); + print(jsonResponse['data']); + globalLandAppraisal.add(newAdditional); + + emit(LandAppraisalLoaded(globalLandAppraisal)); + } + }); + on((event, emit) async { + print(event.id); + http.Response response = + (await LandAppraisalServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + globalLandAppraisal + .removeWhere(((LandAppr element) => element.id == event.id)); + emit(LandAppraisalDeletedState(success: true)); + } + }); + + on((event, emit) async { + emit(ShowAddLandAppraisalScreen()); + }); + } +} diff --git a/lib/bloc/passo/land/land_appraisal/land_appraisal_event.dart b/lib/bloc/passo/land/land_appraisal/land_appraisal_event.dart new file mode 100644 index 0000000..50c1007 --- /dev/null +++ b/lib/bloc/passo/land/land_appraisal/land_appraisal_event.dart @@ -0,0 +1,37 @@ +part of 'land_appraisal_bloc.dart'; + +class LandAppraisalEvent extends Equatable { + const LandAppraisalEvent(); + + @override + List get props => []; +} + +class LoadLandAppraisal extends LandAppraisalEvent { + final List land_appr; + + const LoadLandAppraisal({this.land_appr = const []}); + + @override + List get props => [land_appr]; +} + +class AddLandAppraisal extends LandAppraisalEvent { + final LandAppr land_appr; + + const AddLandAppraisal({required this.land_appr}); + + @override + List get props => [land_appr]; +} + +class DeleteLandAppraisal extends LandAppraisalEvent { + final int id; + + const DeleteLandAppraisal({required this.id}); + + @override + List get props => [id]; +} + +class ShowLandAppraisal extends LandAppraisalEvent {} diff --git a/lib/bloc/passo/land/land_appraisal/land_appraisal_state.dart b/lib/bloc/passo/land/land_appraisal/land_appraisal_state.dart new file mode 100644 index 0000000..d037ad6 --- /dev/null +++ b/lib/bloc/passo/land/land_appraisal/land_appraisal_state.dart @@ -0,0 +1,35 @@ +part of 'land_appraisal_bloc.dart'; + +class LandAppraisalState extends Equatable { + const LandAppraisalState(); + + @override + List get props => []; +} + +class LandAppraisalLoading extends LandAppraisalState {} + +class LandAppraisalLoaded extends LandAppraisalState { + const LandAppraisalLoaded(this.land_appr); + final List land_appr; + + @override + List get props => [land_appr]; +} + +class ShowAddLandAppraisalScreen extends LandAppraisalState {} + +class LandAppraisalErrorState extends LandAppraisalState { + const LandAppraisalErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class LandAppraisalDeletedState extends LandAppraisalState { + final bool success; + const LandAppraisalDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/land/land_classification/land_classification_bloc.dart b/lib/bloc/passo/land/land_classification/land_classification_bloc.dart new file mode 100644 index 0000000..cdecd0f --- /dev/null +++ b/lib/bloc/passo/land/land_classification/land_classification_bloc.dart @@ -0,0 +1,22 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:unit2/sevices/passo/land/land_classification.dart'; + +part 'land_classification_event.dart'; +part 'land_classification_state.dart'; + +class LandClassificationBloc + extends Bloc { + LandClassificationBloc() : super(LandClassificationLoading()) { + on((event, emit) async { + emit(LandClassificationLoading()); + try { + final classs = await LandClassificationService.instance.fetch(); + emit(LandClassificationLoaded(classs)); + } catch (e) { + emit(LandClassificationErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/land/land_classification/land_classification_event.dart b/lib/bloc/passo/land/land_classification/land_classification_event.dart new file mode 100644 index 0000000..d0cea3e --- /dev/null +++ b/lib/bloc/passo/land/land_classification/land_classification_event.dart @@ -0,0 +1,18 @@ +part of 'land_classification_bloc.dart'; + +class LandClassificationEvent extends Equatable { + const LandClassificationEvent(); + + @override + List get props => []; +} + +class LoadLandClassification extends LandClassificationEvent { + final List land_classification; + + const LoadLandClassification( + {this.land_classification = const []}); + + @override + List get props => [land_classification]; +} diff --git a/lib/bloc/passo/land/land_classification/land_classification_state.dart b/lib/bloc/passo/land/land_classification/land_classification_state.dart new file mode 100644 index 0000000..eeef362 --- /dev/null +++ b/lib/bloc/passo/land/land_classification/land_classification_state.dart @@ -0,0 +1,26 @@ +part of 'land_classification_bloc.dart'; + +class LandClassificationState extends Equatable { + const LandClassificationState(); + + @override + List get props => []; +} + +class LandClassificationLoading extends LandClassificationState {} + +class LandClassificationLoaded extends LandClassificationState { + LandClassificationLoaded(this.land_classification); + final List land_classification; + + @override + List get props => [land_classification]; +} + +class LandClassificationErrorState extends LandClassificationState { + LandClassificationErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/land_ext/land_ext_bloc.dart b/lib/bloc/passo/land/land_ext/land_ext_bloc.dart new file mode 100644 index 0000000..7fa7292 --- /dev/null +++ b/lib/bloc/passo/land/land_ext/land_ext_bloc.dart @@ -0,0 +1,57 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/land_ext.dart'; +import 'package:unit2/sevices/passo/land/land_ext.dart'; +import 'package:http/http.dart' as http; +part 'land_ext_event.dart'; +part 'land_ext_state.dart'; + +class LandExtBloc extends Bloc { + LandExtBloc() : super(LandExtInitial()) { + List globalLandExt = []; + on((event, emit) async { + emit(LandExtLoading()); + try { + final tempID = await SharedPreferences.getInstance(); + + final assessments = + await LandExtServices.instance.fetch(tempID.getInt('tempid')! + 1); + + emit(LandExtLoaded(assessments)); + } catch (e) { + emit(LandExtErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = + (await LandExtServices.instance.add(event.landext))!; + print('landext'); + print(response.statusCode); + print(response.body); + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + LandExt newAssessment = LandExt.fromJson(jsonResponse['data']); + + globalLandExt.add(newAssessment); + + emit(LandExtLoaded(globalLandExt)); + } + }); + on((event, emit) async { + final tempID = await SharedPreferences.getInstance(); + final tempID2 = tempID.getInt('tempid')! - 1; + http.Response response = + (await LandExtServices.instance.update(event.landext, tempID2))!; + print('landext'); + print(response.statusCode); + print(response.body); + // if (response.statusCode == 201) { + // final faas = await PropertyInfoRepository.getUsers(); + // emit(FaasLoaded(faas)); + // } + }); + } +} diff --git a/lib/bloc/passo/land/land_ext/land_ext_event.dart b/lib/bloc/passo/land/land_ext/land_ext_event.dart new file mode 100644 index 0000000..8aef275 --- /dev/null +++ b/lib/bloc/passo/land/land_ext/land_ext_event.dart @@ -0,0 +1,37 @@ +part of 'land_ext_bloc.dart'; + +class LandExtEvent extends Equatable { + const LandExtEvent(); + + @override + List get props => []; +} + +class LoadLandExt extends LandExtEvent { + final List landext; + + const LoadLandExt({this.landext = const []}); + + @override + List get props => [landext]; +} + +class AddLandExt extends LandExtEvent { + final LandExt landext; + + const AddLandExt({required this.landext}); + + @override + List get props => [landext]; +} + +class UpdateLandExt extends LandExtEvent { + // ignore: non_constant_identifier_names + final LandExt landext; + + // ignore: non_constant_identifier_names + const UpdateLandExt({required this.landext}); + + @override + List get props => [landext]; +} diff --git a/lib/bloc/passo/land/land_ext/land_ext_state.dart b/lib/bloc/passo/land/land_ext/land_ext_state.dart new file mode 100644 index 0000000..c59eec3 --- /dev/null +++ b/lib/bloc/passo/land/land_ext/land_ext_state.dart @@ -0,0 +1,28 @@ +part of 'land_ext_bloc.dart'; + +class LandExtState extends Equatable { + const LandExtState(); + + @override + List get props => []; +} + +class LandExtInitial extends LandExtState {} + +class LandExtLoading extends LandExtState {} + +class LandExtLoaded extends LandExtState { + LandExtLoaded(this.landext); + final List landext; + + @override + List get props => [landext]; +} + +class LandExtErrorState extends LandExtState { + LandExtErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart new file mode 100644 index 0000000..08d18b0 --- /dev/null +++ b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart @@ -0,0 +1,63 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/land_property_assessment.dart'; +import 'package:unit2/sevices/passo/land/land_property_assessment.dart'; +import 'package:http/http.dart' as http; + +part 'land_property_assessment_event.dart'; +part 'land_property_assessment_state.dart'; + +class LandPropertyAssessmentBloc + extends Bloc { + LandPropertyAssessmentBloc() : super(LandPropertyAssessmentLoading()) { + List globalLandPropertyAssessment = []; + on((event, emit) async { + emit(LandPropertyAssessmentLoading()); + try { + final tempID = await SharedPreferences.getInstance(); + print(tempID.getInt('landid')); + final additionalItems = await LandPropertyAssessmentServices.instance + .fetch(tempID.getInt('tempid')); + + globalLandPropertyAssessment + .addAll(additionalItems); // Append all items to the list + emit(LandPropertyAssessmentLoaded(globalLandPropertyAssessment)); + } catch (e) { + emit(LandPropertyAssessmentErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = (await LandPropertyAssessmentServices.instance + .add(event.assessment))!; + print(response.body); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + LandPropertyAssessment newAdditional = + LandPropertyAssessment.fromJson(jsonResponse['data']); + print(jsonResponse['data']); + globalLandPropertyAssessment.add(newAdditional); + + emit(LandPropertyAssessmentLoaded(globalLandPropertyAssessment)); + } + }); + on((event, emit) async { + print(event.id); + http.Response response = + (await LandPropertyAssessmentServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + globalLandPropertyAssessment.removeWhere( + ((LandPropertyAssessment element) => element.id == event.id)); + emit(LandPropertyAssessmentDeletedState(success: true)); + } + }); + + on((event, emit) async { + emit(ShowAddLandPropertyAssessmentScreen()); + }); + } +} diff --git a/lib/bloc/passo/land/land_property_assessment/land_property_assessment_event.dart b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_event.dart new file mode 100644 index 0000000..7eb84e0 --- /dev/null +++ b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_event.dart @@ -0,0 +1,38 @@ +part of 'land_property_assessment_bloc.dart'; + +class LandPropertyAssessmentEvent extends Equatable { + const LandPropertyAssessmentEvent(); + + @override + List get props => []; +} + +class LoadLandPropertyAssessment extends LandPropertyAssessmentEvent { + final List assessment; + + const LoadLandPropertyAssessment( + {this.assessment = const []}); + + @override + List get props => [assessment]; +} + +class AddLandPropertyAssessment extends LandPropertyAssessmentEvent { + final LandPropertyAssessment assessment; + + const AddLandPropertyAssessment({required this.assessment}); + + @override + List get props => [assessment]; +} + +class DeleteLandPropertyAssessment extends LandPropertyAssessmentEvent { + final int id; + + const DeleteLandPropertyAssessment({required this.id}); + + @override + List get props => [id]; +} + +class ShowLandPropertyAssessment extends LandPropertyAssessmentEvent {} diff --git a/lib/bloc/passo/land/land_property_assessment/land_property_assessment_state.dart b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_state.dart new file mode 100644 index 0000000..ce2d738 --- /dev/null +++ b/lib/bloc/passo/land/land_property_assessment/land_property_assessment_state.dart @@ -0,0 +1,35 @@ +part of 'land_property_assessment_bloc.dart'; + +class LandPropertyAssessmentState extends Equatable { + const LandPropertyAssessmentState(); + + @override + List get props => []; +} + +class LandPropertyAssessmentLoading extends LandPropertyAssessmentState {} + +class LandPropertyAssessmentLoaded extends LandPropertyAssessmentState { + const LandPropertyAssessmentLoaded(this.assessment); + final List assessment; + + @override + List get props => [assessment]; +} + +class ShowAddLandPropertyAssessmentScreen extends LandPropertyAssessmentState {} + +class LandPropertyAssessmentErrorState extends LandPropertyAssessmentState { + const LandPropertyAssessmentErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class LandPropertyAssessmentDeletedState extends LandPropertyAssessmentState { + final bool success; + const LandPropertyAssessmentDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart new file mode 100644 index 0000000..1abcfdc --- /dev/null +++ b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart @@ -0,0 +1,65 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/land_property_boundaries.dart'; +import 'package:unit2/model/passo/land_property_loc.dart'; +import 'package:unit2/model/passo/land_property_owner.dart'; +import 'package:unit2/sevices/passo/land/land_boundaries.dart'; +import 'package:unit2/sevices/passo/land/land_location.dart'; +import 'package:unit2/sevices/passo/land/land_property_owner.dart'; +import 'package:http/http.dart' as http; +part 'land_property_owner_info_event.dart'; +part 'land_property_owner_info_state.dart'; + +class LandPropertyOwnerInfoBloc + extends Bloc { + LandPropertyOwnerInfoBloc() : super(LandLoading()) { + on((event, emit) async { + emit(LandLoading()); + try { + final faas = await LandServices.instance.fetch(); + emit(LandLoaded(faas)); + } catch (e) { + emit(LandErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = (await LandServices.instance.add(event.land))!; + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + var details = jsonResponse['data']['details']; + + if (details != null) { + var id = details['id']; + final tempID = await SharedPreferences.getInstance(); + print(id); + await tempID.setInt('landid', id + 1); + final faas = await LandServices.instance.fetch(); + emit(LandLoaded(faas)); + } else { + print("No 'details' object found in the response."); + // Handle the case when 'details' is missing + } + } + }); + + on((event, emit) async { + final state = this.state; + http.Response response = (await LandLocationService.instance + .update(event.land_loc, event.land_loc.id))!; + print('Land LOc'); + print(response.body); + }); + + on((event, emit) async { + final state = this.state; + http.Response response = (await LandBoundariesService.instance + .update(event.land_boundaries, event.land_boundaries.id))!; + print('Land Boundaries'); + print(response.body); + }); + } +} diff --git a/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_event.dart b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_event.dart new file mode 100644 index 0000000..c05cacf --- /dev/null +++ b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_event.dart @@ -0,0 +1,48 @@ +part of 'land_property_owner_info_bloc.dart'; + +class LandPropertyOwnerInfoEvent extends Equatable { + const LandPropertyOwnerInfoEvent(); + + @override + List get props => []; +} + +class LoadLand extends LandPropertyOwnerInfoEvent { + final List land; + + const LoadLand({this.land = const []}); + + @override + List get props => [land]; +} + +class AddPropertyOwnerLand extends LandPropertyOwnerInfoEvent { + final LandPropertyOwner land; + + const AddPropertyOwnerLand({required this.land}); + + @override + List get props => [land]; +} + +class UpdateLandLoc extends LandPropertyOwnerInfoEvent { + // ignore: non_constant_identifier_names + final LandPropertyLoc land_loc; + + // ignore: non_constant_identifier_names + const UpdateLandLoc({required this.land_loc}); + + @override + List get props => [land_loc]; +} + +class UpdateLandBoundaries extends LandPropertyOwnerInfoEvent { + // ignore: non_constant_identifier_names + final LandPropertyBoundaries land_boundaries; + + // ignore: non_constant_identifier_names + const UpdateLandBoundaries({required this.land_boundaries}); + + @override + List get props => [land_boundaries]; +} diff --git a/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_state.dart b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_state.dart new file mode 100644 index 0000000..ec64d5f --- /dev/null +++ b/lib/bloc/passo/land/land_property_owner_info/land_property_owner_info_state.dart @@ -0,0 +1,34 @@ +part of 'land_property_owner_info_bloc.dart'; + +class LandPropertyOwnerInfoState extends Equatable { + const LandPropertyOwnerInfoState(); + + @override + List get props => []; +} + +class LandLoading extends LandPropertyOwnerInfoState {} + +class LandLoaded extends LandPropertyOwnerInfoState { + const LandLoaded(this.land); + final List land; + + @override + List get props => [land]; +} + +// class PropertyAppraisalLoaded extends AssessorsState { +// PropertyAppraisalLoaded(this.appraisal); +// final List appraisal; + +// @override +// List get props => [appraisal]; +// } + +class LandErrorState extends LandPropertyOwnerInfoState { + const LandErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart b/lib/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart new file mode 100644 index 0000000..edca8e3 --- /dev/null +++ b/lib/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart @@ -0,0 +1,25 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:unit2/model/passo/land_subclassification.dart'; +import 'package:unit2/sevices/passo/land/land_classification.dart'; +import 'package:unit2/sevices/passo/land/land_subclassification.dart'; + +part 'land_subclassification_event.dart'; +part 'land_subclassification_state.dart'; + +class LandSubClassificationBloc + extends Bloc { + LandSubClassificationBloc() : super(LandSubClassificationLoading()) { + on((event, emit) async { + emit(LandSubClassificationLoading()); + try { + final classs = await LandSubClassificationService.instance + .fetch(event.cityCode, event.classCode); + emit(LandSubClassificationLoaded(classs)); + } catch (e) { + emit(LandSubClassificationErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/land/land_subclassification/land_subclassification_event.dart b/lib/bloc/passo/land/land_subclassification/land_subclassification_event.dart new file mode 100644 index 0000000..dfd7a29 --- /dev/null +++ b/lib/bloc/passo/land/land_subclassification/land_subclassification_event.dart @@ -0,0 +1,19 @@ +part of 'land_subclassification_bloc.dart'; + +class LandSubClassificationEvent extends Equatable { + const LandSubClassificationEvent(); + + @override + List get props => []; +} + +class LoadLandSubClassification extends LandSubClassificationEvent { + final String cityCode; + final int classCode; + + const LoadLandSubClassification( + {required this.cityCode, required this.classCode}); + + @override + List get props => [cityCode, classCode]; +} diff --git a/lib/bloc/passo/land/land_subclassification/land_subclassification_state.dart b/lib/bloc/passo/land/land_subclassification/land_subclassification_state.dart new file mode 100644 index 0000000..d0f1be9 --- /dev/null +++ b/lib/bloc/passo/land/land_subclassification/land_subclassification_state.dart @@ -0,0 +1,26 @@ +part of 'land_subclassification_bloc.dart'; + +class LandSubClassificationState extends Equatable { + const LandSubClassificationState(); + + @override + List get props => []; +} + +class LandSubClassificationLoading extends LandSubClassificationState {} + +class LandSubClassificationLoaded extends LandSubClassificationState { + LandSubClassificationLoaded(this.land_subclassification); + final List land_subclassification; + + @override + List get props => [land_subclassification]; +} + +class LandSubClassificationErrorState extends LandSubClassificationState { + LandSubClassificationErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart new file mode 100644 index 0000000..6f270ab --- /dev/null +++ b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart @@ -0,0 +1,22 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/trees_improvements.dart'; +import 'package:unit2/sevices/passo/land/land_trees_improvements.dart'; + +part 'land_trees_improvements_event.dart'; +part 'land_trees_improvements_state.dart'; + +class LandTreesImprovementsBloc + extends Bloc { + LandTreesImprovementsBloc() : super(LandTreesImprovementsInitial()) { + on((event, emit) async { + emit(LandTreesImprovementsLoading()); + try { + final trees_imp = await LandTreesImprovementsServices.instance.fetch(); + emit(LandTreesImprovementsLoaded(trees_imp)); + } catch (e) { + emit(LandTreesImprovementsErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_event.dart b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_event.dart new file mode 100644 index 0000000..690977c --- /dev/null +++ b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_event.dart @@ -0,0 +1,17 @@ +part of 'land_trees_improvements_bloc.dart'; + +class LandTreesImprovementsEvent extends Equatable { + const LandTreesImprovementsEvent(); + + @override + List get props => []; +} + +class LoadLandTreesImprovements extends LandTreesImprovementsEvent { + final List trees_imp; + const LoadLandTreesImprovements( + {this.trees_imp = const []}); + + @override + List get props => [trees_imp]; +} diff --git a/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_state.dart b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_state.dart new file mode 100644 index 0000000..f11621a --- /dev/null +++ b/lib/bloc/passo/land/land_trees_improvements/land_trees_improvements_state.dart @@ -0,0 +1,28 @@ +part of 'land_trees_improvements_bloc.dart'; + +class LandTreesImprovementsState extends Equatable { + const LandTreesImprovementsState(); + + @override + List get props => []; +} + +class LandTreesImprovementsInitial extends LandTreesImprovementsState {} + +class LandTreesImprovementsLoading extends LandTreesImprovementsState {} + +class LandTreesImprovementsLoaded extends LandTreesImprovementsState { + LandTreesImprovementsLoaded(this.trees_imp); + final List trees_imp; + + @override + List get props => [trees_imp]; +} + +class LandTreesImprovementsErrorState extends LandTreesImprovementsState { + LandTreesImprovementsErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart new file mode 100644 index 0000000..7655903 --- /dev/null +++ b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/sevices/passo/land/land_value_adjustment.dart'; +part 'land_value_adjustments_event.dart'; +part 'land_value_adjustments_state.dart'; + +class LandValueAdjustmentsBloc + extends Bloc { + LandValueAdjustmentsBloc() : super(LandValueAdjustmentsLoading()) { + List globalLandValueAdjustments = []; + on((event, emit) async { + emit(LandValueAdjustmentsLoading()); + try { + // final tempID = await SharedPreferences.getInstance(); + // print(tempID.getInt('tempid')); + // final additionalItem = await GetLandValueAdjustments.getLandValueAdjustments( + // tempID.getInt('tempid')); + + emit(LandValueAdjustmentsLoaded(globalLandValueAdjustments)); + } catch (e) { + emit(LandValueAdjustmentsErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = + (await ValueAdjustmentsServices.instance.add(event.val_adj))!; + print(response.body); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + ValueAdjustments newAdditional = + ValueAdjustments.fromJson(jsonResponse['data']); + print(jsonResponse['data']); + globalLandValueAdjustments.add(newAdditional); + + emit(LandValueAdjustmentsLoaded(globalLandValueAdjustments)); + } + }); + on((event, emit) async { + print(event.id); + http.Response response = + (await ValueAdjustmentsServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + globalLandValueAdjustments.removeWhere( + ((ValueAdjustments element) => element.id == event.id)); + emit(LandValueAdjustmentsDeletedState(success: true)); + } + }); + + on((event, emit) async { + emit(ShowAddLandValueAdjustmentsScreen()); + }); + } +} diff --git a/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_event.dart b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_event.dart new file mode 100644 index 0000000..857e6f8 --- /dev/null +++ b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_event.dart @@ -0,0 +1,37 @@ +part of 'land_value_adjustments_bloc.dart'; + +class LandValueAdjustmentsEvent extends Equatable { + const LandValueAdjustmentsEvent(); + + @override + List get props => []; +} + +class LoadLandValueAdjustments extends LandValueAdjustmentsEvent { + final List val_adj; + + const LoadLandValueAdjustments({this.val_adj = const []}); + + @override + List get props => [val_adj]; +} + +class AddLandValueAdjustments extends LandValueAdjustmentsEvent { + final ValueAdjustments val_adj; + + const AddLandValueAdjustments({required this.val_adj}); + + @override + List get props => [val_adj]; +} + +class DeleteLandValueAdjustments extends LandValueAdjustmentsEvent { + final int id; + + const DeleteLandValueAdjustments({required this.id}); + + @override + List get props => [id]; +} + +class ShowLandValueAdjustments extends LandValueAdjustmentsEvent {} diff --git a/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_state.dart b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_state.dart new file mode 100644 index 0000000..8f76eec --- /dev/null +++ b/lib/bloc/passo/land/land_value_adjustments/land_value_adjustments_state.dart @@ -0,0 +1,35 @@ +part of 'land_value_adjustments_bloc.dart'; + +class LandValueAdjustmentsState extends Equatable { + const LandValueAdjustmentsState(); + + @override + List get props => []; +} + +class LandValueAdjustmentsLoading extends LandValueAdjustmentsState {} + +class LandValueAdjustmentsLoaded extends LandValueAdjustmentsState { + const LandValueAdjustmentsLoaded(this.val_adj); + final List val_adj; + + @override + List get props => [val_adj]; +} + +class ShowAddLandValueAdjustmentsScreen extends LandValueAdjustmentsState {} + +class LandValueAdjustmentsErrorState extends LandValueAdjustmentsState { + const LandValueAdjustmentsErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class LandValueAdjustmentsDeletedState extends LandValueAdjustmentsState { + final bool success; + const LandValueAdjustmentsDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/land/other_improvements/other_improvements_bloc.dart b/lib/bloc/passo/land/other_improvements/other_improvements_bloc.dart new file mode 100644 index 0000000..3271961 --- /dev/null +++ b/lib/bloc/passo/land/other_improvements/other_improvements_bloc.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/sevices/passo/land/land_other_improvements.dart'; +import 'package:http/http.dart' as http; +part 'other_improvements_event.dart'; +part 'other_improvements_state.dart'; + +class OtherImprovementsBloc + extends Bloc { + OtherImprovementsBloc() : super(OtherImprovementLoading()) { + List globalOtherImprovement = []; + on((event, emit) async { + emit(OtherImprovementLoading()); + try { + // final tempID = await SharedPreferences.getInstance(); + // print(tempID.getInt('tempid')); + // final additionalItem = await GetOtherImprovement.getOtherImprovement( + // tempID.getInt('tempid')); + + emit(OtherImprovementLoaded(globalOtherImprovement)); + } catch (e) { + emit(OtherImprovementErrorState(e.toString())); + } + }); + on((event, emit) async { + http.Response response = + (await OtherImprovementServices.instance.add(event.other_imp))!; + print(response.body); + + if (response.statusCode == 201) { + var jsonResponse = jsonDecode(response.body); + OtherImprovements newAdditional = + OtherImprovements.fromJson(jsonResponse['data']); + print(jsonResponse['data']); + globalOtherImprovement.add(newAdditional); + + emit(OtherImprovementLoaded(globalOtherImprovement)); + } + }); + on((event, emit) async { + print(event.id); + http.Response response = + (await OtherImprovementServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + globalOtherImprovement.removeWhere( + ((OtherImprovements element) => element.id == event.id)); + emit(OtherImprovementDeletedState(success: true)); + } + }); + + on((event, emit) async { + emit(ShowAddOtherImprovementScreen()); + }); + } +} diff --git a/lib/bloc/passo/land/other_improvements/other_improvements_event.dart b/lib/bloc/passo/land/other_improvements/other_improvements_event.dart new file mode 100644 index 0000000..135746f --- /dev/null +++ b/lib/bloc/passo/land/other_improvements/other_improvements_event.dart @@ -0,0 +1,37 @@ +part of 'other_improvements_bloc.dart'; + +class OtherImprovementsEvent extends Equatable { + const OtherImprovementsEvent(); + + @override + List get props => []; +} + +class LoadOtherImprovement extends OtherImprovementsEvent { + final List other_imp; + + const LoadOtherImprovement({this.other_imp = const []}); + + @override + List get props => [other_imp]; +} + +class AddOtherImprovement extends OtherImprovementsEvent { + final OtherImprovements other_imp; + + const AddOtherImprovement({required this.other_imp}); + + @override + List get props => [other_imp]; +} + +class DeleteOtherImprovement extends OtherImprovementsEvent { + final int id; + + const DeleteOtherImprovement({required this.id}); + + @override + List get props => [id]; +} + +class ShowOtherImprovement extends OtherImprovementsEvent {} diff --git a/lib/bloc/passo/land/other_improvements/other_improvements_state.dart b/lib/bloc/passo/land/other_improvements/other_improvements_state.dart new file mode 100644 index 0000000..75b3b01 --- /dev/null +++ b/lib/bloc/passo/land/other_improvements/other_improvements_state.dart @@ -0,0 +1,35 @@ +part of 'other_improvements_bloc.dart'; + +class OtherImprovementsState extends Equatable { + const OtherImprovementsState(); + + @override + List get props => []; +} + +class OtherImprovementLoading extends OtherImprovementsState {} + +class OtherImprovementLoaded extends OtherImprovementsState { + const OtherImprovementLoaded(this.other_imp); + final List other_imp; + + @override + List get props => [other_imp]; +} + +class ShowAddOtherImprovementScreen extends OtherImprovementsState {} + +class OtherImprovementErrorState extends OtherImprovementsState { + const OtherImprovementErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class OtherImprovementDeletedState extends OtherImprovementsState { + final bool success; + const OtherImprovementDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/land/type_of_location/type_of_location_bloc.dart b/lib/bloc/passo/land/type_of_location/type_of_location_bloc.dart new file mode 100644 index 0000000..439e0e2 --- /dev/null +++ b/lib/bloc/passo/land/type_of_location/type_of_location_bloc.dart @@ -0,0 +1,22 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/type_of_location.dart'; +import 'package:unit2/sevices/passo/land/type_of_location.dart'; + +part 'type_of_location_event.dart'; +part 'type_of_location_state.dart'; + +class TypeOfLocationBloc + extends Bloc { + TypeOfLocationBloc() : super(TypeOfLocationInitial()) { + on((event, emit) async { + emit(TypeOfLocationLoading()); + try { + final locType = await TypeOfLocationServices.instance.fetch(); + emit(TypeOfLocationLoaded(locType)); + } catch (e) { + emit(TypeOfLocationErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/land/type_of_location/type_of_location_event.dart b/lib/bloc/passo/land/type_of_location/type_of_location_event.dart new file mode 100644 index 0000000..dfcd9b9 --- /dev/null +++ b/lib/bloc/passo/land/type_of_location/type_of_location_event.dart @@ -0,0 +1,17 @@ +part of 'type_of_location_bloc.dart'; + +class TypeOfLocationEvent extends Equatable { + const TypeOfLocationEvent(); + + @override + List get props => []; +} + +class LoadTypeOfLocation extends TypeOfLocationEvent { + final List locType; + + const LoadTypeOfLocation({this.locType = const []}); + + @override + List get props => [locType]; +} diff --git a/lib/bloc/passo/land/type_of_location/type_of_location_state.dart b/lib/bloc/passo/land/type_of_location/type_of_location_state.dart new file mode 100644 index 0000000..cbbb893 --- /dev/null +++ b/lib/bloc/passo/land/type_of_location/type_of_location_state.dart @@ -0,0 +1,28 @@ +part of 'type_of_location_bloc.dart'; + +class TypeOfLocationState extends Equatable { + const TypeOfLocationState(); + + @override + List get props => []; +} + +class TypeOfLocationInitial extends TypeOfLocationState {} + +class TypeOfLocationLoading extends TypeOfLocationState {} + +class TypeOfLocationLoaded extends TypeOfLocationState { + TypeOfLocationLoaded(this.loc_type); + final List loc_type; + + @override + List get props => [loc_type]; +} + +class TypeOfLocationErrorState extends TypeOfLocationState { + TypeOfLocationErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/land/type_of_road/type_of_road_bloc.dart b/lib/bloc/passo/land/type_of_road/type_of_road_bloc.dart new file mode 100644 index 0000000..555a75b --- /dev/null +++ b/lib/bloc/passo/land/type_of_road/type_of_road_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/type_of_road.dart'; +import 'package:unit2/sevices/passo/land/type_of_road.dart'; + +part 'type_of_road_event.dart'; +part 'type_of_road_state.dart'; + +class TypeOfRoadBloc extends Bloc { + TypeOfRoadBloc() : super(TypeOfRoadInitial()) { + on((event, emit) async { + emit(TypeOfRoadLoading()); + try { + final roadType = await TypeOfRoadServices.instance.fetch(); + emit(TypeOfRoadLoaded(roadType)); + } catch (e) { + emit(TypeOfRoadErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/land/type_of_road/type_of_road_event.dart b/lib/bloc/passo/land/type_of_road/type_of_road_event.dart new file mode 100644 index 0000000..1d3cdd3 --- /dev/null +++ b/lib/bloc/passo/land/type_of_road/type_of_road_event.dart @@ -0,0 +1,17 @@ +part of 'type_of_road_bloc.dart'; + +class TypeOfRoadEvent extends Equatable { + const TypeOfRoadEvent(); + + @override + List get props => []; +} + +class LoadTypeOfRoad extends TypeOfRoadEvent { + final List roadType; + + const LoadTypeOfRoad({this.roadType = const []}); + + @override + List get props => [roadType]; +} diff --git a/lib/bloc/passo/land/type_of_road/type_of_road_state.dart b/lib/bloc/passo/land/type_of_road/type_of_road_state.dart new file mode 100644 index 0000000..ad65a1c --- /dev/null +++ b/lib/bloc/passo/land/type_of_road/type_of_road_state.dart @@ -0,0 +1,28 @@ +part of 'type_of_road_bloc.dart'; + +class TypeOfRoadState extends Equatable { + const TypeOfRoadState(); + + @override + List get props => []; +} + +class TypeOfRoadInitial extends TypeOfRoadState {} + +class TypeOfRoadLoading extends TypeOfRoadState {} + +class TypeOfRoadLoaded extends TypeOfRoadState { + TypeOfRoadLoaded(this.road_type); + final List road_type; + + @override + List get props => [road_type]; +} + +class TypeOfRoadErrorState extends TypeOfRoadState { + TypeOfRoadErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/location/location_bloc.dart b/lib/bloc/passo/location/location_bloc.dart deleted file mode 100644 index 7bac921..0000000 --- a/lib/bloc/passo/location/location_bloc.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:bloc/bloc.dart'; -import 'package:equatable/equatable.dart'; - -part 'location_event.dart'; -part 'location_state.dart'; - -class LocationBloc extends Bloc { - LocationBloc() : super(LocationInitial()) { - on((event, emit) { - // TODO: implement event handler - }); - } -} diff --git a/lib/bloc/passo/location/location_event.dart b/lib/bloc/passo/location/location_event.dart deleted file mode 100644 index 44dfbee..0000000 --- a/lib/bloc/passo/location/location_event.dart +++ /dev/null @@ -1,8 +0,0 @@ -part of 'location_bloc.dart'; - -abstract class LocationEvent extends Equatable { - const LocationEvent(); - - @override - List get props => []; -} diff --git a/lib/bloc/passo/location/location_state.dart b/lib/bloc/passo/location/location_state.dart deleted file mode 100644 index 64ea7b3..0000000 --- a/lib/bloc/passo/location/location_state.dart +++ /dev/null @@ -1,10 +0,0 @@ -part of 'location_bloc.dart'; - -abstract class LocationState extends Equatable { - const LocationState(); - - @override - List get props => []; -} - -class LocationInitial extends LocationState {} diff --git a/lib/bloc/passo/memoranda/memoranda_bloc.dart b/lib/bloc/passo/memoranda/memoranda_bloc.dart new file mode 100644 index 0000000..c1b1a31 --- /dev/null +++ b/lib/bloc/passo/memoranda/memoranda_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/memoranda.dart'; +import 'package:unit2/sevices/passo/memoranda.dart'; + +part 'memoranda_event.dart'; +part 'memoranda_state.dart'; + +class MemorandaBloc extends Bloc { + MemorandaBloc() : super(MemorandaInitial()) { + on((event, emit) async { + emit(MemorandaLoading()); + try { + final municipality = await MemorandaServices.instance.fetch(); + emit(MemorandaLoaded(municipality)); + } catch (e) { + emit(MemorandaErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/memoranda/memoranda_event.dart b/lib/bloc/passo/memoranda/memoranda_event.dart new file mode 100644 index 0000000..06ac2b6 --- /dev/null +++ b/lib/bloc/passo/memoranda/memoranda_event.dart @@ -0,0 +1,16 @@ +part of 'memoranda_bloc.dart'; + +class MemorandaEvent extends Equatable { + const MemorandaEvent(); + + @override + List get props => []; +} + +class LoadMemoranda extends MemorandaEvent { + final List memoranda; + const LoadMemoranda({this.memoranda = const []}); + + @override + List get props => [memoranda]; +} diff --git a/lib/bloc/passo/memoranda/memoranda_state.dart b/lib/bloc/passo/memoranda/memoranda_state.dart new file mode 100644 index 0000000..1803cd8 --- /dev/null +++ b/lib/bloc/passo/memoranda/memoranda_state.dart @@ -0,0 +1,28 @@ +part of 'memoranda_bloc.dart'; + +class MemorandaState extends Equatable { + const MemorandaState(); + + @override + List get props => []; +} + +class MemorandaInitial extends MemorandaState {} + +class MemorandaLoading extends MemorandaState {} + +class MemorandaLoaded extends MemorandaState { + MemorandaLoaded(this.memorada); + final List memorada; + + @override + List get props => [memorada]; +} + +class MemorandaErrorState extends MemorandaState { + MemorandaErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/municipality/municipality_bloc.dart b/lib/bloc/passo/municipality/municipality_bloc.dart new file mode 100644 index 0000000..3a6a246 --- /dev/null +++ b/lib/bloc/passo/municipality/municipality_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/sevices/passo/municipality.dart'; + +part 'municipality_event.dart'; +part 'municipality_state.dart'; + +class MunicipalityBloc extends Bloc { + MunicipalityBloc() : super(MunicipalityInitial()) { + on((event, emit) async { + emit(MunicipalityLoading()); + try { + final municipality = await MunicipalityServices.instance.fetch(); + emit(MunicipalityLoaded(municipality)); + } catch (e) { + emit(MunicipalityErrorState(e.toString())); + } + }); + } +} diff --git a/lib/bloc/passo/municipality/municipality_event.dart b/lib/bloc/passo/municipality/municipality_event.dart new file mode 100644 index 0000000..4b7556f --- /dev/null +++ b/lib/bloc/passo/municipality/municipality_event.dart @@ -0,0 +1,17 @@ +part of 'municipality_bloc.dart'; + +class MunicipalityEvent extends Equatable { + const MunicipalityEvent(); + + @override + List get props => []; +} + +class LoadMunicipality extends MunicipalityEvent { + final List municipality; + + const LoadMunicipality({this.municipality = const []}); + + @override + List get props => [municipality]; +} diff --git a/lib/bloc/passo/municipality/municipality_state.dart b/lib/bloc/passo/municipality/municipality_state.dart new file mode 100644 index 0000000..25c1131 --- /dev/null +++ b/lib/bloc/passo/municipality/municipality_state.dart @@ -0,0 +1,28 @@ +part of 'municipality_bloc.dart'; + +class MunicipalityState extends Equatable { + const MunicipalityState(); + + @override + List get props => []; +} + +class MunicipalityInitial extends MunicipalityState {} + +class MunicipalityLoading extends MunicipalityState {} + +class MunicipalityLoaded extends MunicipalityState { + MunicipalityLoaded(this.municipality); + final List municipality; + + @override + List get props => [municipality]; +} + +class MunicipalityErrorState extends MunicipalityState { + MunicipalityErrorState(this.error); + final String error; + + @override + List get props => [error]; +} diff --git a/lib/bloc/passo/property_info/property_info_bloc.dart b/lib/bloc/passo/property_info/property_info_bloc.dart deleted file mode 100644 index a808842..0000000 --- a/lib/bloc/passo/property_info/property_info_bloc.dart +++ /dev/null @@ -1,59 +0,0 @@ -import 'dart:convert'; - -import 'package:bloc/bloc.dart'; -import 'package:equatable/equatable.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:unit2/model/passo/bldg_loc.dart'; -import 'package:unit2/model/passo/land_ref.dart'; -import 'package:unit2/model/passo/property_info.dart'; -import 'package:unit2/sevices/passo/building/property_info_services.dart'; -import 'package:http/http.dart' as http; - -part 'property_info_event.dart'; -part 'property_info_state.dart'; - -class PropertyInfoBloc extends Bloc { - PropertyInfoBloc() : super(PropertyInfoLoading()) { - on((event, emit) async { - emit(PropertyInfoLoading()); - try { - final property_info = - await PropertyInfoService.instance.getpropertyInfo(); - emit(PropertyInfoLoaded(property_info)); - } catch (e) { - emit(PropertyInfoErrorState(e.toString())); - } - }); - on((event, emit) async { - final state = this.state; - http.Response response = (await PropertyInfoService.instance - .postPropertyInfo(event.property_info))!; - print(response.body); - - if (response.statusCode == 201) { - var jsonResponse = jsonDecode(response.body); - final tempID = await SharedPreferences.getInstance(); - print(jsonResponse['data']); - await tempID.setInt('tempid', jsonResponse['data']['id'] + 1); - final faas = await PropertyInfoService.instance.getpropertyInfo(); - emit(PropertyInfoLoaded(faas)); - } - }); - on(((event, emit) async { - final state = this.state; - http.Response response = (await PropertyInfoService.instance - .bldgLocPutInfo(event.bldg_loc, event.bldg_loc.id))!; - print('bldgLoc'); - print(response.statusCode); - })); - on( - (event, emit) async { - final state = this.state; - http.Response response = (await PropertyInfoService.instance - .landRefPutInfo(event.land_ref, event.land_ref.id))!; - print('landref'); - print(response.statusCode); - }, - ); - } -} diff --git a/lib/bloc/passo/signatories/signatories_bloc.dart b/lib/bloc/passo/signatories/signatories_bloc.dart index 9d6581c..8c55403 100644 --- a/lib/bloc/passo/signatories/signatories_bloc.dart +++ b/lib/bloc/passo/signatories/signatories_bloc.dart @@ -11,7 +11,7 @@ class SignatoriesBloc extends Bloc { on((event, emit) async { emit(SignatoriesLoading()); try { - final signatories = await SignatoriesServices.instance.getSignatories(); + final signatories = await SignatoriesServices.instance.fetch(); emit(SignatoriesLoaded(signatories)); } catch (e) { emit(SignatoriesErrorState(e.toString())); diff --git a/lib/bloc/rbac/rbac_bloc.dart b/lib/bloc/rbac/rbac_bloc.dart new file mode 100644 index 0000000..8d8287a --- /dev/null +++ b/lib/bloc/rbac/rbac_bloc.dart @@ -0,0 +1,45 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/sevices/roles/rbac_services.dart'; + +import '../../model/rbac/new_permission.dart'; +import '../../model/rbac/rbac.dart'; + +part 'rbac_event.dart'; +part 'rbac_state.dart'; + +class RbacBloc extends Bloc { + + RbacBloc() : super(RbacInitial()) { + List? modules; + List? objects; + List? roles; + List? permissions; + List? operations; + on((event, emit) async { + emit(RbacLoadingState()); + try { + modules = await RbacServices.instance.getModules(); + objects = await RbacServices.instance.getObjects(); + roles = await RbacServices.instance.getRole(); + permissions = await RbacServices.instance.getPermission(); + operations = await RbacServices.instance.getOperations(); + emit(RbacScreenSetted(modules: modules!, objects: objects!, operations: operations!, permission: permissions!, role: roles!)); + } catch (e) { + emit(RbacErrorState(message: e.toString())); + } + });on((event, emit)async{ + try{ + emit(RbacLoadingState()); + Map responseStatus = await RbacServices.instance.assignRBAC(assigneeId: event.assigneeId, assignerId: event.assignerId, selectedRole: event.selectedRole, selectedModule: event.selectedModule, permissionId: event.permissionId, newPermissions: event.newPermissions); + emit(RbacAssignedState(responseStatus: responseStatus)); + }catch(e){ + emit(RbacErrorState(message: e.toString())); + } + }); + on((event,emit){ + emit(RbacScreenSetted(modules: modules!, objects: objects!, operations: operations!, permission: permissions!, role: roles!)); + }); + } +} diff --git a/lib/bloc/rbac/rbac_event.dart b/lib/bloc/rbac/rbac_event.dart new file mode 100644 index 0000000..4daa43e --- /dev/null +++ b/lib/bloc/rbac/rbac_event.dart @@ -0,0 +1,29 @@ +part of 'rbac_bloc.dart'; + +abstract class RbacEvent extends Equatable { + const RbacEvent(); + + @override + List get props => []; +} + +class SetRbacScreen extends RbacEvent {} + +class AssignedRbac extends RbacEvent { + final int assigneeId; + final int assignerId; + final RBAC? selectedRole; + final RBAC? selectedModule; + final List permissionId; + final List newPermissions; + const AssignedRbac( + {required this.assigneeId, + required this.assignerId, + required this.newPermissions, + required this.permissionId, + required this.selectedModule, + required this.selectedRole}); +} +class LoadRbac extends RbacEvent{ + +} diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_bloc.dart b/lib/bloc/rbac/rbac_operations/agency/agency_bloc.dart new file mode 100644 index 0000000..de3cc89 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/agency/agency_bloc.dart @@ -0,0 +1,47 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/utils/agency.dart'; +import 'package:unit2/utils/profile_utilities.dart'; +import '../../../../model/utils/category.dart'; +import '../../../../sevices/roles/rbac_operations/agency_services.dart'; + +part 'agency_event.dart'; +part 'agency_state.dart'; + +class AgencyBloc extends Bloc { + AgencyBloc() : super(AgencyInitial()) { + List agencies = []; + List agencyCategory = []; + on((event, emit) async { + emit(AgencyLoadingState()); + try { + if (agencies.isEmpty) { + agencies = await AgencyServices.instance.getAgencies(); + } + if (agencyCategory.isEmpty) { + agencyCategory = await ProfileUtilities.instance.agencyCategory(); + } + emit( + AgenciesLoaded(agencies: agencies, agencyCategory: agencyCategory)); + } catch (e) { + emit(AgencyErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(AgencyLoadingState()); + try { + Map statusResponse = + await AgencyServices.instance.add(agency: event.agency); + if (statusResponse['success']) { + Agency newAgency = Agency.fromJson(statusResponse['data']); + agencies.add(newAgency); + emit(AgencyAddesState(response: statusResponse)); + } else { + emit(AgencyAddesState(response: statusResponse)); + } + } catch (e) { + emit(AgencyErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart new file mode 100644 index 0000000..8371eba --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart @@ -0,0 +1,16 @@ +part of 'agency_bloc.dart'; + +abstract class AgencyEvent extends Equatable { + const AgencyEvent(); + + @override + List get props => []; +} + +class GetAgencies extends AgencyEvent{ + +} +class AddAgency extends AgencyEvent{ + final Agency agency; + const AddAgency({required this.agency}); +} diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_state.dart b/lib/bloc/rbac/rbac_operations/agency/agency_state.dart new file mode 100644 index 0000000..22aadcb --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/agency/agency_state.dart @@ -0,0 +1,33 @@ +part of 'agency_bloc.dart'; + +abstract class AgencyState extends Equatable { + const AgencyState(); + + @override + List get props => []; +} + +class AgenciesLoaded extends AgencyState { + final List agencies; + final List agencyCategory; + const AgenciesLoaded({required this.agencies, required this.agencyCategory}); +} + +class AgencyErrorState extends AgencyState { + final String message; + const AgencyErrorState({required this.message}); +} + +class AgencyLoadingState extends AgencyState {} + +class AgencyAddesState extends AgencyState { + final Map response; + const AgencyAddesState({required this.response}); +} + +class AgencyDeletedState extends AgencyState { + final bool success; + const AgencyDeletedState({required this.success}); +} + +class AgencyInitial extends AgencyState {} diff --git a/lib/bloc/rbac/rbac_operations/module/module_bloc.dart b/lib/bloc/rbac/rbac_operations/module/module_bloc.dart new file mode 100644 index 0000000..6586411 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module/module_bloc.dart @@ -0,0 +1,84 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/sevices/roles/rbac_operations/module_services.dart'; +import '../../../../model/rbac/rbac.dart'; +part 'module_event.dart'; +part 'module_state.dart'; + +class ModuleBloc extends Bloc { + ModuleBloc() : super(ModuleInitial()) { + List modules = []; + on((event, emit) async { + emit(ModuleLoadingState()); + try { + if (modules.isEmpty) { + modules = await RbacModuleServices.instance.getRbacModule(); + } + + emit(ModuleLoaded(module: modules)); + } catch (e) { + emit(ModuleErrorState(message: e.toString())); + } + }); ////Add + on((event, emit) async { + try { + emit(ModuleLoadingState()); + Map statusResponse = await RbacModuleServices.instance + .add( + name: event.name!, + slug: event.slug, + short: event.shorthand, + id: event.id); + if (statusResponse['success']) { + RBAC newRole = RBAC.fromJson(statusResponse['data']); + modules.add(newRole); + emit(ModuleAddedState(response: statusResponse)); + } else { + emit(ModuleAddedState(response: statusResponse)); + } + } catch (e) { + emit(ModuleErrorState(message: e.toString())); + } + }); + ////update + on((event, emit) async { + emit(ModuleLoadingState()); + try { + Map statusResponse = await RbacModuleServices.instance + .update( + name: event.name, + slug: event.slug, + short: event.short, + moduleId: event.moduleId, + createdBy: event.createdBy, + updatedBy: event.updatedBy); + + if (statusResponse['success']) { + modules.removeWhere((element) => element.id == event.moduleId); + RBAC newRole = RBAC.fromJson(statusResponse['data']); + modules.add(newRole); + emit(ModuleUpdatedState(response: statusResponse)); + } else { + emit(ModuleUpdatedState(response: statusResponse)); + } + } catch (e) { + emit(ModuleErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(ModuleLoadingState()); + try { + bool success = await RbacModuleServices.instance + .deleteRbacModule(moduleId: event.moduleId); + if (success) { + modules.removeWhere((element) => element.id == event.moduleId); + emit(ModuleDeletedState(success: success)); + } else { + emit(ModuleDeletedState(success: success)); + } + } catch (e) { + emit(ModuleErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/module/module_event.dart b/lib/bloc/rbac/rbac_operations/module/module_event.dart new file mode 100644 index 0000000..53b9ed9 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module/module_event.dart @@ -0,0 +1,48 @@ +part of 'module_bloc.dart'; + +abstract class ModuleEvent extends Equatable { + const ModuleEvent(); + + @override + List get props => []; +} + + +class GetModule extends ModuleEvent{ + +} + +class AddRbacModule extends ModuleEvent { + final String? name; + final String? slug; + final String? shorthand; + final int id; + const AddRbacModule( + {required this.id, + required this.name, + required this.shorthand, + required this.slug}); +} + + +class UpdateRbacModule extends ModuleEvent { + final int moduleId; + final String name; + final String? slug; + final String? short; + final int? createdBy; + final int updatedBy; + const UpdateRbacModule({ + required this.moduleId, + required this.createdBy, + required this.name, + required this.short, + required this.slug, + required this.updatedBy, + }); +} + +class DeleteRbacModule extends ModuleEvent { + final int moduleId; + const DeleteRbacModule({required this.moduleId}); +} \ No newline at end of file diff --git a/lib/bloc/rbac/rbac_operations/module/module_state.dart b/lib/bloc/rbac/rbac_operations/module/module_state.dart new file mode 100644 index 0000000..7dcde63 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module/module_state.dart @@ -0,0 +1,36 @@ +part of 'module_bloc.dart'; + +abstract class ModuleState extends Equatable { + const ModuleState(); + + @override + List get props => []; +} + +class ModuleInitial extends ModuleState {} + +class ModuleLoaded extends ModuleState{ + final List module; + const ModuleLoaded({required this.module}); +} + +class ModuleLoadingState extends ModuleState{ + +} +class ModuleErrorState extends ModuleState{ + final String message; + const ModuleErrorState({required this.message}); +} + +class ModuleAddedState extends ModuleState { + final Map response; + const ModuleAddedState({required this.response}); +} +class ModuleUpdatedState extends ModuleState { + final Map response; + const ModuleUpdatedState({required this.response}); +} +class ModuleDeletedState extends ModuleState{ + final bool success; + const ModuleDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart new file mode 100644 index 0000000..0892399 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart @@ -0,0 +1,76 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/login_data/user_info/module.dart'; +import 'package:unit2/model/rbac/rbac_rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/module_objects_services.dart'; +import 'package:unit2/sevices/roles/rbac_operations/object_services.dart'; + +import '../../../../model/rbac/rbac.dart'; +import '../../../../sevices/roles/rbac_operations/module_services.dart'; +part 'module_objects_event.dart'; +part 'module_objects_state.dart'; + +class ModuleObjectsBloc extends Bloc { + ModuleObjectsBloc() : super(ModuleObjectsInitial()) { + List moduleObjects = []; + List objects = []; + List modules = []; + on((event, emit) async { + emit(ModuleObjectLoadingState()); + try { + if (moduleObjects.isEmpty) { + moduleObjects = + await RbacModuleObjectsServices.instance.getModuleObjects(); + } + if (objects.isEmpty) { + objects = await RbacObjectServices.instance.getRbacObjects(); + } + if (modules.isEmpty) { + modules = await RbacModuleServices.instance.getRbacModule(); + } + emit(ModuleObjectLoadedState( + moduleObjects: moduleObjects, objecs: objects, modules: modules)); + } catch (e) { + emit(ModuleObjectsErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(ModuleObjectLoadingState()); + Map statusResponse = + await RbacModuleObjectsServices.instance.add( + assignerId: event.assignerId, + moduleId: event.moduleId, + objectsId: event.objectsId); + + if (statusResponse['success']) { + statusResponse['data'].forEach((var permission) { + ModuleObjects newModuleObject = ModuleObjects.fromJson(permission); + moduleObjects.add(newModuleObject); + emit(ModuleObjectAddedState(response: statusResponse)); + }); + } else { + emit(ModuleObjectAddedState(response: statusResponse)); + } + } catch (e) { + emit(ModuleObjectsErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(ModuleObjectLoadingState()); + try { + bool success = await RbacModuleObjectsServices.instance + .deleteRbacModuleObject(moduleObjectId: event.moduleObjectId); + if (success) { + moduleObjects + .removeWhere((element) => element.id == event.moduleObjectId); + emit(ModuleObjectDeletedState(success: success)); + } else { + emit(ModuleObjectDeletedState(success: success)); + } + } catch (e) { + emit(ModuleObjectsErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_event.dart b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_event.dart new file mode 100644 index 0000000..65d9e89 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_event.dart @@ -0,0 +1,26 @@ +part of 'module_objects_bloc.dart'; + +abstract class ModuleObjectsEvent extends Equatable { + const ModuleObjectsEvent(); + + @override + List get props => []; +} + +class GetModuleObjects extends ModuleObjectsEvent {} + +class DeleteRbacModuleObject extends ModuleObjectsEvent { + final int moduleObjectId; + const DeleteRbacModuleObject({required this.moduleObjectId}); +} + +class AddRbacModuleObjects extends ModuleObjectsEvent { + final int moduleId; + final List objectsId; + final int assignerId; + const AddRbacModuleObjects( + {required this.assignerId, + required this.moduleId, + required this.objectsId}); +} + diff --git a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_state.dart b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_state.dart new file mode 100644 index 0000000..9028df0 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_state.dart @@ -0,0 +1,37 @@ +part of 'module_objects_bloc.dart'; + +abstract class ModuleObjectsState extends Equatable { + const ModuleObjectsState(); + + @override + List get props => []; +} + +class ModuleObjectsInitial extends ModuleObjectsState {} + +class ModuleObjectLoadedState extends ModuleObjectsState { + final List moduleObjects; + final List objecs; + final List modules; + const ModuleObjectLoadedState( + {required this.moduleObjects, + required this.modules, + required this.objecs}); +} + +class ModuleObjectsErrorState extends ModuleObjectsState { + final String message; + const ModuleObjectsErrorState({required this.message}); +} + +class ModuleObjectLoadingState extends ModuleObjectsState {} + +class ModuleObjectAddedState extends ModuleObjectsState { + final Map response; + const ModuleObjectAddedState({required this.response}); +} + +class ModuleObjectDeletedState extends ModuleObjectsState { + final bool success; + const ModuleObjectDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/object/object_bloc.dart b/lib/bloc/rbac/rbac_operations/object/object_bloc.dart new file mode 100644 index 0000000..024aa4d --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/object/object_bloc.dart @@ -0,0 +1,87 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/sevices/roles/rbac_operations/object_services.dart'; + +import '../../../../model/rbac/rbac.dart'; + +part 'object_event.dart'; +part 'object_state.dart'; + +class ObjectBloc extends Bloc { + ObjectBloc() : super(ObjectInitial()) { + List objects = []; + on((event, emit) async { + emit(ObjectLoadingState()); + try { + if (objects.isEmpty) { + objects = await RbacObjectServices.instance.getRbacObjects(); + } + emit(ObjectLoaded(objects: objects)); + } catch (e) { + emit(ObjectErrorState(message: e.toString())); + } + }); + ////Add + on((event, emit) async { + try { + emit(ObjectLoadingState()); + Map statusResponse = await RbacObjectServices.instance + .add( + name: event.name!, + slug: event.slug, + short: event.shorthand, + id: event.id); + if (statusResponse['success']) { + RBAC newObject = RBAC.fromJson(statusResponse['data']); + objects.add(newObject); + emit(ObjectAddedState(response: statusResponse)); + } else { + emit(ObjectAddedState(response: statusResponse)); + } + } catch (e) { + emit(ObjectErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(ObjectLoadingState()); + try { + Map statusResponse = await RbacObjectServices.instance + .update( + name: event.name, + slug: event.slug, + short: event.short, + objectId: event.objectId, + createdBy: event.createdBy, + updatedBy: event.updatedBy); + + if (statusResponse['success']) { + objects.removeWhere((element) => element.id == event.objectId); + RBAC newObject = RBAC.fromJson(statusResponse['data']); + objects.add(newObject); + emit(ObjectUpdatedState(response: statusResponse)); + } else { + emit(ObjectUpdatedState(response: statusResponse)); + } + } catch (e) { + emit(ObjectErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(ObjectLoadingState()); + try { + bool success = await RbacObjectServices.instance + .deleteRbacRole(objectId: event.objectId); + if (success) { + objects.removeWhere((element) => element.id == event.objectId); + emit(ObjectDeletedState(success: success)); + } else { + emit(ObjectDeletedState(success: success)); + } + } catch (e) { + emit(ObjectErrorState(message: e.toString())); + } + }); + } + } + + diff --git a/lib/bloc/rbac/rbac_operations/object/object_event.dart b/lib/bloc/rbac/rbac_operations/object/object_event.dart new file mode 100644 index 0000000..a654e0d --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/object/object_event.dart @@ -0,0 +1,46 @@ +part of 'object_bloc.dart'; + +abstract class ObjectEvent extends Equatable { + const ObjectEvent(); + + @override + List get props => []; +} + +class GetObjects extends ObjectEvent{ + +} +class AddRbacObject extends ObjectEvent { + final String? name; + final String? slug; + final String? shorthand; + final int id; + const AddRbacObject( + {required this.id, + required this.name, + required this.shorthand, + required this.slug}); +} + + +class UpdateRbacObject extends ObjectEvent { + final int objectId; + final String name; + final String? slug; + final String? short; + final int? createdBy; + final int updatedBy; + const UpdateRbacObject({ + required this.objectId, + required this.createdBy, + required this.name, + required this.short, + required this.slug, + required this.updatedBy, + }); +} + +class DeleteRbacObject extends ObjectEvent { + final int objectId; + const DeleteRbacObject({required this.objectId}); +} diff --git a/lib/bloc/rbac/rbac_operations/object/object_state.dart b/lib/bloc/rbac/rbac_operations/object/object_state.dart new file mode 100644 index 0000000..1c45114 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/object/object_state.dart @@ -0,0 +1,36 @@ +part of 'object_bloc.dart'; + +abstract class ObjectState extends Equatable { + const ObjectState(); + + @override + List get props => []; +} + +class ObjectInitial extends ObjectState {} + +class ObjectLoaded extends ObjectState{ + final List objects; + const ObjectLoaded({required this.objects}); +} + +class ObjectLoadingState extends ObjectState{ + +} + +class ObjectErrorState extends ObjectState{ + final String message; + const ObjectErrorState({required this.message}); +} +class ObjectAddedState extends ObjectState { + final Map response; + const ObjectAddedState({required this.response}); +} +class ObjectUpdatedState extends ObjectState { + final Map response; + const ObjectUpdatedState({required this.response}); +} +class ObjectDeletedState extends ObjectState{ + final bool success; + const ObjectDeletedState({required this.success}); +} \ No newline at end of file diff --git a/lib/bloc/rbac/rbac_operations/operation/operation_bloc.dart b/lib/bloc/rbac/rbac_operations/operation/operation_bloc.dart new file mode 100644 index 0000000..5dcf5e8 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/operation/operation_bloc.dart @@ -0,0 +1,84 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/operation_services.dart'; + +part 'operation_event.dart'; +part 'operation_state.dart'; + +class OperationBloc extends Bloc { + OperationBloc() : super(OperationInitial()) { + List operations = []; + on((event, emit) async { + emit(OperationLoadingState()); + try { + if (operations.isEmpty) { + operations = await RbacOperationServices.instance.getRbacOperations(); + } + + emit(OperationsLoaded(operations: operations)); + } catch (e) { + emit(OperationErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(OperationLoadingState()); + Map statusResponse = + await RbacOperationServices.instance.add( + name: event.name!, + slug: event.slug, + short: event.shorthand, + id: event.id); + if (statusResponse['success']) { + RBAC newOperation = RBAC.fromJson(statusResponse['data']); + operations.add(newOperation); + emit(OperationAddedState(response: statusResponse)); + } else { + emit(OperationAddedState(response: statusResponse)); + } + } catch (e) { + emit(OperationErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(OperationLoadingState()); + try { + Map statusResponse = + await RbacOperationServices.instance.update( + name: event.name, + slug: event.slug, + short: event.short, + operationId: event.operationId, + createdBy: event.createdBy, + updatedBy: event.updatedBy); + + if (statusResponse['success']) { + operations.removeWhere((element) => element.id == event.operationId); + RBAC newRole = RBAC.fromJson(statusResponse['data']); + operations.add(newRole); + emit(OperationUpdatedState(response: statusResponse)); + } else { + emit(OperationUpdatedState(response: statusResponse)); + } + } catch (e) { + emit(OperationErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(OperationLoadingState()); + try { + bool success = await RbacOperationServices.instance + .delete(operation: event.operationId); + if (success) { + operations.removeWhere((element) => element.id == event.operationId); + emit(OperationDeletedState(success: success)); + } else { + emit(OperationDeletedState(success: success)); + } + } catch (e) { + emit(OperationErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/operation/operation_event.dart b/lib/bloc/rbac/rbac_operations/operation/operation_event.dart new file mode 100644 index 0000000..35bd990 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/operation/operation_event.dart @@ -0,0 +1,45 @@ +part of 'operation_bloc.dart'; + +abstract class OperationEvent extends Equatable { + const OperationEvent(); + + @override + List get props => []; +} +class GetOperations extends OperationEvent{ + +} +class AddRbacOperation extends OperationEvent { + final String? name; + final String? slug; + final String? shorthand; + final int id; + const AddRbacOperation( + {required this.id, + required this.name, + required this.shorthand, + required this.slug}); +} + + +class UpdateRbacOperation extends OperationEvent { + final int operationId; + final String name; + final String? slug; + final String? short; + final int? createdBy; + final int updatedBy; + const UpdateRbacOperation({ + required this.operationId, + required this.createdBy, + required this.name, + required this.short, + required this.slug, + required this.updatedBy, + }); +} + +class DeleteRbacOperation extends OperationEvent { + final int operationId; + const DeleteRbacOperation({required this.operationId}); +} diff --git a/lib/bloc/rbac/rbac_operations/operation/operation_state.dart b/lib/bloc/rbac/rbac_operations/operation/operation_state.dart new file mode 100644 index 0000000..4490f67 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/operation/operation_state.dart @@ -0,0 +1,34 @@ +part of 'operation_bloc.dart'; + +abstract class OperationState extends Equatable { + const OperationState(); + + @override + List get props => []; +} + +class OperationInitial extends OperationState {} + +class OperationsLoaded extends OperationState { + final List operations; + const OperationsLoaded({required this.operations}); +} + +class OperationLoadingState extends OperationState {} + +class OperationErrorState extends OperationState { + final String message; + const OperationErrorState({required this.message}); +} +class OperationAddedState extends OperationState { + final Map response; + const OperationAddedState({required this.response}); +} +class OperationUpdatedState extends OperationState { + final Map response; + const OperationUpdatedState({required this.response}); +} +class OperationDeletedState extends OperationState{ + final bool success; + const OperationDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/permission/permission_bloc.dart b/lib/bloc/rbac/rbac_operations/permission/permission_bloc.dart new file mode 100644 index 0000000..fe14035 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission/permission_bloc.dart @@ -0,0 +1,81 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/screens/unit2/roles/rbac/add_rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/permission_service.dart'; + +import '../../../../sevices/roles/rbac_operations/object_services.dart'; +import '../../../../sevices/roles/rbac_operations/operation_services.dart'; + +part 'permission_event.dart'; +part 'permission_state.dart'; + +class PermissionBloc extends Bloc { + PermissionBloc() : super(PermissionInitial()) { + List permissions = []; + List objects = []; + List operations = []; + on((event, emit) async { + try { + emit(PermissonLoadingState()); + if (permissions.isEmpty) { + permissions = + await RbacPermissionServices.instance.getRbacPermission(); + } + if (objects.isEmpty) { + objects = await RbacObjectServices.instance.getRbacObjects(); + } + if (operations.isEmpty) { + operations = await RbacOperationServices.instance.getRbacOperations(); + } + emit(PermissionLoaded( + permissions: permissions, + objects: objects, + operations: operations)); + } catch (e) { + emit(PermissionErrorState(message: e.toString())); + } + }); + ////Add + on((event, emit) async { + try { + emit(PermissonLoadingState()); + Map statusResponse = + await RbacPermissionServices.instance.add( + assignerId: event.assignerId, + objectId: event.objectId, + operationsId: event.operationIds); + if (statusResponse['success']) { + statusResponse['data'].forEach((var permission) { + RBACPermission newPermission = RBACPermission.fromJson(permission); + permissions.add(newPermission); + }); + + emit(PermissionAddedState(response: statusResponse)); + } else { + emit(PermissionAddedState(response: statusResponse)); + } + } catch (e) { + emit(PermissionErrorState(message: e.toString())); + } + }); + ////Delete + on((event, emit) async { + emit(PermissonLoadingState()); + try { + bool success = await RbacPermissionServices.instance + .deletePermission(permissionId: event.permissionId); + if (success) { + permissions + .removeWhere((element) => element.id == event.permissionId); + emit(PermissionDeletedState(success: success)); + } else { + emit(PermissionDeletedState(success: success)); + } + } catch (e) { + emit(PermissionErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/permission/permission_event.dart b/lib/bloc/rbac/rbac_operations/permission/permission_event.dart new file mode 100644 index 0000000..c1c2cc3 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission/permission_event.dart @@ -0,0 +1,25 @@ +part of 'permission_bloc.dart'; + +abstract class PermissionEvent extends Equatable { + const PermissionEvent(); + + @override + List get props => []; +} + +class GetPermissions extends PermissionEvent {} + +class AddRbacPermission extends PermissionEvent { + final int objectId; + final List operationIds; + final int assignerId; + const AddRbacPermission( + {required this.assignerId, + required this.objectId, + required this.operationIds}); +} + +class DeleteRbacPermission extends PermissionEvent { + final int permissionId; + const DeleteRbacPermission({required this.permissionId}); +} diff --git a/lib/bloc/rbac/rbac_operations/permission/permission_state.dart b/lib/bloc/rbac/rbac_operations/permission/permission_state.dart new file mode 100644 index 0000000..c8d2487 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission/permission_state.dart @@ -0,0 +1,37 @@ +part of 'permission_bloc.dart'; + +abstract class PermissionState extends Equatable { + const PermissionState(); + + @override + List get props => []; +} + +class PermissionInitial extends PermissionState {} + +class PermissionLoaded extends PermissionState { + final List permissions; + final List objects; + final List operations; + const PermissionLoaded( + {required this.permissions, + required this.objects, + required this.operations}); +} + +class PermissionAddedState extends PermissionState { + final Map response; + const PermissionAddedState({required this.response}); +} + +class PermissonLoadingState extends PermissionState {} + +class PermissionErrorState extends PermissionState { + final String message; + const PermissionErrorState({required this.message}); +} + +class PermissionDeletedState extends PermissionState { + final bool success; + const PermissionDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/role/role_bloc.dart b/lib/bloc/rbac/rbac_operations/role/role_bloc.dart new file mode 100644 index 0000000..5f9980b --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role/role_bloc.dart @@ -0,0 +1,83 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_services.dart'; +part 'role_event.dart'; +part 'role_state.dart'; + +class RoleBloc extends Bloc { + RoleBloc() : super(RoleInitial()) { + List roles = []; + on((event, emit) async { + try { + emit(RoleLoadingState()); + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + emit(RoleLoadedState(roles: roles)); + } catch (e) { + emit(RoleErrorState(message: e.toString())); + } + ////Add + }); + on((event, emit) async { + try { + emit(RoleLoadingState()); + Map statusResponse = await RbacRoleServices.instance + .add( + name: event.name!, + slug: event.slug, + short: event.shorthand, + id: event.id); + if (statusResponse['success']) { + RBAC newRole = RBAC.fromJson(statusResponse['data']); + roles.add(newRole); + emit(RoleAddedState(response: statusResponse)); + } else { + emit(RoleAddedState(response: statusResponse)); + } + } catch (e) { + emit(RoleErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleLoadingState()); + try { + Map statusResponse = await RbacRoleServices.instance + .update( + name: event.name, + slug: event.slug, + short: event.short, + roleId: event.roleId, + createdBy: event.createdBy, + updatedBy: event.updatedBy); + + if (statusResponse['success']) { + roles.removeWhere((element) => element.id == event.roleId); + RBAC newRole = RBAC.fromJson(statusResponse['data']); + roles.add(newRole); + emit(RoleUpdatedState(response: statusResponse)); + } else { + emit(RoleUpdatedState(response: statusResponse)); + } + } catch (e) { + emit(RoleErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleLoadingState()); + try { + bool success = await RbacRoleServices.instance + .deleteRbacRole(roleId: event.roleId); + if (success) { + roles.removeWhere((element) => element.id == event.roleId); + emit(RoleDeletedState(success: success)); + } else { + emit(RoleDeletedState(success: success)); + } + } catch (e) { + emit(RoleErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/role/role_event.dart b/lib/bloc/rbac/rbac_operations/role/role_event.dart new file mode 100644 index 0000000..60987d9 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role/role_event.dart @@ -0,0 +1,45 @@ +part of 'role_bloc.dart'; + +abstract class RoleEvent extends Equatable { + const RoleEvent(); + + @override + List get props => []; +} + +class GetRoles extends RoleEvent {} + +class AddRbacRole extends RoleEvent { + final String? name; + final String? slug; + final String? shorthand; + final int id; + const AddRbacRole( + {required this.id, + required this.name, + required this.shorthand, + required this.slug}); +} + + +class UpdateRbacRole extends RoleEvent { + final int roleId; + final String name; + final String? slug; + final String? short; + final int? createdBy; + final int updatedBy; + const UpdateRbacRole({ + required this.roleId, + required this.createdBy, + required this.name, + required this.short, + required this.slug, + required this.updatedBy, + }); +} + +class DeleteRbacRole extends RoleEvent { + final int roleId; + const DeleteRbacRole({required this.roleId}); +} diff --git a/lib/bloc/rbac/rbac_operations/role/role_state.dart b/lib/bloc/rbac/rbac_operations/role/role_state.dart new file mode 100644 index 0000000..255ce6e --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role/role_state.dart @@ -0,0 +1,37 @@ +part of 'role_bloc.dart'; + +abstract class RoleState extends Equatable { + const RoleState(); + + @override + List get props => []; +} + +class RoleInitial extends RoleState {} + +class RoleLoadedState extends RoleState { + final List roles; + const RoleLoadedState({required this.roles}); +} + +class RoleLoadingState extends RoleState {} + +class RoleErrorState extends RoleState { + final String message; + const RoleErrorState({required this.message}); +} + +class RoleAddedState extends RoleState { + final Map response; + const RoleAddedState({required this.response}); +} +class RoleUpdatedState extends RoleState { + final Map response; + const RoleUpdatedState({required this.response}); +} +class RoleDeletedState extends RoleState{ + final bool success; + const RoleDeletedState({required this.success}); +} + + diff --git a/lib/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart new file mode 100644 index 0000000..f4c75d8 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart @@ -0,0 +1,75 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; +import 'package:unit2/model/rbac/role_extend.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_extend_services.dart'; + +import '../../../../model/rbac/rbac.dart'; +import '../../../../sevices/roles/rbac_operations/role_services.dart'; + +part 'role_extend_event.dart'; +part 'role_extend_state.dart'; + +class RoleExtendBloc extends Bloc { + RoleExtendBloc() : super(RoleExtendInitial()) { + List rolesExtend = []; + List roleExtendIds = []; + List roles = []; + on((event, emit) async { + emit(RoleExtendLoadingState()); + try { + if (rolesExtend.isEmpty) { + rolesExtend = await RbacRoleExtendServices.instance.getRolesExtend(); + } + + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + for (var roleExt in rolesExtend) { + roleExtendIds.add(roleExt.id); + } + emit(RoleExtendLoadedState(rolesExtend: rolesExtend, roles: roles)); + } catch (e) { + emit(RoleExtendErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(RoleExtendLoadingState()); + Map statusResponse = await RbacRoleExtendServices + .instance + .add(roleId: event.roleId, rolesExtendsId: event.roleExtendsId); + + if (statusResponse['success']) { + statusResponse['data'].forEach((var roleExt) { + RolesExtend newRoleExtend = RolesExtend.fromJson(roleExt); + if(!roleExtendIds.contains(newRoleExtend.id)){ + rolesExtend.add(newRoleExtend); + } + }); + emit(RoleExtendAddedState(response: statusResponse)); + } else { + emit(RoleExtendAddedState(response: statusResponse)); + } + } catch (e) { + emit(RoleExtendErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleExtendLoadingState()); + try { + bool success = await RbacRoleExtendServices.instance + .delete(roleExtendId: event.roleExtendId); + if (success) { + rolesExtend + .removeWhere((element) => element.id == event.roleExtendId); + emit(RoleExtendDeletedState(success: success)); + } else { + emit(RoleExtendDeletedState(success: success)); + } + } catch (e) { + emit(RoleExtendErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/role_extend/role_extend_event.dart b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_event.dart new file mode 100644 index 0000000..c0b4637 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_event.dart @@ -0,0 +1,21 @@ +part of 'role_extend_bloc.dart'; + +abstract class RoleExtendEvent extends Equatable { + const RoleExtendEvent(); + + @override + List get props => []; +} + +class GetRoleExtend extends RoleExtendEvent {} + +class DeleteRoleExtend extends RoleExtendEvent { + final int roleExtendId; + const DeleteRoleExtend({required this.roleExtendId}); +} + +class AddRoleExtend extends RoleExtendEvent { + final int roleId; + final List roleExtendsId; + const AddRoleExtend({required this.roleId, required this.roleExtendsId}); +} diff --git a/lib/bloc/rbac/rbac_operations/role_extend/role_extend_state.dart b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_state.dart new file mode 100644 index 0000000..8e788cb --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_extend/role_extend_state.dart @@ -0,0 +1,34 @@ +part of 'role_extend_bloc.dart'; + +abstract class RoleExtendState extends Equatable { + const RoleExtendState(); + + @override + List get props => []; +} + +class RoleExtendInitial extends RoleExtendState {} + +class RoleExtendLoadedState extends RoleExtendState { + final List rolesExtend; + final List roles; + + const RoleExtendLoadedState({required this.rolesExtend, required this.roles}); +} + +class RoleExtendLoadingState extends RoleExtendState {} + +class RoleExtendErrorState extends RoleExtendState { + final String message; + const RoleExtendErrorState({required this.message}); +} + +class RoleExtendAddedState extends RoleExtendState { + final Map response; + const RoleExtendAddedState({required this.response}); +} + +class RoleExtendDeletedState extends RoleExtendState { + final bool success; + const RoleExtendDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart new file mode 100644 index 0000000..3f52bd4 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart @@ -0,0 +1,72 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_module_services.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_services.dart'; +import '../../../../model/rbac/role_module.dart'; +import '../../../../sevices/roles/rbac_operations/module_services.dart'; +part 'role_module_event.dart'; +part 'role_module_state.dart'; + +class RoleModuleBloc extends Bloc { + RoleModuleBloc() : super(RoleModuleInitial()) { + List roleModules = []; + List roles = []; + List modules = []; + on((event, emit) async { + emit(RoleModuleLoadingState()); + try { + if (roleModules.isEmpty) { + roleModules = await RbacRoleModuleServices.instance.getRoleModules(); + } + if (modules.isEmpty) { + modules = await RbacModuleServices.instance.getRbacModule(); + } + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + emit(RoleModuleLoadedState(roleModules: roleModules,modules: modules,roles: roles)); + } catch (e) { + emit(RoleModuleErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(RoleModuleLoadingState()); + Map statusResponse = + await RbacRoleModuleServices.instance.add( + assignerId: event.assignerId, + roleId: event.roleId, + moduleIds: event.moduleIds); + + if (statusResponse['success']) { + statusResponse['data'].forEach((var roleMod) { + RoleModules newRoleModule = RoleModules.fromJson(roleMod); + roleModules.add(newRoleModule); + emit(RoleModuleAddedState(response: statusResponse)); + }); + } else { + emit(RoleModuleAddedState(response: statusResponse)); + } + } catch (e) { + emit(RoleModuleErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleModuleLoadingState()); + try { + bool success = await RbacRoleModuleServices.instance + .deleteRbacRoleModule(moduleObjectId: event.roleModuleId); + if (success) { + roleModules + .removeWhere((element) => element.id == event.roleModuleId); + emit(RoleModuleDeletedState(success: success)); + } else { + RoleModuleDeletedState(success: success); + } + } catch (e) { + emit(RoleModuleErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_event.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_event.dart new file mode 100644 index 0000000..b0cfa8a --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_event.dart @@ -0,0 +1,25 @@ +part of 'role_module_bloc.dart'; + +abstract class RoleModuleEvent extends Equatable { + const RoleModuleEvent(); + + @override + List get props => []; +} + +class GetRoleModules extends RoleModuleEvent {} + +class DeleteRoleModule extends RoleModuleEvent { + final int roleModuleId; + const DeleteRoleModule({required this.roleModuleId}); +} + +class AddRoleModule extends RoleModuleEvent { + final int roleId; + final List moduleIds; + final int assignerId; + const AddRoleModule( + {required this.assignerId, + required this.roleId, + required this.moduleIds}); +} diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_state.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_state.dart new file mode 100644 index 0000000..733d56c --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_state.dart @@ -0,0 +1,36 @@ +part of 'role_module_bloc.dart'; + +abstract class RoleModuleState extends Equatable { + const RoleModuleState(); + + @override + List get props => []; +} + +class RoleModuleInitial extends RoleModuleState {} + +class RoleModuleLoadedState extends RoleModuleState { + final List roleModules; + final List roles; + final List modules; + + const RoleModuleLoadedState( + {required this.roleModules, required this.modules, required this.roles}); +} + +class RoleModuleLoadingState extends RoleModuleState {} + +class RoleModuleErrorState extends RoleModuleState { + final String message; + const RoleModuleErrorState({required this.message}); +} + +class RoleModuleAddedState extends RoleModuleState { + final Map response; + const RoleModuleAddedState({required this.response}); +} + +class RoleModuleDeletedState extends RoleModuleState { + final bool success; + const RoleModuleDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart new file mode 100644 index 0000000..f8fc508 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart @@ -0,0 +1,67 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/role_under.dart'; +import 'package:unit2/sevices/roles/rbac_operations/roles_under_services.dart'; + +import '../../../../model/rbac/rbac.dart'; +import '../../../../sevices/roles/rbac_operations/role_services.dart'; + +part 'roles_under_event.dart'; +part 'roles_under_state.dart'; + +class RolesUnderBloc extends Bloc { + RolesUnderBloc() : super(RolesUnderInitial()) { + List rolesUnder = []; + List roles = []; + on((event, emit) async { + emit(RoleUnderLoadingState()); + try { + if (rolesUnder.isEmpty) { + rolesUnder = await RbacRoleUnderServices.instance.getRolesUnder(); + } + + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + emit(RoleUnderLoadedState(rolesUnder: rolesUnder, roles: roles)); + } catch (e) { + emit(RoleUnderErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(RoleUnderLoadingState()); + Map statusResponse = await RbacRoleUnderServices + .instance + .add(roleId: event.roleId, rolesId: event.roleUnderIds); + + if (statusResponse['success']) { + statusResponse['data'].forEach((var roleMod) { + RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod); + rolesUnder.add(newRoleUnder); + emit(RoleUnderAddedState(response: statusResponse)); + }); + } else { + emit(RoleUnderAddedState(response: statusResponse)); + } + } catch (e) { + emit(RoleUnderErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleUnderLoadingState()); + try { + bool success = await RbacRoleUnderServices.instance + .deleteRbacRoleUnder(roleUnderId: event.roleUnderId); + if (success) { + rolesUnder.removeWhere((element) => element.id == event.roleUnderId); + emit(RoleUnderDeletedState(success: success)); + } else { + emit(RoleUnderDeletedState(success: success)); + } + } catch (e) { + emit(RoleUnderErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_event.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_event.dart new file mode 100644 index 0000000..3c17f46 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_event.dart @@ -0,0 +1,21 @@ +part of 'roles_under_bloc.dart'; + +abstract class RolesUnderEvent extends Equatable { + const RolesUnderEvent(); + + @override + List get props => []; +} + +class GetRolesUnder extends RolesUnderEvent {} + +class DeleteRoleUnder extends RolesUnderEvent { + final int roleUnderId; + const DeleteRoleUnder({required this.roleUnderId}); +} + +class AddRoleUnder extends RolesUnderEvent{ + final int roleId; + final List roleUnderIds; + const AddRoleUnder({required this.roleId, required this.roleUnderIds}); +} diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_state.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_state.dart new file mode 100644 index 0000000..0263414 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_state.dart @@ -0,0 +1,34 @@ +part of 'roles_under_bloc.dart'; + +abstract class RolesUnderState extends Equatable { + const RolesUnderState(); + + @override + List get props => []; +} + +class RolesUnderInitial extends RolesUnderState {} + +class RoleUnderLoadedState extends RolesUnderState { + final List rolesUnder; + final List roles; + + const RoleUnderLoadedState({required this.rolesUnder, required this.roles}); +} + +class RoleUnderLoadingState extends RolesUnderState {} + +class RoleUnderErrorState extends RolesUnderState { + final String message; + const RoleUnderErrorState({required this.message}); +} + +class RoleUnderAddedState extends RolesUnderState { + final Map response; + const RoleUnderAddedState({required this.response}); +} + +class RoleUnderDeletedState extends RolesUnderState { + final bool success; + const RoleUnderDeletedState({required this.success}); +} diff --git a/lib/bloc/rbac/rbac_operations/station/station_bloc.dart b/lib/bloc/rbac/rbac_operations/station/station_bloc.dart new file mode 100644 index 0000000..2dec814 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/station/station_bloc.dart @@ -0,0 +1,47 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/rbac_station.dart'; +import 'package:unit2/sevices/roles/rbac_operations/station_services.dart'; +import '../../../../model/utils/agency.dart'; +import '../../../../utils/profile_utilities.dart'; +part 'station_event.dart'; +part 'station_state.dart'; + +class StationBloc extends Bloc { + StationBloc() : super(StationInitial()) { + List stations = []; + List agencies = []; + on((event, emit) async { + emit(StationLoadingState()); + try { + stations = await RbacStationServices.instance + .getStations(agencyId: event.agencyId); + + if (agencies.isEmpty) { + List newAgencies = + await ProfileUtilities.instance.getAgecies(); + agencies = newAgencies; + } + emit(StationLoadedState(stations: stations, agencies: agencies)); + } catch (e) { + emit(StationErrorState(message: e.toString())); + } + }); + on((event, emit)async { + // emit(StationLoadingState()); + try { + stations = await RbacStationServices.instance + .getStations(agencyId: event.agencyId); + + if (agencies.isEmpty) { + List newAgencies = + await ProfileUtilities.instance.getAgecies(); + agencies = newAgencies; + } + emit(StationLoadedState(stations: stations, agencies: agencies)); + } catch (e) { + emit(StationErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/station/station_event.dart b/lib/bloc/rbac/rbac_operations/station/station_event.dart new file mode 100644 index 0000000..ea2c989 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/station/station_event.dart @@ -0,0 +1,18 @@ +part of 'station_bloc.dart'; + +abstract class StationEvent extends Equatable { + const StationEvent(); + + @override + List get props => []; +} + +class GetStations extends StationEvent { + final int agencyId; + const GetStations({required this.agencyId}); +} + +class FilterStation extends StationEvent { + final int agencyId; + const FilterStation({required this.agencyId}); +} diff --git a/lib/bloc/rbac/rbac_operations/station/station_state.dart b/lib/bloc/rbac/rbac_operations/station/station_state.dart new file mode 100644 index 0000000..7ab511f --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/station/station_state.dart @@ -0,0 +1,32 @@ +part of 'station_bloc.dart'; + +abstract class StationState extends Equatable { + const StationState(); + + @override + List get props => []; +} + +class StationInitial extends StationState {} + +class StationLoadedState extends StationState { + final List agencies; + final List stations; + const StationLoadedState({required this.stations, required this.agencies}); + @override + List get props => [agencies,stations]; +} + +class StationLoadingState extends StationState {} + +class StationErrorState extends StationState { + final String message; + const StationErrorState({required this.message}); + @override + List get props => [message]; +} + +class FilterStationState extends StationState { + final int agencyId; + const FilterStationState({required this.agencyId}); +} diff --git a/lib/bloc/rbac/rbac_state.dart b/lib/bloc/rbac/rbac_state.dart new file mode 100644 index 0000000..6c793a5 --- /dev/null +++ b/lib/bloc/rbac/rbac_state.dart @@ -0,0 +1,36 @@ +part of 'rbac_bloc.dart'; + +abstract class RbacState extends Equatable { + const RbacState(); + + @override + List get props => []; +} + +class RbacInitial extends RbacState {} + +class RbacScreenSetted extends RbacState { + final List modules; + final List objects; + final List role; + final List permission; + final List operations; + const RbacScreenSetted( + {required this.modules, + required this.objects, + required this.operations, + required this.permission, + required this.role}); +} + +class RbacLoadingState extends RbacState {} + +class RbacErrorState extends RbacState { + final String message; + const RbacErrorState({required this.message}); +} + +class RbacAssignedState extends RbacState{ +final Map responseStatus; + const RbacAssignedState({required this.responseStatus}); +} diff --git a/lib/bloc/role/pass_check/pass_check_bloc.dart b/lib/bloc/role/pass_check/pass_check_bloc.dart index c1d157a..9458357 100644 --- a/lib/bloc/role/pass_check/pass_check_bloc.dart +++ b/lib/bloc/role/pass_check/pass_check_bloc.dart @@ -22,15 +22,15 @@ class PassCheckBloc extends Bloc { int? stationId; String? cpId; on((event, emit) async { - try { + // try { emit(PassCheckLoadingState()); List response = await PassCheckServices.instance .getPassCheckArea(roleId: event.roleId, userId: event.userId); roleId = event.roleId; emit(AssignAreaLoaded(assignedArea: response, roleId: roleId!)); - } catch (e) { - emit(PassCheckErrorState(message: e.toString())); - } + // } catch (e) { + // emit(PassCheckErrorState(message: e.toString())); + // } }); on((event, emit) { otherInputs = event.includeOtherInputs; diff --git a/lib/bloc/role_assignment/role_assignment_bloc.dart b/lib/bloc/role_assignment/role_assignment_bloc.dart new file mode 100644 index 0000000..2d75f2d --- /dev/null +++ b/lib/bloc/role_assignment/role_assignment_bloc.dart @@ -0,0 +1,96 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/sevices/roles/rbac_services.dart'; + +import '../../model/profile/basic_information/primary-information.dart'; +import '../../model/rbac/assigned_role.dart'; +import '../../model/rbac/rbac.dart'; +import '../../sevices/roles/rbac_operations/role_assignment_services.dart'; +import '../../sevices/roles/rbac_operations/role_services.dart'; + +part 'role_assignment_event.dart'; +part 'role_assignment_state.dart'; + +class RoleAssignmentBloc + extends Bloc { + RoleAssignmentBloc() : super(RoleAssignmentInitial()) { + List assignedRoles = []; + int userId; + String? fname; + String? lname; + String? fullname; + Profile? profile; + 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) { + assignedRoles = await RbacRoleAssignmentServices.instance + .getAssignedRoles( + firstname: event.firstname, lastname: event.lastname); + + 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())); + } + }); + on((event, emit) { + emit(AssignedRoleLoaded( + assignedRoles: assignedRoles, fullname: fullname!, roles: roles)); + }); + on((event, emit) async { + emit(RoleAssignmentLoadingState()); + try { + bool success = await RbacRoleAssignmentServices.instance + .deleteAssignedRole(roleId: event.roleId); + if (success) { + assignedRoles.removeWhere((element) => element.id == event.roleId); + emit(AssignedRoleDeletedState(success: success)); + } else { + emit(AssignedRoleDeletedState(success: success)); + } + } catch (e) { + emit(RoleAssignmentErrorState(message: e.toString())); + } + }); + on((event, emit) async { + emit(RoleAssignmentLoadingState()); + try { + Map statusResponse = + await RbacRoleAssignmentServices.instance.add( + userId: profile!.webuserId!, + assignerId: event.assignerId, + roles: event.roles); + if (statusResponse['success']) { + assignedRoles = []; + statusResponse['data'].forEach((var roles) { + AssignedRole newAssignRole = AssignedRole.fromJson(roles); + if (!event.roles.contains(newAssignRole.id)) { + assignedRoles.add(newAssignRole); + } + }); + emit(AssignedRoleAddedState(response: statusResponse)); + } else { + emit(AssignedRoleAddedState(response: statusResponse)); + } + } catch (e) { + emit(RoleAssignmentErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/role_assignment/role_assignment_event.dart b/lib/bloc/role_assignment/role_assignment_event.dart new file mode 100644 index 0000000..016ce40 --- /dev/null +++ b/lib/bloc/role_assignment/role_assignment_event.dart @@ -0,0 +1,28 @@ +part of 'role_assignment_bloc.dart'; + +abstract class RoleAssignmentEvent extends Equatable { + const RoleAssignmentEvent(); + + @override + List get props => []; +} + +class GetAssignedRoles extends RoleAssignmentEvent { + final String firstname; + final String lastname; + const GetAssignedRoles({required this.firstname, required this.lastname}); +} + +class DeleteAssignRole extends RoleAssignmentEvent { + final int roleId; + const DeleteAssignRole({required this.roleId}); +} + +class LoadAssignedRole extends RoleAssignmentEvent {} + +class AssignRole extends RoleAssignmentEvent { + final List roles; + final int assignerId; + const AssignRole( + {required this.assignerId, required this.roles}); +} diff --git a/lib/bloc/role_assignment/role_assignment_state.dart b/lib/bloc/role_assignment/role_assignment_state.dart new file mode 100644 index 0000000..98dc25a --- /dev/null +++ b/lib/bloc/role_assignment/role_assignment_state.dart @@ -0,0 +1,37 @@ +part of 'role_assignment_bloc.dart'; + +abstract class RoleAssignmentState extends Equatable { + const RoleAssignmentState(); + + @override + List get props => []; +} + +class RoleAssignmentInitial extends RoleAssignmentState {} + +class AssignedRoleLoaded extends RoleAssignmentState { + final String fullname; + final List assignedRoles; + final List roles; + const AssignedRoleLoaded( + {required this.assignedRoles, required this.fullname, required this.roles}); +} + +class RoleAssignmentLoadingState extends RoleAssignmentState {} + +class RoleAssignmentErrorState extends RoleAssignmentState { + final String message; + const RoleAssignmentErrorState({required this.message}); +} +class UserNotExistError extends RoleAssignmentState{ + +} +class AssignedRoleDeletedState extends RoleAssignmentState { + final bool success; + const AssignedRoleDeletedState({required this.success}); +} + +class AssignedRoleAddedState extends RoleAssignmentState { + final Map response; + const AssignedRoleAddedState({required this.response}); +} diff --git a/lib/main.dart b/lib/main.dart index b7f782d..35e1207 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,7 +7,6 @@ import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hive/hive.dart'; import 'package:hive_flutter/hive_flutter.dart'; -import 'package:unit2/bloc/passo/property_info/property_info_bloc.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; import 'package:unit2/bloc/user/user_bloc.dart'; import 'package:unit2/theme-data.dart/colors.dart'; @@ -65,8 +64,6 @@ class MyApp extends StatelessWidget { BlocProvider( create: (_) => ProfileBloc(), ), - BlocProvider( - create: (context) => PropertyInfoBloc()..add(LoadPropertyInfo())), ], child: MaterialApp( navigatorKey: NavigationService.navigatorKey, diff --git a/lib/model/login_data/user_info/module.dart b/lib/model/login_data/user_info/module.dart index 700d9a5..a72f278 100644 --- a/lib/model/login_data/user_info/module.dart +++ b/lib/model/login_data/user_info/module.dart @@ -11,7 +11,7 @@ class Module { String? icon; String? name; String? slug; - List? objects; + List? objects; factory Module.fromJson(Map json) => Module( id: json["id"], @@ -20,8 +20,8 @@ class Module { slug: json["slug"], objects: json["objects"] == null ? [] - : List.from( - json["objects"]!.map((x) => Object.fromJson(x))), + : List.from( + json["objects"]!.map((x) => ModuleObject.fromJson(x))), ); Map toJson() => { @@ -35,8 +35,8 @@ class Module { }; } -class Object { - Object({ +class ModuleObject { + ModuleObject({ this.id, this.name, this.slug, @@ -48,7 +48,7 @@ class Object { String? slug; List? operations; - factory Object.fromJson(Map json) => Object( + factory ModuleObject.fromJson(Map json) => ModuleObject( id: json["id"], name: json["name"], slug: json["slug"], diff --git a/lib/model/login_data/user_info/role.dart b/lib/model/login_data/user_info/role.dart index ef371f7..ff7c545 100644 --- a/lib/model/login_data/user_info/role.dart +++ b/lib/model/login_data/user_info/role.dart @@ -41,34 +41,4 @@ class Role { ? [] : List.from(assignedArea!.map((x) => x!.toJson())), }; -}class Object { - Object({ - this.id, - this.name, - this.slug, - this.operations, - }); - - int? id; - String? name; - String? slug; - List? operations; - - factory Object.fromJson(Map json) => Object( - id: json["id"], - name: json["name"], - slug: json["slug"], - operations: json["operations"] == null - ? [] - : List.from(json["operations"]!.map((x) => x)), - ); - - Map toJson() => { - "id": id, - "name": name, - "slug": slug, - "operations": operations == null - ? [] - : List.from(operations!.map((x) => x)), - }; } \ No newline at end of file diff --git a/lib/model/passo/barangay.dart b/lib/model/passo/barangay.dart new file mode 100644 index 0000000..6dacfa1 --- /dev/null +++ b/lib/model/passo/barangay.dart @@ -0,0 +1,37 @@ +// To parse this JSON data, do +// +// final barangay = barangayFromJson(jsonString); + +import 'dart:convert'; + +Brgy barangayFromJson(String str) => Brgy.fromJson(json.decode(str)); + +String barangayToJson(Brgy data) => json.encode(data.toJson()); + +class Brgy { + final int? barangayId; + final String? barangayCode; + final String? cityCode; + final String? barangayDescription; + + Brgy({ + this.barangayId, + this.barangayCode, + this.cityCode, + this.barangayDescription, + }); + + factory Brgy.fromJson(Map json) => Brgy( + barangayId: json["barangay_id"], + barangayCode: json["barangay_code"], + cityCode: json["city_code"], + barangayDescription: json["barangay_description"], + ); + + Map toJson() => { + "barangay_id": barangayId, + "barangay_code": barangayCode, + "city_code": cityCode, + "barangay_description": barangayDescription, + }; +} diff --git a/lib/model/passo/bldg_loc.dart b/lib/model/passo/bldg_loc.dart index 0e9e80d..06714fb 100644 --- a/lib/model/passo/bldg_loc.dart +++ b/lib/model/passo/bldg_loc.dart @@ -9,25 +9,41 @@ BldgLoc bldgLocFromJson(String str) => BldgLoc.fromJson(json.decode(str)); String bldgLocToJson(BldgLoc data) => json.encode(data.toJson()); class BldgLoc { + final int? id; + final int? bldgapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final dynamic street; + final dynamic barangay; + final dynamic municipality; + final dynamic province; + BldgLoc({ this.id, this.bldgapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, this.street, this.barangay, this.municipality, this.province, }); - final int? id; - final int? bldgapprDetailsId; - final String? street; - final String? barangay; - final String? municipality; - final String? province; - factory BldgLoc.fromJson(Map json) => BldgLoc( id: json["id"], bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), street: json["street"], barangay: json["barangay"], municipality: json["municipality"], @@ -37,6 +53,10 @@ class BldgLoc { Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), "street": street, "barangay": barangay, "municipality": municipality, diff --git a/lib/model/passo/city.dart b/lib/model/passo/city.dart new file mode 100644 index 0000000..eb22f22 --- /dev/null +++ b/lib/model/passo/city.dart @@ -0,0 +1,29 @@ +// To parse this JSON data, do +// +// final city = cityFromJson(jsonString); + +import 'dart:convert'; + +City cityFromJson(String str) => City.fromJson(json.decode(str)); + +String cityToJson(City data) => json.encode(data.toJson()); + +class City { + final String? cityCode; + final String? cityDescription; + + City({ + this.cityCode, + this.cityDescription, + }); + + factory City.fromJson(Map json) => City( + cityCode: json["city_code"], + cityDescription: json["city_description"], + ); + + Map toJson() => { + "city_code": cityCode, + "city_description": cityDescription, + }; +} diff --git a/lib/model/passo/general_description.dart b/lib/model/passo/general_description.dart new file mode 100644 index 0000000..68002a5 --- /dev/null +++ b/lib/model/passo/general_description.dart @@ -0,0 +1,137 @@ +// To parse this JSON data, do +// +// final generalDesc = generalDescFromJson(jsonString); + +import 'dart:convert'; + +GeneralDesc generalDescFromJson(String str) => + GeneralDesc.fromJson(json.decode(str)); + +String generalDescToJson(GeneralDesc data) => json.encode(data.toJson()); + +class GeneralDesc { + final int? id; + final int? bldgapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final String? bldgKind; + final String? strucType; + final String? bldgPermit; + final DateTime? dateIssued; + final String? cct; + final DateTime? certCompletionIssued; + final DateTime? certOccupancyIssued; + final DateTime? dateCompleted; + final DateTime? dateOccupied; + final int? bldgAge; + final int? noStoreys; + final String? area1Stfloor; + final String? area2Ndfloor; + final String? area3Rdfloor; + final String? area4Thfloor; + final String? totalFloorArea; + final dynamic floorSketch; + final String? actualUse; + + GeneralDesc({ + this.id, + this.bldgapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.bldgKind, + this.strucType, + this.bldgPermit, + this.dateIssued, + this.cct, + this.certCompletionIssued, + this.certOccupancyIssued, + this.dateCompleted, + this.dateOccupied, + this.bldgAge, + this.noStoreys, + this.area1Stfloor, + this.area2Ndfloor, + this.area3Rdfloor, + this.area4Thfloor, + this.totalFloorArea, + this.floorSketch, + this.actualUse, + }); + + factory GeneralDesc.fromJson(Map json) => GeneralDesc( + id: json["id"], + bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), + bldgKind: json["bldg_kind"], + strucType: json["struc_type"], + bldgPermit: json["bldg_permit"], + dateIssued: json["date_issued"] == null + ? null + : DateTime.parse(json["date_issued"]), + cct: json["cct"], + certCompletionIssued: json["cert_completion_issued"] == null + ? null + : DateTime.parse(json["cert_completion_issued"]), + certOccupancyIssued: json["cert_occupancy_issued"] == null + ? null + : DateTime.parse(json["cert_occupancy_issued"]), + dateCompleted: json["date_completed"] == null + ? null + : DateTime.parse(json["date_completed"]), + dateOccupied: json["date_occupied"] == null + ? null + : DateTime.parse(json["date_occupied"]), + bldgAge: json["bldg_age"], + noStoreys: json["no_storeys"], + area1Stfloor: json["area_1stfloor"], + area2Ndfloor: json["area_2ndfloor"], + area3Rdfloor: json["area_3rdfloor"], + area4Thfloor: json["area_4thfloor"], + totalFloorArea: json["total_floor_area"], + floorSketch: json["floor_sketch"], + actualUse: json["actual_use"], + ); + + Map toJson() => { + "id": id, + "bldgappr_details_id": bldgapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), + "bldg_kind": bldgKind, + "struc_type": strucType, + "bldg_permit": bldgPermit, + "date_issued": + "${dateIssued!.year.toString().padLeft(4, '0')}-${dateIssued!.month.toString().padLeft(2, '0')}-${dateIssued!.day.toString().padLeft(2, '0')}", + "cct": cct, + "cert_completion_issued": + "${certCompletionIssued!.year.toString().padLeft(4, '0')}-${certCompletionIssued!.month.toString().padLeft(2, '0')}-${certCompletionIssued!.day.toString().padLeft(2, '0')}", + "cert_occupancy_issued": + "${certOccupancyIssued!.year.toString().padLeft(4, '0')}-${certOccupancyIssued!.month.toString().padLeft(2, '0')}-${certOccupancyIssued!.day.toString().padLeft(2, '0')}", + "date_completed": + "${dateCompleted!.year.toString().padLeft(4, '0')}-${dateCompleted!.month.toString().padLeft(2, '0')}-${dateCompleted!.day.toString().padLeft(2, '0')}", + "date_occupied": + "${dateOccupied!.year.toString().padLeft(4, '0')}-${dateOccupied!.month.toString().padLeft(2, '0')}-${dateOccupied!.day.toString().padLeft(2, '0')}", + "bldg_age": bldgAge, + "no_storeys": noStoreys, + "area_1stfloor": area1Stfloor, + "area_2ndfloor": area2Ndfloor, + "area_3rdfloor": area3Rdfloor, + "area_4thfloor": area4Thfloor, + "total_floor_area": totalFloorArea, + "floor_sketch": floorSketch, + "actual_use": actualUse, + }; +} diff --git a/lib/model/passo/land_appr.dart b/lib/model/passo/land_appr.dart new file mode 100644 index 0000000..91e9b1b --- /dev/null +++ b/lib/model/passo/land_appr.dart @@ -0,0 +1,49 @@ +// To parse this JSON data, do +// +// final landAppr = landApprFromJson(jsonString); + +import 'dart:convert'; + +LandAppr landApprFromJson(String str) => LandAppr.fromJson(json.decode(str)); + +String landApprToJson(LandAppr data) => json.encode(data.toJson()); + +class LandAppr { + final int? id; + final int? landapprDetailsId; + final String? classification; + final String? subClass; + final String? area; + final String? unitValue; + final String? baseMarketval; + + LandAppr({ + this.id, + this.landapprDetailsId, + this.classification, + this.subClass, + this.area, + this.unitValue, + this.baseMarketval, + }); + + factory LandAppr.fromJson(Map json) => LandAppr( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + classification: json["classification"], + subClass: json["sub_class"], + area: json["area"], + unitValue: json["unit_value"], + baseMarketval: json["base_marketval"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "classification": classification, + "sub_class": subClass, + "area": area, + "unit_value": unitValue, + "base_marketval": baseMarketval, + }; +} diff --git a/lib/model/passo/land_classification.dart b/lib/model/passo/land_classification.dart new file mode 100644 index 0000000..0315271 --- /dev/null +++ b/lib/model/passo/land_classification.dart @@ -0,0 +1,36 @@ +// To parse this JSON data, do +// +// final landClassification = landClassificationFromJson(jsonString); + +import 'dart:convert'; + +LandClassification landClassificationFromJson(String str) => + LandClassification.fromJson(json.decode(str)); + +String landClassificationToJson(LandClassification data) => + json.encode(data.toJson()); + +class LandClassification { + final int? id; + final String? classificationCode; + final String? description; + + LandClassification({ + this.id, + this.classificationCode, + this.description, + }); + + factory LandClassification.fromJson(Map json) => + LandClassification( + id: json["id"], + classificationCode: json["classification_code"], + description: json["description"], + ); + + Map toJson() => { + "id": id, + "classification_code": classificationCode, + "description": description, + }; +} diff --git a/lib/model/passo/land_ext.dart b/lib/model/passo/land_ext.dart new file mode 100644 index 0000000..5c935f8 --- /dev/null +++ b/lib/model/passo/land_ext.dart @@ -0,0 +1,124 @@ +// To parse this JSON data, do +// +// final landExt = landExtFromJson(jsonString); + +import 'dart:convert'; + +LandExt landExtFromJson(String str) => LandExt.fromJson(json.decode(str)); + +String landExtToJson(LandExt data) => json.encode(data.toJson()); + +class LandExt { + final int? id; + final int? landapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final bool? taxable; + final bool? exempt; + final int? qtr; + final int? yr; + final String? appraisedbyName; + final DateTime? appraisedbyDate; + final String? recommendapprName; + final DateTime? recommendapprDate; + final String? approvedbyName; + final DateTime? approvedbyDate; + final String? memoranda; + final String? swornstatementNo; + final DateTime? dateReceived; + final DateTime? entryDateAssessment; + final String? entryDateBy; + + LandExt({ + this.id, + this.landapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.taxable, + this.exempt, + this.qtr, + this.yr, + this.appraisedbyName, + this.appraisedbyDate, + this.recommendapprName, + this.recommendapprDate, + this.approvedbyName, + this.approvedbyDate, + this.memoranda, + this.swornstatementNo, + this.dateReceived, + this.entryDateAssessment, + this.entryDateBy, + }); + + factory LandExt.fromJson(Map json) => LandExt( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), + taxable: json["taxable"], + exempt: json["exempt"], + qtr: json["qtr"], + yr: json["yr"], + appraisedbyName: json["appraisedby_name"], + appraisedbyDate: json["appraisedby_date"] == null + ? null + : DateTime.parse(json["appraisedby_date"]), + recommendapprName: json["recommendappr_name"], + recommendapprDate: json["recommendappr_date"] == null + ? null + : DateTime.parse(json["recommendappr_date"]), + approvedbyName: json["approvedby_name"], + approvedbyDate: json["approvedby_date"] == null + ? null + : DateTime.parse(json["approvedby_date"]), + memoranda: json["memoranda"], + swornstatementNo: json["swornstatement_no"], + dateReceived: json["date_received"] == null + ? null + : DateTime.parse(json["date_received"]), + entryDateAssessment: json["entry_date_assessment"] == null + ? null + : DateTime.parse(json["entry_date_assessment"]), + entryDateBy: json["entry_date_by"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), + "taxable": taxable, + "exempt": exempt, + "qtr": qtr, + "yr": yr, + "appraisedby_name": appraisedbyName, + "appraisedby_date": + "${appraisedbyDate!.year.toString().padLeft(4, '0')}-${appraisedbyDate!.month.toString().padLeft(2, '0')}-${appraisedbyDate!.day.toString().padLeft(2, '0')}", + "recommendappr_name": recommendapprName, + "recommendappr_date": + "${recommendapprDate!.year.toString().padLeft(4, '0')}-${recommendapprDate!.month.toString().padLeft(2, '0')}-${recommendapprDate!.day.toString().padLeft(2, '0')}", + "approvedby_name": approvedbyName, + "approvedby_date": + "${approvedbyDate!.year.toString().padLeft(4, '0')}-${approvedbyDate!.month.toString().padLeft(2, '0')}-${approvedbyDate!.day.toString().padLeft(2, '0')}", + "memoranda": memoranda, + "swornstatement_no": swornstatementNo, + "date_received": + "${dateReceived!.year.toString().padLeft(4, '0')}-${dateReceived!.month.toString().padLeft(2, '0')}-${dateReceived!.day.toString().padLeft(2, '0')}", + "entry_date_assessment": + "${entryDateAssessment!.year.toString().padLeft(4, '0')}-${entryDateAssessment!.month.toString().padLeft(2, '0')}-${entryDateAssessment!.day.toString().padLeft(2, '0')}", + "entry_date_by": entryDateBy, + }; +} diff --git a/lib/model/passo/land_property_assessment.dart b/lib/model/passo/land_property_assessment.dart new file mode 100644 index 0000000..cbab632 --- /dev/null +++ b/lib/model/passo/land_property_assessment.dart @@ -0,0 +1,56 @@ +// To parse this JSON data, do +// +// final landPropertyAssessment = landPropertyAssessmentFromJson(jsonString); + +import 'dart:convert'; + +LandPropertyAssessment landPropertyAssessmentFromJson(String str) => + LandPropertyAssessment.fromJson(json.decode(str)); + +String landPropertyAssessmentToJson(LandPropertyAssessment data) => + json.encode(data.toJson()); + +class LandPropertyAssessment { + final int? id; + final int? landapprDetailsId; + final String? actualUse; + final String? marketval; + final String? assessmentLevel; + final String? assessedValue; + final String? totalMarketval; + final String? totalAssessedval; + + LandPropertyAssessment({ + this.id, + this.landapprDetailsId, + this.actualUse, + this.marketval, + this.assessmentLevel, + this.assessedValue, + this.totalMarketval, + this.totalAssessedval, + }); + + factory LandPropertyAssessment.fromJson(Map json) => + LandPropertyAssessment( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + actualUse: json["actual_use"], + marketval: json["marketval"], + assessmentLevel: json["assessment_level"], + assessedValue: json["assessed_value"], + totalMarketval: json["total_marketval"], + totalAssessedval: json["total_assessedval"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "actual_use": actualUse, + "marketval": marketval, + "assessment_level": assessmentLevel, + "assessed_value": assessedValue, + "total_marketval": totalMarketval, + "total_assessedval": totalAssessedval, + }; +} diff --git a/lib/model/passo/land_property_boundaries.dart b/lib/model/passo/land_property_boundaries.dart new file mode 100644 index 0000000..49a3ada --- /dev/null +++ b/lib/model/passo/land_property_boundaries.dart @@ -0,0 +1,72 @@ +// To parse this JSON data, do +// +// final landPropertyBoundaries = landPropertyBoundariesFromJson(jsonString); + +import 'dart:convert'; + +LandPropertyBoundaries landPropertyBoundariesFromJson(String str) => + LandPropertyBoundaries.fromJson(json.decode(str)); + +String landPropertyBoundariesToJson(LandPropertyBoundaries data) => + json.encode(data.toJson()); + +class LandPropertyBoundaries { + final int? id; + final int? landapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final String? north; + final String? east; + final String? south; + final String? west; + final dynamic sketch; + + LandPropertyBoundaries({ + this.id, + this.landapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.north, + this.east, + this.south, + this.west, + this.sketch, + }); + + factory LandPropertyBoundaries.fromJson(Map json) => + LandPropertyBoundaries( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), + north: json["north"], + east: json["east"], + south: json["south"], + west: json["west"], + sketch: json["sketch"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), + "north": north, + "east": east, + "south": south, + "west": west, + "sketch": sketch, + }; +} diff --git a/lib/model/passo/land_property_loc.dart b/lib/model/passo/land_property_loc.dart new file mode 100644 index 0000000..25a7466 --- /dev/null +++ b/lib/model/passo/land_property_loc.dart @@ -0,0 +1,68 @@ +// To parse this JSON data, do +// +// final lnadPropertyLoc = lnadPropertyLocFromJson(jsonString); + +import 'dart:convert'; + +LandPropertyLoc lnadPropertyLocFromJson(String str) => + LandPropertyLoc.fromJson(json.decode(str)); + +String lnadPropertyLocToJson(LandPropertyLoc data) => + json.encode(data.toJson()); + +class LandPropertyLoc { + final int? id; + final int? landapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final String? street; + final String? municipality; + final String? barangay; + final String? province; + + LandPropertyLoc({ + this.id, + this.landapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.street, + this.municipality, + this.barangay, + this.province, + }); + + factory LandPropertyLoc.fromJson(Map json) => + LandPropertyLoc( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), + street: json["street"], + municipality: json["municipality"], + barangay: json["barangay"], + province: json["province"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), + "street": street, + "municipality": municipality, + "barangay": barangay, + "province": province, + }; +} diff --git a/lib/model/passo/land_property_owner.dart b/lib/model/passo/land_property_owner.dart new file mode 100644 index 0000000..9c644af --- /dev/null +++ b/lib/model/passo/land_property_owner.dart @@ -0,0 +1,117 @@ +// To parse this JSON data, do +// +// final landPropertyOwner = landPropertyOwnerFromJson(jsonString); + +import 'dart:convert'; + +LandPropertyOwner landPropertyOwnerFromJson(String str) => + LandPropertyOwner.fromJson(json.decode(str)); + +String landPropertyOwnerToJson(LandPropertyOwner data) => + json.encode(data.toJson()); + +class LandPropertyOwner { + final int? id; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final String? transCode; + final String? tdn; + final String? pin; + final String? cloaNo; + final DateTime? dated; + final String? surveyNo; + final String? lotNo; + final String? blkNo; + final String? owner; + final String? address; + final String? telno; + final String? tin; + final String? adminUser; + final String? adminAddress; + final String? adminTelno; + final String? adminTin; + final String? faasType; + + LandPropertyOwner({ + this.id, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.transCode, + this.tdn, + this.pin, + this.cloaNo, + this.dated, + this.surveyNo, + this.lotNo, + this.blkNo, + this.owner, + this.address, + this.telno, + this.tin, + this.adminUser, + this.adminAddress, + this.adminTelno, + this.adminTin, + this.faasType, + }); + + factory LandPropertyOwner.fromJson(Map json) => + LandPropertyOwner( + id: json["id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), + transCode: json["trans_code"], + tdn: json["tdn"], + pin: json["pin"], + cloaNo: json["cloa_no"], + dated: json["dated"] == null ? null : DateTime.parse(json["dated"]), + surveyNo: json["survey_no"], + lotNo: json["lot_no"], + blkNo: json["blk_no"], + owner: json["owner"], + address: json["address"], + telno: json["telno"], + tin: json["tin"], + adminUser: json["admin_user"], + adminAddress: json["admin_address"], + adminTelno: json["admin_telno"], + adminTin: json["admin_tin"], + faasType: json["faas_type"], + ); + + Map toJson() => { + "id": id, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), + "trans_code": transCode, + "tdn": tdn, + "pin": pin, + "cloa_no": cloaNo, + "dated": + "${dated!.year.toString().padLeft(4, '0')}-${dated!.month.toString().padLeft(2, '0')}-${dated!.day.toString().padLeft(2, '0')}", + "survey_no": surveyNo, + "lot_no": lotNo, + "blk_no": blkNo, + "owner": owner, + "address": address, + "telno": telno, + "tin": tin, + "admin_user": adminUser, + "admin_address": adminAddress, + "admin_telno": adminTelno, + "admin_tin": adminTin, + "faas_type": faasType, + }; +} diff --git a/lib/model/passo/land_ref.dart b/lib/model/passo/land_ref.dart index 58de998..8f4649d 100644 --- a/lib/model/passo/land_ref.dart +++ b/lib/model/passo/land_ref.dart @@ -9,9 +9,27 @@ LandRef landRefFromJson(String str) => LandRef.fromJson(json.decode(str)); String landRefToJson(LandRef data) => json.encode(data.toJson()); class LandRef { + final int? id; + final int? bldgapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final dynamic owner; + final dynamic cloaNo; + final dynamic lotNo; + final dynamic tdn; + final dynamic area; + final dynamic surveyNo; + final dynamic blkNo; + LandRef({ this.id, this.bldgapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, this.owner, this.cloaNo, this.lotNo, @@ -21,19 +39,17 @@ class LandRef { this.blkNo, }); - final int? id; - final int? bldgapprDetailsId; - final String? owner; - final String? cloaNo; - final String? lotNo; - final String? tdn; - final String? area; - final String? surveyNo; - final String? blkNo; - factory LandRef.fromJson(Map json) => LandRef( id: json["id"], bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), owner: json["owner"], cloaNo: json["cloa_no"], lotNo: json["lot_no"], @@ -46,6 +62,10 @@ class LandRef { Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), "owner": owner, "cloa_no": cloaNo, "lot_no": lotNo, diff --git a/lib/model/passo/land_subclassification.dart b/lib/model/passo/land_subclassification.dart new file mode 100644 index 0000000..8bb042a --- /dev/null +++ b/lib/model/passo/land_subclassification.dart @@ -0,0 +1,48 @@ +// To parse this JSON data, do +// +// final landSubClassification = landSubClassificationFromJson(jsonString); + +import 'dart:convert'; + +LandSubClassification landSubClassificationFromJson(String str) => + LandSubClassification.fromJson(json.decode(str)); + +String landSubClassificationToJson(LandSubClassification data) => + json.encode(data.toJson()); + +class LandSubClassification { + final int? id; + final int? classificationId; + final String? cityCode; + final String? subclassCode; + final String? subclassDescription; + final String? baseUnitMarketval; + + LandSubClassification({ + this.id, + this.classificationId, + this.cityCode, + this.subclassCode, + this.subclassDescription, + this.baseUnitMarketval, + }); + + factory LandSubClassification.fromJson(Map json) => + LandSubClassification( + id: json["id"], + classificationId: json["classification_id"], + cityCode: json["city_code"], + subclassCode: json["subclass_code"], + subclassDescription: json["subclass_description"], + baseUnitMarketval: json["base_unit_marketval"], + ); + + Map toJson() => { + "id": id, + "classification_id": classificationId, + "city_code": cityCode, + "subclass_code": subclassCode, + "subclass_description": subclassDescription, + "base_unit_marketval": baseUnitMarketval, + }; +} diff --git a/lib/model/passo/land_value_adjustment.dart b/lib/model/passo/land_value_adjustment.dart new file mode 100644 index 0000000..33bdc59 --- /dev/null +++ b/lib/model/passo/land_value_adjustment.dart @@ -0,0 +1,52 @@ +// To parse this JSON data, do +// +// final valueAdjustments = valueAdjustmentsFromJson(jsonString); + +import 'dart:convert'; + +ValueAdjustments valueAdjustmentsFromJson(String str) => + ValueAdjustments.fromJson(json.decode(str)); + +String valueAdjustmentsToJson(ValueAdjustments data) => + json.encode(data.toJson()); + +class ValueAdjustments { + final int? id; + final int? landapprDetailsId; + final String? baseMarketval; + final String? adjustmentFactors; + final String? adjustment; + final String? valueAdjustment; + final String? marketValue; + + ValueAdjustments({ + this.id, + this.landapprDetailsId, + this.baseMarketval, + this.adjustmentFactors, + this.adjustment, + this.valueAdjustment, + this.marketValue, + }); + + factory ValueAdjustments.fromJson(Map json) => + ValueAdjustments( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + baseMarketval: json["base_marketval"], + adjustmentFactors: json["adjustment_factors"], + adjustment: json["adjustment"], + valueAdjustment: json["value_adjustment"], + marketValue: json["market_value"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "base_marketval": baseMarketval, + "adjustment_factors": adjustmentFactors, + "adjustment": adjustment, + "value_adjustment": valueAdjustment, + "market_value": marketValue, + }; +} diff --git a/lib/model/passo/memoranda.dart b/lib/model/passo/memoranda.dart new file mode 100644 index 0000000..8c629fd --- /dev/null +++ b/lib/model/passo/memoranda.dart @@ -0,0 +1,33 @@ +// To parse this JSON data, do +// +// final memoranda = memorandaFromJson(jsonString); + +import 'dart:convert'; + +Memoranda memorandaFromJson(String str) => Memoranda.fromJson(json.decode(str)); + +String memorandaToJson(Memoranda data) => json.encode(data.toJson()); + +class Memoranda { + final int? id; + final String? code; + final String? memoranda; + + Memoranda({ + this.id, + this.code, + this.memoranda, + }); + + factory Memoranda.fromJson(Map json) => Memoranda( + id: json["id"], + code: json["code"], + memoranda: json["memoranda"], + ); + + Map toJson() => { + "id": id, + "code": code, + "memoranda": memoranda, + }; +} diff --git a/lib/model/passo/other_improvements.dart b/lib/model/passo/other_improvements.dart new file mode 100644 index 0000000..bb36523 --- /dev/null +++ b/lib/model/passo/other_improvements.dart @@ -0,0 +1,64 @@ +// To parse this JSON data, do +// +// final otherImprovements = otherImprovementsFromJson(jsonString); + +import 'dart:convert'; + +OtherImprovements otherImprovementsFromJson(String str) => + OtherImprovements.fromJson(json.decode(str)); + +String otherImprovementsToJson(OtherImprovements data) => + json.encode(data.toJson()); + +class OtherImprovements { + final int? id; + final int? landapprDetailsId; + final String? kindsOfTrees; + final String? subclassAge; + final int? quantity; + final String? unitValue; + final String? baseMarketval; + final int? noOfProductive; + final int? noOfNonproductive; + final bool? fruitBearing; + + OtherImprovements({ + this.id, + this.landapprDetailsId, + this.kindsOfTrees, + this.subclassAge, + this.quantity, + this.unitValue, + this.baseMarketval, + this.noOfProductive, + this.noOfNonproductive, + this.fruitBearing, + }); + + factory OtherImprovements.fromJson(Map json) => + OtherImprovements( + id: json["id"], + landapprDetailsId: json["landappr_details_id"], + kindsOfTrees: json["kinds_of_trees"], + subclassAge: json["subclass_age"], + quantity: json["quantity"], + unitValue: json["unit_value"], + baseMarketval: json["base_marketval"], + noOfProductive: json["no_of_productive"], + noOfNonproductive: json["no_of_nonproductive"], + fruitBearing: json["fruit_bearing"], + ); + + Map toJson() => { + "id": id, + "landappr_details_id": landapprDetailsId, + "kinds_of_trees": kindsOfTrees, + "subclass_age": subclassAge, + "quantity": quantity, + "unit_value": unitValue, + "base_marketval": baseMarketval, + "no_of_productive": noOfProductive, + "no_of_nonproductive": noOfNonproductive, + "fruit_bearing": fruitBearing, + }; +} diff --git a/lib/model/passo/property_appraisal.dart b/lib/model/passo/property_appraisal.dart index 4244db8..9ebe509 100644 --- a/lib/model/passo/property_appraisal.dart +++ b/lib/model/passo/property_appraisal.dart @@ -11,36 +11,53 @@ String propertyAppraisalToJson(PropertyAppraisal data) => json.encode(data.toJson()); class PropertyAppraisal { - final int id; - final int bldgapprDetailsId; - final String unitconstructCost; - final String buildingCore; - final String unitconstructSubtotal; - final String depreciationRate; - final String depreciationCost; - final String costAddItems; - final String addItemsSubtotal; - final String totalpercentDepreciation; - final String marketValue; + final int? id; + final int? bldgapprDetailsId; + final String? assessedById; + final String? assessedByName; + final DateTime? dateCreated; + final DateTime? dateModified; + final String? unitconstructCost; + final String? buildingCore; + final String? unitconstructSubtotal; + final String? depreciationRate; + final String? depreciationCost; + final String? costAddItems; + final String? addItemsSubtotal; + final String? totalpercentDepreciation; + final String? marketValue; + final String? totalArea; - PropertyAppraisal({ - required this.id, - required this.bldgapprDetailsId, - required this.unitconstructCost, - required this.buildingCore, - required this.unitconstructSubtotal, - required this.depreciationRate, - required this.depreciationCost, - required this.costAddItems, - required this.addItemsSubtotal, - required this.totalpercentDepreciation, - required this.marketValue, - }); + PropertyAppraisal( + {this.id, + this.bldgapprDetailsId, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.unitconstructCost, + this.buildingCore, + this.unitconstructSubtotal, + this.depreciationRate, + this.depreciationCost, + this.costAddItems, + this.addItemsSubtotal, + this.totalpercentDepreciation, + this.marketValue, + this.totalArea}); factory PropertyAppraisal.fromJson(Map json) => PropertyAppraisal( id: json["id"], bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"] == null + ? null + : DateTime.parse(json["date_created"]), + dateModified: json["date_modified"] == null + ? null + : DateTime.parse(json["date_modified"]), unitconstructCost: json["unitconstruct_cost"], buildingCore: json["building_core"], unitconstructSubtotal: json["unitconstruct_subtotal"], @@ -50,11 +67,16 @@ class PropertyAppraisal { addItemsSubtotal: json["add_items_subtotal"], totalpercentDepreciation: json["totalpercent_depreciation"], marketValue: json["market_value"], + totalArea: json["total_area"], ); Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated?.toIso8601String(), + "date_modified": dateModified?.toIso8601String(), "unitconstruct_cost": unitconstructCost, "building_core": buildingCore, "unitconstruct_subtotal": unitconstructSubtotal, @@ -64,5 +86,6 @@ class PropertyAppraisal { "add_items_subtotal": addItemsSubtotal, "totalpercent_depreciation": totalpercentDepreciation, "market_value": marketValue, + "total_area": totalArea }; } diff --git a/lib/model/passo/property_appraisal_edit.dart b/lib/model/passo/property_appraisal_edit.dart new file mode 100644 index 0000000..43e37ee --- /dev/null +++ b/lib/model/passo/property_appraisal_edit.dart @@ -0,0 +1,71 @@ +// To parse this JSON data, do +// +// final propertyAppraisal = propertyAppraisalFromJson(jsonString); + +import 'dart:convert'; + +PropertyAppraisalEdit propertyAppraisalFromJson(String str) => + PropertyAppraisalEdit.fromJson(json.decode(str)); + +String propertyAppraisalToJson(PropertyAppraisalEdit data) => + json.encode(data.toJson()); + +class PropertyAppraisalEdit { + final int? id; + final int? bldgapprDetailsId; + final String? unitconstructCost; + final String? buildingCore; + final String? unitconstructSubtotal; + final String? depreciationRate; + final String? depreciationCost; + final String? costAddItems; + final String? addItemsSubtotal; + final String? totalpercentDepreciation; + final String? marketValue; + final String? totalArea; + + PropertyAppraisalEdit( + {this.id, + this.bldgapprDetailsId, + this.unitconstructCost, + this.buildingCore, + this.unitconstructSubtotal, + this.depreciationRate, + this.depreciationCost, + this.costAddItems, + this.addItemsSubtotal, + this.totalpercentDepreciation, + this.marketValue, + this.totalArea}); + + factory PropertyAppraisalEdit.fromJson(Map json) => + PropertyAppraisalEdit( + id: json["id"], + bldgapprDetailsId: json["bldgappr_details_id"], + unitconstructCost: json["unitconstruct_cost"], + buildingCore: json["building_core"], + unitconstructSubtotal: json["unitconstruct_subtotal"], + depreciationRate: json["depreciation_rate"], + depreciationCost: json["depreciation_cost"], + costAddItems: json["cost_add_items"], + addItemsSubtotal: json["add_items_subtotal"], + totalpercentDepreciation: json["totalpercent_depreciation"], + marketValue: json["market_value"], + totalArea: json["total_area"], + ); + + Map toJson() => { + "id": id, + "bldgappr_details_id": bldgapprDetailsId, + "unitconstruct_cost": unitconstructCost, + "building_core": buildingCore, + "unitconstruct_subtotal": unitconstructSubtotal, + "depreciation_rate": depreciationRate, + "depreciation_cost": depreciationCost, + "cost_add_items": costAddItems, + "add_items_subtotal": addItemsSubtotal, + "totalpercent_depreciation": totalpercentDepreciation, + "market_value": marketValue, + "total_area": totalArea + }; +} diff --git a/lib/model/passo/property_assessment_edit.dart b/lib/model/passo/property_assessment_edit.dart new file mode 100644 index 0000000..5e0ee15 --- /dev/null +++ b/lib/model/passo/property_assessment_edit.dart @@ -0,0 +1,109 @@ +// To parse this JSON data, do +// +// final propertyAssessment = propertyAssessmentFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +PropertyAssessmentEdit propertyAssessmentFromJson(String str) => + PropertyAssessmentEdit.fromJson(json.decode(str)); + +String propertyAssessmentToJson(PropertyAssessmentEdit data) => + json.encode(data.toJson()); + +class PropertyAssessmentEdit { + final int? id; + final int? bldgapprDetailsId; + final String? actualUse; + final String? marketValue; + final String? assessmentLevel; + final String? assessedValue; + final bool? taxable; + final bool? exempt; + final int? qtr; + final int? yr; + final String? appraisedbyName; + final DateTime? appraisedbyDate; + final String? recommendapprName; + final DateTime? recommendapprDate; + final String? approvedbyName; + final String? memoranda; + final String? swornstatementNo; + final DateTime? dateReceived; + final DateTime? entryDateAssessment; + final String? entryDateBy; + + PropertyAssessmentEdit({ + this.id, + this.bldgapprDetailsId, + this.actualUse, + this.marketValue, + this.assessmentLevel, + this.assessedValue, + this.taxable, + this.exempt, + this.qtr, + this.yr, + this.appraisedbyName, + this.appraisedbyDate, + this.recommendapprName, + this.recommendapprDate, + this.approvedbyName, + this.memoranda, + this.swornstatementNo, + this.dateReceived, + this.entryDateAssessment, + this.entryDateBy, + }); + + factory PropertyAssessmentEdit.fromJson(Map json) => + PropertyAssessmentEdit( + id: json["id"], + bldgapprDetailsId: json["bldgappr_details_id"], + actualUse: json["actual_use"], + marketValue: json["market_value"], + assessmentLevel: json["assessment_level"], + assessedValue: json["assessed_value"], + taxable: json["taxable"], + exempt: json["exempt"], + qtr: json["qtr"], + yr: json["yr"], + appraisedbyName: json["appraisedby_name"], + appraisedbyDate: DateTime.parse(json["appraisedby_date"]), + recommendapprName: json["recommendappr_name"], + recommendapprDate: DateTime.parse(json["recommendappr_date"]), + approvedbyName: json["approvedby_name"], + memoranda: json["memoranda"], + swornstatementNo: json["swornstatement_no"], + dateReceived: DateTime.parse(json["date_received"]), + entryDateAssessment: DateTime.parse(json["entry_date_assessment"]), + entryDateBy: json["entry_date_by"], + ); + + Map toJson() => { + "id": id, + "bldgappr_details_id": bldgapprDetailsId, + "actual_use": actualUse, + "market_value": marketValue, + "assessment_level": assessmentLevel, + "assessed_value": assessedValue, + "taxable": taxable, + "exempt": exempt, + "qtr": qtr, + "yr": yr, + "appraisedby_name": appraisedbyName, + "appraisedby_date": + "${appraisedbyDate!.year.toString().padLeft(4, '0')}-${appraisedbyDate!.month.toString().padLeft(2, '0')}-${appraisedbyDate!.day.toString().padLeft(2, '0')}", + "recommendappr_name": recommendapprName, + "recommendappr_date": + "${recommendapprDate!.year.toString().padLeft(4, '0')}-${recommendapprDate!.month.toString().padLeft(2, '0')}-${recommendapprDate!.day.toString().padLeft(2, '0')}", + "approvedby_name": approvedbyName, + "memoranda": memoranda, + "swornstatement_no": swornstatementNo, + "date_received": + "${dateReceived!.year.toString().padLeft(4, '0')}-${dateReceived!.month.toString().padLeft(2, '0')}-${dateReceived!.day.toString().padLeft(2, '0')}", + "entry_date_assessment": + "${entryDateAssessment!.year.toString().padLeft(4, '0')}-${entryDateAssessment!.month.toString().padLeft(2, '0')}-${entryDateAssessment!.day.toString().padLeft(2, '0')}", + "entry_date_by": entryDateBy, + }; +} diff --git a/lib/model/passo/property_info.dart b/lib/model/passo/property_info.dart index 89cd807..68406e2 100644 --- a/lib/model/passo/property_info.dart +++ b/lib/model/passo/property_info.dart @@ -26,6 +26,7 @@ class PropertyInfo { final String? adminAddress; final String? adminTelno; final String? adminTin; + final String? faasType; PropertyInfo({ this.id, @@ -44,6 +45,7 @@ class PropertyInfo { this.adminAddress, this.adminTelno, this.adminTin, + this.faasType, }); factory PropertyInfo.fromJson(Map json) => PropertyInfo( @@ -67,6 +69,7 @@ class PropertyInfo { adminAddress: json["admin_address"], adminTelno: json["admin_telno"], adminTin: json["admin_tin"], + faasType: json["faas_type"], ); Map toJson() => { @@ -86,5 +89,6 @@ class PropertyInfo { "admin_address": adminAddress, "admin_telno": adminTelno, "admin_tin": adminTin, + "faas_type": faasType, }; } diff --git a/lib/model/passo/structural_materials_ii.dart b/lib/model/passo/structural_materials_ii.dart new file mode 100644 index 0000000..cfa3ec2 --- /dev/null +++ b/lib/model/passo/structural_materials_ii.dart @@ -0,0 +1,60 @@ +// To parse this JSON data, do +// +// final structureMaterialsIi = structureMaterialsIiFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +StructureMaterialsII structureMaterialsIiFromJson(String str) => + StructureMaterialsII.fromJson(json.decode(str)); + +String structureMaterialsIiToJson(StructureMaterialsII data) => + json.encode(data.toJson()); + +class StructureMaterialsII { + final int? id; + final List? foundation; + final List? columns; + final List? beams; + final List? trussFraming; + final List? roof; + final List? flooring; + final List? walls; + final List? others; + + StructureMaterialsII( + {this.id, + this.foundation, + this.columns, + this.beams, + this.trussFraming, + this.roof, + this.flooring, + this.walls, + this.others}); + + factory StructureMaterialsII.fromJson(Map json) => + StructureMaterialsII( + id: json["id"], + foundation: List.from(json["foundation"].map((x) => x)), + columns: List.from(json["columns"].map((x) => x)), + beams: List.from(json["beams"].map((x) => x)), + trussFraming: List.from(json["truss_framing"].map((x) => x)), + roof: List.from(json["roof"].map((x) => x)), + flooring: List.from(json["flooring"].map((x) => x)), + walls: List.from(json["walls"].map((x) => x)), + others: List.from(json["others"].map((x) => x)), + ); + + Map toJson() => { + "id": id, + "foundation": List.from(foundation!.map((x) => x)), + "columns": List.from(columns!.map((x) => x)), + "beams": List.from(beams!.map((x) => x)), + "truss_framing": List.from(trussFraming!.map((x) => x)), + "roof": List.from(roof!.map((x) => x)), + "flooring": List.from(flooring!.map((x) => x)), + "walls": List.from(walls!.map((x) => x)), + "others": List.from(others!.map((x) => x)), + }; +} diff --git a/lib/model/passo/structureMaterial.dart b/lib/model/passo/structureMaterial.dart new file mode 100644 index 0000000..4c07c23 --- /dev/null +++ b/lib/model/passo/structureMaterial.dart @@ -0,0 +1,57 @@ +// To parse this JSON data, do +// +// final structureMaterials = structureMaterialsFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +StructureMaterials structureMaterialsFromJson(String str) => + StructureMaterials.fromJson(json.decode(str)); + +String structureMaterialsToJson(StructureMaterials data) => + json.encode(data.toJson()); + +class StructureMaterials { + final int? id; + final String? foundation; + final String? columns; + final String? beams; + final String? trussFraming; + final String? roof; + final String? flooring; + final String? walls; + + StructureMaterials({ + this.id, + this.foundation, + this.columns, + this.beams, + this.trussFraming, + this.roof, + this.flooring, + this.walls, + }); + + factory StructureMaterials.fromJson(Map json) => + StructureMaterials( + id: json["id"], + foundation: json["foundation"], + columns: json["columns"], + beams: json["beams"], + trussFraming: json["truss_framing"], + roof: json["roof"], + flooring: json["flooring"], + walls: json["walls"], + ); + + Map toJson() => { + "id": id, + "foundation": foundation, + "columns": columns, + "beams": beams, + "truss_framing": trussFraming, + "roof": roof, + "flooring": flooring, + "walls": walls, + }; +} diff --git a/lib/model/passo/trees_improvements.dart b/lib/model/passo/trees_improvements.dart new file mode 100644 index 0000000..cc72f4a --- /dev/null +++ b/lib/model/passo/trees_improvements.dart @@ -0,0 +1,40 @@ +// To parse this JSON data, do +// +// final treesImprovements = treesImprovementsFromJson(jsonString); + +import 'dart:convert'; + +TreesImprovements treesImprovementsFromJson(String str) => + TreesImprovements.fromJson(json.decode(str)); + +String treesImprovementsToJson(TreesImprovements data) => + json.encode(data.toJson()); + +class TreesImprovements { + final int? id; + final String? improvement; + final String? pricePerTree; + final dynamic subclassCode; + + TreesImprovements({ + this.id, + this.improvement, + this.pricePerTree, + this.subclassCode, + }); + + factory TreesImprovements.fromJson(Map json) => + TreesImprovements( + id: json["id"], + improvement: json["improvement"], + pricePerTree: json["price_per_tree"], + subclassCode: json["subclass_code"], + ); + + Map toJson() => { + "id": id, + "improvement": improvement, + "price_per_tree": pricePerTree, + "subclass_code": subclassCode, + }; +} diff --git a/lib/model/passo/type_of_location.dart b/lib/model/passo/type_of_location.dart new file mode 100644 index 0000000..9990236 --- /dev/null +++ b/lib/model/passo/type_of_location.dart @@ -0,0 +1,38 @@ +// To parse this JSON data, do +// +// final typeOfLocation = typeOfLocationFromJson(jsonString); + +import 'dart:convert'; + +TypeOfLocation typeOfLocationFromJson(String str) => + TypeOfLocation.fromJson(json.decode(str)); + +String typeOfLocationToJson(TypeOfLocation data) => json.encode(data.toJson()); + +class TypeOfLocation { + final int? id; + final String? distanceKm; + final String? allRoadTypes; + final String? localTradingCenter; + + TypeOfLocation({ + this.id, + this.distanceKm, + this.allRoadTypes, + this.localTradingCenter, + }); + + factory TypeOfLocation.fromJson(Map json) => TypeOfLocation( + id: json["id"], + distanceKm: json["distance_km"], + allRoadTypes: json["all_road_types"], + localTradingCenter: json["local_trading_center"], + ); + + Map toJson() => { + "id": id, + "distance_km": distanceKm, + "all_road_types": allRoadTypes, + "local_trading_center": localTradingCenter, + }; +} diff --git a/lib/model/passo/type_of_road.dart b/lib/model/passo/type_of_road.dart new file mode 100644 index 0000000..e545e29 --- /dev/null +++ b/lib/model/passo/type_of_road.dart @@ -0,0 +1,34 @@ +// To parse this JSON data, do +// +// final typeOfRoad = typeOfRoadFromJson(jsonString); + +import 'dart:convert'; + +TypeOfRoad typeOfRoadFromJson(String str) => + TypeOfRoad.fromJson(json.decode(str)); + +String typeOfRoadToJson(TypeOfRoad data) => json.encode(data.toJson()); + +class TypeOfRoad { + final int? id; + final String? roadType; + final String? deduction; + + TypeOfRoad({ + this.id, + this.roadType, + this.deduction, + }); + + factory TypeOfRoad.fromJson(Map json) => TypeOfRoad( + id: json["id"], + roadType: json["road_type"], + deduction: json["deduction"], + ); + + Map toJson() => { + "id": id, + "road_type": roadType, + "deduction": deduction, + }; +} diff --git a/lib/model/profile/basic_information/primary-information.dart b/lib/model/profile/basic_information/primary-information.dart index 80b7535..c936a39 100644 --- a/lib/model/profile/basic_information/primary-information.dart +++ b/lib/model/profile/basic_information/primary-information.dart @@ -14,6 +14,7 @@ Profile primaryInformationFromJson(String str) => Profile.fromJson(json.decode(s String primaryInformationToJson(Profile data) => json.encode(data.toJson()); class Profile { + int? webuserId; int? id; String? lastName; String? firstName; @@ -40,6 +41,7 @@ class Profile { String? ip; Profile({ + required this.webuserId, required this.id, required this.lastName, required this.firstName, @@ -67,13 +69,14 @@ class Profile { }); factory Profile.fromJson(Map json) => Profile( + webuserId: null, id: json["id"], lastName: json["last_name"], firstName: json["first_name"], middleName: json["middle_name"], nameExtension: json["name_extension"], sex: json["sex"], - birthdate: DateTime.parse(json["birthdate"]), + birthdate:json['birthdate'] ==null?null: DateTime.parse(json["birthdate"]), civilStatus: json["civil_status"], bloodType: json["blood_type"], heightM: json["height_m"]?.toDouble(), diff --git a/lib/model/rbac/assigned_role.dart b/lib/model/rbac/assigned_role.dart new file mode 100644 index 0000000..52a1b78 --- /dev/null +++ b/lib/model/rbac/assigned_role.dart @@ -0,0 +1,130 @@ +// To parse this JSON data, do +// +// final assignedRole = assignedRoleFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +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 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: json['role'] == null?null: Role.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"]), + 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, + "role": role?.toJson(), + "user": user?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "created_by": createdBy?.toJson(), + "updated_by": updatedBy?.toJson(), + }; +} + +class CreatedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + CreatedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory CreatedBy.fromJson(Map json) => CreatedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + +class 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: 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, + "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/model/rbac/new_permission.dart b/lib/model/rbac/new_permission.dart new file mode 100644 index 0000000..8c84b49 --- /dev/null +++ b/lib/model/rbac/new_permission.dart @@ -0,0 +1,70 @@ +// To parse this JSON data, do +// +// final newPermission = newPermissionFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +NewPermission newPermissionFromJson(String str) => NewPermission.fromJson(json.decode(str)); + +String newPermissionToJson(NewPermission data) => json.encode(data.toJson()); + +class NewPermission { + final int? newPermissionObjectId; + final String? newObjectName; + final String? newObjectSlug; + final String? newObjectShorthand; + final List newPermissionOperationIds; + final List newOperations; + + NewPermission({ + required this.newPermissionObjectId, + required this.newObjectName, + required this.newObjectSlug, + required this.newObjectShorthand, + required this.newPermissionOperationIds, + required this.newOperations, + }); + + factory NewPermission.fromJson(Map json) => NewPermission( + newPermissionObjectId: json["_new_permission_object_id"], + newObjectName: json["_new_object_name"], + newObjectSlug: json["_new_object_slug"], + newObjectShorthand: json["_new_object_shorthand"], + newPermissionOperationIds: List.from(json["_new_permission_operation_ids"].map((x) => x)), + newOperations: List.from(json["_new_operations"].map((x) => NewOperation.fromJson(x))), + ); + + Map toJson() => { + "_new_permission_object_id": newPermissionObjectId, + "_new_object_name": newObjectName, + "_new_object_slug": newObjectSlug, + "_new_object_shorthand": newObjectShorthand, + "_new_permission_operation_ids": List.from(newPermissionOperationIds.map((x) => x)), + "_new_operations": List.from(newOperations.map((x) => x.toJson())), + }; +} + +class NewOperation { + final String newOperationName; + final String newOperationSlug; + final String newOperationShorthand; + + NewOperation({ + required this.newOperationName, + required this.newOperationSlug, + required this.newOperationShorthand, + }); + + factory NewOperation.fromJson(Map json) => NewOperation( + newOperationName: json["_new_operation_name"], + newOperationSlug: json["_new_operation_slug"], + newOperationShorthand: json["_new_operation_shorthand"], + ); + + Map toJson() => { + "_new_operation_name": newOperationName, + "_new_operation_slug": newOperationSlug, + "_new_operation_shorthand": newOperationShorthand, + }; +} diff --git a/lib/model/rbac/permission.dart b/lib/model/rbac/permission.dart new file mode 100644 index 0000000..dd2c2e3 --- /dev/null +++ b/lib/model/rbac/permission.dart @@ -0,0 +1,79 @@ +import 'package:unit2/model/rbac/rbac.dart'; + +class RBACPermission { + final int? id; + final RBAC? object; + final RBAC? operation; + final DateTime? createdAt; + final dynamic updatedAt; + final CreatedBy? createdBy; + final dynamic updatedBy; + + RBACPermission({ + required this.id, + required this.object, + required this.operation, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory RBACPermission.fromJson(Map json) => RBACPermission( + id: json["id"], + object: json['object'] == null?null:RBAC.fromJson(json["object"]), + operation: json['operation'] == null?null: RBAC.fromJson(json["operation"]), + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "object": object?.toJson(), + "operation": operation?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy?.toJson(), + "updated_by": updatedBy, + }; +} + +class CreatedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + CreatedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory CreatedBy.fromJson(Map json) => CreatedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + + diff --git a/lib/model/rbac/rbac.dart b/lib/model/rbac/rbac.dart new file mode 100644 index 0000000..9fb897d --- /dev/null +++ b/lib/model/rbac/rbac.dart @@ -0,0 +1,94 @@ +// To parse this JSON data, do +// +// final rbac = rbacFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +RBAC rbacFromJson(String str) => RBAC.fromJson(json.decode(str)); + +String rbacToJson(RBAC data) => json.encode(data.toJson()); + +class RBAC { + final int? id; + final String? name; + final String? slug; + final String? shorthand; + final String? fontawesomeIcon; + final DateTime? createdAt; + final dynamic updatedAt; + final CreatedBy? createdBy; + final dynamic updatedBy; + + RBAC({ + required this.id, + required this.name, + required this.slug, + required this.shorthand, + required this.fontawesomeIcon, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory RBAC.fromJson(Map json) => RBAC( + id: json["id"], + name: json["name"], + slug: json["slug"], + shorthand: json["shorthand"], + fontawesomeIcon: json["fontawesome_icon"], + createdAt: json['created_at'] == null?null: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: json['created_by']==null?null: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "name": name, + "slug": slug, + "shorthand": shorthand, + "fontawesome_icon": fontawesomeIcon, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy?.toJson(), + "updated_by": updatedBy, + }; +} + +class CreatedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + CreatedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory CreatedBy.fromJson(Map json) => CreatedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} diff --git a/lib/model/rbac/rbac_rbac.dart b/lib/model/rbac/rbac_rbac.dart new file mode 100644 index 0000000..ec5bc5f --- /dev/null +++ b/lib/model/rbac/rbac_rbac.dart @@ -0,0 +1,122 @@ +class ModuleObjects { + final int id; + final Module object; + final Module module; + final DateTime? createdAt; + final dynamic updatedAt; + final AtedBy createdBy; + final dynamic updatedBy; + + ModuleObjects({ + required this.id, + required this.object, + required this.module, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory ModuleObjects.fromJson(Map json) => ModuleObjects( + id:json['id'], + object: Module.fromJson(json["object"]), + module: Module.fromJson(json["module"]), + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: AtedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "object": object.toJson(), + "module": module.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy.toJson(), + "updated_by": updatedBy, + }; +} + +class AtedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + AtedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory AtedBy.fromJson(Map json) => AtedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + +class Module { + final int id; + final String? name; + final String? slug; + final String? shorthand; + final String? fontawesomeIcon; + final DateTime? createdAt; + final DateTime? updatedAt; + final AtedBy? createdBy; + final AtedBy? updatedBy; + + Module({ + required this.id, + required this.name, + required this.slug, + required this.shorthand, + required this.fontawesomeIcon, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Module.fromJson(Map json) => Module( + id: json["id"], + name: json["name"], + slug: json["slug"], + shorthand: json["shorthand"], + fontawesomeIcon: json['fontawesome_icon'] == null?null: json["fontawesome_icon"], + 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:AtedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"] == null? null:AtedBy.fromJson(json["updated_by"]), + ); + + Map toJson() => { + "id": id, + "name": name, + "slug": slug, + "shorthand": shorthand, + "fontawesome_icon": fontawesomeIcon, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "created_by": createdBy?.toJson(), + "updated_by": updatedBy?.toJson(), + }; +} diff --git a/lib/model/rbac/rbac_station.dart b/lib/model/rbac/rbac_station.dart new file mode 100644 index 0000000..2a73bd5 --- /dev/null +++ b/lib/model/rbac/rbac_station.dart @@ -0,0 +1,164 @@ +// To parse this JSON data, do +// +// final assignArea = assignAreaFromJson(jsonString); + + + +class RbacStation { + final int? id; + final String? stationName; + final StationType? stationType; + final int? hierarchyOrderNo; + final String? headPosition; + final GovernmentAgency? governmentAgency; + final String? acronym; + final int? parentStation; + final String? code; + final String? fullcode; + final List? childStationInfo; + final bool? islocationUnderParent; + final int? mainParentStation; + final String? description; + final bool? ishospital; + final bool? isactive; + final bool? sellingStation; + + RbacStation({ + required this.id, + required this.stationName, + required this.stationType, + required this.hierarchyOrderNo, + required this.headPosition, + required this.governmentAgency, + required this.acronym, + required this.parentStation, + required this.code, + required this.fullcode, + required this.childStationInfo, + required this.islocationUnderParent, + required this.mainParentStation, + required this.description, + required this.ishospital, + required this.isactive, + required this.sellingStation, + }); + + factory RbacStation.fromJson(Map json) => RbacStation( + id: json["id"], + stationName: json["station_name"], + stationType:json["station_type"] ==null?null: StationType.fromJson(json["station_type"]), + hierarchyOrderNo: json["hierarchy_order_no"], + headPosition: json["head_position"], + governmentAgency: json["government_agency"] == null?null:GovernmentAgency.fromJson(json["government_agency"]), + acronym: json["acronym"], + parentStation: json["parent_station"], + code: json["code"], + fullcode: json["fullcode"], + childStationInfo: null, + islocationUnderParent: json["islocation_under_parent"], + mainParentStation: json["main_parent_station"], + description: json["description"], + ishospital: json["ishospital"], + isactive: json["isactive"], + sellingStation: json["selling_station"], + ); + + Map toJson() => { + "id": id, + "station_name": stationName, + "station_type": stationType?.toJson(), + "hierarchy_order_no": hierarchyOrderNo, + "head_position": headPosition, + "government_agency": governmentAgency?.toJson(), + "acronym": acronym, + "parent_station": parentStation, + "code": code, + "fullcode": fullcode, + "child_station_info": List.from(childStationInfo!.map((x) => x.toJson())), + "islocation_under_parent": islocationUnderParent, + "main_parent_station": mainParentStation, + "description": description, + "ishospital": ishospital, + "isactive": isactive, + "selling_station": sellingStation, + }; +} + +class ChildStationInfo { + final int? id; + final String? stationName; + final String? acroym; + bool? motherStation; + + ChildStationInfo({ + required this.id, + required this.stationName, + required this.acroym, + this.motherStation + }); + + factory ChildStationInfo.fromJson(Map json) => ChildStationInfo( + id: json["id"], + stationName: json["station_name"], + acroym: json["acroym"], + + ); + + Map toJson() => { + "id": id, + "station_name": stationName, + "acroym": acroym, + }; +} + +class GovernmentAgency { + final int? agencyid; + final String? agencyname; + final int? agencycatid; + final bool? privateEntity; + final int? contactinfoid; + + GovernmentAgency({ + required this.agencyid, + required this.agencyname, + required this.agencycatid, + required this.privateEntity, + required this.contactinfoid, + }); + + factory GovernmentAgency.fromJson(Map json) => GovernmentAgency( + agencyid: json["agencyid"], + agencyname: json["agencyname"], + agencycatid: json["agencycatid"], + privateEntity: json["private_entity"], + contactinfoid: json["contactinfoid"], + ); + + Map toJson() => { + "agencyid": agencyid, + "agencyname": agencyname, + "agencycatid": agencycatid, + "private_entity": privateEntity, + "contactinfoid": contactinfoid, + }; +} + +class StationType { + final int? id; + final String? typeName; + + StationType({ + required this.id, + required this.typeName, + }); + + factory StationType.fromJson(Map json) => StationType( + id: json["id"], + typeName: json["type_name"], + ); + + Map toJson() => { + "id": id, + "type_name": typeName, + }; +} diff --git a/lib/model/rbac/role_extend.dart b/lib/model/rbac/role_extend.dart new file mode 100644 index 0000000..acd95fb --- /dev/null +++ b/lib/model/rbac/role_extend.dart @@ -0,0 +1,37 @@ +// To parse this JSON data, do +// +// final rolesExtend = rolesExtendFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; + +RolesExtend rolesExtendFromJson(String str) => RolesExtend.fromJson(json.decode(str)); + +String rolesExtendToJson(RolesExtend data) => json.encode(data.toJson()); + +class RolesExtend { + final int id; + final RBAC roleExtendMain; + final RBAC roleExtendChild; + + RolesExtend({ + required this.id, + required this.roleExtendMain, + required this.roleExtendChild, + }); + + factory RolesExtend.fromJson(Map json) => RolesExtend( + id: json["id"], + roleExtendMain: RBAC.fromJson(json["role_extend_main"]), + roleExtendChild: RBAC.fromJson(json["role_extend_child"]), + ); + + Map toJson() => { + "id": id, + "role_extend_main": roleExtendMain.toJson(), + "role_extend_child": roleExtendChild.toJson(), + }; +} + diff --git a/lib/model/rbac/role_module.dart b/lib/model/rbac/role_module.dart new file mode 100644 index 0000000..295f1cf --- /dev/null +++ b/lib/model/rbac/role_module.dart @@ -0,0 +1,124 @@ + +class RoleModules { + final int? id; + final Module? role; + final Module? module; + final DateTime? createdAt; + final dynamic updatedAt; + final AtedBy? createdBy; + final dynamic updatedBy; + + RoleModules({ + required this.id, + required this.role, + required this.module, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory RoleModules.fromJson(Map json) => RoleModules( + id: json["id"], + role:json['role'] == null?null: Module.fromJson(json["role"]), + module: json['module'] == null?null:Module.fromJson(json["module"]), + createdAt: json["created_at"] == null? null: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: json["created_by"]==null? null: AtedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "role": role?.toJson(), + "module": module?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy?.toJson(), + "updated_by": updatedBy, + }; +} + +class AtedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + AtedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory AtedBy.fromJson(Map json) => AtedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + +class Module { + final int? id; + final String? name; + final String? slug; + final String? shorthand; + final String? fontawesomeIcon; + final DateTime? createdAt; + final DateTime? updatedAt; + final AtedBy? createdBy; + final AtedBy? updatedBy; + + Module({ + required this.id, + required this.name, + required this.slug, + required this.shorthand, + required this.fontawesomeIcon, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Module.fromJson(Map json) => Module( + id: json["id"], + name: json["name"], + slug: json["slug"], + shorthand: json["shorthand"], + fontawesomeIcon: null, + 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: AtedBy.fromJson(json["created_by"]), + updatedBy:json["updated_by"] == null?null: AtedBy.fromJson(json["updated_by"]), + ); + + Map toJson() => { + "id": id, + "name": name, + "slug": slug, + "shorthand": shorthand, + "fontawesome_icon": fontawesomeIcon, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "created_by": createdBy?.toJson(), + "updated_by": updatedBy?.toJson(), + }; +} diff --git a/lib/model/rbac/role_under.dart b/lib/model/rbac/role_under.dart new file mode 100644 index 0000000..dedc7c2 --- /dev/null +++ b/lib/model/rbac/role_under.dart @@ -0,0 +1,37 @@ +// To parse this JSON data, do +// +// final rolesUnder = rolesUnderFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; + +RolesUnder rolesUnderFromJson(String str) => RolesUnder.fromJson(json.decode(str)); + +String rolesUnderToJson(RolesUnder data) => json.encode(data.toJson()); + +class RolesUnder { + final int id; + final RBAC roleUnderMain; + final RBAC roleUnderChild; + + RolesUnder({ + required this.id, + required this.roleUnderMain, + required this.roleUnderChild, + }); + + factory RolesUnder.fromJson(Map json) => RolesUnder( + id: json["id"], + roleUnderMain: RBAC.fromJson(json["role_under_main"]), + roleUnderChild: RBAC.fromJson(json["role_under_child"]), + ); + + Map toJson() => { + "id": id, + "role_under_main": roleUnderMain.toJson(), + "role_under_child": roleUnderChild.toJson(), + }; +} + diff --git a/lib/model/roles/pass_check/station_assign_area.dart b/lib/model/roles/pass_check/station_assign_area.dart index 4251403..cbece06 100644 --- a/lib/model/roles/pass_check/station_assign_area.dart +++ b/lib/model/roles/pass_check/station_assign_area.dart @@ -4,7 +4,7 @@ class StationAssignArea { final bool? isactive; - final Area? area; + final Station? area; StationAssignArea({ required this.isactive, @@ -13,7 +13,7 @@ class StationAssignArea { factory StationAssignArea.fromJson(Map json) => StationAssignArea( isactive: json["isactive"], - area: json["area"] == null?null: Area.fromJson(json["area"]), + area: json["area"] == null?null: Station.fromJson(json["area"]), ); Map toJson() => { @@ -22,7 +22,7 @@ class StationAssignArea { }; } -class Area { +class Station { final int? id; final String? stationName; final StationType? stationType; @@ -41,7 +41,7 @@ class Area { final bool? isactive; final bool? sellingStation; - Area({ + Station({ required this.id, required this.stationName, required this.stationType, @@ -61,7 +61,7 @@ class Area { required this.sellingStation, }); - factory Area.fromJson(Map json) => Area( + factory Station.fromJson(Map json) => Station( id: json["id"], stationName: json["station_name"], stationType:json["station_type"] ==null?null: StationType.fromJson(json["station_type"]), @@ -72,7 +72,7 @@ class Area { parentStation: json["parent_station"], code: json["code"], fullcode: json["fullcode"], - childStationInfo: json['child_station_info']==null?[]:List.from(json["child_station_info"].map((x) => ChildStationInfo.fromJson(x))), + childStationInfo: json['child_station_info']==null || json['child_station_info'].isEmpty ?[]:List.from(json["child_station_info"].map((x) => ChildStationInfo.fromJson(x))), islocationUnderParent: json["islocation_under_parent"], mainParentStation: json["main_parent_station"], description: json["description"], @@ -81,7 +81,7 @@ class Area { sellingStation: json["selling_station"], ); - Map toJson() => { + Map toJson() => { "id": id, "station_name": stationName, "station_type": stationType?.toJson(), diff --git a/lib/screens/passo/Building/add_building.dart b/lib/screens/passo/Building/add_building.dart index 30922cc..d2d94a8 100644 --- a/lib/screens/passo/Building/add_building.dart +++ b/lib/screens/passo/Building/add_building.dart @@ -3,13 +3,19 @@ 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:unit2/bloc/passo/class_components/class_components_bloc.dart'; -import 'package:unit2/bloc/passo/property_info/property_info_bloc.dart'; -import 'package:unit2/bloc/passo/unit_construct/unit_construct_bloc.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart'; import 'package:unit2/model/passo/bldg_loc.dart'; import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/general_description.dart'; import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; import 'package:unit2/screens/passo/Building/add_building_components/additional_items.dart'; import 'package:unit2/screens/passo/Building/add_building_components/bldg_location_landref.dart'; import 'package:unit2/screens/passo/Building/add_building_components/general_description.dart'; @@ -19,6 +25,8 @@ import 'package:unit2/screens/passo/Building/add_building_components/property_in import 'package:unit2/screens/passo/Building/add_building_components/structural_materials.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:im_stepper/stepper.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; GlobalKey formKey = GlobalKey(); @@ -40,74 +48,49 @@ class _AddBuilding extends State { bool saveStep7 = false; int tempId = 0; - void onPostPropertyInfo() { - formKey.currentState?.save(); - if (formKey.currentState!.value['transaction_code'].toString() != null && - formKey.currentState!.value['owner'] != null) { - if (activeStep < upperBound && saveStep1 == false) { - setState(() { - activeStep++; - saveStep1 = true; - }); - } else { - setState(() { - activeStep++; - }); - } - - var property_info = PropertyInfo( - id: 1, - transCode: formKey.currentState!.value['transaction_code'].toString(), - tdn: formKey.currentState!.value['arp_td'], - pin: formKey.currentState!.value['pin'], - owner: formKey.currentState!.value['owner'], - address: formKey.currentState!.value['address'], - telno: formKey.currentState!.value['tel_no'], - tin: formKey.currentState!.value['tin'], - adminUser: formKey.currentState!.value['benificiary'], - adminAddress: formKey.currentState!.value['benificiary_address'], - adminTin: formKey.currentState!.value['benificiary_tin'], - adminTelno: formKey.currentState!.value['benificiary_telno'], - assessedById: '1', - assessedByName: 'Cyril', - dateModified: DateTime.now(), - dateCreated: DateTime.now()); - - context - .read() - .add(AddPropertyInfo(property_info: property_info)); -// _loadTempId(); - } + Future _loadTempId() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + tempId = (prefs.getInt('tempid') ?? 0); + }); } - void onPutBldgLandref() { - // Increment activeStep, when the next button is tapped. However, check for upper bound. - if (activeStep < upperBound && saveStep2 == false) { + void PrevBtn() { + setState(() { + activeStep--; + }); + } + + void NextBtn() { + setState(() { + activeStep++; + }); + } + + void onPutStructuralMaterials() { + if (activeStep < upperBound) { setState(() { activeStep++; - saveStep2 = true; }); } - var bldgLocData = BldgLoc( - id: tempId, - street: formKey.currentState?.value['street'], - barangay: formKey.currentState?.value['brgy'], - municipality: formKey.currentState?.value['municipality'], - province: formKey.currentState?.value['province'], - ); - var landRefData = LandRef( - id: tempId, - owner: formKey.currentState?.value['l_owner'], - cloaNo: formKey.currentState?.value['oct_tct_cloa'], - lotNo: formKey.currentState?.value['lot_no'], - tdn: formKey.currentState?.value['l_td_arp'], - area: formKey.currentState?.value['area'], - surveyNo: formKey.currentState?.value['survey_no'], - blkNo: formKey.currentState?.value['blk_no'], - ); - context.read() - ..add(UpdateBldgLoc(bldg_loc: bldgLocData)) - ..add(UpdateLandRef(land_ref: landRefData)); + // var strucMaterials = StructureMaterialsII( + // foundation: _foundations.getSelectedAsString().split(","), + // columns: _coumns.getSelectedAsString().split(","), + // beams: _beams.getSelectedAsString().split(","), + // trussFraming: + // _trussframing.getSelectedAsString().split(","), + // roof: _roof.getSelectedAsString().split(","), + // flooring: _flooring.getSelectedAsString().split(","), + // walls: _walls.getSelectedAsString().split(",")); + } + + void onPutPropertyAppraisal() {} + void bldgPrevBtn() { + if (activeStep > 0) { + setState(() { + activeStep--; + }); + } } @override @@ -130,98 +113,159 @@ class _AddBuilding extends State { final progress = ProgressHUD.of(context); progress!.showWithText("Please wait..."); } - if (state is PropertyInfoLoaded || - state is PropertyInfoErrorState) { + if (state is PropertyInfoLoaded) { final progress = ProgressHUD.of(context); progress?.dismiss(); } + if (state is PropertyInfoErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + Fluttertoast.showToast( + msg: onError, + fontSize: 24, + toastLength: Toast.LENGTH_LONG, + gravity: ToastGravity.CENTER, + backgroundColor: Colors.black, + textColor: Colors.white); + } }, builder: (context, state) { - if (state is PropertyInfoLoaded) { + if (state is PropertyInfoLoaded || + state is PropertyInfoErrorState) { return BlocConsumer( - listener: (context, state) { - // TODO: implement listener + listener: ( + context, + state, + ) { + if (state is UnitConstructLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is UnitConstructLoaded || + state is UnitConstructErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } }, builder: (context, state) { if (state is UnitConstructLoaded) { final unit = state.unit; return BlocConsumer( - listener: (context, state) { - // TODO: implement listener + listener: ( + context, + state, + ) { + if (state is ClassComponentLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ClassComponentLoaded || + state is ClassComponentErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } }, builder: (context, state) { if (state is ClassComponentLoaded) { + final classes = state.classes; + return Column( children: [ NumberStepper( numbers: [1, 2, 3, 4, 5, 6, 7], stepPadding: 5, - activeStepColor: Colors.red, - numberStyle: - const TextStyle(color: Colors.white), - activeStepBorderColor: Colors.white, + activeStepColor: primary, + numberStyle: TextStyle(color: Colors.white), + lineColor: primary, // activeStep property set to activeStep variable defined above. activeStep: activeStep, - + activeStepBorderColor: Colors.white, + activeStepBorderWidth: 1, // This ensures step-tapping updates the activeStep. onStepReached: (index) { setState(() { activeStep = index; }); }, + enableStepTapping: false, ), Expanded( - child: FormBuilder( - key: formKey, - - // enabled: false, - onChanged: () { - formKey.currentState?.save(); - - print(formKey.currentState?.value.toString()); - }, - autovalidateMode: AutovalidateMode.disabled, - skipDisabled: true, - child: Container( - child: content( - onPostPropertyInfo, unit, state.classes), - ), - )), + child: StatefulBuilder(builder: + (BuildContext context, + StateSetter setState) { + return FormBuilder( + key: formKey, + onChanged: () { + formKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Container( + child: content( + unit, + classes, + PrevBtn, + NextBtn, + ), + ), + ); + }), + ), ], ); } + if (state is ClassComponentErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadClassComponents()); + }, + ); + } return Container(); }, ); } + if (state is UnitConstructErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadUnitConstruct()); + }, + ); + } return Container(); }, ); } + return Container(); })), ); } - Widget content(handleButtonPress, unit, List classes) { + Widget content(unit, List classes, PrevBtn, NextBtn) { switch (activeStep) { case 0: - return PropertyInfoPage(onPostPropertyInfo); + return PropertyInfoPage(NextBtn); case 1: - return BldgLocationLandrefPage(); + return BldgLocationLandrefPage(PrevBtn, NextBtn); case 2: - return GeneralDescriptionPage(unit); + return GeneralDescriptionPage(unit, NextBtn, PrevBtn); case 3: - return StructuralMaterialsPage(); + return StructuralMaterialsPage(PrevBtn, NextBtn); case 4: - return AdditionalItemPage(unit, classes); + return AdditionalItemPage(unit, classes, PrevBtn, NextBtn); case 5: - return PropertyAppraisalPage(); + return PropertyAppraisalPage(NextBtn, PrevBtn); case 6: return PropertyAssessmentPage(onSAveAll); diff --git a/lib/screens/passo/Building/add_building_components/AddExtraItems.dart b/lib/screens/passo/Building/add_building_components/AddExtraItems.dart index 8e36686..eb3a9a7 100644 --- a/lib/screens/passo/Building/add_building_components/AddExtraItems.dart +++ b/lib/screens/passo/Building/add_building_components/AddExtraItems.dart @@ -4,7 +4,8 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:intl/intl.dart'; import 'package:searchfield/searchfield.dart'; -import 'package:unit2/bloc/passo/additional_item/additional_item_bloc.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; import 'package:unit2/model/passo/additional_items.dart'; import 'package:unit2/model/passo/class_components.dart'; import 'package:unit2/model/passo/unit_construct.dart'; @@ -23,21 +24,19 @@ class AddExtraItems extends StatefulWidget { class _AddExtraItems extends State { GlobalKey formKey = GlobalKey(); final focus = FocusNode(); - double _computedValue = 0; bool isPainted = false; bool isSecondHand = false; TextEditingController textEditingController = TextEditingController(); double _unitBase = 0; int _areaValue = 0; - double _depValue = 0; + final double _depValue = 0; double _unitValue = 0; - double _marketValue = 0; String _className = ""; int _classId = 0; String _structureType = ""; bool _withoutBUCC = false; - double _notPaintedUnitVal = 0; - double _secondHandUnitVal = 0; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; BoxDecoration box1() { return const BoxDecoration(boxShadow: [ @@ -45,26 +44,16 @@ class _AddExtraItems extends State { ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); } - double _computeValue(double unitbase, double unitvalue, double area) { -// Compute some value based on the text here - return (unitbase * unitvalue) * area; - } - double _amountofDepreciation(unitVal, unitBase, area, depreciation) { return ((unitVal * unitBase) * area) * depreciation; } - double _adjustedMarketValue(unitVal, unitBase, area, depreciation) { - double depAmount = ((unitVal * unitBase) * area) * depreciation; - - return ((unitVal * unitBase) * area) - depAmount; - } - double _totalMarketValue(unitVal, unitBase, area, depreciation, withBUCC, className, painted, secondHand, paintedUnitVal, secondhandUntVal) { if (withBUCC == false) { if (painted == true || secondHand == true) { - final deductions = paintedUnitVal + secondhandUntVal; + final deductions = (paintedUnitVal + secondhandUntVal) / 100; + print(deductions); return (((unitVal - deductions) * unitBase) * area); } else { @@ -91,7 +80,7 @@ class _AddExtraItems extends State { child: Padding( padding: const EdgeInsets.all(8.0), child: Container( - height: 1000, + height: 800, child: SingleChildScrollView( padding: const EdgeInsets.all(8.0), child: Column( @@ -216,15 +205,11 @@ class _AddExtraItems extends State { suggestions: widget.unit .map((UnitConstruct unit) => SearchFieldListItem( - unit.bldgType! + - ' - ' + - unit.building, + '${unit.bldgType} - ${unit.building}', item: unit, child: ListTile( title: Text( - unit.bldgType + - ' - ' + - unit.building!.toUpperCase(), + '${unit.bldgType} - ${unit.building!.toUpperCase()}', overflow: TextOverflow.ellipsis, ), ))) @@ -245,9 +230,8 @@ class _AddExtraItems extends State { setState(() { _unitBase = double.parse(unit.item!.unitValue); - _structureType = unit.item!.bldgType + - ' - ' + - unit.item!.building; + _structureType = + '${unit.item!.bldgType} - ${unit.item!.building}'; }); focus.unfocus(); }, @@ -361,7 +345,7 @@ class _AddExtraItems extends State { child: Column( children: [ const SizedBox(height: 10), - Text('Building is not painted?'), + const Text('Building is not painted?'), const SizedBox(height: 5), Container( child: Row( @@ -372,9 +356,9 @@ class _AddExtraItems extends State { setState(() { isPainted = value!; if (value == false) { - _notPaintedUnitVal = 0.00; + _notPaintedUnitVal = 0; } else { - _notPaintedUnitVal = 0.10; + _notPaintedUnitVal = 10; } }); }, @@ -395,13 +379,14 @@ class _AddExtraItems extends State { child: Align( alignment: Alignment.center, child: Text(' - ' + - _notPaintedUnitVal.toString())), + _notPaintedUnitVal.toString() + + '%')), ), ], ), ), const SizedBox(height: 10), - Text('Uses second hand materials?'), + const Text('Uses second hand materials?'), const SizedBox(height: 5), Container( child: Row( @@ -416,39 +401,56 @@ class _AddExtraItems extends State { formKey.currentState!.patchValue( {'secondHandMat': '0'}); } else { - _secondHandUnitVal = 0.05; + _secondHandUnitVal = 5; formKey.currentState!.patchValue( - {'secondHandMat': '0.05'}); + {'secondHandMat': '5'}); } }); }, ), const SizedBox(width: 10), - SizedBox( - height: 40, - width: 100, - child: FormBuilderTextField( - enabled: isSecondHand, - name: 'secondHandMat', - textAlign: TextAlign.center, - decoration: normalTextFieldStyle( - "Unit Value", ""), - validator: - FormBuilderValidators.compose([]), - onChanged: (value) { - // Check if the value is not null before parsing to double - if (value != null && - value.isNotEmpty) { - setState(() { - _secondHandUnitVal = - double.parse(value); - }); - } else { - // Handle the case when the value is empty or null - // For example, set _secondHandUnitVal to a default value or show an error message. - } - }, - ), + Row( + children: [ + SizedBox( + height: 40, + width: 100, + child: FormBuilderTextField( + enabled: isSecondHand, + name: 'secondHandMat', + textAlign: TextAlign.center, + decoration: normalTextFieldStyle( + "Unit Value", ""), + validator: + FormBuilderValidators.compose( + []), + onChanged: (value) { + // Check if the value is not null before parsing to double + if (value != null && + value.isNotEmpty) { + setState(() { + _secondHandUnitVal = + int.parse(value); + }); + } else { + // Handle the case when the value is empty or null + // For example, set _secondHandUnitVal to a default value or show an error message. + } + }, + ), + ), + const SizedBox( + height: 40, + width: 40, + child: Center( + child: Text( + '%', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold), + ), + ), + ) + ], ), ], ), @@ -458,7 +460,7 @@ class _AddExtraItems extends State { ), const SizedBox(height: 10), - Text('Market Value'), + const Text('Market Value'), const SizedBox(height: 5), Container( height: 45.0, @@ -495,25 +497,34 @@ class _AddExtraItems extends State { height: 60, padding: const EdgeInsets.all(8.0), child: ElevatedButton( - onPressed: () { + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); var itemss = AdditionalItems( id: 1, - bldgapprDetailsId: 528, + bldgapprDetailsId: + tempID.getInt('tempid')! - 1, classId: _classId, className: _className, structType: _structureType, - unitValue: _unitValue, + unitValue: + _withoutBUCC == true ? 0 : _unitValue, baseUnitValue: _unitBase, area: _areaValue, marketValue: (_unitValue * _unitBase) * _areaValue, depreciationRate: _depValue, - adjustedMarketVal: _adjustedMarketValue( - _unitValue, - _unitBase, - _areaValue, - _depValue, - ), + adjustedMarketVal: _totalMarketValue( + _unitValue, + _unitBase, + _areaValue, + _depValue, + _withoutBUCC, + _className, + isPainted, + isSecondHand, + _notPaintedUnitVal, + _secondHandUnitVal), actualUse: 'Test', amtDepreciation: _amountofDepreciation( _unitValue, @@ -536,7 +547,7 @@ class _AddExtraItems extends State { child: const Text("Submit"), ), ), - SizedBox( + const SizedBox( width: 5), // Use SizedBox for horizontal spacing in a Row Container( @@ -547,7 +558,7 @@ class _AddExtraItems extends State { onPressed: () { context .read() - .add(LoadAdditionalItems()); + .add(const LoadAdditionalItems()); }, style: ElevatedButton.styleFrom( primary: Colors.black, diff --git a/lib/screens/passo/Building/add_building_components/ExtraItems.dart b/lib/screens/passo/Building/add_building_components/ExtraItems.dart deleted file mode 100644 index 90c6573..0000000 --- a/lib/screens/passo/Building/add_building_components/ExtraItems.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flutter/material.dart'; - -class ExtraItemsPage extends StatefulWidget { - @override - _ExtraItemsPage createState() => _ExtraItemsPage(); -} - -class _ExtraItemsPage extends State { - @override - Widget build(BuildContext context) { - return Container(); - } -} diff --git a/lib/screens/passo/Building/add_building_components/additional_items.dart b/lib/screens/passo/Building/add_building_components/additional_items.dart index d58bc5b..f087534 100644 --- a/lib/screens/passo/Building/add_building_components/additional_items.dart +++ b/lib/screens/passo/Building/add_building_components/additional_items.dart @@ -1,15 +1,22 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:unit2/bloc/passo/additional_item/additional_item_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; import 'package:unit2/model/passo/class_components.dart'; import 'package:unit2/model/passo/unit_construct.dart'; import 'package:unit2/screens/passo/Building/add_building_components/AddExtraItems.dart'; import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; class AdditionalItemPage extends StatefulWidget { final List unit; final List options; - AdditionalItemPage(this.unit, this.options); + + final VoidCallback additionalItemsPrevBtn; + final VoidCallback additionalItemsNextBtn; + + const AdditionalItemPage(this.unit, this.options, this.additionalItemsPrevBtn, + this.additionalItemsNextBtn); @override _AdditionalItemPage createState() => _AdditionalItemPage(); @@ -20,6 +27,14 @@ class _AdditionalItemPage extends State { context.read().add(DeleteAdditionalItems(id: itemId)); } + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketVal); + }); + return total; + } + @override Widget build(BuildContext context) { return BlocConsumer( @@ -29,130 +44,178 @@ class _AdditionalItemPage extends State { builder: (context, state) { final state = context.watch().state; if (state is AdditionalItemsLoaded) { - return SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.all(15.0), - child: Column( - children: [ - Container( - margin: const EdgeInsets.only( - left: 0, top: 20, right: 0, bottom: 10), - child: const Text('ADDITIONAL ITEMS', - style: TextStyle( - fontWeight: FontWeight.bold, fontSize: 18), - textAlign: TextAlign.left), - ), - Align( - alignment: Alignment.topRight, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.red, - ), - onPressed: () { - context - .read() - .add(ShowAdditionalItems()); - }, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Text('ADD ITEM'), // <-- Text - const SizedBox( - width: 5, - ), - const Icon( - // <-- Icon - Icons.add, - size: 24.0, - ), - ], - ), - ), - ), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: DataTable( - // ignore: prefer_const_literals_to_create_immutables - columns: [ - const DataColumn( - label: Text('Items'), + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('ADDITIONAL ITEMS', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), ), - const DataColumn( - label: Text('Unit Value'), - ), - const DataColumn( - label: Text('% of BUCC'), - ), - const DataColumn( - label: Text('Market Value'), - ), - const DataColumn( - label: Text('Action'), - ) - ], - rows: state.items.map((dataRow) { - return DataRow( - cells: [ - DataCell(Text(dataRow.className)), - DataCell(Text(dataRow.baseUnitValue)), - DataCell(Text(dataRow.unitValue)), - DataCell(Text(((double.parse(dataRow.unitValue) * - double.parse(dataRow.baseUnitValue) * - double.parse(dataRow.area))) - .toString())), - DataCell(Row( - children: [ - InkWell( - child: Container( - height: 30, - width: 30, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.red, - ), - child: Icon( - Icons.delete, - color: Colors.white, - size: 20.0, - ), - ), - onTap: () { - deleteItem(dataRow.id); - }, - ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowAdditionalItems()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Text('ADD ITEM'), // <-- Text SizedBox( - width: 10, + width: 5, ), - InkWell( - child: Container( - height: 30, - width: 30, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.red, - ), - child: Icon( - Icons.edit, - color: Colors.white, - size: 20.0, - ), - ), - onTap: () {}, + Icon( + // <-- Icon + Icons.add, + size: 24.0, ), ], - )) - ], - ); - }).toList(), + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Items'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('% of BUCC'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.items.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.className)), + DataCell(Text(dataRow.baseUnitValue)), + DataCell(Text(dataRow.unitValue)), + DataCell(Text(((double.parse( + dataRow.adjustedMarketVal))) + .toString())), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: const Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id); + }, + ), + const SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: const Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList(), + ), + ), + ], ), ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [Text('Total'), Text("0.00")], - ) - ], + ), ), - ), + Padding( + padding: const EdgeInsets.only(left: 20.0, right: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total', + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + ), + Text( + NumberFormat.currency(locale: 'en-PH', symbol: "₱") + .format(_totalMarketValue(state.items)), + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + ) + ], + ), + ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.additionalItemsPrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.additionalItemsNextBtn(); + } + ; + }, + ) + ], + ), + ), + ], ); } if (state is AdditionalItemsDeletedState) { @@ -172,11 +235,11 @@ class _AdditionalItemPage extends State { return ConstrainedBox( constraints: BoxConstraints(maxHeight: 1000.0), child: AlertDialog( - insetPadding: EdgeInsets.symmetric( + insetPadding: const EdgeInsets.symmetric( horizontal: 20.0, vertical: 10.0, ), - title: Text( + title: const Text( 'ADD EXTRA ITEMS', textAlign: TextAlign.center, ), @@ -210,12 +273,12 @@ class _AdditionalItemPage extends State { }, child: Row( mainAxisSize: MainAxisSize.min, - children: [ - const Text('ADD ITEM'), // <-- Text - const SizedBox( + children: const [ + Text('ADD ITEM'), // <-- Text + SizedBox( width: 5, ), - const Icon( + Icon( // <-- Icon Icons.add, size: 24.0, diff --git a/lib/screens/passo/Building/add_building_components/bldg_location_landref.dart b/lib/screens/passo/Building/add_building_components/bldg_location_landref.dart index 0d92c22..0ecfe0a 100644 --- a/lib/screens/passo/Building/add_building_components/bldg_location_landref.dart +++ b/lib/screens/passo/Building/add_building_components/bldg_location_landref.dart @@ -1,9 +1,32 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/barangay/barangay_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; + +import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart'; +import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; + +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/passo/custom_button.dart'; import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; +import '../../../../model/passo/barangay.dart'; + class BldgLocationLandrefPage extends StatefulWidget { - BldgLocationLandrefPage(); + final VoidCallback PrevBtn; + final VoidCallback NextBtn; + BldgLocationLandrefPage(this.PrevBtn, this.NextBtn); @override _BldgLocationLandrefPage createState() => _BldgLocationLandrefPage(); @@ -12,119 +35,302 @@ class BldgLocationLandrefPage extends StatefulWidget { class _BldgLocationLandrefPage extends State { @override Widget build(BuildContext context) { - return SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.all(20.0), - child: Column( - children: [ - Container( - margin: - const EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 10), - child: const Text('BUILDING LOCATION', - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), - textAlign: TextAlign.left), - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Expanded( - flex: 1, - child: customTextField("No. / Street", "", 'street'), - ), - const SizedBox(width: 10.0), - Expanded( - // optional flex property if flex is 1 because the default flex is 1 - flex: 1, - child: customTextField("Brgy. / District", "", 'brgy')) - ]), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Expanded( - flex: 1, - child: customTextField("Municipality", "", 'municipality'), - ), - const SizedBox(width: 10.0), - Expanded( - // optional flex property if flex is 1 because the default flex is 1 - flex: 1, - child: customTextField("Province / City", "", 'province')) - ]), - Container( - margin: - const EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 10), - child: const Text('LAND REFERENCE', - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), - textAlign: TextAlign.left), - ), - customTextField("Land Owner", "", 'l_owner'), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Expanded( - flex: 1, - child: - customTextField("OCT/TCT/CLOA No.", "", 'oct_tct_cloa'), - ), - const SizedBox(width: 10.0), - Expanded( - // optional flex property if flex is 1 because the default flex is 1 - flex: 1, - child: customTextField("Survey No.", "", 'survey_no')) - ]), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Expanded( - flex: 1, - child: customTextField("Lot No.", "", 'lot_no'), - ), - const SizedBox(width: 10.0), - Expanded( - // optional flex property if flex is 1 because the default flex is 1 - flex: 1, - child: customTextField("Blk No.", "", 'blk_no')) - ]), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Expanded( - flex: 1, - child: customTextField("TD / ARP No.", "", 'l_td_arp'), - ), - const SizedBox(width: 10.0), - Expanded( - // optional flex property if flex is 1 because the default flex is 1 - flex: 1, - child: customTextField("Area", "", 'area')) - ]), - SizedBox( - height: 50, - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - CustomButton( - icon: const Icon(Icons.chevron_left_rounded, - color: Colors.white), - onPressed: () { - {} - ; - }, - ), - CustomButton( - icon: const Icon(Icons.chevron_right_rounded, - color: Colors.white), - onPressed: () { - {} - ; - }, - ) - ], - ) - ], + return Scaffold( + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is MunicipalityLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is MunicipalityLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is MunicipalityErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is MunicipalityLoaded) { + List cityList = state.municipality; + + return BlocConsumer( + listener: (context, state) { + if (state is BarangayLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is BarangayLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is BarangayErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is BarangayLoaded) { + List brgyList = state.brgy; + List brgyNAmes = brgyList + .map((brgy) => brgy.barangayDescription) + .toList() + .cast(); + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('BUILDING LOCATION', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Province / City", "", 'province')), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'municipality', + autofocus: false, + decoration: normalTextFieldStyle( + "Municipality", ""), + items: cityList + .map((city) => + DropdownMenuItem( + value: city, + child: Text(city + .cityDescription!), // Use cityDescription instead of cityName + )) + .toList(), + onChanged: (selectedCity) { + if (selectedCity != null) { + final selectedCityCode = + selectedCity.cityCode; + final barangayBloc = + context.read(); + barangayBloc.add(LoadBarangay( + id: selectedCityCode!)); // Use selectedCityCode directly + } + }, + )), + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "No. / Street", "", 'street'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDropDownField( + "Brgy. / District", + "", + 'brgy', + brgyNAmes)) + ]), + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('LAND REFERENCE', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + customTextField("Land Owner", "", 'l_owner'), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "OCT/TCT/CLOA No.", "", 'oct_tct_cloa'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Survey No.", "", 'survey_no')) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Lot No.", "", 'lot_no'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Blk No.", "", 'blk_no')) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "TD / ARP No.", "", 'l_td_arp'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: + customTextField("Area", "", 'area')) + ]), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () async { + { + final tempID = + await SharedPreferences.getInstance(); + var bldgLocData = BldgLoc( + id: tempID.getInt('tempid')! - 1, + street: formKey + .currentState?.value['street'], + barangay: + formKey.currentState?.value['brgy'], + municipality: formKey + .currentState + ?.value['municipality'] + .cityDescription, + province: formKey + .currentState?.value['province'], + ); + var landRefData = LandRef( + id: tempID.getInt('tempid')! - 1, + owner: formKey + .currentState?.value['l_owner'], + cloaNo: formKey.currentState + ?.value['oct_tct_cloa'], + lotNo: formKey + .currentState?.value['lot_no'], + tdn: formKey + .currentState?.value['l_td_arp'], + area: + formKey.currentState?.value['area'], + surveyNo: formKey + .currentState?.value['survey_no'], + blkNo: formKey + .currentState?.value['blk_no'], + ); + context.read() + ..add(UpdateBldgLoc( + bldg_loc: bldgLocData)) + ..add(UpdateLandRef( + land_ref: landRefData)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ); + } + if (state is BarangayErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add(LoadBarangay(id: '1')); + }, + ); + } + return Container(); + }, + ); + } + if (state is MunicipalityErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add(LoadMunicipality()); + }, + ); + } + return Container(); + }, ), ), ); } + + Future _waitForAddPropertyInfoToComplete() async { + // Wait for the state change indicating completion + final propertyInfoState = context.read().state; + + if (propertyInfoState is PropertyInfoErrorState) { + // Check if the add operation was successful + return true; // You'll need to define this in your state class + } + + // Return false if the state didn't change as expected + return false; + } } diff --git a/lib/screens/passo/Building/add_building_components/general_description.dart b/lib/screens/passo/Building/add_building_components/general_description.dart index 7fc58f0..78bbbe2 100644 --- a/lib/screens/passo/Building/add_building_components/general_description.dart +++ b/lib/screens/passo/Building/add_building_components/general_description.dart @@ -1,13 +1,22 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/model/passo/general_description.dart'; import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/widgets/passo/custom_button.dart'; import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; class GeneralDescriptionPage extends StatefulWidget { final List unit; - GeneralDescriptionPage(this.unit); + final VoidCallback onPutGeneralDescription; + final VoidCallback gendescPrevBtn; + + GeneralDescriptionPage( + this.unit, this.onPutGeneralDescription, this.gendescPrevBtn); @override _GeneralDescriptionPage createState() => _GeneralDescriptionPage(); @@ -46,7 +55,7 @@ class _GeneralDescriptionPage extends State { items: widget.unit .map((e) => DropdownMenuItem( value: e, - child: Text(e.bldgType + '-' + e.building), + child: Text('${e.bldgType}-${e.building}'), )) .toList(), ), @@ -157,15 +166,53 @@ class _GeneralDescriptionPage extends State { icon: const Icon(Icons.chevron_left_rounded, color: Colors.white), onPressed: () { - {} + { + widget.gendescPrevBtn(); + } ; }, ), CustomButton( icon: const Icon(Icons.chevron_right_rounded, color: Colors.white), - onPressed: () { - {} + onPressed: () async { + { + final tempID = await SharedPreferences.getInstance(); + widget.onPutGeneralDescription(); + var genDescData = GeneralDesc( + id: tempID.getInt('tempid')! - 1, + bldgKind: + formKey.currentState?.value['bldg_type'].building, + strucType: + formKey.currentState?.value['bldg_type'].bldgType, + bldgPermit: + formKey.currentState?.value['bldg_permit'], + dateIssued: formKey.currentState?.value['coc_issued'], + cct: formKey.currentState?.value['cct'], + certCompletionIssued: + formKey.currentState?.value['coc_issued'], + certOccupancyIssued: + formKey.currentState?.value['coo_issued'], + dateCompleted: + formKey.currentState?.value['date_cnstructed'], + dateOccupied: + formKey.currentState?.value['date_occupied'], + bldgAge: int.tryParse( + formKey.currentState?.value['bldg_age']), + noStoreys: int.tryParse( + formKey.currentState?.value['no_of_storeys']), + area1Stfloor: '0', + area2Ndfloor: '0', + area3Rdfloor: '0', + area4Thfloor: '0', + totalFloorArea: + formKey.currentState?.value['total_area'], + floorSketch: null, + actualUse: formKey.currentState?.value['actual_use']); + + context.read() + ..add(UpdateGeneralDesc(gen_desc: genDescData)); + } ; }, ) diff --git a/lib/screens/passo/Building/add_building_components/property_appraisal.dart b/lib/screens/passo/Building/add_building_components/property_appraisal.dart index 9b909e0..e746860 100644 --- a/lib/screens/passo/Building/add_building_components/property_appraisal.dart +++ b/lib/screens/passo/Building/add_building_components/property_appraisal.dart @@ -3,13 +3,20 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:intl/intl.dart'; -import 'package:unit2/bloc/passo/additional_item/additional_item_bloc.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart'; import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; import 'package:unit2/screens/passo/Building/add_building.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; class PropertyAppraisalPage extends StatefulWidget { - PropertyAppraisalPage(); + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + PropertyAppraisalPage(this.NextBtn, this.PrevBtn); @override _PropertyAppraisalPage createState() => _PropertyAppraisalPage(); @@ -17,6 +24,433 @@ class PropertyAppraisalPage extends StatefulWidget { class _PropertyAppraisalPage extends State { double depRate = 0; + + double _depRate = 0; + + double assessment_level = 0; + bool isTaxable = false; + bool isExempt = false; + String _memoranda = ''; + final focus = FocusNode(); + + String assessmentLevel(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return '0 '; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return '10 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return '20 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return '25 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return '80 '; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + default: + } + return ''; + } + + double assessmentValue(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return marketValue * 0; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return marketValue * 0.10; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return marketValue * 0.20; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return marketValue * 0.25; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return marketValue * 0.80; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + default: + } + return 0; + } + calculateAdditionalItems(List items) { double sum = 0; double product = 1; @@ -68,9 +502,7 @@ class _PropertyAppraisalPage extends State { @override Widget build(BuildContext context) { return BlocConsumer( - listener: (context, state) { - // TODO: implement listener - }, + listener: (context, state) {}, builder: (context, state) { if (state is AdditionalItemsLoaded) { return SingleChildScrollView( @@ -233,7 +665,7 @@ class _PropertyAppraisalPage extends State { height: 25, child: FormBuilderTextField( name: 'depRate', - decoration: normalTextFieldStyle("0.00", ""), + decoration: normalTextFieldStyle("", ""), validator: FormBuilderValidators.compose([]), onChanged: (value) { setState(() { @@ -285,7 +717,7 @@ class _PropertyAppraisalPage extends State { ), Container( child: Text( - '0.00', + '${(depRate * 100).toStringAsFixed(2)}%', textAlign: TextAlign.right, ), ) @@ -315,9 +747,279 @@ class _PropertyAppraisalPage extends State { .toString(), textAlign: TextAlign.right, ), + ), + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Container( + margin: const EdgeInsets.only( + left: 20.0, right: 20.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text('PROPERTY ASSESSMENT', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + Column( + children: [ + Row( + children: [ + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: const Text( + 'Actual Use', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: const Text( + 'Market Value', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: const Text( + 'Ass. Level', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: const Text( + 'Ass. Value', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + ], + ), + SizedBox( + height: 59, + child: Row( + children: [ + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: Text( + formKey.currentState + ?.value['actual_use']!, + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: Text( + calculateMarketValue( + (double.parse(formKey + .currentState! + .value[ + 'total_area']) * + double.parse(formKey + .currentState! + .value[ + 'bldg_type'] + .unitValue)), + state.items, + depRate) + .toString(), + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: Text( + assessmentLevel( + calculateMarketValue( + (double.parse(formKey + .currentState! + .value[ + 'total_area']) * + double.parse(formKey + .currentState! + .value[ + 'bldg_type'] + .unitValue)), + state.items, + depRate) + .toString(), + formKey.currentState + ?.value[ + 'actual_use']), + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + Container( + width: 100, + margin: const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all(5.0), + child: Text( + assessmentValue( + calculateMarketValue( + (double.parse(formKey.currentState!.value[ + 'total_area']) * + double.parse(formKey + .currentState! + .value[ + 'bldg_type'] + .unitValue)), + state.items, + depRate) + .toString(), + formKey.currentState + ?.value[ + 'actual_use']) + .toString(), + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + ], + ), + ) + ], + ), + ]))), + ), + ], + ), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () async { + { + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('tempid')); + var appraisals = PropertyAppraisal( + id: 1, + bldgapprDetailsId: tempID.getInt('tempid')!, + unitconstructCost: formKey + .currentState!.value['bldg_type'].unitValue, + buildingCore: 'test', + unitconstructSubtotal: + (double.parse(formKey.currentState!.value['total_area']) * + double.parse(formKey.currentState! + .value['bldg_type'].unitValue)) + .toString(), + depreciationRate: depRate.toString(), + depreciationCost: calculateDepCost( + (double.parse(formKey.currentState!.value['total_area']) * + double.parse( + formKey.currentState!.value['bldg_type'].unitValue)), + state.items, + depRate) + .toString(), + costAddItems: calculateAdditionalItems(state.items).toString(), + addItemsSubtotal: calculateAdditionalItems(state.items).toString(), + totalpercentDepreciation: (depRate * 100).toStringAsFixed(2), + marketValue: calculateMarketValue((double.parse(formKey.currentState!.value['total_area']) * double.parse(formKey.currentState!.value['bldg_type'].unitValue)), state.items, depRate).toString(), + totalArea: formKey.currentState!.value['total_area']); + context.read() + ..add( + AddPropertyAppraisal(appraisal: appraisals)); + + widget.NextBtn(); + } + ; + }, ) ], - ) + ), ], ), ), diff --git a/lib/screens/passo/Building/add_building_components/property_assessment.dart b/lib/screens/passo/Building/add_building_components/property_assessment.dart index e93a223..ff0d03c 100644 --- a/lib/screens/passo/Building/add_building_components/property_assessment.dart +++ b/lib/screens/passo/Building/add_building_components/property_assessment.dart @@ -2,16 +2,26 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:intl/intl.dart'; -import 'package:unit2/bloc/passo/property_appraisal/property_appraisal_bloc.dart'; -import 'package:unit2/bloc/passo/property_assessment/property_assessment_bloc.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart'; + import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; +import 'package:unit2/model/passo/memoranda.dart'; import 'package:unit2/model/passo/property_appraisal.dart'; import 'package:unit2/model/passo/property_assessment.dart'; import 'package:unit2/model/passo/signatories.dart'; import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; class PropertyAssessmentPage extends StatefulWidget { @@ -27,8 +37,11 @@ class _PropertyAssessmentPage extends State { double assessment_level = 0; bool isTaxable = false; bool isExempt = false; + String _memoranda = ''; + final focus = FocusNode(); - String assessmentLevel(marketValue, property_class) { + String assessmentLevel(marketValues, property_class) { + final marketValue = double.parse(marketValues); switch (property_class) { case 'Residential': if (marketValue < 175000) { @@ -236,7 +249,8 @@ class _PropertyAssessmentPage extends State { return ''; } - double assessmentValue(marketValue, property_class, appraisal) { + double assessmentValue(marketValues, property_class) { + final marketValue = double.parse(marketValues); switch (property_class) { case 'Residential': if (marketValue < 175000) { @@ -446,761 +460,709 @@ class _PropertyAssessmentPage extends State { @override Widget build(BuildContext context) { - return BlocBuilder( - builder: (context, state) { - if (state is PropertyAssessmentLoaded) { - return BlocConsumer( - listener: (context, state) { - // TODO: implement listener - }, builder: (context, state) { - if (state is PropertyAppraisalLoaded) { - final appraisal = state.appraisal; + return Scaffold( + resizeToAvoidBottomInset: true, + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is PropertyAssessmentLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PropertyAssessmentLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is PropertyAssessmentErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is PropertyAssessmentLoaded) { return BlocConsumer( listener: (context, state) { - // TODO: implement listener + if (state is SignatoriesLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is SignatoriesLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is SignatoriesErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } }, builder: (context, state) { if (state is SignatoriesLoaded) { - return Column( - children: [ - Expanded( - flex: 1, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Container( - margin: const EdgeInsets.only( - left: 20.0, right: 20.0), - child: Column( - mainAxisAlignment: - MainAxisAlignment.start, - children: [ - Container( - margin: const EdgeInsets.only( - left: 0, - top: 20, - right: 0, - bottom: 20), - child: const Text( - 'PROPERTY ASSESSMENT', - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 18), - textAlign: TextAlign.left), + final signatories = state.signatories; + return BlocConsumer( + listener: (context, state) { + if (state is MemorandaLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is MemorandaLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is MemorandaErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + final memoranda = state.memorada; + return BlocConsumer( + listener: (context, state) { + if (state is PropertyAppraisalLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PropertyAppraisalLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is PropertyAppraisalErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, builder: (context, state) { + if (state is PropertyAppraisalLoaded) { + return ListView( + children: [ + Align( + alignment: Alignment.center, + child: Container( + margin: const EdgeInsets.fromLTRB( + 0, 20, 0, 20), + child: const Text( + 'PROPERTY ASSESSMENT cont..', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, ), - Column( + textAlign: TextAlign.left, + ), + ), + ), + Expanded( + flex: 3, + child: SingleChildScrollView( + padding: EdgeInsets.only( + left: 20.0, right: 20.0), + scrollDirection: Axis.vertical, + child: Column(children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, children: [ Row( children: [ - Container( - width: 100, - margin: const EdgeInsets.only( - top: 15, left: 15), - padding: - const EdgeInsets.all(5.0), - child: const Text( - 'Actual Use', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 13, - ), - textAlign: TextAlign.center, + const Text('Taxable'), + Checkbox( + checkColor: Colors.white, + value: isTaxable, + onChanged: (bool? value) { + setState(() { + isTaxable = value!; + }); + }, + ) + ], + ), + Row( + children: [ + const Text('Exempt'), + Checkbox( + checkColor: Colors.white, + value: isExempt, + onChanged: (bool? value) { + setState(() { + isExempt = value!; + }); + }, + ) + ], + ), + ], + ), + Column( + children: [ + const SizedBox( + height: 20, + ), + const Text( + 'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :', + style: TextStyle( + fontWeight: FontWeight.bold), + ), + const SizedBox( + height: 20, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + const Text('Qtr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'qtr', + validator: + FormBuilderValidators + .compose([]), ), ), - Container( - width: 100, - margin: const EdgeInsets.only( - top: 15, left: 15), - padding: - const EdgeInsets.all(5.0), - child: const Text( - 'Market Value', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 13, - ), - textAlign: TextAlign.center, - ), + const SizedBox( + width: 20, ), - Container( - width: 100, - margin: const EdgeInsets.only( - top: 15, left: 15), - padding: - const EdgeInsets.all(5.0), - child: const Text( - 'Ass. Level', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 13, - ), - textAlign: TextAlign.center, - ), - ), - Container( - width: 100, - margin: const EdgeInsets.only( - top: 15, left: 15), - padding: - const EdgeInsets.all(5.0), - child: const Text( - 'Ass. Value', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 13, - ), - textAlign: TextAlign.center, + const Text('Yr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'yr', + validator: + FormBuilderValidators + .compose([]), ), ), ], ), - SizedBox( - height: 59, - child: SingleChildScrollView( - scrollDirection: - Axis.horizontal, - child: Row( - children: List.generate( - appraisal.length, - (index) { - return Container( - height: 100, - child: Row( - children: [ - Container( - width: 100, - margin: - const EdgeInsets - .only( - top: 15, - left: 15), - padding: - const EdgeInsets - .all(5.0), - child: Text( - formKey.currentState! - .value[ - 'actual_use'], - style: - TextStyle( - fontWeight: - FontWeight - .bold, - fontSize: 13, - ), - textAlign: - TextAlign - .center, - ), - ), - Container( - width: 100, - margin: - const EdgeInsets - .only( - top: 15, - left: 15), - padding: - const EdgeInsets - .all(5.0), - child: Text( - NumberFormat - .currency( - locale: - 'en-PH', - symbol: "₱", - ).format(double - .parse(appraisal[ - index] - .marketValue)), - style: - TextStyle( - fontWeight: - FontWeight - .bold, - fontSize: 13, - ), - textAlign: - TextAlign - .center, - ), - ), - Container( - width: 100, - margin: - const EdgeInsets - .only( - top: 15, - left: 15), - padding: - const EdgeInsets - .all(5.0), - child: Text( - assessmentLevel( - double - .parse( - appraisal - .elementAt(index) - .marketValue, - ), - formKey - .currentState! - .value['actual_use'], - ) + - '%', - style: - TextStyle( - fontWeight: - FontWeight - .bold, - fontSize: 13, - ), - textAlign: - TextAlign - .center, - ), - ), - Container( - width: 100, - margin: - const EdgeInsets - .only( - top: 15, - left: 15), - padding: - const EdgeInsets - .all(5.0), - child: Text( - NumberFormat - .currency( - locale: - 'en-PH', - symbol: "₱", - ).format( - assessmentValue( - double.parse( - appraisal[index] - .marketValue), - formKey.currentState! - .value[ - 'actual_use'], - appraisal, - ), - ), - style: - TextStyle( - fontWeight: - FontWeight - .bold, - fontSize: 13, - ), - textAlign: - TextAlign - .center, - ), - ), - const SizedBox( - height: 80, - ), - ], - ), - ); - }, - ), - ), - ), - ) ], ), - ]))), - ), - Expanded( - flex: 3, - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column(children: [ - Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - children: [ - Row( - children: [ - const Text('Taxable'), - Checkbox( - checkColor: Colors.white, - value: isTaxable, - onChanged: (bool? value) { - setState(() { - isTaxable = value!; - }); - }, - ) - ], - ), - Row( - children: [ - const Text('Exempt'), - Checkbox( - checkColor: Colors.white, - value: isExempt, - onChanged: (bool? value) { - setState(() { - isExempt = value!; - }); - }, - ) - ], - ), - ], - ), - Column( - children: [ - const SizedBox( - height: 20, - ), - const Text( - 'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :', - style: - TextStyle(fontWeight: FontWeight.bold), - ), - const SizedBox( - height: 20, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - children: [ - const Text('Qtr.'), - SizedBox( - width: 70, - height: 25, - child: FormBuilderTextField( - name: 'qtr', - validator: - FormBuilderValidators.compose([]), + const SizedBox( + height: 30, ), - ), - const SizedBox( - width: 20, - ), - const Text('Yr.'), - SizedBox( - width: 70, - height: 25, - child: FormBuilderTextField( - name: 'yr', - validator: - FormBuilderValidators.compose([]), + Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPRAISED/ASSESSED BY:', + style: TextStyle( + fontWeight: FontWeight.bold), + textAlign: TextAlign.start, + ), ), - ), - ], - ), - ], - ), - const SizedBox( - height: 30, - ), - Align( - alignment: Alignment.centerLeft, - child: Text( - 'APPRAISED/ASSESSED BY:', - style: TextStyle(fontWeight: FontWeight.bold), - textAlign: TextAlign.start, - ), - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - children: [ - Column( - children: [ - SizedBox( - width: 200, - child: FormBuilderDropdown( - name: 'appraised_by', - autofocus: false, - items: state.signatories - .map((signatories) => - DropdownMenuItem( - value: signatories, - child: Text(signatories - .firstname + - ' ' + - signatories - .middlename + - ' ' + - signatories.lastname), - )) - .toList()), - ), - Text('Name'), - ], - ), - SizedBox( - width: 15, - ), - Column( - children: [ - SizedBox( - width: 100, - child: customDatTimePicker( - "Date", "", 'app_date')), - Text('Date'), - ], - ), - ], - ), - SizedBox( - height: 30, - ), - Align( - alignment: Alignment.centerLeft, - child: Text( - 'RECOMMENDING APPROVAL:', - style: - TextStyle(fontWeight: FontWeight.bold), - )), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - children: [ - Column( - children: [ - SizedBox( - width: 200, - child: FormBuilderDropdown( - name: 'rec_approval', - autofocus: false, - items: state.signatories - .map((signatories) => - DropdownMenuItem( - value: signatories, - child: Text(signatories - .firstname + - ' ' + - signatories - .middlename + - ' ' + - signatories.lastname), - )) - .toList()), - ), - Text('Name'), - ], - ), - SizedBox( - width: 15, - ), - Column( - children: [ - SizedBox( - width: 100, - child: customDatTimePicker( - "Date", "", 'rec_date'), - ), - Text('Date'), - ], - ), - ], - ), - SizedBox( - height: 30, - ), - Align( - alignment: Alignment.centerLeft, - child: Text( - 'APPROVED BY:', - style: TextStyle( - fontWeight: FontWeight.bold, - ), - )), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Column( - children: [ - SizedBox( - width: 200, - child: FormBuilderDropdown( - name: 'apprvd_by', - autofocus: false, - items: state.signatories - .map((signatories) => - DropdownMenuItem( - value: signatories, - child: Text(signatories - .firstname + - ' ' + - signatories - .middlename + - ' ' + - signatories.lastname), - )) - .toList()), - ), - Text('Name'), - ], - ), - ], - ), - SizedBox( - height: 50, - ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'appraised_by', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: + FormBuilderDateTimePicker( + name: 'app_date', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: + DateTime.now(), + inputType: InputType.date, - Align( - alignment: Alignment.centerLeft, - child: Text( - 'MEMORANDA: ', - style: TextStyle( - fontWeight: FontWeight.bold, - ), - )), - SizedBox( - height: 30, - ), - SizedBox( - width: 500, - child: FormBuilderTextField( - name: 'memoranda', - decoration: - normalTextFieldStyle("Memoranda", ""), - minLines: - 6, // any number you need (It works as the rows for the textarea) - keyboardType: TextInputType.multiline, - maxLines: null, - ), - ), - SizedBox( - height: 30, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Text('Sworn Statement No. :'), - SizedBox( - width: 150, - height: 20, - child: FormBuilderTextField( - name: 'sworn_statement', - decoration: InputDecoration(), - validator: - FormBuilderValidators.compose([]), - ), - ), - ], - ), - SizedBox( - height: 30, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Text('Date Received:'), - SizedBox( - width: 150, - height: 20, - child: customDatTimePicker( - "Date Received", - "", - 'date_received')), - ], - ), - SizedBox( - height: 30, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Text('Date of Entry in the Rec. of Ass. :'), - SizedBox( - width: 150, - height: 20, - child: customDatTimePicker( - 'Date of Entry in the Rec. of Ass. :', - '', - 'date_of_entry')), - ], - ), - SizedBox( - height: 30, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Text('By:'), - SizedBox( - width: 150, - height: 20, - child: FormBuilderTextField( - name: 'by', - decoration: InputDecoration(), - validator: - FormBuilderValidators.compose([]), - ), - ), - ], - ), - SizedBox( - height: 30, - ), - ElevatedButton( - onPressed: () { - final List - propertyAssessments = []; - - appraisal.asMap().forEach( - (index, PropertyAppraisal appraisal) { - PropertyAssessment ass = PropertyAssessment( - id: 1, - bldgapprDetailsId: 440, - actualUse: formKey - .currentState!.value['actual_use'], - marketValue: appraisal.marketValue, - assessmentLevel: assessmentLevel( - double.parse( - appraisal.marketValue, + initialTime: + const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], ), - formKey - .currentState!.value['actual_use'], - ), - assessedValue: assessmentValue( - double.parse(appraisal.marketValue), - formKey - .currentState!.value['actual_use'], - appraisal, - ).toString(), - taxable: isTaxable, - exempt: isExempt, - qtr: int.parse( - formKey.currentState!.value['qtr']), - yr: int.parse( - formKey.currentState!.value['yr']), - appraisedbyName: formKey.currentState! - .value['appraised_by'].firstname + - ' ' + - formKey - .currentState! - .value['appraised_by'] - .middlename + - ' ' + - formKey.currentState! - .value['appraised_by'].lastname, - appraisedbyDate: formKey - .currentState!.value['app_date'], - recommendapprName: formKey.currentState! - .value['rec_approval'].firstname + - ' ' + - formKey - .currentState! - .value['rec_approval'] - .middlename + - ' ' + - formKey.currentState! - .value['rec_approval'].lastname, - recommendapprDate: formKey - .currentState!.value['rec_date'], - approvedbyName: formKey.currentState! - .value['apprvd_by'].firstname + - ' ' + - formKey.currentState! - .value['apprvd_by'].middlename + - ' ' + - formKey.currentState! - .value['apprvd_by'].lastname, - memoranda: formKey - .currentState!.value['memoranda'], - swornstatementNo: formKey.currentState! - .value['sworn_statement'], - dateReceived: formKey - .currentState!.value['date_received'], - entryDateAssessment: formKey - .currentState!.value['date_of_entry'], - entryDateBy: - formKey.currentState!.value['by'], - ); + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'RECOMMENDING APPROVAL:', + style: TextStyle( + fontWeight: FontWeight.bold), + )), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'rec_approval', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: + FormBuilderDateTimePicker( + name: 'rec_date', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: + DateTime.now(), + inputType: InputType.date, - propertyAssessments.add(ass); - }); + initialTime: + const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPROVED BY:', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'apprvd_by', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + ], + ), + const SizedBox( + height: 50, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'MEMORANDA: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + SizedBox( + height: 30, + ), + SizedBox( + width: 500, + height: 100, + child: SearchField( + itemHeight: 70, + suggestions: memoranda + .map((Memoranda memoranda) => + SearchFieldListItem( + '${memoranda.memoranda}', + item: + memoranda, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${memoranda.memoranda}', + overflow: + TextOverflow + .ellipsis, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + // searchInputDecoration: + // normalTextFieldStyle( + // "Memoranda", "") + // .copyWith( + // suffixIcon: const Icon( + // Icons.arrow_drop_down), + // ), + // focusNode: focus, + suggestionState: + Suggestion.expand, + onSuggestionTap: (memoranda) { + setState(() { + _memoranda = memoranda + .item!.memoranda!; + }); + focus.unfocus(); + }, + )), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('Sworn Statement No. :'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'sworn_statement', + decoration: InputDecoration(), + validator: FormBuilderValidators + .compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('Date Received:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_received', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, - context.read() - ..add(UpdatePropertyAssessment( - assessment: propertyAssessments[0])); - widget.function(); + initialTime: const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Date of Entry in the Rec. of Ass. :'), + SizedBox( + width: 100, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_of_entry', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('By:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'by', + decoration: InputDecoration(), + validator: FormBuilderValidators + .compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences + .getInstance(); + print(tempID.getInt('tempid')! - 1); + final List + propertyAssessments = []; + + PropertyAssessment ass = + PropertyAssessment( + id: 1, + bldgapprDetailsId: + tempID.getInt('tempid')! - 1, + actualUse: formKey.currentState! + .value['actual_use'], + marketValue: '0.00', + assessmentLevel: '0.00', + assessedValue: '0.00', + taxable: isTaxable, + exempt: isExempt, + qtr: int.parse(formKey + .currentState!.value['qtr']), + yr: int.parse(formKey + .currentState!.value['yr']), + appraisedbyName: formKey + .currentState! + .value['appraised_by'] + .firstname + + ' ' + + formKey + .currentState! + .value['appraised_by'] + .middlename + + ' ' + + formKey + .currentState! + .value['appraised_by'] + .lastname, + appraisedbyDate: formKey + .currentState! + .value['app_date'], + recommendapprName: formKey + .currentState! + .value['rec_approval'] + .firstname + + ' ' + + formKey + .currentState! + .value['rec_approval'] + .middlename + + ' ' + + formKey + .currentState! + .value['rec_approval'] + .lastname, + recommendapprDate: formKey + .currentState! + .value['rec_date'], + approvedbyName: formKey + .currentState! + .value['apprvd_by'] + .firstname + + ' ' + + formKey + .currentState! + .value['apprvd_by'] + .middlename + + ' ' + + formKey + .currentState! + .value['apprvd_by'] + .lastname, + memoranda: _memoranda, + swornstatementNo: formKey + .currentState! + .value['sworn_statement'], + dateReceived: formKey + .currentState! + .value['date_received'], + entryDateAssessment: formKey + .currentState! + .value['date_of_entry'], + entryDateBy: formKey + .currentState!.value['by'], + ); + + propertyAssessments.add(ass); + + context + .read() + ..add(UpdatePropertyAssessment( + assessment: + propertyAssessments[0])); + widget.function(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: primary, + foregroundColor: Colors.red), + child: SizedBox( + width: 200, + height: 50, + child: Align( + alignment: Alignment.center, + child: Text( + 'Save', + style: TextStyle( + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + SizedBox( + height: 30, + ), + ]), + ), + ) + ], + ); + } + if (state is PropertyAppraisalErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add( + LoadPropertyAppraisal( + appraisal: PropertyAppraisal())); }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.red, - foregroundColor: Colors.red), - child: SizedBox( - width: 200, - height: 50, - child: Align( - alignment: Alignment.center, - child: Text( - 'Save', - style: TextStyle( - color: Colors.white, - ), - textAlign: TextAlign.center, - ), - ), - ), - ), - SizedBox( - height: 30, - ), - // Row( - // mainAxisAlignment: - // MainAxisAlignment.spaceAround, - // children: [ - // ElevatedButton( - // onPressed: () { - // // Decrement activeStep, when the previous button is tapped. However, check for lower bound i.e., must be greater than 0. - // if (activeStep > 0) { - // setState(() { - // activeStep--; - // }); - // } - // }, - // style: ElevatedButton.styleFrom( - // shape: const CircleBorder(), - // padding: - // const EdgeInsets.all(30), - // backgroundColor: Colors.red, - // foregroundColor: Colors.red), - // child: const Icon( - // Icons.chevron_left, - // color: Colors.white)), - - // ], - // ) - ]), - ), - ) - ], + ); + } + return Container(); + }); + } + if (state is MemorandaErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadMemoranda()); + }, + ); + } + return Container(); + }, + ); + } + if (state is SignatoriesErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add(LoadSignatories()); + }, ); } return Container(); }, ); } - if (state is PropertyAppraisalErrorState) { - return Text(state.error); + if (state is PropertyAssessmentErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadPropertyAssessment()); + }, + ); } return Container(); - }); - } - if (state is PropertyAssessmentErrorState) { - return Text(state.error); - } - return Text('null'); - }, + }, + ), + ), ); } } diff --git a/lib/screens/passo/Building/add_building_components/property_info.dart b/lib/screens/passo/Building/add_building_components/property_info.dart index 86c49d9..6cad1fc 100644 --- a/lib/screens/passo/Building/add_building_components/property_info.dart +++ b/lib/screens/passo/Building/add_building_components/property_info.dart @@ -1,15 +1,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package:intl/intl.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; import 'package:unit2/widgets/passo/custom_button.dart'; import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; +GlobalKey ownerKey = GlobalKey(); + class PropertyInfoPage extends StatefulWidget { final VoidCallback handleButtonPress; - PropertyInfoPage(this.handleButtonPress); + const PropertyInfoPage(this.handleButtonPress, {super.key}); @override _PropertyInfoPage createState() => _PropertyInfoPage(); @@ -19,13 +21,6 @@ class _PropertyInfoPage extends State { int tempId = 0; final transaction_codes = ['New', 'Revision']; - Future _loadTempId() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - tempId = (prefs.getInt('tempid') ?? 0); - }); - } - @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -102,12 +97,60 @@ class _PropertyInfoPage extends State { const SizedBox(height: 25), CustomButton( icon: const Icon(Icons.chevron_right, color: Colors.white), - onPressed: () { - widget.handleButtonPress(); + onPressed: () async { + var property_info = PropertyInfo( + id: 1, + transCode: formKey.currentState!.value['transaction_code'] + .toString(), + tdn: formKey.currentState!.value['arp_td'], + pin: formKey.currentState!.value['pin'], + owner: formKey.currentState!.value['owner'], + address: formKey.currentState!.value['address'], + telno: formKey.currentState!.value['tel_no'], + tin: formKey.currentState!.value['tin'], + adminUser: formKey.currentState!.value['benificiary'], + adminAddress: + formKey.currentState!.value['benificiary_address'], + adminTin: formKey.currentState!.value['benificiary_tin'], + adminTelno: + formKey.currentState!.value['benificiary_telno'], + assessedById: '1', + assessedByName: 'Cyril', + faasType: "BUILDING", + dateModified: DateTime.now(), + dateCreated: DateTime.now()); + + // Dispatch the event to add the property_info + context.read().add( + AddPropertyInfo(property_info: property_info), + ); + + // Wait for the event to complete and get the result + bool success = await _waitForAddPropertyInfoToComplete(); + + if (success) { + // Proceed to the next step or perform an action + widget.handleButtonPress(); + } else { + // Stay or show an error message + } }, ) ]), ), ); } + + Future _waitForAddPropertyInfoToComplete() async { + // Wait for the state change indicating completion + final propertyInfoState = context.read().state; + + if (propertyInfoState is PropertyInfoLoaded) { + // Check if the add operation was successful + return true; // You'll need to define this in your state class + } + + // Return false if the state didn't change as expected + return false; + } } diff --git a/lib/screens/passo/Building/add_building_components/structural_materials.dart b/lib/screens/passo/Building/add_building_components/structural_materials.dart index 31476be..67f6edd 100644 --- a/lib/screens/passo/Building/add_building_components/structural_materials.dart +++ b/lib/screens/passo/Building/add_building_components/structural_materials.dart @@ -1,5 +1,12 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:multiselect/multiselect.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; class MaterialOption { final String id; @@ -9,6 +16,11 @@ class MaterialOption { } class StructuralMaterialsPage extends StatefulWidget { + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + StructuralMaterialsPage(this.NextBtn, this.PrevBtn); + @override _StructuralMaterialsPage createState() => _StructuralMaterialsPage(); } @@ -21,6 +33,13 @@ class _StructuralMaterialsPage extends State { List roof = []; List flooring = []; List walls = []; + bool foundationOthers = false; + bool columOthers = false; + bool beamsOthers = false; + bool tfOthers = false; + bool roofOthers = false; + bool flooringOthers = false; + bool wpOthers = false; List columnOptions = [ MaterialOption('steel', 'Steel'), @@ -43,184 +62,358 @@ class _StructuralMaterialsPage extends State { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), textAlign: TextAlign.left), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'FOUNDATION', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: foundationOthers, + onChanged: (bool? value) { + setState(() { + foundationOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - foundation = x; - }); - }, - options: const ['Reinforced Concrete', 'Plain Concrete'], - selectedValues: foundation, - whenEmpty: 'Select Foundations', + child: Visibility( + visible: foundationOthers, + child: customTextField( + "Enter other foundation", "", "other_foundation"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + foundation = x; + }); + }, + options: const ['Reinforced Concrete', 'Plain Concrete'], + selectedValues: foundation, + whenEmpty: 'Select Foundations', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'COLUMNS', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: columOthers, + onChanged: (bool? value) { + setState(() { + columOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - column = x; - }); - }, - options: const ['Steel', 'Reinforced Concrete', 'Wood'], - selectedValues: column, - whenEmpty: 'Select Columns', + child: Visibility( + visible: columOthers, + child: customTextField("Enter other columns", "", "other_column"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + column = x; + }); + }, + options: const ['Steel', 'Reinforced Concrete', 'Wood'], + selectedValues: column, + whenEmpty: 'Select Column/s', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'BEAMS', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: beamsOthers, + onChanged: (bool? value) { + setState(() { + beamsOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - beam = x; - }); - }, - options: const ['Steel', 'Reinforced Concrete', 'Wood'], - selectedValues: beam, - whenEmpty: 'Select Beams', + child: Visibility( + visible: beamsOthers, + child: customTextField("Enter other beam/s", "", "other_beam"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + beam = x; + }); + }, + options: const ['Steel', 'Reinforced Concrete', 'Wood'], + selectedValues: beam, + whenEmpty: 'Select Beam/s', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'TRUSS FRAMING', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: tfOthers, + onChanged: (bool? value) { + setState(() { + tfOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - truss_framing = x; - }); - }, - options: const ['Steel', 'Wood'], - selectedValues: truss_framing, - whenEmpty: 'Select Truss Framing', + child: Visibility( + visible: tfOthers, + child: customTextField( + "Enter other truss framing/s", "", "other_tf"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + truss_framing = x; + }); + }, + options: const ['Steel', 'Wood'], + selectedValues: truss_framing, + whenEmpty: 'Select Truss Framing/s', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'ROOF', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: roofOthers, + onChanged: (bool? value) { + setState(() { + roofOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - roof = x; - }); - }, - options: const [ - 'Reinforced Concrete', - 'Tiles', - 'G.I Sheet', - 'Aluminum', - 'Asbestos', - 'Long Span', - 'Concrete Desk', - 'Nipa/Anahaw/Cogon' - ], - selectedValues: roof, - whenEmpty: 'Select Roofs', + child: Visibility( + visible: roofOthers, + child: customTextField("Enter other roof/s", "", "other_roof"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + roof = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Tiles', + 'G.I Sheet', + 'Aluminum', + 'Asbestos', + 'Long Span', + 'Concrete Desk', + 'Nipa/Anahaw/Cogon' + ], + selectedValues: roof, + whenEmpty: 'Select Roof/s', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'FLOORING', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: flooringOthers, + onChanged: (bool? value) { + setState(() { + flooringOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - flooring = x; - }); - }, - options: const [ - 'Reinforced Concrete', - 'Plain Cement', - 'Marble', - 'Wood', - 'Tiles' - ], - selectedValues: flooring, - whenEmpty: 'Select Floorings', + child: Visibility( + visible: flooringOthers, + child: customTextField( + "Enter other flooring/s", "", "other_flooring"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + flooring = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Plain Cement', + 'Marble', + 'Wood', + 'Tiles' + ], + selectedValues: flooring, + whenEmpty: 'Select Flooring/s', + ), ), ), - const Align( - alignment: Alignment.centerLeft, - child: Text( + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( 'WALLS & PARTITIONS', textAlign: TextAlign.start, ), - ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: wpOthers, + onChanged: (bool? value) { + setState(() { + wpOthers = value!; + }); + }, + ) + ], + ), + ]), Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.black), - onChanged: (List x) { - setState(() { - walls = x; - }); - }, - options: const [ - 'Reinforced Concrete', - 'Plain Concrete', - 'Wood', - 'CHIB', - 'G.I Sheet', - 'Build-a-wall', - 'Sawali', - 'Bamboo' - ], - selectedValues: walls, - whenEmpty: 'Select Foundation', + child: Visibility( + visible: wpOthers, + child: customTextField( + "Enter other walls & partition/s", "", "other_wp"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + walls = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Plain Concrete', + 'Wood', + 'CHIB', + 'G.I Sheet', + 'Build-a-wall', + 'Sawali', + 'Bamboo' + ], + selectedValues: walls, + whenEmpty: 'Select Walls & Partition/s', + ), ), ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: + const Icon(Icons.chevron_left_rounded, color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () async { + { + final tempID = await SharedPreferences.getInstance(); + var strucMaterials = StructureMaterialsII( + id: tempID.getInt('tempid')! - 1, + foundation: foundationOthers + ? formKey.currentState!.value['other_foundation'] + .split(',') + : foundation, + columns: columOthers + ? formKey.currentState!.value['other_column'] + .split(',') + : column, + beams: beamsOthers + ? formKey.currentState!.value['other_beam'] + .split(',') + : beam, + trussFraming: tfOthers + ? formKey.currentState!.value['other_tf'].split(',') + : truss_framing, + roof: roofOthers + ? formKey.currentState!.value['other_roof'] + .split(',') + : roof, + flooring: flooringOthers + ? formKey.currentState!.value['other_flooring'] + .split(',') + : flooring, + walls: wpOthers + ? formKey.currentState!.value['other_wp'].split(',') + : walls, + others: ["Others"]); + context.read() + ..add(UpdateStrucMaterials(data: strucMaterials)); + + widget.PrevBtn(); + } + ; + }, + ) + ], + ) ], ), ); diff --git a/lib/screens/passo/Building/edit_building.dart b/lib/screens/passo/Building/edit_building.dart new file mode 100644 index 0000000..6a1dde5 --- /dev/null +++ b/lib/screens/passo/Building/edit_building.dart @@ -0,0 +1,204 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; + +import 'package:im_stepper/stepper.dart'; +import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/screens/passo/Building/edit_building/additional_items.dart'; +import 'package:unit2/screens/passo/Building/edit_building/bldgloc_landref.dart'; +import 'package:unit2/screens/passo/Building/edit_building/general_description.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_appraisal.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_assessement_edit.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_owner_info.dart'; +import 'package:unit2/screens/passo/Building/edit_building/structural_materials.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; + +class EditBuilding extends StatefulWidget { + final int index; + final PropertyInfo faas; + final String title; + + const EditBuilding( + {super.key, + required this.title, + required this.index, + required this.faas}); + @override + _EditBuilding createState() => _EditBuilding(); +} + +class _EditBuilding extends State { + // THE FOLLOWING TWO VARIABLES ARE REQUIRED TO CONTROL THE STEPPER. + int activeStep = 0; // Initial step set to 5. + + int upperBound = 6; // upperBound MUST BE total number of icons minus 1. + + void PrevBtn() { + setState(() { + activeStep--; + }); + } + + void NextBtn() { + setState(() { + activeStep++; + }); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + home: Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: Text('Building FAAS Edit'), + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is UnitConstructLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is UnitConstructLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is UnitConstructErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + final unit = state.unit; + return BlocConsumer( + listener: (context, state) { + if (state is ClassComponentLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ClassComponentLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is ClassComponentErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is ClassComponentLoaded) { + return Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + NumberStepper( + numbers: [1, 2, 3, 4, 5, 6, 7], + activeStepColor: primary, + numberStyle: TextStyle(color: Colors.white), + lineColor: primary, + // activeStep property set to activeStep variable defined above. + activeStep: activeStep, + activeStepBorderColor: Colors.white, + activeStepBorderWidth: 1, + // This ensures step-tapping updates the activeStep. + onStepReached: (index) { + setState(() { + activeStep = index; + }); + }, + ), + content(unit, state.classes), + ], + ), + ); + } + if (state is ClassComponentErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadClassComponents()); + }, + ); + } + return Container(); + }, + ); + } + if (state is UnitConstructErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add(LoadUnitConstruct()); + }, + ); + } + return Container(); + }, + ), + ), + ), + ); + } + + // Returns the header text based on the activeStep. + Widget content(List unit, classes) { + switch (activeStep) { + case 0: + return PropertyOwnerInfoEdit( + widget.index, widget.faas, widget.title, NextBtn, PrevBtn); + + case 1: + return BldgLocLandRefEdit(widget.faas.id!, NextBtn, PrevBtn); + + case 2: + return GeneralDescriptionEdit(unit, widget.faas.id!, NextBtn, PrevBtn); + + case 3: + return StructuralMaterialsPageEdit(widget.faas.id!, NextBtn, PrevBtn); + + case 4: + return AdditionalItemEditPage( + unit, classes, widget.faas.id!, NextBtn, PrevBtn); + + case 5: + return PropertyAppraisalEditPage(widget.faas.id!, NextBtn, PrevBtn); + + case 6: + return PropertyAssessmentEditPage(widget.faas.id!); + + default: + return PropertyOwnerInfoEdit( + widget.index, widget.faas, widget.title, NextBtn, PrevBtn); + } + } +} diff --git a/lib/screens/passo/Building/edit_building/AddExtraItems.dart b/lib/screens/passo/Building/edit_building/AddExtraItems.dart new file mode 100644 index 0000000..374968d --- /dev/null +++ b/lib/screens/passo/Building/edit_building/AddExtraItems.dart @@ -0,0 +1,594 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:intl/intl.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +class AddExtraItemsEdit extends StatefulWidget { + final List unit; + final List options; + final int tempId; + + AddExtraItemsEdit(this.unit, this.options, this.tempId); + + @override + _AddExtraItemsEdit createState() => _AddExtraItemsEdit(); +} + +class _AddExtraItemsEdit extends State { + GlobalKey formKey = GlobalKey(); + final focus = FocusNode(); + double _computedValue = 0; + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + int _areaValue = 0; + double _depValue = 0; + double _unitValue = 0; + double _marketValue = 0; + String _className = ""; + int _classId = 0; + String _structureType = ""; + bool _withoutBUCC = false; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + + BoxDecoration box1() { + return const BoxDecoration(boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5) + ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); + } + + double _computeValue(double unitbase, double unitvalue, double area) { +// Compute some value based on the text here + return (unitbase * unitvalue) * area; + } + + double _amountofDepreciation(unitVal, unitBase, area, depreciation) { + return ((unitVal * unitBase) * area) * depreciation; + } + + double _adjustedMarketValue(unitVal, unitBase, area, depreciation) { + double depAmount = ((unitVal * unitBase) * area) * depreciation; + + return ((unitVal * unitBase) * area) - depAmount; + } + + double _totalMarketValue(unitVal, unitBase, area, depreciation, withBUCC, + className, painted, secondHand, paintedUnitVal, secondhandUntVal) { + if (withBUCC == false) { + if (painted == true || secondHand == true) { + final deductions = (paintedUnitVal + secondhandUntVal) / 100; + + print(deductions); + return (((unitVal - deductions) * unitBase) * area); + } else { + return ((unitVal * unitBase) * area); + } + } else { + return (unitVal * area); + } + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddItemsScreenEdit) { + return FormBuilder( + key: formKey, + onChanged: () { + formKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + height: 800, + child: SingleChildScrollView( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: FormBuilderDropdown( + name: 'extra_item', + autofocus: false, + decoration: + normalTextFieldStyle("Additional Item", ""), + items: widget.options + .map((e) => DropdownMenuItem( + value: e, + child: Text(e.componentName), + )) + .toList(), + onChanged: (value) { + if (value!.minBaseUnitvalPercent != '0.00') { + setState(() { + _unitValue = + double.parse(value.minBaseUnitvalPercent); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minBaseUnitvalPercent}); + } + if (value.maxBaseUnitvalPercent != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxBaseUnitvalPercent); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxBaseUnitvalPercent}); + } + if (value.minUnitvalSqrmtr != '0.00') { + setState(() { + _unitValue = + double.parse(value.minUnitvalSqrmtr); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minUnitvalSqrmtr}); + } + if (value.maxUnitvalSqrmtr != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxUnitvalSqrmtr); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxUnitvalSqrmtr}); + } + if (value.minAddBaseunitval != '0.00') { + setState(() { + _unitValue = + double.parse(value.minAddBaseunitval); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minAddBaseunitval}); + } + if (value.maxAddBaseunitval != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxAddBaseunitval); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxAddBaseunitval}); + } + if (value.minDeductBaserate != '0.00') { + setState(() { + _unitValue = + double.parse(value.minDeductBaserate); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minDeductBaserate}); + } + if (value.maxDeductBaserate != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxDeductBaserate); + _className = value.componentName; + _classId = value.id; + _withoutBUCC = value.withoutBucc; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxDeductBaserate}); + } + }, + ), + ), + const SizedBox(height: 10), + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: SizedBox( + height: 45, + child: SearchField( + itemHeight: 70, + suggestions: widget.unit + .map((UnitConstruct unit) => + SearchFieldListItem( + unit.bldgType! + + ' - ' + + unit.building, + item: unit, + child: ListTile( + title: Text( + unit.bldgType + + ' - ' + + unit.building!.toUpperCase(), + overflow: TextOverflow.ellipsis, + ), + ))) + .toList(), + + validator: FormBuilderValidators.required( + errorText: "This field is required"), + + searchInputDecoration: normalTextFieldStyle( + "Structure Type", "") + .copyWith( + suffixIcon: + const Icon(Icons.arrow_drop_down)), + ////agency suggestion tap + focusNode: focus, + suggestionState: Suggestion.expand, + onSuggestionTap: (unit) { + setState(() { + _unitBase = + double.parse(unit.item!.unitValue); + _structureType = unit.item!.bldgType + + ' - ' + + unit.item!.building; + }); + focus.unfocus(); + }, + ), + ), + ), + // const SizedBox(height: 10), + // Container( + // margin: const EdgeInsets.only( + // left: 0, top: 10, right: 0, bottom: 0), + // child: FormBuilderDropdown( + // name: 'struc_type', + // autofocus: false, + // decoration: + // normalTextFieldStyle("Structure Type", ""), + // items: widget.unit + // .map((e) => DropdownMenuItem( + // value: e, + // child: + // Text(e.bldgType + " - " + e.building), + // )) + // .toList(), + // onChanged: (val) { + // setState(() { + // _unitBase = double.parse(val!.unitValue); + // _structureType = val.bldgType; + // }); + // }, + // ), + // ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'unitValue', + decoration: + normalTextFieldStyle("Unit Value", ""), + validator: FormBuilderValidators.compose([]), + ), + ), + const SizedBox(width: 10), + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'areaValue', + decoration: normalTextFieldStyle("Area", ""), + validator: FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + _areaValue = int.parse(value!); + }); + }, + ), + ), + ], + ), + // const SizedBox(height: 10), + // FormBuilderTextField( + // name: 'depRate', + // decoration: + // normalTextFieldStyle("Depreciation Rate", ""), + // validator: FormBuilderValidators.compose([]), + // onChanged: (value) { + // setState(() { + // _depValue = double.parse(value!); + // }); + // }, + // ), + // const SizedBox(height: 10), + // FormBuilderTextField( + // name: 'marketValue', + // decoration: normalTextFieldStyle( + // NumberFormat.currency( + // locale: 'en-PH', symbol: "₱") + // .format(_totalMarketValue(_unitValue, + // _unitBase, _areaValue, _depValue)), + // ""), + // validator: FormBuilderValidators.compose([]), + // onChanged: (value) { + // setState(() { + // _marketValue = double.parse(value!); + // }); + // }, + // ), + // const SizedBox(height: 10), + // Text('Amount of Depreciation'), + // const SizedBox(height: 5), + // Container( + // height: 45.0, + // width: double.infinity, + // decoration: BoxDecoration( + // color: Colors.white, + // border: Border.all( + // color: Colors.grey, + // width: 1.0, + // ), + // borderRadius: BorderRadius.circular(5.0), + // ), + // child: Align( + // alignment: Alignment.center, + // child: Text(NumberFormat.currency( + // locale: 'en-PH', symbol: "₱") + // .format(_amountofDepreciation(_unitValue, + // _unitBase, _areaValue, _depValue)))), + // ), + + Visibility( + visible: !_withoutBUCC, + child: Column( + children: [ + const SizedBox(height: 10), + Text('Building is not painted?'), + const SizedBox(height: 5), + Container( + child: Row( + children: [ + Checkbox( + value: isPainted, + onChanged: (bool? value) { + setState(() { + isPainted = value!; + if (value == false) { + _notPaintedUnitVal = 0; + } else { + _notPaintedUnitVal = 10; + } + }); + }, + ), + const SizedBox(width: 10), + Container( + height: 40.0, + width: 100, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: + BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(' - ' + + _notPaintedUnitVal.toString() + + '%')), + ), + ], + ), + ), + const SizedBox(height: 10), + Text('Uses second hand materials?'), + const SizedBox(height: 5), + Container( + child: Row( + children: [ + Checkbox( + value: isSecondHand, + onChanged: (bool? value) { + setState(() { + isSecondHand = value!; + if (isSecondHand == false) { + _secondHandUnitVal = 0; + formKey.currentState!.patchValue( + {'secondHandMat': '0'}); + } else { + _secondHandUnitVal = 5; + formKey.currentState!.patchValue( + {'secondHandMat': '5'}); + } + }); + }, + ), + const SizedBox(width: 10), + Row( + children: [ + SizedBox( + height: 40, + width: 100, + child: FormBuilderTextField( + enabled: isSecondHand, + name: 'secondHandMat', + textAlign: TextAlign.center, + decoration: normalTextFieldStyle( + "Unit Value", ""), + validator: + FormBuilderValidators.compose( + []), + onChanged: (value) { + // Check if the value is not null before parsing to double + if (value != null && + value.isNotEmpty) { + setState(() { + _secondHandUnitVal = + int.parse(value); + }); + } else { + // Handle the case when the value is empty or null + // For example, set _secondHandUnitVal to a default value or show an error message. + } + }, + ), + ), + SizedBox( + height: 40, + width: 40, + child: Center( + child: Text( + '%', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold), + ), + ), + ) + ], + ), + ], + ), + ), + ], + ), + ), + + const SizedBox(height: 10), + Text('Market Value'), + const SizedBox(height: 5), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(_totalMarketValue( + _unitValue, + _unitBase, + _areaValue, + _depValue, + _withoutBUCC, + _className, + isPainted, + isSecondHand, + _notPaintedUnitVal, + _secondHandUnitVal)))), + ), + const SizedBox(height: 10), + Row( + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + var itemss = AdditionalItems( + id: 1, + bldgapprDetailsId: widget.tempId, + classId: _classId, + className: _className, + structType: _structureType, + unitValue: + _withoutBUCC == true ? 0 : _unitValue, + baseUnitValue: _unitBase, + area: _areaValue, + marketValue: + (_unitValue * _unitBase) * _areaValue, + depreciationRate: _depValue, + adjustedMarketVal: _totalMarketValue( + _unitValue, + _unitBase, + _areaValue, + _depValue, + _withoutBUCC, + _className, + isPainted, + isSecondHand, + _notPaintedUnitVal, + _secondHandUnitVal), + actualUse: 'Test', + amtDepreciation: _amountofDepreciation( + _unitValue, + _unitBase, + _areaValue, + _depValue, + ), + painted: true, + secondhand: true, + paintedUnitval: '1', + secondhandUnitval: '1'); + + context.read().add( + AddAdditionalItemsEdit(items: itemss)); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Submit"), + ), + ), + SizedBox( + width: + 5), // Use SizedBox for horizontal spacing in a Row + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + context + .read() + .add(LoadAdditionalItems()); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ))); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Building/edit_building/additional_items.dart b/lib/screens/passo/Building/edit_building/additional_items.dart new file mode 100644 index 0000000..b5b9872 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/additional_items.dart @@ -0,0 +1,305 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/screens/passo/Building/edit_building/AddExtraItems.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class AdditionalItemEditPage extends StatefulWidget { + final List unit; + final List options; + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + AdditionalItemEditPage( + this.unit, this.options, this.tempId, this.NextBtn, this.PrevBtn); + + @override + _AdditionalItemEditPage createState() => _AdditionalItemEditPage(); +} + +class _AdditionalItemEditPage extends State { + void deleteItem(int itemId) { + context + .read() + .add(DeleteAdditionalItemsEdit(id: itemId)); + } + + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row.adjustedMarketVal); + // }); + // return total; + // } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + final state = context.watch().state; + if (state is AdditionalItemsEditLoaded) { + return Column( + children: [ + Container( + height: 500, + child: Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('ADDITIONAL ITEMS', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowAdditionalItemsEdit()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Items'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('% of BUCC'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.items.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.className)), + DataCell(Text(dataRow.baseUnitValue)), + DataCell(Text(dataRow.unitValue)), + DataCell(Text(((double.parse( + dataRow.adjustedMarketVal))) + .toString())), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id); + }, + ), + SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList(), + ), + ), + ], + ), + ), + ), + ), + ), + // Padding( + // padding: const EdgeInsets.only(left: 20.0, right: 20.0), + // child: Row( + // mainAxisAlignment: MainAxisAlignment.spaceBetween, + // children: [ + // Text( + // 'Total', + // style: + // TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ), + // Text( + // NumberFormat.currency(locale: 'en-PH', symbol: "₱") + // .format(_totalMarketValue(state.items)), + // style: + // TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ) + // ], + // ), + // ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ), + ], + ); + } + if (state is AdditionalItemsEditDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context.read().add( + LoadAdditionalItemsEdit( + items: const [], id: widget.tempId)); + }); + }); + } + } + if (state is ShowAddItemsScreenEdit) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: Text( + 'ADD EXTRA ITEMS', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: AddExtraItemsEdit( + widget.unit, widget.options, widget.tempId)) + ], + ), + ), + ); + } + return Container( + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('ADDITIONAL MATERIALS', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + onPressed: () { + context + .read() + .add(ShowAdditionalItems()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/bldgloc_landref.dart b/lib/screens/passo/Building/edit_building/bldgloc_landref.dart new file mode 100644 index 0000000..2b6ced8 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/bldgloc_landref.dart @@ -0,0 +1,453 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:unit2/bloc/passo/barangay/barangay_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/landref/landref_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/location/location_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; + +import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart'; + +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_owner_info.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class BldgLocLandRefEdit extends StatefulWidget { + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + BldgLocLandRefEdit(this.tempId, this.NextBtn, this.PrevBtn); + @override + _BldgLocLandRefEdit createState() => _BldgLocLandRefEdit(); +} + +class _BldgLocLandRefEdit extends State { + Set seenCityCodes = Set(); + @override + Widget build(BuildContext context) { + return ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is LocationLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is LocationLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is LocationErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is LocationLoaded) { + final bldgloc = state.bldgloc; + return BlocConsumer( + listener: (context, state) { + if (state is LandrefLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is LandrefLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is LandrefErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, + builder: (context, state) { + if (state is LandrefLoaded) { + final landRef = state.landRef; + return BlocConsumer( + listener: (context, state) { + if (state is MunicipalityLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is MunicipalityLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is MunicipalityErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, builder: (context, state) { + if (state is MunicipalityLoaded) { + final cityList = state.municipality; + Set uniqueItems = {}; + + // Iterate through the dropdownItems list to filter out duplicates + for (var item in cityList) { + uniqueItems.add(item); + } + return BlocConsumer( + listener: (context, state) { + if (state is BarangayLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is BarangayLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is BarangayErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + // Fluttertoast.showToast( + // msg: onError, + // fontSize: 24, + // toastLength: Toast.LENGTH_LONG, + // gravity: ToastGravity.CENTER, + // backgroundColor: Colors.black, + // textColor: Colors.white); + } + }, builder: (context, state) { + if (state is BarangayLoaded) { + List brgyList = state.brgy; + List brgyNAmes = brgyList + .map((brgy) => brgy.barangayDescription) + .toList() + .cast(); + return FormBuilder( + key: keys, + initialValue: { + 'street': bldgloc.street, + // 'brgy': bldgloc.barangay, + // 'municipality': bldgloc.municipality, + 'province': bldgloc.province, + 'l_owner': landRef.owner, + 'oct_tct_cloa': landRef.cloaNo, + 'survey_no': landRef.surveyNo, + 'lot_no': landRef.lotNo, + 'blk_no': landRef.blkNo, + 'l_td_arp': landRef.tdn, + 'area': landRef.area + }, + enabled: true, + onChanged: () { + keys.currentState!.save(); + debugPrint(keys.currentState!.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(20.0), + child: ListView( + shrinkWrap: true, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 10), + child: const Text('BUILDING LOCATION', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'municipality', + autofocus: false, + decoration: normalTextFieldStyle( + bldgloc.municipality ?? + "Municipality", + "", + ), + items: uniqueItems + .map( + (city) => + DropdownMenuItem( + value: city, + child: Text( + city.cityDescription ?? + ''), + ), + ) + .toList(), + onChanged: (selectedCityCode) { + // Find the corresponding City object using selectedCityCode + final selectedCity = cityList + .firstWhere((city) => + city.cityCode == + selectedCityCode); + + final barangayBloc = context + .read(); + barangayBloc.add(LoadBarangay( + id: selectedCityCode! + .cityCode!)); + }, + ), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Province / City", + "", + 'province')) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "No. / Street", "", 'street'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDropDownField( + bldgloc.barangay, + "", + 'brgy', + brgyNAmes)) + ]), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 10), + child: const Text('LAND REFERENCE', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + customTextField( + "Land Owner", "", 'l_owner'), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "OCT/TCT/CLOA No.", + "", + 'oct_tct_cloa'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Survey No.", + "", + 'survey_no')) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Lot No.", "", 'lot_no'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Blk No.", "", 'blk_no')) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "TD / ARP No.", "", 'l_td_arp'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Area", "", 'area')) + ]), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon( + Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon( + Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + var bldgLocData = BldgLoc( + id: widget.tempId, + street: keys.currentState + ?.value['street'], + barangay: keys.currentState + ?.value['brgy'], + municipality: keys + .currentState + ?.value['municipality'] + ?.cityDescription ?? + bldgloc.municipality, + province: keys.currentState + ?.value['province'], + ); + var landRefData = LandRef( + id: widget.tempId, + owner: keys.currentState + ?.value['l_owner'], + cloaNo: keys.currentState + ?.value['oct_tct_cloa'], + lotNo: keys.currentState + ?.value['lot_no'], + tdn: keys.currentState + ?.value['l_td_arp'], + area: keys.currentState + ?.value['area'], + surveyNo: keys.currentState + ?.value['survey_no'], + blkNo: keys.currentState + ?.value['blk_no'], + ); + context.read() + ..add(UpdateBldgLoc( + bldg_loc: bldgLocData)) + ..add(UpdateLandRef( + land_ref: landRefData)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ), + ); + } + if (state is BarangayErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadBarangay(id: '01')); + }, + ); + } + return Container(); + }); + } + if (state is MunicipalityErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadMunicipality()); + }, + ); + } + return Container(); + }); + } + if (state is LandrefErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add( + LoadLandref(id: widget.tempId, landRef: LandRef())); + }, + ); + } + return Container(); + }, + ); + } + + if (state is LocationErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadLocation(id: widget.tempId, bldgloc: BldgLoc())); + }, + ); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/general_description.dart b/lib/screens/passo/Building/edit_building/general_description.dart new file mode 100644 index 0000000..201d6b7 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/general_description.dart @@ -0,0 +1,306 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:unit2/bloc/passo/bulding/general_description/general_description_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_owner_info.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +import '../add_building.dart'; + +class GeneralDescriptionEdit extends StatefulWidget { + final List unit; + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + GeneralDescriptionEdit(this.unit, this.tempId, this.NextBtn, this.PrevBtn); + @override + _GeneralDescriptionEdit createState() => _GeneralDescriptionEdit(); +} + +class _GeneralDescriptionEdit extends State { + final actual_use = [ + "Residential", + "Agricultural", + "Commercial", + "Industrial", + "Mineral", + "Timberland", + ]; + + @override + Widget build(BuildContext context) { + return Expanded( + child: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is GenDescLoaded) { + return FormBuilder( + key: keys, + initialValue: { + 'bldg_permit': state.gendesc.bldgPermit, + 'date_issued': state.gendesc.dateIssued.toString(), + 'cct': state.gendesc.cct.toString(), + 'coc_issued': state.gendesc.certCompletionIssued.toString(), + 'coo_issued': state.gendesc.certOccupancyIssued.toString(), + 'date_cnstructed': state.gendesc.dateIssued.toString(), + 'date_occupied': state.gendesc.dateOccupied.toString(), + 'bldg_age': state.gendesc.bldgAge.toString(), + 'no_of_storeys': state.gendesc.noStoreys.toString(), + 'area_of_1stFl': state.gendesc.area1Stfloor, + 'area_of_2ndFl': state.gendesc.area2Ndfloor, + 'area_of_3rdFl': state.gendesc.area3Rdfloor, + 'area_of_4thFl': state.gendesc.area4Thfloor, + 'total_area': state.gendesc.totalFloorArea.toString(), + 'actual_use': state.gendesc.actualUse + }, + enabled: true, + onChanged: () { + keys.currentState!.save(); + debugPrint(keys.currentState!.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('GENERAL DESCRIPTION', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: FormBuilderDropdown( + name: 'bldg_type', + autofocus: false, + decoration: normalTextFieldStyle( + state.gendesc.bldgKind ?? "Kind of Building", + "Kind of Building"), + items: widget.unit + .map((e) => DropdownMenuItem( + value: e, + child: + Text(e.bldgType + '-' + e.building), + )) + .toList(), + ), + ), + customDropDownField( + "Actual Use", "", 'actual_use', actual_use), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Bldg. Permit No.", "", 'bldg_permit'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDatTimePicker( + "Certificate of Occupancy Issued ON", + "", + 'date_issued')) + ]), + customTextField( + "Condominium Certificate of Title (CCT)", + "", + 'cct'), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customDatTimePicker( + "Certificate of Completion Issued ON", + "", + 'coc_issued'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDatTimePicker( + "Certificate of Occupancy Issued ON", + "", + 'coo_issued')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customDatTimePicker( + "Date Constructed /Completed", + "", + 'date_cnstructed'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDatTimePicker( + "Date Occupied", "", 'date_occupied')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Bldg. Age", "", 'bldg_age'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "No. of storeys", "", 'no_of_storeys')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Area of 1st Floor", "", 'area_of_1stFl'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Area of 2nd Floor", + "", 'area_of_2ndFl')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Area of 3rd Floor", + "", 'area_of_3rdFl')), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Area of 4th Floor", + "", 'area_of_4thFl')) + ]), + customTextField("Total Area", "", 'total_area'), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + keys.currentState!.save(); + var genDescData = GeneralDesc( + id: widget.tempId, + bldgKind: keys + .currentState + ?.value['bldg_type'] + ?.building ?? + state.gendesc.bldgKind, + strucType: keys + .currentState + ?.value['bldg_type'] + ?.bldgType ?? + state.gendesc.strucType, + bldgPermit: keys + .currentState?.value['bldg_permit'], + dateIssued: keys + .currentState?.value['coc_issued'], + cct: keys.currentState?.value['cct'], + certCompletionIssued: keys + .currentState?.value['coc_issued'], + certOccupancyIssued: keys + .currentState?.value['coo_issued'], + dateCompleted: keys.currentState + ?.value['date_cnstructed'], + dateOccupied: keys.currentState + ?.value['date_occupied'], + bldgAge: int.tryParse(keys.currentState?.value['bldg_age']), + noStoreys: int.tryParse(keys.currentState?.value['no_of_storeys']), + area1Stfloor: keys.currentState?.value['area_of_1stFl'], + area2Ndfloor: keys.currentState?.value['area_of_2ndFl'], + area3Rdfloor: keys.currentState?.value['area_of_3rdFl'], + area4Thfloor: keys.currentState?.value['area_of_4thFl'], + totalFloorArea: keys.currentState?.value['total_area'], + floorSketch: null, + actualUse: keys.currentState?.value['actual_use']); + + context.read() + ..add(UpdateGeneralDesc( + gen_desc: genDescData)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ), + ), + ); + } + if (state is GenDescErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add( + LoadGenDesc(id: widget.tempId, gendesc: GeneralDesc())); + }, + ); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/property_appraisal.dart b/lib/screens/passo/Building/edit_building/property_appraisal.dart new file mode 100644 index 0000000..535eb1f --- /dev/null +++ b/lib/screens/passo/Building/edit_building/property_appraisal.dart @@ -0,0 +1,1135 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/general_description/general_description_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart'; + +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/model/passo/property_appraisal_edit.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_owner_info.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class PropertyAppraisalEditPage extends StatefulWidget { + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + PropertyAppraisalEditPage(this.tempId, this.NextBtn, this.PrevBtn); + + @override + _PropertyAppraisalEditPage createState() => _PropertyAppraisalEditPage(); +} + +class _PropertyAppraisalEditPage extends State { + double depRate = 0; + + calculateAdditionalItems(List items) { + double sum = 0; + double product = 1; + + for (AdditionalItems value in items) { + sum += double.parse(value.adjustedMarketVal); + } + + return sum; + } + + calculateMarketValue(buildingCost, additionalItems, dep) { + double sum = 0; + double depreciation = 0; + double total = 0; + + sum = buildingCost + calculateAdditionalItems(additionalItems); + + depreciation = sum * dep; + + total = sum - depreciation; + + return total; + } + + calculateDepCost(buildingCost, additionalItems, dep) { + double sum = 0; + double depreciation = 0; + double total = 0; + + sum = buildingCost + calculateAdditionalItems(additionalItems); + + depreciation = sum * dep; + + total = sum - depreciation; + + return depreciation; + } + + calculateConstructionCost(constructioncost, addtionalCost) { + double sum = 0; + sum = constructioncost + addtionalCost; + + return sum; + } + + String assessmentLevel(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return '0 '; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return '10 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return '20 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return '25 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return '80 '; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + default: + } + return ''; + } + + double assessmentValue(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return marketValue * 0; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return marketValue * 0.10; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return marketValue * 0.20; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return marketValue * 0.25; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return marketValue * 0.80; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + default: + } + return 0; + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is PropertyAppraisalEditLoaded) { + final appraisal = state.appraisalEdit; + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is AdditionalItemsEditLoaded) { + final item = state.items; + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is GenDescLoaded) { + double totalArea = double.tryParse( + state.gendesc.totalFloorArea ?? + appraisal.totalArea.toString()) ?? + 0.0; + + double bldgUnitValue = double.tryParse( + keys.currentState?.value['bldg_type']?.unitValue ?? + appraisal.unitconstructCost) ?? + 0.0; + return Expanded( + child: SingleChildScrollView( + child: Container( + margin: const EdgeInsets.only(left: 20.0, right: 20.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 20), + child: const Text('PROPERTY APPRAISAL', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.left), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Unit Construction Cost", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + bldgUnitValue.toString() + ' sq.m', + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Building Core", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + '', + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 40), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Sub-total", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + bldgUnitValue.toString(), + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 40), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Cost of Additional Items", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + '', + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Sub-total", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + appraisal.addItemsSubtotal!, + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Total Construction Cost", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + calculateConstructionCost( + double.parse(appraisal + .unitconstructSubtotal!), + double.parse( + appraisal.addItemsSubtotal!)) + .toString()!, + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 40), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Depreciation Rate", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + SizedBox( + width: 90, + height: 25, + child: FormBuilderTextField( + name: 'depRate', + decoration: + normalTextFieldStyle("0.00", ""), + validator: + FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + depRate = double.parse(value!); + }); + }, + ), + ), + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Depreciation Cost", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + calculateDepCost( + (totalArea * bldgUnitValue), + item, + double.parse(keys.currentState + ?.value['depRate'] ?? + appraisal.depreciationRate)) + .toString(), + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Total % Depreciation", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + '${(double.parse(keys.currentState?.value['depRate'] ?? appraisal.depreciationRate) * 100).toStringAsFixed(2)}%', + textAlign: TextAlign.right, + ), + ) + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + child: Text( + "Market Value", + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13), + textAlign: TextAlign.left, + ), + ), + Container( + child: Text( + calculateMarketValue( + (totalArea * bldgUnitValue), + item, + double.parse(keys.currentState + ?.value['depRate'] ?? + appraisal.depreciationRate)) + .toString(), + textAlign: TextAlign.right, + ), + ) + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Container( + margin: const EdgeInsets.symmetric( + horizontal: 20.0), + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + children: [ + Container( + margin: const EdgeInsets.fromLTRB( + 0, 20, 0, 20), + child: const Text( + 'PROPERTY ASSESSMENT', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, + ), + textAlign: TextAlign.left, + ), + ), + Column( + children: [ + Row( + children: [ + Container( + width: 100, + margin: + const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all( + 5.0), + child: const Text( + 'Actual Use', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: + TextAlign.center, + ), + ), + Container( + width: 150, + margin: + const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all( + 5.0), + child: const Text( + 'Market Value', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: + TextAlign.center, + ), + ), + Container( + width: 100, + margin: + const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all( + 5.0), + child: const Text( + 'Ass. Level', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: + TextAlign.center, + ), + ), + Container( + width: 150, + margin: + const EdgeInsets.only( + top: 15, left: 15), + padding: + const EdgeInsets.all( + 5.0), + child: const Text( + 'Ass. Value', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: + TextAlign.center, + ), + ), + ], + ), + SizedBox( + height: 50, + child: SingleChildScrollView( + scrollDirection: + Axis.horizontal, + child: Row(children: [ + Container( + height: 100, + child: Row( + children: [ + Container( + width: 100, + margin: + const EdgeInsets + .only( + top: 15, + left: 15), + padding: + const EdgeInsets + .all(5.0), + child: Text( + state.gendesc + .actualUse ?? + "", + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 13, + ), + textAlign: + TextAlign + .center, + ), + ), + Container( + width: 150, + margin: + const EdgeInsets + .only( + top: 15, + left: 15), + padding: + const EdgeInsets + .all(5.0), + child: Text( + NumberFormat + .currency( + locale: 'en-PH', + symbol: "₱", + ).format( + calculateMarketValue( + (totalArea * + bldgUnitValue), + item, + double.parse(keys + .currentState + ?.value['depRate'] ?? + appraisal.depreciationRate)), + ), + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 13, + ), + textAlign: + TextAlign + .center, + ), + ), + Container( + width: 100, + margin: + const EdgeInsets + .only( + top: 15, + left: 15), + padding: + const EdgeInsets + .all(5.0), + child: Text( + assessmentLevel( + calculateMarketValue( + (totalArea * bldgUnitValue), + item, + double.parse(keys.currentState?.value['depRate'] ?? appraisal.depreciationRate)) + .toString(), + state.gendesc.actualUse) + + '%', + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 13, + ), + textAlign: + TextAlign + .center, + ), + ), + Container( + width: 150, + margin: + const EdgeInsets + .only( + top: 15, + left: 15), + padding: + const EdgeInsets + .all(5.0), + child: Text( + NumberFormat + .currency( + locale: 'en-PH', + symbol: "₱", + ).format(assessmentValue( + calculateMarketValue( + (totalArea * + bldgUnitValue), + item, + double.parse(keys.currentState?.value['depRate'] ?? + appraisal + .depreciationRate)) + .toString(), + state.gendesc + .actualUse)), + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 13, + ), + textAlign: + TextAlign + .center, + ), + ), + const SizedBox( + height: 80, + ), + ], + ), + ) + ]), + ), + ) + ], + ) + ], + ), + ), + ), + ), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); + + final id = tempID.getInt('tempid')! - 1; + { + var appraisals = PropertyAppraisalEdit( + id: 1, + bldgapprDetailsId: id, + unitconstructCost: + bldgUnitValue.toString(), + buildingCore: 'test', + unitconstructSubtotal: + (totalArea * bldgUnitValue) + .toString(), + depreciationRate: depRate.toString(), + depreciationCost: calculateDepCost( + (totalArea * bldgUnitValue), + item, + depRate) + .toString(), + costAddItems: + calculateAdditionalItems(item) + .toString(), + addItemsSubtotal: + calculateAdditionalItems(item) + .toString(), + totalpercentDepreciation: + (depRate * 100) + .toStringAsFixed(2), + marketValue: calculateMarketValue( + (totalArea * bldgUnitValue), + item, + depRate) + .toString(), + totalArea: totalArea.toString()); + context.read() + ..add(UpdatePropertyAppraisalEdit( + appraisalEdit: appraisals, + id: widget.tempId)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ), + ); + } + return Container(); + }); + } + return Container(); + }); + } + if (state is PropertyAppraisalEditErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadPropertyAppraisalEdit( + appraisalEdit: PropertyAppraisalEdit(), + id: widget.tempId, + )); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/property_assessement_edit.dart b/lib/screens/passo/Building/edit_building/property_assessement_edit.dart new file mode 100644 index 0000000..e2b20e3 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/property_assessement_edit.dart @@ -0,0 +1,1093 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:intl/intl.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart'; +import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart'; +import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; +import 'package:unit2/model/passo/memoranda.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/model/passo/property_appraisal_edit.dart'; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:unit2/model/passo/signatories.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/screens/passo/Building/edit_building/property_owner_info.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/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; + +import '../../../../model/passo/general_description.dart'; + +class PropertyAssessmentEditPage extends StatefulWidget { + int tempId; + PropertyAssessmentEditPage(this.tempId); + @override + _PropertyAssessmentEditPage createState() => _PropertyAssessmentEditPage(); +} + +class _PropertyAssessmentEditPage extends State { + double assessment_level = 0; + bool isTaxable = false; + bool isExempt = false; + String _memoranda = ''; + final focus = FocusNode(); + + String assessmentLevel(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return '0 '; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return '10 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return '20 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return '25 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return '30 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return '35 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return '40 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return '75 '; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return '80 '; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return '45 '; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return '50 '; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return '55 '; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return '60 '; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return '65 '; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return '70 '; + } + break; + default: + } + return ''; + } + + double assessmentValue(marketValues, property_class) { + final marketValue = double.parse(marketValues); + switch (property_class) { + case 'Residential': + if (marketValue < 175000) { + // setState(() { + // assessment_level = 0; + // }); + return marketValue * 0; + } else if (marketValue < 300000 && marketValue > 175000) { + // setState(() { + // assessment_level = 0.10; + // }); + return marketValue * 0.10; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.20; + // }); + return marketValue * 0.20; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.25; + // }); + return marketValue * 0.25; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } + break; + case 'Agricultural': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + case 'Commercial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + } + break; + case 'Industrial': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.30; + // }); + return marketValue * 0.30; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.35; + // }); + return marketValue * 0.35; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.40; + // }); + return marketValue * 0.40; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 5000000 && marketValue > 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } else if (marketValue < 10000000 && marketValue > 5000000) { + // setState(() { + // assessment_level = 0.75; + // }); + return marketValue * 0.75; + } else if (marketValue > 10000000) { + // setState(() { + // assessment_level = 0.80; + // }); + return marketValue * 0.80; + } + break; + case 'Mineral': + break; + case 'Timberland': + if (marketValue < 300000) { + // setState(() { + // assessment_level = 0.45; + // }); + return marketValue * 0.45; + } else if (marketValue < 500000 && marketValue > 300000) { + // setState(() { + // assessment_level = 0.50; + // }); + return marketValue * 0.50; + } else if (marketValue < 750000 && marketValue > 500000) { + // setState(() { + // assessment_level = 0.55; + // }); + return marketValue * 0.55; + } else if (marketValue < 1000000 && marketValue > 750000) { + // setState(() { + // assessment_level = 0.60; + // }); + return marketValue * 0.60; + } else if (marketValue < 2000000 && marketValue > 1000000) { + // setState(() { + // assessment_level = 0.65; + // }); + return marketValue * 0.65; + } else if (marketValue < 2000000) { + // setState(() { + // assessment_level = 0.70; + // }); + return marketValue * 0.70; + } + break; + default: + } + return 0; + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is PropertyAssessmentEditLoaded) { + final assessment = state.assessmentsEdit; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is SignatoriesLoaded) { + final signatories = state.signatories; + + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + return FormBuilder( + key: keys, + initialValue: { + 'qtr': assessment.qtr.toString(), + 'yr': assessment.qtr.toString(), + // 'appraised_by': assessment.appraisedbyName, + 'app_date': assessment.appraisedbyDate.toString(), + // 'rec_approval': assessment.recommendapprName, + 'rec_date': assessment.recommendapprDate.toString(), + // 'apprvd_by': assessment.approvedbyName, + 'memoranda': assessment.memoranda, + 'sworn_statement': assessment.swornstatementNo, + 'date_received': assessment.dateReceived.toString(), + 'date_of_entry': + assessment.entryDateAssessment.toString(), + 'by': assessment.entryDateBy + }, + enabled: true, + onChanged: () { + keys.currentState!.save(); + debugPrint(keys.currentState!.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: Expanded( + child: Column( + children: [ + Container( + margin: const EdgeInsets.fromLTRB(0, 20, 0, 20), + child: const Text( + 'PROPERTY ASSESSMENT cont..', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, + ), + textAlign: TextAlign.left, + ), + ), + Expanded( + flex: 3, + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Row( + children: [ + const Text('Taxable'), + Checkbox( + checkColor: Colors.white, + value: isTaxable, + onChanged: (bool? value) { + setState(() { + isTaxable = value!; + }); + }, + ) + ], + ), + Row( + children: [ + const Text('Exempt'), + Checkbox( + checkColor: Colors.white, + value: isExempt, + onChanged: (bool? value) { + setState(() { + isExempt = value!; + }); + }, + ) + ], + ), + ], + ), + Column( + children: [ + const SizedBox( + height: 20, + ), + const Text( + 'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :', + style: TextStyle( + fontWeight: FontWeight.bold), + ), + const SizedBox( + height: 20, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + const Text('Qtr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'qtr', + validator: + FormBuilderValidators + .compose([]), + ), + ), + const SizedBox( + width: 20, + ), + const Text('Yr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'yr', + validator: + FormBuilderValidators + .compose([]), + ), + ), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPRAISED/ASSESSED BY:', + style: TextStyle( + fontWeight: FontWeight.bold), + textAlign: TextAlign.start, + ), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'appraised_by', + decoration: + InputDecoration( + labelText: assessment + .appraisedbyName!, + labelStyle: + const TextStyle( + color: Colors + .black), + ), + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: + FormBuilderDateTimePicker( + name: 'app_date', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: + DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'RECOMMENDING APPROVAL:', + style: TextStyle( + fontWeight: FontWeight.bold), + )), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'rec_approval', + decoration: + InputDecoration( + labelText: assessment + .recommendapprName!, + labelStyle: + const TextStyle( + color: Colors + .black), + ), + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: + FormBuilderDateTimePicker( + name: 'rec_date', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: + DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPROVED BY:', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown< + Signatories>( + name: 'apprvd_by', + autofocus: false, + decoration: + InputDecoration( + labelText: assessment + .approvedbyName!, + labelStyle: + const TextStyle( + color: Colors + .black), + ), + items: signatories + .map((signatories) => + DropdownMenuItem( + value: + signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + ], + ), + const SizedBox( + height: 50, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'MEMORANDA: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + SizedBox( + height: 30, + ), + SizedBox( + width: 500, + height: 100, + child: SearchField( + itemHeight: 70, + + suggestions: state.memorada + .map((Memoranda memoranda) => + SearchFieldListItem( + '${memoranda.memoranda}', + item: + memoranda, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${memoranda.memoranda}', + overflow: + TextOverflow + .ellipsis, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + // searchInputDecoration: + // normalTextFieldStyle( + // "Memoranda", "") + // .copyWith( + // suffixIcon: const Icon( + // Icons.arrow_drop_down), + // ), + // focusNode: focus, + suggestionState: + Suggestion.expand, + onSuggestionTap: (memoranda) { + setState(() { + _memoranda = memoranda + .item!.memoranda!; + }); + focus.unfocus(); + }, + )), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('Sworn Statement No. :'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'sworn_statement', + decoration: InputDecoration(), + validator: FormBuilderValidators + .compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('Date Received:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_received', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Date of Entry in the Rec. of Ass. :'), + SizedBox( + width: 100, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_of_entry', + initialEntryMode: + DatePickerEntryMode + .calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: const TimeOfDay( + hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text('By:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'by', + decoration: InputDecoration(), + validator: FormBuilderValidators + .compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + SizedBox( + width: + MediaQuery.of(context).size.width, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: primary, + foregroundColor: Colors.red), + child: SizedBox( + width: 200, + height: 50, + child: Align( + alignment: Alignment.center, + child: Text( + 'Save', + style: TextStyle( + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + ), + ), + onPressed: () { + final List + propertyAssessments = []; + + PropertyAssessmentEdit ass = + PropertyAssessmentEdit( + id: 1, + bldgapprDetailsId: 440, + actualUse: assessment.actualUse, + marketValue: '0.0', + assessmentLevel: '0.0', + assessedValue: "1.0", + taxable: isTaxable, + exempt: isExempt, + qtr: int.parse(keys + .currentState! + .value['qtr']), + yr: int.parse(keys + .currentState!.value['yr']), + appraisedbyName: keys + .currentState! + .value['appraised_by'] + .firstname + + ' ' + + keys + .currentState! + .value['appraised_by'] + .middlename + + ' ' + + keys + .currentState! + .value['appraised_by'] + .lastname, + appraisedbyDate: keys + .currentState! + .value['app_date'], + recommendapprName: keys + .currentState! + .value['rec_approval'] + .firstname + + ' ' + + keys + .currentState! + .value['rec_approval'] + .middlename + + ' ' + + keys + .currentState! + .value['rec_approval'] + .lastname, + recommendapprDate: keys + .currentState! + .value['rec_date'], + approvedbyName: keys + .currentState! + .value['apprvd_by'] + .firstname + + ' ' + + keys + .currentState! + .value['apprvd_by'] + .middlename + + ' ' + + keys + .currentState! + .value['apprvd_by'] + .lastname, + memoranda: _memoranda, + swornstatementNo: keys + .currentState! + .value['sworn_statement'], + dateReceived: keys.currentState! + .value['date_received'], + entryDateAssessment: keys + .currentState! + .value['date_of_entry'], + entryDateBy: keys + .currentState!.value['by'], + ); + + propertyAssessments.add(ass); + + context.read< + PropertyAssessmentEditBloc>() + ..add( + UpdatePropertyAssessmentEdit( + assessmentsEdit: + propertyAssessments[ + 0])); + }, + ), + ), + ], + ), + )) + ], + ), + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + if (state is PropertyAssessmentEditErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add( + LoadPropertyAssessmentEdit( + assessmentsEdit: PropertyAssessmentEdit(), + id: widget.tempId)); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/property_owner_info.dart b/lib/screens/passo/Building/edit_building/property_owner_info.dart new file mode 100644 index 0000000..7e81231 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/property_owner_info.dart @@ -0,0 +1,229 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:multiselect/multiselect.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +GlobalKey keys = GlobalKey(); + +class PropertyOwnerInfoEdit extends StatefulWidget { + final int index; + final PropertyInfo faas; + final String title; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + const PropertyOwnerInfoEdit( + this.index, this.faas, this.title, this.NextBtn, this.PrevBtn); + + @override + State createState() => _PropertyOwnerInfoEdit(); +} + +ButtonStyle secondaryBtnStyle( + Color background, Color borderColor, Color overlay) { + return ButtonStyle( + elevation: MaterialStateProperty.all(0), + backgroundColor: MaterialStateProperty.all(background), + overlayColor: MaterialStateProperty.all(overlay), + shape: MaterialStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8.0), + side: BorderSide( + width: 2, + color: borderColor, + )))); +} + +class _PropertyOwnerInfoEdit extends State { + // late List selectedFoundation = widget.faas.foundations; + // late List selectedColumns = widget.faas.columns; + // late List selectedBeams = widget.faas.beams; + // late List selectedTFraming = widget.faas.truss_framing; + // late List selectedRoof = widget.faas.roof; + // late List selectedFlooring = widget.faas.flooring; + // late List selectedWallPartition = widget.faas.walls_and_partition; + + Map myMap = {'zero': 0, 'one': 1, 'two': 2}; + + final transaction_codes = ['New', 'Revision']; + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is PropertyInfoLoaded) { + return SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Expanded( + child: Column( + children: [ + FormBuilder( + key: keys, + initialValue: { + 'transaction_code': widget.faas.transCode, + 'arp_td': widget.faas.tdn, + 'pin': widget.faas.pin, + 'owner': widget.faas.owner, + 'address': widget.faas.address, + 'tel_no': widget.faas.telno, + 'tin': widget.faas.tin, + 'benificiary': widget.faas.adminUser, + 'benificiary_telno': widget.faas.adminTelno, + 'benificiary_address': widget.faas.adminAddress, + 'benificaiary_tin': widget.faas.adminTin, + }, + enabled: true, + onChanged: () { + keys.currentState!.save(); + debugPrint(keys.currentState!.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY OWNER INFO', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + const SizedBox(height: 15), + customDropDownField("Transaction Code", "", + "transaction_code", transaction_codes), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "ARP No. / TD No.", "", 'arp_td')), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Pin", "", 'pin')), + ], + ), + customTextField("Owner", "", 'owner'), + customTextField("Address", "", 'address'), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: + customTextField("Tel No.", "", 'tel_no'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("TIN", "", 'tin')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Administrator / Benificial User", + "", + 'benificiary'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "TIN", "", 'benificiary_tin')) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Address", "", 'benificiary_address'), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Tel No.", "", 'benificiary_telno')) + ]), + const SizedBox(height: 25), + SizedBox( + width: MediaQuery.of(context).size.width, + child: CustomButton( + icon: const Icon(Icons.chevron_right, + color: Colors.white), + onPressed: () { + var property_info = PropertyInfo( + id: widget.faas.id, + transCode: keys + .currentState!.value['transaction_code'] + .toString(), + tdn: keys.currentState!.value['arp_td'], + pin: keys.currentState!.value['pin'], + owner: keys.currentState!.value['owner'], + address: + keys.currentState!.value['address'], + telno: keys.currentState!.value['tel_no'], + tin: keys.currentState!.value['tin'], + adminUser: + keys.currentState!.value['benificiary'], + adminAddress: keys.currentState! + .value['benificiary_address'], + adminTin: keys + .currentState!.value['benificiary_tin'], + adminTelno: keys.currentState! + .value['benificiary_telno'], + assessedById: '1', + assessedByName: 'Cyril', + dateModified: DateTime.now(), + dateCreated: DateTime.now()); + + context.read().add( + UpdatPropertyInfo( + property_info: property_info)); + + widget.NextBtn(); + }, + ), + ), + ])), + ], + ), + ), + ); + } + if (state is PropertyInfoErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context.read().add(LoadPropertyInfo()); + }, + ); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Building/edit_building/structural_materials.dart b/lib/screens/passo/Building/edit_building/structural_materials.dart new file mode 100644 index 0000000..5d37368 --- /dev/null +++ b/lib/screens/passo/Building/edit_building/structural_materials.dart @@ -0,0 +1,416 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:multiselect/multiselect.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/structural_material/structural_material_bloc.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class StructuralMaterialsPageEdit extends StatefulWidget { + // final VoidCallback onPutStructuralMaterials; + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + StructuralMaterialsPageEdit(this.tempId, this.NextBtn, this.PrevBtn); + + @override + _StructuralMaterialsPageEdit createState() => _StructuralMaterialsPageEdit(); +} + +class _StructuralMaterialsPageEdit extends State { + bool foundationOthers = false; + bool columOthers = false; + bool beamsOthers = false; + bool tfOthers = false; + bool roofOthers = false; + bool flooringOthers = false; + bool wpOthers = false; + List foundation = []; + List column = []; + List beam = []; + List truss_framing = []; + List roof = []; + List flooring = []; + List walls = []; + + List selectedColumnValues = []; + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + if (state is StructuralMaterialsLoaded) { + setState(() { + foundation = state.structure.foundation!.split(','); + column = state.structure.columns!.split(','); + beam = state.structure.beams!.split(','); + truss_framing = state.structure.trussFraming!.split(','); + roof = state.structure.roof!.split(','); + flooring = state.structure.flooring!.split(','); + walls = state.structure.walls!.split(','); + // Update other local state variables here if needed + }); + } + // TODO: implement listener + }, builder: (context, state) { + if (state is StructuralMaterialsLoaded) { + return Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(30.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('STRUCTURAL MATERIALS', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'FOUNDATION', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: foundationOthers, + onChanged: (bool? value) { + setState(() { + foundationOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: foundationOthers, + child: customTextField( + "Enter other foundation", "", "other_foundation"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + foundation = x; + }); + }, + options: const ['Reinforced Concrete', 'Plain Concrete'], + selectedValues: foundation, + whenEmpty: 'Select Foundations', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'COLUMNS', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: columOthers, + onChanged: (bool? value) { + setState(() { + columOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: columOthers, + child: customTextField( + "Enter other columns", "", "other_column"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + column = x; + }); + }, + options: const ['Steel', 'Reinforced Concrete', 'Wood'], + selectedValues: column, + whenEmpty: 'Select Column/s', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'BEAMS', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: beamsOthers, + onChanged: (bool? value) { + setState(() { + beamsOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: beamsOthers, + child: + customTextField("Enter other beam/s", "", "other_beam"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + beam = x; + }); + }, + options: const ['Steel', 'Reinforced Concrete', 'Wood'], + selectedValues: beam, + whenEmpty: 'Select Beam/s', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'TRUSS FRAMING', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: tfOthers, + onChanged: (bool? value) { + setState(() { + tfOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: tfOthers, + child: customTextField( + "Enter other truss framing/s", "", "other_tf"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + truss_framing = x; + }); + }, + options: const ['Steel', 'Wood'], + selectedValues: truss_framing, + whenEmpty: 'Select Truss Framing/s', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'ROOF', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: roofOthers, + onChanged: (bool? value) { + setState(() { + roofOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: roofOthers, + child: + customTextField("Enter other roof/s", "", "other_roof"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + roof = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Tiles', + 'G.I Sheet', + 'Aluminum', + 'Asbestos', + 'Long Span', + 'Concrete Desk', + 'Nipa/Anahaw/Cogon' + ], + selectedValues: roof, + whenEmpty: 'Select Roof/s', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'FLOORING', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: flooringOthers, + onChanged: (bool? value) { + setState(() { + flooringOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: flooringOthers, + child: customTextField( + "Enter other flooring/s", "", "other_flooring"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + flooring = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Plain Cement', + 'Marble', + 'Wood', + 'Tiles' + ], + selectedValues: flooring, + whenEmpty: 'Select Flooring/s', + ), + ), + ), + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text( + 'WALLS & PARTITIONS', + textAlign: TextAlign.start, + ), + Row( + children: [ + const Text('Others'), + Checkbox( + checkColor: Colors.white, + value: wpOthers, + onChanged: (bool? value) { + setState(() { + wpOthers = value!; + }); + }, + ) + ], + ), + ]), + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: Visibility( + visible: wpOthers, + child: customTextField( + "Enter other walls & partition/s", "", "other_wp"), + replacement: DropDownMultiSelect( + selected_values_style: TextStyle(color: Colors.black), + onChanged: (List x) { + setState(() { + walls = x; + }); + }, + options: const [ + 'Reinforced Concrete', + 'Plain Concrete', + 'Wood', + 'CHIB', + 'G.I Sheet', + 'Build-a-wall', + 'Sawali', + 'Bamboo' + ], + selectedValues: walls, + whenEmpty: 'Select Walls & Partition/s', + ), + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + var strucMaterials = StructureMaterialsII( + id: widget.tempId, + foundation: foundation, + columns: column, + beams: beam, + trussFraming: truss_framing, + roof: roof, + flooring: flooring, + walls: walls, + others: ["Others"]); + context.read() + ..add(UpdateStrucMaterials(data: strucMaterials)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + )); + } + if (state is StructuralMaterialsErrorState) { + return Text(state.error); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Land/add_land.dart b/lib/screens/passo/Land/add_land.dart new file mode 100644 index 0000000..4b7e3aa --- /dev/null +++ b/lib/screens/passo/Land/add_land.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; + +import 'package:im_stepper/stepper.dart'; +import 'package:unit2/screens/passo/Land/add_land/land_appraisal.dart'; +import 'package:unit2/screens/passo/Land/add_land/location_and_boundaries.dart'; +import 'package:unit2/screens/passo/Land/add_land/other_improvements.dart'; +import 'package:unit2/screens/passo/Land/add_land/property_assessment.dart'; +import 'package:unit2/screens/passo/Land/add_land/property_assessment_cont.dart'; +import 'package:unit2/screens/passo/Land/add_land/property_owner_info.dart'; +import 'package:unit2/screens/passo/Land/add_land/value_adjustments.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +GlobalKey landKey = GlobalKey(); + +class AddLand extends StatefulWidget { + @override + _AddLand createState() => _AddLand(); +} + +class _AddLand extends State { + // THE FOLLOWING TWO VARIABLES ARE REQUIRED TO CONTROL THE STEPPER. + int activeStep = 0; // Initial step set to 5. + + int upperBound = 6; // upperBound MUST BE total number of icons minus 1. + + void PrevBtn() { + setState(() { + activeStep--; + }); + } + + void NextBtn() { + setState(() { + activeStep++; + }); + } + + void onSAveAll() { + return Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: Text('Land FAAS'), + ), + body: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + NumberStepper( + numbers: [1, 2, 3, 4, 5, 6, 7], + activeStepColor: primary, + numberStyle: TextStyle(color: Colors.white), + lineColor: primary, + // activeStep property set to activeStep variable defined above. + activeStep: activeStep, + activeStepBorderColor: Colors.white, + activeStepBorderWidth: 1, + // This ensures step-tapping updates the activeStep. + onStepReached: (index) { + setState(() { + activeStep = index; + }); + }, + ), + Expanded( + child: FormBuilder( + key: landKey, + + // enabled: false, + onChanged: () { + landKey.currentState?.save(); + + print(landKey.currentState?.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: Container( + child: content(PrevBtn, NextBtn, onSAveAll), + ), + ), + ), + ], + ), + ), + ); + } + + /// Returns the next button. + + // Returns the content widget based on the activeStep. + Widget content(PrevBtn, NextBtn, onSAveAll) { + switch (activeStep) { + case 0: + return LandPropertyOwnerInfo(NextBtn); + case 1: + return LandLocationAndBoundaries(PrevBtn, NextBtn); + case 2: + return LandAppraisal(PrevBtn, NextBtn); + case 3: + return OtherImprovementPage(PrevBtn, NextBtn); + case 4: + return ValueAdjustmentPage(PrevBtn, NextBtn); + case 5: + return LandPropertyAssessmentPage(PrevBtn, NextBtn); + case 6: + return LandSignatories(onSAveAll); + + default: + return LandPropertyOwnerInfo(NextBtn); + } + } +} diff --git a/lib/screens/passo/Land/add_land/AddLandAppraisal.dart b/lib/screens/passo/Land/add_land/AddLandAppraisal.dart new file mode 100644 index 0000000..6e70768 --- /dev/null +++ b/lib/screens/passo/Land/add_land/AddLandAppraisal.dart @@ -0,0 +1,415 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:intl/intl.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_classification/land_classification_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:unit2/model/passo/land_subclassification.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class AddLandAppraisalModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddLandAppraisalModal createState() => _AddLandAppraisalModal(); +} + +class _AddLandAppraisalModal extends State { + final focus = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + int _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _subClassDesc = ""; + int _classId = 0; + String _structureType = ""; + bool _withoutBUCC = false; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + String cityCode = ''; + String cityDesc = ''; + int classCode = 1; + String _classDesc = ''; + + GlobalKey appraisalLandKey = GlobalKey(); + + BoxDecoration box1() { + return const BoxDecoration(boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5) + ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); + } + + double _amountofDepreciation(unitVal, unitBase, area, depreciation) { + return ((unitVal * unitBase) * area) * depreciation; + } + + double _totalMarketValue(unitBase, area) { + return unitBase * area; + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddLandAppraisalScreen) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandClassificationLoaded) { + final classification = state.land_classification; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandSubClassificationLoaded) { + final subclassification = state.land_subclassification; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MunicipalityLoaded) { + return FormBuilder( + key: appraisalLandKey, + onChanged: () { + appraisalLandKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + height: 800, + child: SingleChildScrollView( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: + FormBuilderDropdown( + name: + 'appraisal_municipality', + autofocus: false, + decoration: + normalTextFieldStyle( + cityDesc ?? + "Municipality", + ""), + items: state.municipality + .map((municipality) => + DropdownMenuItem< + City>( + value: municipality, + child: Text(municipality + .cityDescription!), // Use cityDescription instead of cityName + )) + .toList(), + onChanged: (selectedCity) { + if (selectedCity != null) { + final selectedCityCode = + selectedCity.cityCode; + setState(() { + cityCode = + selectedCityCode!; + cityDesc = selectedCity + .cityDescription!; + }); + final barangayBloc = + context.read< + LandSubClassificationBloc>(); + barangayBloc.add( + LoadLandSubClassification( + classCode: + classCode!, + cityCode: + selectedCityCode!)); // Use selectedCityCode directly + } + }, + )), + ), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown< + LandClassification>( + name: 'classification', + autofocus: false, + decoration: + normalTextFieldStyle( + _classDesc + .toString() ?? + "Classification", + ""), + items: classification + .map((classification) => + DropdownMenuItem< + LandClassification>( + value: + classification, + child: Text( + classification + .description!), // Use cityDescription instead of cityName + )) + .toList(), + onChanged: (selectedClass) { + if (selectedClass != null) { + final selectedClassCode = + selectedClass.id; + setState(() { + classCode = + selectedClassCode!; + _classDesc = + selectedClass + .description!; + }); + final barangayBloc = + context.read< + LandSubClassificationBloc>(); + barangayBloc.add( + LoadLandSubClassification( + classCode: + selectedClassCode!, + cityCode: + cityCode)); // Use selectedCityCode directly + } + }, + )), + ), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: SizedBox( + height: 45, + child: SearchField( + itemHeight: 70, + suggestions: subclassification + .map((LandSubClassification + subclass) => + SearchFieldListItem( + '${subclass.subclassCode} - ${subclass.subclassDescription}', + item: subclass, + child: ListTile( + title: Text( + '${subclass.subclassCode} - ${subclass.subclassDescription!.toUpperCase()}', + overflow: + TextOverflow + .ellipsis, + ), + ))) + .toList(), + + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + + searchInputDecoration: + normalTextFieldStyle( + "Structure Type", + "") + .copyWith( + suffixIcon: + const Icon(Icons + .arrow_drop_down)), + ////agency suggestion tap + focusNode: focus, + suggestionState: + Suggestion.expand, + onSuggestionTap: (subclass) { + setState(() { + _unitBase = double.parse( + subclass.item! + .baseUnitMarketval!); + _subClassDesc = + '${subclass.item!.subclassCode} - ${subclass.item!.subclassDescription}'; + }); + focus.unfocus(); + }, + ), + ), + ), + const SizedBox(height: 10), + FormBuilderTextField( + name: 'land_appraisal_area', + decoration: normalTextFieldStyle( + "Area", ""), + validator: + FormBuilderValidators.compose( + []), + onChanged: (value) { + setState(() { + _areaValue = int.parse(value!); + }); + }, + ), + const SizedBox(height: 10), + const Text('Market Value'), + const SizedBox(height: 5), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: + BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱") + .format( + _totalMarketValue( + _unitBase, + _areaValue)))), + ), + const SizedBox(height: 10), + Row( + children: [ + Container( + width: 120, + height: 60, + padding: + const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences + .getInstance(); + print(tempID + .getInt('landid')); + var land_appraisal = LandAppr( + landapprDetailsId: + tempID.getInt( + 'landid')! - + 1, + classification: + _classDesc, + subClass: _subClassDesc, + area: _areaValue + .toString(), + unitValue: _unitBase + .toString(), + baseMarketval: + _totalMarketValue( + _unitBase, + _areaValue) + .toString()); + + context + .read< + LandAppraisalBloc>() + .add(AddLandAppraisal( + land_appr: + land_appraisal)); + }, + style: + ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Submit"), + ), + ), + const SizedBox( + width: + 5), // Use SizedBox for horizontal spacing in a Row + Container( + width: 120, + height: 60, + padding: + const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + context + .read< + LandAppraisalBloc>() + .add( + const LoadLandAppraisal()); + }, + style: + ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ))); + } + if (state is MunicipalityErrorState) { + return Text(state.error); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + if (state is LandAppraisalErrorState) { + return Text(state.error); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart b/lib/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart new file mode 100644 index 0000000..64a53b6 --- /dev/null +++ b/lib/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart @@ -0,0 +1,467 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; +import 'package:unit2/model/passo/type_of_location.dart'; +import 'package:unit2/model/passo/type_of_road.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +class AddLandValueAdjustmentModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddLandValueAdjustmentModal createState() => _AddLandValueAdjustmentModal(); +} + +class _AddLandValueAdjustmentModal extends State { + final focus = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + int _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _subClassDesc = ""; + int _classId = 0; + String _structureType = ""; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + String cityCode = ''; + String cityDesc = ''; + int classCode = 1; + String _classDesc = ''; + String _treeType = ""; + bool _nonfruitBearing = false; + bool _fruitBearing = false; + int qty = 0; + int pr_qty = 0; + int nonpr_qty = 0; + double _roadTypeDeduction = 0; + double _locTypeRoad = 0; + double _locTypePob = 0; + String _roadType = ''; + String _distance = ''; + String _locRdDistance = ''; + String _locPobDistance = ''; + + GlobalKey otherImpKey = GlobalKey(); + + _calculateBaseMarketValue() { + double base = 0.00; + if (_fruitBearing) { + base = (pr_qty + nonpr_qty) * _unitValue; + } else { + base = qty * _unitValue; + } + return base; + } + + double calculateAdjustment() { + double adjustment = 0; + + if (_locPobDistance == '0 TO 1') { + adjustment = _locTypePob - (_roadTypeDeduction + _locTypeRoad); + } else { + adjustment = (_roadTypeDeduction + _locTypeRoad + _locTypePob) * -1; + } + + return adjustment; + } + + double calculateValueAdjustment() { + double adjustment = calculateAdjustment(); + double valueAdjustment = _unitValue * adjustment; + + return valueAdjustment; + } + + double calculateMarketValue() { + double marketValue = 0; + + marketValue = _unitValue + calculateValueAdjustment(); // Adding adjustment + + return marketValue; + } + + BoxDecoration box1() { + return const BoxDecoration(boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5) + ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddLandValueAdjustmentsScreen) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is LandAppraisalLoaded) { + final land_appr = state.land_appr; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfRoadLoaded) { + final roadType = state.road_type; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfLocationLoaded) { + return FormBuilder( + key: otherImpKey, + onChanged: () { + otherImpKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: SingleChildScrollView( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: + FormBuilderDropdown( + name: 'land_appr_item', + autofocus: false, + decoration: normalTextFieldStyle( + "Land Appraisal Items", ""), + items: land_appr + .map((land_appr) => + DropdownMenuItem< + LandAppr?>( + value: land_appr, + child: Text((land_appr + .subClass ?? + "")), + )) + .toList(), + onChanged: (selectedLandAppr) { + if (selectedLandAppr != null) { + setState(() { + _unitValue = double.parse( + selectedLandAppr + .baseMarketval!); + }); + } + }, + )), + ), + SizedBox( + height: 10, + ), + Text("Adjustment Factors"), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown< + TypeOfRoad?>( + name: 'road_type', + autofocus: false, + decoration: normalTextFieldStyle( + "Type of Road", ""), + items: roadType + .map((roadType) => + DropdownMenuItem< + TypeOfRoad?>( + value: roadType, + child: Text((roadType + .roadType ?? + "")), + )) + .toList(), + onChanged: (selectedRoad) { + if (selectedRoad != null) { + setState(() { + _roadTypeDeduction = + double.parse( + selectedRoad + .deduction!); + _roadType = + selectedRoad.roadType!; + }); + } + }, + )), + ), + SizedBox( + height: 10, + ), + Text("Type of Location"), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown< + TypeOfLocation?>( + name: 'loc_type_road', + autofocus: false, + decoration: normalTextFieldStyle( + "Distance to Road", ""), + items: state.loc_type + .map((locTypeRoad) => + DropdownMenuItem< + TypeOfLocation?>( + value: locTypeRoad, + child: Text((locTypeRoad + .distanceKm ?? + "")), + )) + .toList(), + onChanged: (selectedLoadRoad) { + if (selectedLoadRoad != null) { + setState(() { + _locTypeRoad = double.parse( + selectedLoadRoad + .allRoadTypes!); + _locRdDistance = + selectedLoadRoad + .distanceKm!; + }); + } + }, + )), + ), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 10, + right: 0, + bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown< + TypeOfLocation?>( + name: 'loc_type_pob', + autofocus: false, + decoration: normalTextFieldStyle( + "Distance to Poblacion", ""), + items: state.loc_type + .map((locTypePob) => + DropdownMenuItem< + TypeOfLocation?>( + value: locTypePob, + child: Text((locTypePob + .distanceKm ?? + "")), + )) + .toList(), + onChanged: (selectedLocPob) { + if (selectedLocPob != null) { + setState(() { + _locTypePob = double.parse( + selectedLocPob + .localTradingCenter!); + + _locPobDistance = + selectedLocPob + .distanceKm!; + }); + } + }, + )), + ), + const SizedBox(height: 10), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: + BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text( + (calculateAdjustment() * 100) + .toString() + + '%'), + ), + ), + const SizedBox(height: 10), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: + BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(calculateValueAdjustment())), + ), + ), + const SizedBox(height: 10), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: + BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(calculateMarketValue())), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences + .getInstance(); + print(tempID.getInt('landid')); + var adjustments = ValueAdjustments( + landapprDetailsId: tempID + .getInt('landid')! - + 1, + baseMarketval: + _unitValue.toString(), + adjustmentFactors: + _roadType + + ' , ' + + _locPobDistance + + ' km from road , ' + + _locPobDistance + + ' km from poblacion', + adjustment: + calculateAdjustment() + .toString(), + valueAdjustment: + calculateValueAdjustment() + .toString(), + marketValue: + calculateMarketValue() + .toString()); + + context + .read< + LandValueAdjustmentsBloc>() + .add( + AddLandValueAdjustments( + val_adj: + adjustments)); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Submit"), + ), + ), + const SizedBox( + width: + 5), // Use SizedBox for horizontal spacing in a Row + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + context + .read< + LandValueAdjustmentsBloc>() + .add( + const LoadLandValueAdjustments()); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ), + )); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + + return Container(); + }); + } + if (state is LandValueAdjustmentsErrorState) { + return Text(state.error); + } + return Container( + child: Text("Land Value Adjustment"), + ); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart b/lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart new file mode 100644 index 0000000..c89300d --- /dev/null +++ b/lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart @@ -0,0 +1,344 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart'; +import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/model/passo/trees_improvements.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +class AddOtherImprovementModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddOtherImprovementModal createState() => _AddOtherImprovementModal(); +} + +class _AddOtherImprovementModal extends State { + final focus = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + int _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _subClassDesc = ""; + int _classId = 0; + String _structureType = ""; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + String cityCode = ''; + String cityDesc = ''; + int classCode = 1; + String _classDesc = ''; + String _treeType = ""; + bool _nonfruitBearing = false; + bool _fruitBearing = false; + int qty = 0; + int pr_qty = 0; + int nonpr_qty = 0; + + GlobalKey otherImpKey = GlobalKey(); + + final typeOfTree = [ + "Non-Fruit Bearing", + "Fruit Bearing", + ]; + + _calculateBaseMarketValue() { + double base = 0.00; + if (_fruitBearing) { + base = (pr_qty + nonpr_qty) * _unitValue; + } else { + base = qty * _unitValue; + } + return base; + } + + BoxDecoration box1() { + return const BoxDecoration(boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5) + ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); + } + + double _amountofDepreciation(unitVal, unitBase, area, depreciation) { + return ((unitVal * unitBase) * area) * depreciation; + } + + double _totalMarketValue(unitBase, area) { + return unitBase * area; + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddOtherImprovementScreen) { + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is LandTreesImprovementsLoaded) { + final trees = state.trees_imp; + return FormBuilder( + key: otherImpKey, + onChanged: () { + otherImpKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: SingleChildScrollView( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'kinds_of_trees', + autofocus: false, + decoration: normalTextFieldStyle( + "Kinds of Trees", ""), + items: state.trees_imp + .map((trees) => + DropdownMenuItem( + value: trees, + child: Text( + (trees.improvement ?? "") + + " " + + (trees.subclassCode ?? ""), + ), + )) + .toList(), + onChanged: (selectedTree) { + if (selectedTree != null) { + setState(() { + _unitValue = double.parse( + selectedTree.pricePerTree!); + _treeType = selectedTree.improvement!; + }); + } + }, + )), + ), + Container( + child: Row( + children: [ + Row( + children: [ + Checkbox( + value: _fruitBearing, + onChanged: (bool? value) { + setState(() { + _fruitBearing = value!; + }); + }, + ), + Text('Fruit Bearing ?'), + ], + ), + ], + ), + ), + Visibility( + visible: !_fruitBearing, + child: Row( + children: [ + Expanded( + child: FormBuilderTextField( + name: 'subClass', + decoration: normalTextFieldStyle( + "SubClass/Age", ""), + validator: + FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + _subClassDesc = value!; + }); + }, + ), + ), + SizedBox( + width: 10, + ), + Expanded( + child: FormBuilderTextField( + name: 'qty', + decoration: normalTextFieldStyle("No.", ""), + validator: + FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + qty = int.parse(value!); + }); + }, + ), + ), + ], + ), + replacement: Column( + children: [ + FormBuilderTextField( + name: 'no_of_productive', + decoration: normalTextFieldStyle( + "No. of Productive", ""), + validator: FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + pr_qty = int.parse(value!); + }); + }, + ), + const SizedBox(height: 10), + FormBuilderTextField( + name: 'no_of_nonproductive', + decoration: normalTextFieldStyle( + "No. of Non-Productive", ""), + validator: FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + nonpr_qty = int.parse(value!); + }); + }, + ), + ], + ), + ), + const SizedBox(height: 10), + const Text('Market Value'), + const SizedBox(height: 5), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(_unitValue))), + ), + const SizedBox(height: 10), + const Text('Base Market Value'), + const SizedBox(height: 5), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(_calculateBaseMarketValue().toString() == + "0.00" + ? "00.0" + : _calculateBaseMarketValue())), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('landid')); + var improvement = OtherImprovements( + landapprDetailsId: + tempID.getInt('landid')! - 1, + kindsOfTrees: _treeType, + subclassAge: _subClassDesc, + quantity: qty, + unitValue: _unitValue.toString(), + baseMarketval: + _calculateBaseMarketValue() + .toString(), + noOfProductive: pr_qty, + noOfNonproductive: nonpr_qty, + fruitBearing: _fruitBearing); + + context.read().add( + AddOtherImprovement( + other_imp: improvement)); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Submit"), + ), + ), + const SizedBox( + width: + 5), // Use SizedBox for horizontal spacing in a Row + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + context + .read() + .add(const LoadOtherImprovement()); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ), + )); + } + + return Container(); + }); + } + if (state is OtherImprovementErrorState) { + return Text(state.error); + } + return Container( + child: Text("Other Improvement"), + ); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart b/lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart new file mode 100644 index 0000000..35bf7f6 --- /dev/null +++ b/lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart @@ -0,0 +1,342 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/model/passo/land_property_assessment.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +class AddPropertyAssessmentModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddPropertyAssessmentModal createState() => _AddPropertyAssessmentModal(); +} + +class _AddPropertyAssessmentModal extends State { + final focus = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + int _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _subClassDesc = ""; + int _classId = 0; + String _structureType = ""; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + String cityCode = ''; + String cityDesc = ''; + int classCode = 1; + String _classDesc = ''; + String _treeType = ""; + bool _nonfruitBearing = false; + bool _fruitBearing = false; + int qty = 0; + int pr_qty = 0; + int nonpr_qty = 0; + String _actualUse = "Residential"; + String _assessmentLevel = ""; + + GlobalKey assessmentKey = GlobalKey(); + + final typeOfTree = [ + "Non-Fruit Bearing", + "Fruit Bearing", + ]; + + final actual_use = [ + "Residential", + "Agricultural", + "Commercial", + "Industrial", + "Mineral", + "Timberland", + ]; + + calculateAssessmentValue() { + switch (_actualUse) { + case "Residential": + return _unitValue * 0.20; + break; + case "Agricultural": + return _unitValue * 0.40; + break; + case "Commercial": + return _unitValue * 0.50; + break; + case "Industrial": + return _unitValue * 0.50; + break; + case "Mineral": + return _unitValue * 0.50; + break; + case "Timberland": + return _unitValue * 0.20; + break; + default: + } + } + + BoxDecoration box1() { + return const BoxDecoration(boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5) + ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3))); + } + + double _amountofDepreciation(unitVal, unitBase, area, depreciation) { + return ((unitVal * unitBase) * area) * depreciation; + } + + double _totalMarketValue(unitBase, area) { + return unitBase * area; + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddLandPropertyAssessmentScreen) { + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is LandValueAdjustmentsLoaded) { + final assessment = state.val_adj; + return FormBuilder( + key: assessmentKey, + onChanged: () { + assessmentKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: SingleChildScrollView( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'value_adjustments', + autofocus: false, + decoration: normalTextFieldStyle( + "Value Adjustments", ""), + items: state.val_adj + .map((adj) => + DropdownMenuItem( + value: adj, + child: Text( + (adj.adjustmentFactors ?? ""), + ), + )) + .toList(), + onChanged: (selectedAdj) { + if (selectedAdj != null) { + setState(() { + _unitValue = double.parse( + selectedAdj.marketValue!); + }); + } + }, + )), + ), + SizedBox( + height: 10, + ), + FormBuilderDropdown( + name: "land_actual_use", + autofocus: false, + decoration: normalTextFieldStyle("Actual Use", ""), + items: actual_use + .map((item) => DropdownMenuItem( + value: item, + child: Text(item), + )) + .toList(), + onChanged: (value) { + setState(() { + _actualUse = value!; + + switch (value) { + case "Residential": + setState(() { + _assessmentLevel = '20'; + }); + + break; + case "Agricultural": + setState(() { + _assessmentLevel = '40'; + }); + + break; + case "Commercial": + setState(() { + _assessmentLevel = '50'; + }); + + break; + case "Industrial": + setState(() { + _assessmentLevel = '50'; + }); + + break; + case "Mineral": + setState(() { + _assessmentLevel = '50'; + }); + + break; + case "Timberland": + setState(() { + _assessmentLevel = '20'; + }); + + break; + default: + } + }); + }, + ), + SizedBox( + height: 10, + ), + Text('Assessment Level'), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(_assessmentLevel + '%'), + ), + ), + SizedBox( + height: 10, + ), + Text('Assessment Value'), + Container( + height: 45.0, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all( + color: Colors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(5.0), + ), + child: Align( + alignment: Alignment.center, + child: Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(calculateAssessmentValue().toString() == + "0.00" + ? "00.0" + : calculateAssessmentValue())), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('landid')! - 1); + var assessment = LandPropertyAssessment( + landapprDetailsId: + tempID.getInt('landid')! - 1, + actualUse: _actualUse, + marketval: _unitValue.toString(), + assessmentLevel: _assessmentLevel, + assessedValue: + calculateAssessmentValue() + .toString(), + totalMarketval: '0', + totalAssessedval: '0'); + + context + .read() + .add(AddLandPropertyAssessment( + assessment: assessment)); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Submit"), + ), + ), + const SizedBox( + width: + 5), // Use SizedBox for horizontal spacing in a Row + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () { + context + .read() + .add( + const LoadLandPropertyAssessment()); + }, + style: ElevatedButton.styleFrom( + primary: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ), + )); + } + + return Container(); + }); + } + if (state is LandPropertyAssessmentErrorState) { + return Text(state.error); + } + return Container( + child: Text("Property Assessment"), + ); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/land_appraisal.dart b/lib/screens/passo/Land/add_land/land_appraisal.dart new file mode 100644 index 0000000..fa0ca77 --- /dev/null +++ b/lib/screens/passo/Land/add_land/land_appraisal.dart @@ -0,0 +1,248 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/screens/passo/Land/add_land/AddLandAppraisal.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class LandAppraisal extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandAppraisal(this.PrevBtn, this.NextBtn); + @override + _LandAppraisal createState() => _LandAppraisal(); +} + +class _LandAppraisal extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context.read().add(DeleteLandAppraisal(id: itemId)); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + final state = context.watch().state; + if (state is LandAppraisalLoaded) { + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('LAND APPRAISAL', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowLandAppraisal()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Classification'), + ), + const DataColumn( + label: Text('Sub-Classification'), + ), + const DataColumn( + label: Text('Area'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('Base MArket Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.land_appr.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.classification!)), + DataCell(Text(dataRow.subClass!)), + DataCell(Text(dataRow.area!)), + DataCell(Text( + ((double.parse(dataRow.unitValue!))) + .toString())), + DataCell(Text( + ((double.parse(dataRow.baseMarketval!))) + .toString())), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id!); + }, + ), + SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList())) + ], + ), + ), + )), + // Padding( + // padding: const EdgeInsets.only(left: 20.0, right: 20.0), + // child: Row( + // mainAxisAlignment: MainAxisAlignment.spaceBetween, + // children: [ + // Text( + // 'Total', + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ), + // Text( + // NumberFormat.currency(locale: 'en-PH', symbol: "₱") + // .format('1.0'), + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ) + // ], + // ), + // ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ), + ], + ); + } + if (state is LandAppraisalDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context.read().add(const LoadLandAppraisal()); + }); + }); + } + } + if (state is ShowAddLandAppraisalScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: Text( + 'ADD LAND APPRAISAL', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: AddLandAppraisalModal())], + ), + ), + ); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/location_and_boundaries.dart b/lib/screens/passo/Land/add_land/location_and_boundaries.dart new file mode 100644 index 0000000..f27db38 --- /dev/null +++ b/lib/screens/passo/Land/add_land/location_and_boundaries.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart'; +import 'package:unit2/model/passo/land_property_boundaries.dart'; +import 'package:unit2/model/passo/land_property_loc.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class LandLocationAndBoundaries extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandLocationAndBoundaries(this.PrevBtn, this.NextBtn); + @override + _LandLocationAndBoundaries createState() => _LandLocationAndBoundaries(); +} + +class _LandLocationAndBoundaries extends State { + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY LOCATION', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("No. / Street", "", "street")), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Brgy./District", "", "brgy")), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: + customTextField("Municipality", "", "municipality"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Province/City", "", "province")) + ]), + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY BOUNDARIES', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("North", "", "north"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("East", "", "east")) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("South", "", "south"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("West", "", "west")) + ]), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left, color: Colors.white), + onPressed: () { + widget.PrevBtn(); + }), + CustomButton( + icon: + const Icon(Icons.chevron_right, color: Colors.white), + onPressed: () { + var boundaries = LandPropertyBoundaries( + id: 3, + north: landKey.currentState?.value['north'], + east: landKey.currentState?.value['east'], + west: landKey.currentState?.value['west'], + south: landKey.currentState?.value['south'], + ); + var location = LandPropertyLoc( + id: 3, + street: landKey.currentState?.value['street'], + barangay: landKey.currentState?.value['brgy'], + municipality: + landKey.currentState?.value['municipality'], + province: landKey.currentState?.value['province'], + ); + + context.read() + ..add( + UpdateLandBoundaries(land_boundaries: boundaries)) + ..add(UpdateLandLoc(land_loc: location)); + + widget.NextBtn(); + }) + ], + ) + ]), + ), + ); + } +} diff --git a/lib/screens/passo/Land/add_land/other_improvements.dart b/lib/screens/passo/Land/add_land/other_improvements.dart new file mode 100644 index 0000000..295e1b7 --- /dev/null +++ b/lib/screens/passo/Land/add_land/other_improvements.dart @@ -0,0 +1,263 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/screens/passo/Land/add_land/AddOtherImprovementModal.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class OtherImprovementPage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + OtherImprovementPage(this.PrevBtn, this.NextBtn); + @override + _OtherImprovementPage createState() => _OtherImprovementPage(); +} + +class _OtherImprovementPage extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteOtherImprovement(id: itemId)); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + final state = context.watch().state; + if (state is OtherImprovementLoaded) { + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('OTHER IMPROVEMENTS', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowOtherImprovement()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Kinds of Tress'), + ), + const DataColumn( + label: Text('Sub-Class / Age'), + ), + const DataColumn( + label: Text('Type of Tree'), + ), + const DataColumn( + label: Text('No.'), + ), + const DataColumn( + label: Text('No. of Productive'), + ), + const DataColumn( + label: Text('No. of Non-Productive'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('Base Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.other_imp.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.kindsOfTrees!)), + DataCell(Text(dataRow.subclassAge!)), + DataCell(Text(dataRow.fruitBearing! + ? "Fruit Bearing" + : "Non-Fruit Bearing")), + DataCell(Text(dataRow.quantity.toString()!)), + DataCell( + Text(dataRow.noOfProductive.toString()!)), + DataCell(Text( + dataRow.noOfNonproductive.toString()!)), + DataCell(Text(dataRow.unitValue.toString()!)), + DataCell( + Text(dataRow.baseMarketval.toString()!)), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id!); + }, + ), + SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList())) + ], + ), + ), + )), + // Padding( + // padding: const EdgeInsets.only(left: 20.0, right: 20.0), + // child: Row( + // mainAxisAlignment: MainAxisAlignment.spaceBetween, + // children: [ + // Text( + // 'Total', + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ), + // Text( + // NumberFormat.currency(locale: 'en-PH', symbol: "₱") + // .format('1.0'), + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ) + // ], + // ), + // ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ), + ], + ); + } + if (state is OtherImprovementDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadOtherImprovement()); + }); + }); + } + } + if (state is ShowAddOtherImprovementScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: Text( + 'ADD OTHER IMPROVEMENTS', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: AddOtherImprovementModal())], + ), + ), + ); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/property_assessment.dart b/lib/screens/passo/Land/add_land/property_assessment.dart new file mode 100644 index 0000000..19f43bf --- /dev/null +++ b/lib/screens/passo/Land/add_land/property_assessment.dart @@ -0,0 +1,243 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class LandPropertyAssessmentPage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandPropertyAssessmentPage(this.PrevBtn, this.NextBtn); + @override + _LandPropertyAssessmentPage createState() => _LandPropertyAssessmentPage(); +} + +class _LandPropertyAssessmentPage extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteLandPropertyAssessment(id: itemId)); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + final state = context.watch().state; + if (state is LandPropertyAssessmentLoaded) { + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY ASSESSMENT', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowLandPropertyAssessment()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Actual Use'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Assessment Level'), + ), + const DataColumn( + label: Text('Assessed Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.assessment.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.actualUse!)), + DataCell(Text(dataRow.marketval!)), + DataCell( + Text(dataRow.assessmentLevel! + '%')), + DataCell(Text(dataRow.assessedValue!)), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id!); + }, + ), + SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList())) + ], + ), + ), + )), + // Padding( + // padding: const EdgeInsets.only(left: 20.0, right: 20.0), + // child: Row( + // mainAxisAlignment: MainAxisAlignment.spaceBetween, + // children: [ + // Text( + // 'Total', + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ), + // Text( + // NumberFormat.currency(locale: 'en-PH', symbol: "₱") + // .format('1.0'), + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ) + // ], + // ), + // ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ), + ], + ); + } + if (state is LandPropertyAssessmentDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadLandPropertyAssessment()); + }); + }); + } + } + if (state is ShowAddLandPropertyAssessmentScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: Text( + 'ADD PROPERTY ASSESSMENT', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: AddPropertyAssessmentModal())], + ), + ), + ); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Land/add_land/property_assessment_cont.dart b/lib/screens/passo/Land/add_land/property_assessment_cont.dart new file mode 100644 index 0000000..ad1f710 --- /dev/null +++ b/lib/screens/passo/Land/add_land/property_assessment_cont.dart @@ -0,0 +1,541 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/passo/land/land_ext/land_ext_bloc.dart'; +import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart'; +import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; +import 'package:unit2/model/passo/land_ext.dart'; +import 'package:unit2/model/passo/memoranda.dart'; +import 'package:unit2/model/passo/signatories.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +class LandSignatories extends StatefulWidget { + Function onSAve; + LandSignatories(this.onSAve); + + @override + _LandSignatories createState() => _LandSignatories(); +} + +class _LandSignatories extends State { + bool isTaxable = false; + bool isExempt = false; + final focus = FocusNode(); + String _memoranda = ""; + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandExtLoaded) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is SignatoriesLoaded) { + final signatories = state.signatories; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + return SingleChildScrollView( + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY ASSESSMENT cont..', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Row( + children: [ + const Text('Taxable'), + Checkbox( + checkColor: Colors.white, + value: isTaxable, + onChanged: (bool? value) { + setState(() { + isTaxable = value!; + }); + }, + ) + ], + ), + Row( + children: [ + const Text('Exempt'), + Checkbox( + checkColor: Colors.white, + value: isExempt, + onChanged: (bool? value) { + setState(() { + isExempt = value!; + }); + }, + ) + ], + ), + ], + ), + Column( + children: [ + const SizedBox( + height: 20, + ), + const Text( + 'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :', + style: TextStyle(fontWeight: FontWeight.bold), + ), + const SizedBox( + height: 20, + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + const Text('Qtr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'land_qtr', + validator: + FormBuilderValidators.compose([]), + ), + ), + const SizedBox( + width: 20, + ), + const Text('Yr.'), + SizedBox( + width: 70, + height: 25, + child: FormBuilderTextField( + name: 'land_yr', + validator: + FormBuilderValidators.compose([]), + ), + ), + ], + ), + ], + ), + Container( + margin: const EdgeInsets.only( + left: 0, top: 40, right: 0, bottom: 10), + child: const Text('SIGNATORIES', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + const SizedBox( + height: 30, + ), + Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPRAISED/ASSESSED BY:', + style: TextStyle(fontWeight: FontWeight.bold), + textAlign: TextAlign.start, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown( + name: 'appraised_by_land', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: FormBuilderDateTimePicker( + name: 'app_date_land', + initialEntryMode: + DatePickerEntryMode.calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay(hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'RECOMMENDING APPROVAL:', + style: TextStyle(fontWeight: FontWeight.bold), + )), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown( + name: 'rec_approval_land', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: FormBuilderDateTimePicker( + name: 'rec_date_land', + initialEntryMode: + DatePickerEntryMode.calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay(hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPROVED BY:', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Column( + children: [ + SizedBox( + width: 200, + child: FormBuilderDropdown( + name: 'apprvd_by_land', + autofocus: false, + items: signatories + .map((signatories) => + DropdownMenuItem( + value: signatories, + child: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'), + )) + .toList()), + ), + Text('Name'), + ], + ), + const SizedBox( + width: 15, + ), + Column( + children: [ + SizedBox( + width: 100, + child: FormBuilderDateTimePicker( + name: 'apprvd_by_date_land', + initialEntryMode: + DatePickerEntryMode.calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay(hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + Text('Date'), + ], + ), + ], + ), + const SizedBox( + height: 50, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'MEMORANDA: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + SizedBox( + height: 50, + ), + SizedBox( + width: 500, + height: 100, + child: SearchField( + suggestions: state.memorada + .map((Memoranda memoranda) => + SearchFieldListItem( + '${memoranda.memoranda}', + item: + memoranda, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${memoranda.memoranda}', + overflow: TextOverflow.ellipsis, + ), + ), + )) + .toList(), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + // searchInputDecoration: + // normalTextFieldStyle( + // "Memoranda", "") + // .copyWith( + // suffixIcon: const Icon( + // Icons.arrow_drop_down), + // ), + // focusNode: focus, + suggestionState: Suggestion.expand, + onSuggestionTap: (memoranda) { + setState(() { + _memoranda = memoranda.item!.memoranda!; + }); + focus.unfocus(); + }, + )), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Sworn Statement No. :'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'sworn_statement_land', + decoration: InputDecoration(), + validator: FormBuilderValidators.compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Date Received:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_received_land', + initialEntryMode: + DatePickerEntryMode.calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay(hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Date of Entry in the Rec. of Ass. :'), + SizedBox( + width: 100, + height: 20, + child: FormBuilderDateTimePicker( + name: 'date_of_entry_land', + initialEntryMode: + DatePickerEntryMode.calendarOnly, + initialValue: DateTime.now(), + inputType: InputType.date, + + initialTime: + const TimeOfDay(hour: 8, minute: 0), + // locale: const Locale.fromSubtags(languageCode: 'fr'), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('By:'), + SizedBox( + width: 150, + height: 20, + child: FormBuilderTextField( + name: 'by_land', + decoration: InputDecoration(), + validator: FormBuilderValidators.compose([]), + ), + ), + ], + ), + SizedBox( + height: 30, + ), + ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); + var ext = LandExt( + landapprDetailsId: + tempID.getInt('landid')! - 1, + taxable: isTaxable, + exempt: isExempt, + qtr: int.parse( + landKey.currentState!.value['land_qtr']), + yr: int.parse( + landKey.currentState!.value['land_yr']), + appraisedbyName: landKey.currentState!.value['appraised_by_land'].firstname + + ' ' + + landKey + .currentState! + .value['appraised_by_land'] + .middlename + + ' ' + + landKey.currentState! + .value['appraised_by_land'].lastname, + appraisedbyDate: landKey + .currentState!.value['app_date_land'], + recommendapprName: landKey + .currentState! + .value['rec_approval_land'] + .firstname + + ' ' + + landKey + .currentState! + .value['rec_approval_land'] + .middlename + + ' ' + + landKey.currentState! + .value['rec_approval_land'].lastname, + recommendapprDate: landKey + .currentState!.value['rec_date_land'], + approvedbyName: landKey.currentState!.value['apprvd_by_land'].firstname + + ' ' + + landKey.currentState!.value['apprvd_by_land'].middlename + + ' ' + + landKey.currentState!.value['apprvd_by_land'].lastname, + approvedbyDate: landKey.currentState!.value['apprvd_by_date_land'], + memoranda: _memoranda, + swornstatementNo: landKey.currentState!.value['sworn_statement_land'], + dateReceived: landKey.currentState!.value['date_received_land'], + entryDateAssessment: landKey.currentState!.value['date_of_entry_land'], + entryDateBy: landKey.currentState!.value['by_land']); + + context.read() + ..add(UpdateLandExt(landext: ext)); + widget.onSAve(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: primary, + foregroundColor: Colors.red), + child: SizedBox( + width: 250, + height: 50, + child: Align( + alignment: Alignment.center, + child: Text( + 'Save', + style: TextStyle( + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + SizedBox( + height: 30, + ), + ], + )); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/passo/Land/add_land/property_owner_info.dart b/lib/screens/passo/Land/add_land/property_owner_info.dart new file mode 100644 index 0000000..ec1391f --- /dev/null +++ b/lib/screens/passo/Land/add_land/property_owner_info.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart'; +import 'package:unit2/model/passo/land_property_owner.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class LandPropertyOwnerInfo extends StatefulWidget { + Function NextBtn; + LandPropertyOwnerInfo(this.NextBtn); + @override + _LandPropertyOwnerInfo createState() => _LandPropertyOwnerInfo(); +} + +class _LandPropertyOwnerInfo extends State { + final transaction_codes = ['New', 'Revision']; + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + margin: + const EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 10), + child: const Text('PROPERTY OWNER INFO', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + const SizedBox(height: 15), + customDropDownField( + "Transaction Code", "", "transaction_code", transaction_codes), + customTextField("ARP No./ TD No.", "", "td_no"), + customTextField("Owner", "", "owner"), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded(flex: 1, child: customTextField("PIN", "", "pin")), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("TIN", "", "tin")) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("OCT/TCT CLOA No.", "", "cloa_no"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDatTimePicker("Dated", "", "dated")) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Survey No.", "", "survey_no"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Lot No.", "", "lot_no")), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Blk", "", "blk")), + ]), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Address", "", "address"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Tel No.", "", "tel_no")) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Administrator/Beneficial User", "", "admin"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("TIN", "", "admin_tin")) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Address", "", "admin_address"), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Tel No.", "", "admin_telno")) + ]), + + // SizedBox( + // width: double.infinity, + // height: 50, + // child: ElevatedButton( + // style: secondaryBtnStyle(const Color(0xffd92828), + // Color.fromARGB(0, 253, 252, 252), Colors.white54), + // child: const Text( + // "SUBMIT & PROCEED", + // style: TextStyle( + // color: Color.fromARGB(239, 255, 255, 255), + // fontWeight: FontWeight.w700), + // ), + // onPressed: () { + // // formKey.currentState?.save(); + // // // var faas = PropertyInfo( + // // // id: 1, + // // // transCode: formKey + // // // .currentState!.value['transaction_code'] + // // // .toString(), + // // // tdn: formKey.currentState!.value['arp_td'], + // // // pin: formKey.currentState!.value['pin'], + // // // owner: formKey.currentState!.value['owner'], + // // // address: formKey.currentState!.value['address'], + // // // telno: formKey.currentState!.value['tel_no'], + // // // tin: formKey.currentState!.value['tin'], + // // // adminUser: formKey.currentState!.value['benificiary'], + // // // adminAddress: formKey + // // // .currentState!.value['benificiary_address'], + // // // adminTin: + // // // formKey.currentState!.value['benificiary_tin'], + // // // adminTelno: + // // // formKey.currentState!.value['benificiary_telno']); + // // // context.read().add(AddFaas(faas: faas)); + // // // _loadTempId(); + // // _pageController.nextPage( + // // duration: _kDuration, curve: _kCurve); + // }), + // ), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_right, color: Colors.white), + onPressed: () { + var land = LandPropertyOwner( + id: 1, + transCode: landKey + .currentState!.value['transaction_code'] + .toString(), + tdn: landKey.currentState!.value['td_no'], + cloaNo: landKey.currentState!.value['cloa_no'], + dated: landKey.currentState!.value['dated'], + assessedById: "1", + assessedByName: "cyril", + dateCreated: landKey.currentState!.value['dated'], + dateModified: landKey.currentState!.value['dated'], + pin: landKey.currentState!.value['pin'], + surveyNo: landKey.currentState!.value['survey_no'], + lotNo: landKey.currentState!.value['lot_no'], + blkNo: landKey.currentState!.value['blk'], + owner: landKey.currentState!.value['owner'], + address: landKey.currentState!.value['address'], + telno: landKey.currentState!.value['tel_no'], + tin: landKey.currentState!.value['tin'], + adminUser: landKey.currentState!.value['admin'], + adminAddress: + landKey.currentState!.value['admin_address'], + adminTin: landKey.currentState!.value['admin_tin'], + // faasType: "LAND", + adminTelno: landKey.currentState!.value['admin_telno']); + + context + .read() + .add(AddPropertyOwnerLand(land: land)); + + widget.NextBtn(); + }, + ) + ], + ), + const SizedBox( + height: 20, + ), + ]), + )); + } +} diff --git a/lib/screens/passo/Land/add_land/value_adjustments.dart b/lib/screens/passo/Land/add_land/value_adjustments.dart new file mode 100644 index 0000000..35dbaf2 --- /dev/null +++ b/lib/screens/passo/Land/add_land/value_adjustments.dart @@ -0,0 +1,246 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +class ValueAdjustmentPage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + ValueAdjustmentPage(this.PrevBtn, this.NextBtn); + @override + _ValueAdjustmentPage createState() => _ValueAdjustmentPage(); +} + +class _ValueAdjustmentPage extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteLandValueAdjustments(id: itemId)); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + final state = context.watch().state; + if (state is LandValueAdjustmentsLoaded) { + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('VALUE ADJUSTMENTS', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.left), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowLandValueAdjustments()); + }, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('ADD ITEM'), // <-- Text + const SizedBox( + width: 5, + ), + const Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Base Market Value'), + ), + const DataColumn( + label: Text('Adjustment Factors'), + ), + const DataColumn( + label: Text('% Adjustment'), + ), + const DataColumn( + label: Text('Value Adjustment'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.val_adj.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.baseMarketval!)), + DataCell(Text(dataRow.adjustmentFactors!)), + DataCell(Text(dataRow.adjustment!)), + DataCell(Text(dataRow.valueAdjustment!)), + DataCell(Text(dataRow.marketValue!)), + DataCell(Row( + children: [ + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.delete, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () { + deleteItem(dataRow.id!); + }, + ), + SizedBox( + width: 10, + ), + InkWell( + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.red, + ), + child: Icon( + Icons.edit, + color: Colors.white, + size: 20.0, + ), + ), + onTap: () {}, + ), + ], + )) + ], + ); + }).toList())) + ], + ), + ), + )), + // Padding( + // padding: const EdgeInsets.only(left: 20.0, right: 20.0), + // child: Row( + // mainAxisAlignment: MainAxisAlignment.spaceBetween, + // children: [ + // Text( + // 'Total', + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ), + // Text( + // NumberFormat.currency(locale: 'en-PH', symbol: "₱") + // .format('1.0'), + // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + // ) + // ], + // ), + // ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + CustomButton( + icon: const Icon(Icons.chevron_right_rounded, + color: Colors.white), + onPressed: () { + { + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ), + ], + ); + } + if (state is LandValueAdjustmentsDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadLandValueAdjustments()); + }); + }); + } + } + if (state is ShowAddLandValueAdjustmentsScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: Text( + 'ADD VALUE ADJUSTMENTS', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: AddLandValueAdjustmentModal())], + ), + ), + ); + } + return Container(); + }); + } +} diff --git a/lib/screens/passo/building_home.dart b/lib/screens/passo/building_home.dart new file mode 100644 index 0000000..c2dcaeb --- /dev/null +++ b/lib/screens/passo/building_home.dart @@ -0,0 +1,406 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; + +import 'package:unit2/bloc/passo/barangay/barangay_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/general_description/general_description_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/landref/landref_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/location/location_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/structural_material/structural_material_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_classification/land_classification_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_ext/land_ext_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_road/type_of_road_bloc.dart'; + +import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart'; +import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart'; + +import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; + +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/model/passo/property_appraisal_edit.dart'; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/model/passo/structureMaterial.dart'; +import 'package:unit2/model/profile/basic_information/primary-information.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/screens/passo/Building/edit_building.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/screens/passo/Test%20Envi/multi_dropdown.dart'; +import 'package:unit2/screens/passo/Test%20Envi/speed_dial.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/global_context.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:flutter_speed_dial/flutter_speed_dial.dart'; + +import '../../model/passo/bldg_loc.dart'; + +class BuildingHome extends StatelessWidget { + const BuildingHome({super.key}); + + @override + Widget build(BuildContext context) { + int? profileId; + String? token; + Profile profile; + return Scaffold( + body: ProgressHUD( + padding: const EdgeInsets.only(left: 24, right: 24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder(builder: (context, state) { + if (state is UserLoggedIn) { + profileId = state.userData!.user!.login!.user!.profileId; + token = state.userData!.user!.login!.token!; + profile = state.userData!.employeeInfo!.profile!; + return BlocConsumer( + listener: ( + context, + state, + ) { + if (state is PropertyInfoLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PropertyInfoLoaded || + state is PropertyInfoErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is PropertyInfoLoaded) { + List propertyList = state.property_info; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Expanded( + child: ListView.builder( + shrinkWrap: true, + itemCount: propertyList.length, + itemBuilder: (BuildContext context, int index) { + return _listCard( + propertyList[index], context, index); + }, + ), + ), + ); + } + if (state is PropertyInfoErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadPropertyInfo()); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + })), + floatingActionButton: SpeedDial( + +//provide here features of your parent FAB + icon: Icons.add, + backgroundColor: primary, + heroTag: null, + useRotationAnimation: true, + activeIcon: Icons.close, + animationCurve: Curves.elasticInOut, + children: [ + SpeedDialChild( + child: const Icon( + Icons.maps_home_work_rounded, + color: primary, + ), + label: 'Building & Other Structure', + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return MultiBlocProvider(providers: [ + BlocProvider( + create: (context) => + PropertyInfoBloc()..add(LoadPropertyInfo()), + ), + BlocProvider( + create: (context) => + ClassComponentsBloc()..add(LoadClassComponents()), + ), + BlocProvider( + create: (context) => + UnitConstructBloc()..add(LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => + AdditionalItemBloc()..add(LoadAdditionalItems()), + ), + BlocProvider( + create: (context) => PropertyAppraisalBloc() + ..add(LoadPropertyAppraisal( + appraisal: PropertyAppraisal())), + ), + BlocProvider( + create: (context) => PropertyAssessmentBloc() + ..add(LoadPropertyAssessment())), + BlocProvider( + create: (context) => + SignatoriesBloc()..add(LoadSignatories())), + BlocProvider( + create: (context) => + MunicipalityBloc()..add(LoadMunicipality())), + BlocProvider( + create: (context) => + BarangayBloc()..add(LoadBarangay(id: '01'))), + BlocProvider( + create: (context) => + MemorandaBloc()..add(LoadMemoranda())), + ], child: AddBuilding()); + })); + }), + SpeedDialChild( + child: const Icon( + Icons.forest_rounded, + color: primary, + ), + label: 'Land/Other Improvements', + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return MultiBlocProvider(providers: [ + BlocProvider( + create: (context) => + LandPropertyOwnerInfoBloc()..add(LoadLand())), + BlocProvider( + create: (context) => LandClassificationBloc() + ..add(LoadLandClassification())), + BlocProvider( + create: (context) => LandSubClassificationBloc() + ..add(LoadLandSubClassification( + cityCode: "1", classCode: 1))), + BlocProvider( + create: (context) => + LandAppraisalBloc()..add(LoadLandAppraisal())), + BlocProvider( + create: (context) => + MunicipalityBloc()..add(LoadMunicipality())), + BlocProvider( + create: (context) => + BarangayBloc()..add(LoadBarangay(id: '01'))), + BlocProvider( + create: (context) => OtherImprovementsBloc() + ..add(LoadOtherImprovement())), + BlocProvider( + create: (context) => LandTreesImprovementsBloc() + ..add(LoadLandTreesImprovements())), + BlocProvider( + create: (context) => LandValueAdjustmentsBloc() + ..add(LoadLandValueAdjustments())), + BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(LoadTypeOfLocation())), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(LoadTypeOfRoad())), + BlocProvider( + create: (context) => LandPropertyAssessmentBloc() + ..add(LoadLandPropertyAssessment())), + BlocProvider( + create: (context) => + SignatoriesBloc()..add(LoadSignatories())), + BlocProvider( + create: (context) => LandExtBloc()..add(LoadLandExt())), + BlocProvider( + create: (context) => + MemorandaBloc()..add(LoadMemoranda())), + ], child: AddLand()); + })); + }, + ), + SpeedDialChild( + child: const Icon( + Icons.precision_manufacturing_rounded, + color: primary, + ), + label: 'Machinery', + onTap: () {}, + ), + // SpeedDialChild( + // child: const Icon( + // Icons.report_problem_rounded, + // color: primary, + // ), + // label: 'Testing Screen', + // onTap: () { + // Navigator.of(context) + // .push(MaterialPageRoute(builder: (ctx) => Multi_Select())); + // }, + // ), + ]), + ); + } +} + +Card _listCard(PropertyInfo property_info, context, index) { + return Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + //set border radius more than 50% of height and width to make circle + ), + margin: const EdgeInsets.all(5.0), + elevation: 5, + shadowColor: Colors.grey, + child: Padding( + padding: const EdgeInsets.all(15.0), + child: InkWell( + onTap: () async { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return MultiBlocProvider( + providers: [ + BlocProvider( + create: (context) => + PropertyInfoBloc()..add(LoadPropertyInfo()), + ), + BlocProvider( + create: (context) => + UnitConstructBloc()..add(LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => + ClassComponentsBloc()..add(LoadClassComponents()), + ), + BlocProvider( + create: (context) => + SignatoriesBloc()..add(LoadSignatories())), + BlocProvider( + create: (context) => LocationBloc() + ..add( + LoadLocation(bldgloc: BldgLoc(), id: property_info.id)), + ), + BlocProvider( + create: (context) => LandrefBloc() + ..add( + LoadLandref(landRef: LandRef(), id: property_info.id)), + ), + BlocProvider( + create: (context) => GeneralDescriptionBloc() + ..add(LoadGenDesc( + gendesc: GeneralDesc(), id: property_info.id)), + ), + BlocProvider( + create: (context) => AdditionalItemsEditBloc() + ..add(LoadAdditionalItemsEdit( + items: const [], + id: property_info.id)), + ), + BlocProvider( + create: (context) => PropertyAssessmentEditBloc() + ..add(LoadPropertyAssessmentEdit( + assessmentsEdit: PropertyAssessmentEdit(), + id: property_info.id)), + ), + BlocProvider( + create: (context) => PropertyAppraisalEditBloc() + ..add(LoadPropertyAppraisalEdit( + appraisalEdit: PropertyAppraisalEdit(), + id: property_info.id)), + ), + BlocProvider( + create: (context) => + MunicipalityBloc()..add(LoadMunicipality())), + BlocProvider( + create: (context) => + BarangayBloc()..add(LoadBarangay(id: '01'))), + BlocProvider( + create: (context) => MemorandaBloc()..add(LoadMemoranda())), + BlocProvider( + create: (context) => StructuralMaterialBloc() + ..add(LoadStructuralMaterial( + structure: StructureMaterials(), + id: property_info.id))), + ], + child: EditBuilding( + index: index, + faas: property_info, + title: 'Bldg & Structure Edit', + ), + ); + })); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 40, // Adjust this to your desired size + height: 40, // Adjust this to your desired size + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: primary, // Border color + width: 2, // Border width + ), + ), + child: Icon( + Icons.maps_home_work_rounded, + color: primary, // Icon color + ), + ), + SizedBox( + width: 20, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${property_info.owner}', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.left, + ), + SizedBox(height: 5), + Text( + '${property_info.tdn}', + style: TextStyle( + fontSize: 13, + ), + textAlign: TextAlign.left, + ), + ], + ), + ), + IconButton(onPressed: () {}, icon: const Icon(Icons.chevron_right)), + ], + ), + ), + ), + ); +} diff --git a/lib/screens/passo/land_home .dart b/lib/screens/passo/land_home .dart new file mode 100644 index 0000000..4326133 --- /dev/null +++ b/lib/screens/passo/land_home .dart @@ -0,0 +1,406 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; + +import 'package:unit2/bloc/passo/barangay/barangay_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/general_description/general_description_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/landref/landref_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/location/location_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/structural_material/structural_material_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_classification/land_classification_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_ext/land_ext_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/passo/land/type_of_road/type_of_road_bloc.dart'; + +import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart'; +import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart'; + +import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; + +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/model/passo/land_property_owner.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/model/passo/property_appraisal_edit.dart'; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/model/passo/structureMaterial.dart'; +import 'package:unit2/model/profile/basic_information/primary-information.dart'; +import 'package:unit2/screens/passo/Building/add_building.dart'; +import 'package:unit2/screens/passo/Building/edit_building.dart'; +import 'package:unit2/screens/passo/Land/add_land.dart'; +import 'package:unit2/screens/passo/Test%20Envi/multi_dropdown.dart'; +import 'package:unit2/screens/passo/Test%20Envi/speed_dial.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:flutter_speed_dial/flutter_speed_dial.dart'; + +import '../../model/passo/bldg_loc.dart'; + +class LandHome extends StatelessWidget { + const LandHome({super.key}); + + @override + Widget build(BuildContext context) { + int? profileId; + String? token; + Profile profile; + return Scaffold( + body: ProgressHUD( + padding: const EdgeInsets.only(left: 24, right: 24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder(builder: (context, state) { + if (state is UserLoggedIn) { + profileId = state.userData!.user!.login!.user!.profileId; + token = state.userData!.user!.login!.token!; + profile = state.userData!.employeeInfo!.profile!; + return BlocConsumer( + listener: ( + context, + state, + ) { + if (state is LandLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is LandLoaded || state is LandErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is LandLoaded) { + List propertyList = state.land; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Expanded( + child: ListView.builder( + shrinkWrap: true, + itemCount: propertyList.length, + itemBuilder: (BuildContext context, int index) { + return _listCard( + propertyList[index], context, index); + }, + ), + ), + ); + } + if (state is LandErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadLand()); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + })), + floatingActionButton: SpeedDial( + +//provide here features of your parent FAB + icon: Icons.add, + backgroundColor: primary, + heroTag: null, + useRotationAnimation: true, + activeIcon: Icons.close, + animationCurve: Curves.elasticInOut, + children: [ + SpeedDialChild( + child: const Icon( + Icons.maps_home_work_rounded, + color: primary, + ), + label: 'Building & Other Structure', + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return MultiBlocProvider(providers: [ + BlocProvider( + create: (context) => + PropertyInfoBloc()..add(LoadPropertyInfo()), + ), + BlocProvider( + create: (context) => + ClassComponentsBloc()..add(LoadClassComponents()), + ), + BlocProvider( + create: (context) => + UnitConstructBloc()..add(LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => + AdditionalItemBloc()..add(LoadAdditionalItems()), + ), + BlocProvider( + create: (context) => PropertyAppraisalBloc() + ..add(LoadPropertyAppraisal( + appraisal: PropertyAppraisal())), + ), + BlocProvider( + create: (context) => PropertyAssessmentBloc() + ..add(LoadPropertyAssessment())), + BlocProvider( + create: (context) => + SignatoriesBloc()..add(LoadSignatories())), + BlocProvider( + create: (context) => + MunicipalityBloc()..add(LoadMunicipality())), + BlocProvider( + create: (context) => + BarangayBloc()..add(LoadBarangay(id: '01'))), + BlocProvider( + create: (context) => + MemorandaBloc()..add(LoadMemoranda())), + ], child: AddBuilding()); + })); + }), + SpeedDialChild( + child: const Icon( + Icons.forest_rounded, + color: primary, + ), + label: 'Land/Other Improvements', + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return MultiBlocProvider(providers: [ + BlocProvider( + create: (context) => + LandPropertyOwnerInfoBloc()..add(LoadLand())), + BlocProvider( + create: (context) => LandClassificationBloc() + ..add(LoadLandClassification())), + BlocProvider( + create: (context) => LandSubClassificationBloc() + ..add(LoadLandSubClassification( + cityCode: "1", classCode: 1))), + BlocProvider( + create: (context) => + LandAppraisalBloc()..add(LoadLandAppraisal())), + BlocProvider( + create: (context) => + MunicipalityBloc()..add(LoadMunicipality())), + BlocProvider( + create: (context) => + BarangayBloc()..add(LoadBarangay(id: '01'))), + BlocProvider( + create: (context) => OtherImprovementsBloc() + ..add(LoadOtherImprovement())), + BlocProvider( + create: (context) => LandTreesImprovementsBloc() + ..add(LoadLandTreesImprovements())), + BlocProvider( + create: (context) => LandValueAdjustmentsBloc() + ..add(LoadLandValueAdjustments())), + BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(LoadTypeOfLocation())), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(LoadTypeOfRoad())), + BlocProvider( + create: (context) => LandPropertyAssessmentBloc() + ..add(LoadLandPropertyAssessment())), + BlocProvider( + create: (context) => + SignatoriesBloc()..add(LoadSignatories())), + BlocProvider( + create: (context) => LandExtBloc()..add(LoadLandExt())), + BlocProvider( + create: (context) => + MemorandaBloc()..add(LoadMemoranda())), + ], child: AddLand()); + })); + }, + ), + SpeedDialChild( + child: const Icon( + Icons.precision_manufacturing_rounded, + color: primary, + ), + label: 'Machinery', + onTap: () {}, + ), + // SpeedDialChild( + // child: const Icon( + // Icons.report_problem_rounded, + // color: primary, + // ), + // label: 'Testing Screen', + // onTap: () { + // Navigator.of(context) + // .push(MaterialPageRoute(builder: (ctx) => Multi_Select())); + // }, + // ), + ]), + ); + } +} + +Card _listCard(LandPropertyOwner property_info, context, index) { + return Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + //set border radius more than 50% of height and width to make circle + ), + margin: const EdgeInsets.all(5.0), + elevation: 5, + shadowColor: Colors.grey, + child: Padding( + padding: const EdgeInsets.all(15.0), + child: InkWell( + onTap: () async { + // Navigator.push(context, + // MaterialPageRoute(builder: (BuildContext context) { + // return MultiBlocProvider( + // providers: [ + // BlocProvider( + // create: (context) => + // PropertyInfoBloc()..add(LoadPropertyInfo()), + // ), + // BlocProvider( + // create: (context) => + // UnitConstructBloc()..add(LoadUnitConstruct()), + // ), + // BlocProvider( + // create: (context) => + // ClassComponentsBloc()..add(LoadClassComponents()), + // ), + // BlocProvider( + // create: (context) => + // SignatoriesBloc()..add(LoadSignatories())), + // BlocProvider( + // create: (context) => LocationBloc() + // ..add( + // LoadLocation(bldgloc: BldgLoc(), id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => LandrefBloc() + // ..add( + // LoadLandref(landRef: LandRef(), id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => GeneralDescriptionBloc() + // ..add(LoadGenDesc( + // gendesc: GeneralDesc(), id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => AdditionalItemsEditBloc() + // ..add(LoadAdditionalItemsEdit( + // items: const [], + // id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => PropertyAssessmentEditBloc() + // ..add(LoadPropertyAssessmentEdit( + // assessmentsEdit: PropertyAssessmentEdit(), + // id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => PropertyAppraisalEditBloc() + // ..add(LoadPropertyAppraisalEdit( + // appraisalEdit: PropertyAppraisalEdit(), + // id: property_info.id)), + // ), + // BlocProvider( + // create: (context) => + // MunicipalityBloc()..add(LoadMunicipality())), + // BlocProvider( + // create: (context) => + // BarangayBloc()..add(LoadBarangay(id: '01'))), + // BlocProvider( + // create: (context) => MemorandaBloc()..add(LoadMemoranda())), + // BlocProvider( + // create: (context) => StructuralMaterialBloc() + // ..add(LoadStructuralMaterial( + // structure: StructureMaterials(), + // id: property_info.id))), + // ], + // child: EditBuilding( + // index: index, + // faas: property_info, + // title: 'Bldg & Structure Edit', + // ), + // ); + // })); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 40, // Adjust this to your desired size + height: 40, // Adjust this to your desired size + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: primary, // Border color + width: 2, // Border width + ), + ), + child: Icon( + Icons.forest_rounded, + color: primary, // Icon color + ), + ), + SizedBox( + width: 20, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${property_info.owner}', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.left, + ), + SizedBox(height: 5), + Text( + '${property_info.tdn}', + style: TextStyle( + fontSize: 13, + ), + textAlign: TextAlign.left, + ), + ], + ), + ), + IconButton(onPressed: () {}, icon: const Icon(Icons.chevron_right)), + ], + ), + ), + ), + ); +} diff --git a/lib/screens/passo/passo_dashboard.dart b/lib/screens/passo/passo_dashboard.dart new file mode 100644 index 0000000..c423b8f --- /dev/null +++ b/lib/screens/passo/passo_dashboard.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; +import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart'; +import 'package:unit2/screens/passo/building_home.dart'; +import 'package:unit2/screens/passo/land_home%20.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/widgets/empty_data.dart'; + +class PassoDashBoard extends StatefulWidget { + @override + _PassoDashBoard createState() => _PassoDashBoard(); +} + +class _PassoDashBoard extends State { + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 3, + child: Scaffold( + body: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return [ + new SliverAppBar( + backgroundColor: primary, + title: Text('Faas Dashboard'), + centerTitle: true, + pinned: true, + floating: true, + bottom: TabBar( + isScrollable: true, + tabs: [ + Tab(child: Text('Building')), + Tab(child: Text('Land')), + Tab(child: Text('Machineries')), + ], + ), + ), + ]; + }, + body: TabBarView( + children: [ + BlocProvider( + create: (context) => + PropertyInfoBloc()..add(const LoadPropertyInfo()), + child: const BuildingHome(), + ), + BlocProvider( + create: (context) => + LandPropertyOwnerInfoBloc()..add(const LoadLand()), + child: const LandHome(), + ), + EmptyData( + message: "Development ongoing ...", + ) + ], + ), + )), + ); + } +} diff --git a/lib/screens/passo/passo_home.dart b/lib/screens/passo/passo_home.dart deleted file mode 100644 index dc6240d..0000000 --- a/lib/screens/passo/passo_home.dart +++ /dev/null @@ -1,235 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:unit2/bloc/passo/additional_item/additional_item_bloc.dart'; -import 'package:unit2/bloc/passo/class_components/class_components_bloc.dart'; -import 'package:unit2/bloc/passo/property_appraisal/property_appraisal_bloc.dart'; -import 'package:unit2/bloc/passo/property_assessment/property_assessment_bloc.dart'; -import 'package:unit2/bloc/passo/property_info/property_info_bloc.dart'; -import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart'; -import 'package:unit2/bloc/passo/unit_construct/unit_construct_bloc.dart'; -import 'package:unit2/bloc/user/user_bloc.dart'; -import 'package:unit2/model/passo/property_info.dart'; -import 'package:unit2/model/profile/basic_information/primary-information.dart'; -import 'package:unit2/screens/passo/Building/add_building.dart'; -import 'package:unit2/screens/passo/Test%20Envi/multi_dropdown.dart'; -import 'package:unit2/screens/passo/Test%20Envi/speed_dial.dart'; -import 'package:unit2/theme-data.dart/colors.dart'; -import 'package:unit2/widgets/error_state.dart'; -import 'package:flutter_speed_dial/flutter_speed_dial.dart'; - -class PassoHome extends StatelessWidget { - const PassoHome({super.key}); - - @override - Widget build(BuildContext context) { - int? profileId; - String? token; - Profile profile; - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - centerTitle: true, - title: const Text("FAAS LIST"), - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocBuilder(builder: (context, state) { - if (state is UserLoggedIn) { - profileId = state.userData!.user!.login!.user!.profileId; - token = state.userData!.user!.login!.token!; - profile = state.userData!.employeeInfo!.profile!; - return BlocConsumer( - listener: ( - context, - state, - ) { - if (state is PropertyInfoLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is PropertyInfoLoaded || - state is PropertyInfoErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is PropertyInfoLoaded) { - List propertyList = state.property_info; - return Container( - padding: const EdgeInsets.symmetric( - vertical: 12, horizontal: 12), - child: Expanded( - child: ListView.builder( - shrinkWrap: true, - itemCount: propertyList.length, - itemBuilder: (BuildContext context, int index) { - return _listCard( - propertyList[index], context, index); - }, - ), - ), - ); - } - // if(state is PropertyInfoErrorState){ - // return SomethingWentWrong( - // message: onError, - // onpressed: () { - // BlocProvider.of( - // NavigationService.navigatorKey.currentContext!) - // .add(GetApkVersion()); - // return MaterialPageRoute(builder: (_) { - // return const UniT2Login(); - // }); - // }, - // ); - // } - return Container(); - }, - ); - } - return Container(); - })), - floatingActionButton: SpeedDial( - -//provide here features of your parent FAB - icon: Icons.add, - backgroundColor: const Color(0xffd92828), - heroTag: null, - useRotationAnimation: true, - activeIcon: Icons.close, - animationCurve: Curves.elasticInOut, - children: [ - SpeedDialChild( - child: const Icon( - Icons.maps_home_work_rounded, - color: Color(0xffd92828), - ), - label: 'Building & Other Structure', - onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (BuildContext context) { - return MultiBlocProvider(providers: [ - BlocProvider( - create: (context) => - ClassComponentsBloc()..add(LoadClassComponents()), - ), - BlocProvider( - create: (context) => - UnitConstructBloc()..add(LoadUnitConstruct()), - ), - BlocProvider( - create: (context) => - AdditionalItemBloc()..add(LoadAdditionalItems()), - ), - BlocProvider( - create: (context) => PropertyAppraisalBloc() - ..add(LoadPropertyAppraisal()), - ), - BlocProvider( - create: (context) => PropertyAssessmentBloc() - ..add(LoadPropertyAssessment())), - BlocProvider( - create: (context) => - SignatoriesBloc()..add(LoadSignatories())), - ], child: AddBuilding()); - })); - }), - SpeedDialChild( - child: const Icon( - Icons.forest_rounded, - color: Color(0xffd92828), - ), - label: 'Land/Other Improvements', - onTap: () {}, - ), - SpeedDialChild( - child: const Icon( - Icons.precision_manufacturing_rounded, - color: Color(0xffd92828), - ), - label: 'Machinery', - onTap: () {}, - ), - SpeedDialChild( - child: const Icon( - Icons.report_problem_rounded, - color: Color(0xffd92828), - ), - label: 'Testing Screen', - onTap: () { - Navigator.of(context) - .push(MaterialPageRoute(builder: (ctx) => Multi_Select())); - }, - ), - ]), - ); - } -} - -Card _listCard(PropertyInfo property_info, context, index) { - return Card( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - //set border radius more than 50% of height and width to make circle - ), - margin: const EdgeInsets.all(5.0), - elevation: 5, - shadowColor: Colors.grey, - child: Padding( - padding: const EdgeInsets.all(15.0), - child: InkWell( - onTap: () async {}, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - const SizedBox(width: 20), - Row( - children: [ - Text( - '${property_info.owner}', - textAlign: TextAlign.start, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - const SizedBox(height: 5), - Text( - '${property_info.tdn}', - textAlign: TextAlign.start, - style: const TextStyle( - fontSize: 13, - ), - ), - ], - ), - Container( - alignment: Alignment.topCenter, - padding: const EdgeInsets.all(3.0), - decoration: BoxDecoration( - border: Border.all(color: Colors.red), - borderRadius: BorderRadius.all(Radius.circular(8.0))), - child: const Text(' BUILDING ', - style: TextStyle( - color: Colors.red, - fontSize: 10, - fontWeight: FontWeight.bold)), - ), - IconButton(onPressed: () {}, icon: const Icon(Icons.chevron_right)), - ], - ), - ), - ), - ); -} 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 253ea7d..095ca78 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 @@ -493,6 +493,7 @@ class _EditBasicProfileInfoScreenState : double.tryParse( _formKey.currentState?.value['weigth']); Profile primaryInformation = Profile( + webuserId: null, id: state.primaryInformation.id, lastName: lastName, firstName: firstName, diff --git a/lib/screens/profile/components/education_screen.dart b/lib/screens/profile/components/education_screen.dart index 3da29ed..4514284 100644 --- a/lib/screens/profile/components/education_screen.dart +++ b/lib/screens/profile/components/education_screen.dart @@ -3,14 +3,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:fluttericon/font_awesome_icons.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; import 'package:unit2/bloc/user/user_bloc.dart'; import 'package:unit2/model/profile/educational_background.dart'; import 'package:unit2/screens/profile/components/education/add_modal.dart'; import 'package:unit2/theme-data.dart/box_shadow.dart'; import 'package:unit2/theme-data.dart/colors.dart'; -import 'package:unit2/utils/text_container.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/empty_data.dart'; import 'package:unit2/widgets/error_state.dart'; @@ -18,28 +16,37 @@ import '../../../bloc/profile/education/education_bloc.dart'; import '../../../utils/alerts.dart'; import '../../../widgets/Leadings/close_leading.dart'; import 'education/edit_modal.dart'; - class EducationScreen extends StatelessWidget { const EducationScreen({super.key}); - @override Widget build(BuildContext context) { int profileId; String? token; return Scaffold( appBar: AppBar( - title:context.watch().state is AddEducationState? const FittedBox(child: Text("Add Educational Background")): context.watch().state is EditEducationState?const FittedBox(child: Text("Edit Educational Background")):const Text("Education Background"), + title: context.watch().state is AddEducationState + ? const FittedBox(child: Text("Add Educational Background")) + : context.watch().state is EditEducationState + ? const FittedBox(child: Text("Edit Educational Background")) + : const Text("Education Background"), centerTitle: true, backgroundColor: primary, - actions: context.watch().state is EducationalBackgroundLoadedState?[ - AddLeading(onPressed: () { - context.read().add(ShowAddEducationForm()); - }) - ]:(context.watch().state is AddEducationState || context.watch().state is EditEducationState)?[ - CloseLeading(onPressed: () { - context.read().add( LoadEducations()); - }) - ]:[], + actions: context.watch().state + is EducationalBackgroundLoadedState + ? [ + AddLeading(onPressed: () { + context.read().add(ShowAddEducationForm()); + }) + ] + : (context.watch().state is AddEducationState || + context.watch().state + is EditEducationState) + ? [ + CloseLeading(onPressed: () { + context.read().add(LoadEducations()); + }) + ] + : [], ), //userbloc body: ProgressHUD( @@ -66,7 +73,8 @@ class EducationScreen extends StatelessWidget { state is EducationalBackgroundErrorState || state is AddEducationState || state is EditEducationState || - state is EducationDeletedState || state is EditedEducationState) { + state is EducationDeletedState || + state is EditedEducationState) { final progress = ProgressHUD.of(context); progress!.dismiss(); } @@ -92,7 +100,6 @@ class EducationScreen extends StatelessWidget { } } ////EDITED STATE - if (state is EditedEducationState) { if (state.response['success']) { successAlert(context, "Update Successfull!", @@ -188,14 +195,11 @@ class EducationScreen extends StatelessWidget { Row( children: [ Expanded( - child: Text( - level, - style: Theme.of( - context) - .textTheme - .titleSmall! - - )), + child: Text(level, + style: Theme.of( + context) + .textTheme + .titleSmall!)), Text( "$periodFrom - $periodTo", style: Theme.of( @@ -212,7 +216,12 @@ class EducationScreen extends StatelessWidget { school, style: Theme.of(context) .textTheme - .titleMedium!.copyWith(color: primary,fontWeight: FontWeight.w500), + .titleMedium! + .copyWith( + color: primary, + fontWeight: + FontWeight + .w500), ), Container( padding: @@ -228,7 +237,9 @@ class EducationScreen extends StatelessWidget { CrossAxisAlignment .start, children: [ - const SizedBox(height: 8,), + const SizedBox( + height: 8, + ), const Text( " honors: ", style: TextStyle( @@ -237,8 +248,10 @@ class EducationScreen extends StatelessWidget { ), Column( children: honors - .map((Honor honor) => - Text("-${honor.name!.trim()}",style: Theme.of(context).textTheme.labelMedium,)) + .map((Honor honor) => Text( + "-${honor.name!.trim()}", + style: Theme.of(context).textTheme.labelMedium, + )) .toList(), ), ], @@ -312,11 +325,10 @@ class EducationScreen extends StatelessWidget { text: "Remove", value: 2, icon: Icons.delete), - popMenuItem( + popMenuItem( text: "Attach", value: 2, icon: Icons.attach_file), - ], icon: const Icon( Icons.more_vert, @@ -341,8 +353,11 @@ class EducationScreen extends StatelessWidget { } if (state is EducationalBackgroundErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetEducationalBackground(profileId: profileId, token: token!)); + message: state.message, + onpressed: () { + context.read().add( + GetEducationalBackground( + profileId: profileId, token: token!)); }); } if (state is AddEducationState) { diff --git a/lib/screens/profile/components/learning_development/add_modal.dart b/lib/screens/profile/components/learning_development/add_modal.dart index 5a0e4f7..9eed392 100644 --- a/lib/screens/profile/components/learning_development/add_modal.dart +++ b/lib/screens/profile/components/learning_development/add_modal.dart @@ -150,7 +150,6 @@ class _AddLearningAndDevelopmentScreenState setState(() { show = false; showOtherInputs = true; - selectedTrainingController .text = addTrainingController.text diff --git a/lib/screens/profile/components/work_history/add_modal.dart b/lib/screens/profile/components/work_history/add_modal.dart index 9f16525..f7ee97d 100644 --- a/lib/screens/profile/components/work_history/add_modal.dart +++ b/lib/screens/profile/components/work_history/add_modal.dart @@ -14,7 +14,7 @@ import 'package:unit2/model/utils/category.dart'; import 'package:unit2/theme-data.dart/box_shadow.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/theme-data.dart/form-style.dart'; import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/text_container.dart'; import 'package:unit2/utils/validators.dart'; diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index a7dc9f9..b601337 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -13,7 +13,6 @@ import 'package:unit2/bloc/profile/primary_information/citizenship/citizenship_b import 'package:unit2/bloc/profile/primary_information/contact/contact_bloc.dart'; import 'package:unit2/bloc/profile/primary_information/identification/identification_bloc.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; -import 'package:unit2/model/login_data/user_info/user_data.dart'; import 'package:unit2/screens/profile/components/basic_information/address_screen.dart'; import 'package:unit2/screens/profile/components/basic_information/citizenship_screen.dart'; import 'package:unit2/screens/profile/components/basic_information/contact_information_screen.dart'; diff --git a/lib/screens/profile/shared/add_for_empty_search.dart b/lib/screens/profile/shared/add_for_empty_search.dart index 8d90f98..2d67130 100644 --- a/lib/screens/profile/shared/add_for_empty_search.dart +++ b/lib/screens/profile/shared/add_for_empty_search.dart @@ -11,7 +11,10 @@ class EmptyWidget extends StatelessWidget { final Function()? onpressed; final String title; const EmptyWidget( - {super.key, required this.controller, required this.onpressed,required this.title}); + {super.key, + required this.controller, + required this.onpressed, + required this.title}); @override Widget build(BuildContext context) { @@ -36,15 +39,13 @@ class EmptyWidget extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: Text(title), + title: Text(title), content: SizedBox( height: 130, child: Column( children: [ TextFormField( - inputFormatters: [ - UpperCaseTextFormatter() - ], + inputFormatters: [UpperCaseTextFormatter()], controller: controller, decoration: normalTextFieldStyle("", ""), ), @@ -65,8 +66,8 @@ class EmptyWidget extends StatelessWidget { ); }); }, - child: Text(title)) + child: Text(title)) ]), ); } -} \ No newline at end of file +} diff --git a/lib/screens/superadmin/agency.dart/agency_screen.dart b/lib/screens/superadmin/agency.dart/agency_screen.dart new file mode 100644 index 0000000..909f387 --- /dev/null +++ b/lib/screens/superadmin/agency.dart/agency_screen.dart @@ -0,0 +1,267 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:fluttericon/font_awesome_icons.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; +import 'package:unit2/model/utils/agency.dart'; +import 'package:unit2/model/utils/category.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/utils/global_context.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/formatters.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/Leadings/add_leading.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacAgencyScreen extends StatelessWidget { + final int id; + const RbacAgencyScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + List agencyCategory = []; + Category? selectedAgencyCategory; + bool? isPrivate; + final agencyCategoryFocusNode = FocusNode(); + BuildContext parent; + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Agencies"), + actions: [ + AddLeading(onPressed: () { + parent = context; + showDialog( + context: NavigationService.navigatorKey.currentContext!, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add Agency"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "name", + decoration: normalTextFieldStyle( + "Agency name ", "Agency name"), + ), + const SizedBox( + height: 12, + ), + SearchField( + focusNode: agencyCategoryFocusNode, + itemHeight: 80, + suggestions: agencyCategory + .map((Category category) => + SearchFieldListItem(category.name!, + item: category, + child: ListTile( + title: Text(category.name!), + subtitle: Text( + category.industryClass!.name!), + ))) + .toList(), + emptyWidget: Container( + height: 100, + decoration: box1(), + child: const Center( + child: Text("No result found ...")), + ), + onSuggestionTap: (agencyCategory) { + selectedAgencyCategory = agencyCategory.item; + agencyCategoryFocusNode.unfocus(); + }, + searchInputDecoration: + normalTextFieldStyle("Category *", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyCategoryFocusNode.unfocus(); + }, + )), + validator: (value) { + if (value!.isEmpty) { + return "This field is required"; + } + return null; + }, + ), + FormBuilderRadioGroup( + decoration: InputDecoration( + border: InputBorder.none, + label: Row( + children: [ + Text( + "Is this private sector? ", + style: Theme.of(context) + .textTheme + .headlineSmall! + .copyWith(fontSize: 24), + ), + const Icon(FontAwesome.help_circled) + ], + ), + ), + + ////onvhange private sector + onChanged: (value) { + if (value.toString() == "YES") { + isPrivate = true; + } else { + isPrivate = false; + } + }, + + name: 'isPrivate', + validator: FormBuilderValidators.required(), + options: ["YES", "NO"] + .map((lang) => + FormBuilderFieldOption(value: lang)) + .toList(growable: false), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = + formKey.currentState!.value['name']; + parent.read().add(AddAgency( + agency: Agency( + category: selectedAgencyCategory, + id: null, + name: name, + privateEntity: isPrivate))); + Navigator.pop(context); + } + + }, + child: const Text("Add")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is AgencyLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is AgenciesLoaded || + state is AgencyAddesState || + state is AgencyErrorState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is AgencyDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Agency Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetAgencies()); + }); + } else { + errorAlert(context, "Delete Failed", "Object Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is AgenciesLoaded) { + agencyCategory = state.agencyCategory; + if (state.agencies.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.agencies.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Expanded( + 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)), + ), + ], + )), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Object available. Please click + to add."); + } + } + if (state is AgencyErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetObjects()); + }); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/module/module_screen.dart b/lib/screens/superadmin/module/module_screen.dart new file mode 100644 index 0000000..7520f77 --- /dev/null +++ b/lib/screens/superadmin/module/module_screen.dart @@ -0,0 +1,373 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/module/module_bloc.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacModuleScreen extends StatelessWidget { + final int id; + const RbacModuleScreen({super.key, required this.id}); + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Module Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Module name *", "Module name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle("Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState!.value['object_name']; + String? slug = + formKey.currentState!.value['slug']; + String? short = formKey + .currentState!.value['shorthand']; + parent.read().add( + AddRbacModule( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is ModuleLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ModuleLoaded || + state is ModuleErrorState || + state is ModuleAddedState || + state is ModuleDeletedState || + state is ModuleUpdatedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Added State + if (state is ModuleAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } + } + ////Updated state + if (state is ModuleUpdatedState) { + if (state.response['success']) { + successAlert( + context, "Updated Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } else { + errorAlert(context, "Update Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } + } + ////Deleted State + if (state is ModuleDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } else { + errorAlert(context, "Delete Failed", "Module Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(GetModule()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is ModuleLoaded) { + if (state.module.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.module.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar(child: Text('${index+1}'),), + const SizedBox(width: 12,), + Text(state.module[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Update Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: state + .module[index].name, + name: "object_name", + decoration: + normalTextFieldStyle( + "Module name *", + "Module name "), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .module[index].slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .module[index] + .shorthand, + validator: + FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value[ + 'object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value[ + 'shorthand']; + + ////Update + parent.read().add(UpdateRbacModule( + moduleId: state + .module[ + index] + .id!, + name: name, + slug: slug, + short: + short, + createdBy: state + .module[ + index] + .createdBy + ?.id, + updatedBy: + id)); + Navigator.pop( + context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + ////delete + confirmAlert(context, () { + context.read().add( + DeleteRbacModule( + moduleId: + state.module[index].id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is ModuleErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetModule()); + }); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/module_objects/module_objects_screen.dart b/lib/screens/superadmin/module_objects/module_objects_screen.dart new file mode 100644 index 0000000..30ff430 --- /dev/null +++ b/lib/screens/superadmin/module_objects/module_objects_screen.dart @@ -0,0 +1,298 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/models/value_item.dart'; +import 'package:multi_dropdown/multiselect_dropdown.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/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacModuleObjectsScreen extends StatelessWidget { + final int id; + const RbacModuleObjectsScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> moduleObjects = {}; + List modules = []; + List objects = []; + RBAC? selectedModule; + List valueItemObjects = []; + List selectedValueItemObjects = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Module Object Screen"), + actions: [ + AddLeading(onPressed: () { + showDialog( + context: NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemObjects = objects.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add New Module Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "module", + decoration: + normalTextFieldStyle("Module", "Module"), + items: modules.isEmpty + ? [] + : modules.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedModule = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemObjects = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Objects", + padding: const EdgeInsets.all(8), + options: valueItemObjects, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemObjects.isNotEmpty) { + int assignerId = id; + int moduleId = selectedModule!.id!; + List objectId = []; + for (var object in objects) { + selectedValueItemObjects + .forEach((element) { + if (element.label.toLowerCase() == + object.name?.toLowerCase()) { + objectId.add(object.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRbacModuleObjects( + assignerId: assignerId, + moduleId: moduleId, + objectsId: objectId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + print(state); + if (state is ModuleObjectLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ModuleObjectLoadedState || + state is ModuleObjectsErrorState || + state is ModuleObjectAddedState || + state is ModuleObjectDeletedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is ModuleObjectDeletedState) { + if (state.success) { + successAlert( + context, "Delete Successfull!", "Role Deleted Successfully", + () { + Navigator.of(context).pop(); + context.read().add(GetModuleObjects()); + }); + } else { + errorAlert(context, "Delete Failed", "Role Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetModuleObjects()); + }); + } + } + ////Added State + if (state is ModuleObjectAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModuleObjects()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetModuleObjects()); + }); + } + } + }, + builder: (context, state) { + if (state is ModuleObjectLoadedState) { + modules = state.modules; + objects = state.objecs; + moduleObjects = {}; + if (state.moduleObjects.isNotEmpty) { + for (var modObjects in state.moduleObjects) { + if (!moduleObjects.keys + .contains(modObjects.module.name!.toLowerCase())) { + moduleObjects + .addAll({modObjects.module.name!.toLowerCase(): []}); + moduleObjects[modObjects.module.name!.toLowerCase()]!.add( + Content( + id: modObjects.id, name: modObjects.object.name!)); + } else { + moduleObjects[modObjects.module.name!.toLowerCase()]!.add( + Content( + id: modObjects.id, name: modObjects.object.name!)); + } + } + } + + if (state.moduleObjects.isNotEmpty) { + return GroupListView( + sectionsCount: moduleObjects.keys.toList().length, + countOfItemInSection: (int section) { + return moduleObjects.values.toList()[section].length; + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + trailing: IconButton( + color: Colors.grey.shade600, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context, () { + context.read().add( + DeleteRbacModuleObject( + moduleObjectId: moduleObjects.values + .toList()[index.section][index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + moduleObjects.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w600, + color: primary), + ), + ), + ], + ), + ); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: second, + title: Text( + moduleObjects.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith(color: Colors.white), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is ModuleObjectsErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/object/object_screen.dart b/lib/screens/superadmin/object/object_screen.dart new file mode 100644 index 0000000..98edea4 --- /dev/null +++ b/lib/screens/superadmin/object/object_screen.dart @@ -0,0 +1,376 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/Leadings/add_leading.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacObjectScreen extends StatelessWidget { + final int id; + const RbacObjectScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Objects Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Object name *", "Object name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle("Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState!.value['object_name']; + String? slug = + formKey.currentState!.value['slug']; + String? short = formKey + .currentState!.value['shorthand']; + parent.read().add( + AddRbacObject( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is ObjectLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ObjectLoaded || + state is ObjectAddedState || + state is ObjectErrorState || + state is ObjectUpdatedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Added State + if (state is ObjectAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } + } + ////Updated state + if (state is ObjectUpdatedState) { + if (state.response['success']) { + successAlert( + context, "Updated Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } else { + errorAlert(context, "Update Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } + } + ////Deleted State + if (state is ObjectDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Object Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } else { + errorAlert(context, "Delete Failed", "Object Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(GetObjects()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is ObjectLoaded) { + if (state.objects.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.objects.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.objects[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: + const Text("Update Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: state + .objects[index].name, + name: "object_name", + decoration: + normalTextFieldStyle( + "Object name *", + "Object name "), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .objects[index].slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .objects[index] + .shorthand, + validator: + FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value[ + 'object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value[ + 'shorthand']; + + parent.read().add(UpdateRbacObject( + objectId: state + .objects[ + index] + .id!, + name: name, + slug: slug, + short: + short, + createdBy: state + .objects[ + index] + .createdBy + ?.id, + updatedBy: + id)); + Navigator.pop( + context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + context.read().add( + DeleteRbacObject( + objectId: + state.objects[index].id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Object available. Please click + to add."); + } + } + if (state is ObjectErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetObjects()); + }); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/operation/operation_screen.dart b/lib/screens/superadmin/operation/operation_screen.dart new file mode 100644 index 0000000..f9a9f8d --- /dev/null +++ b/lib/screens/superadmin/operation/operation_screen.dart @@ -0,0 +1,375 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/Leadings/add_leading.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacOperationScreen extends StatelessWidget { + final int id; + const RbacOperationScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Operations Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Operation name *", "Operation name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle("Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState!.value['object_name']; + String? slug = + formKey.currentState!.value['slug']; + String? short = formKey + .currentState!.value['shorthand']; + parent.read().add( + AddRbacOperation( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is OperationLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is OperationsLoaded || + state is OperationErrorState || + state is OperationAddedState || + state is OperationUpdatedState || + state is OperationDeletedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Added State + if (state is OperationAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } + } + ////Updated state + if (state is OperationUpdatedState) { + if (state.response['success']) { + successAlert( + context, "Updated Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } else { + errorAlert(context, "Update Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } + } + ////Deleted State + if (state is OperationDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Operation Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } else { + errorAlert(context, "Delete Failed", "Operation Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(GetOperations()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is OperationsLoaded) { + if (state.operations.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.operations.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar(child: Text('${index+1}'),), + const SizedBox(width: 12,), + Text(state.operations[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Update Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: state + .operations[index] + .name, + name: "object_name", + decoration: + normalTextFieldStyle( + "Operation name *", + "Operation name "), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .operations[index] + .slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .operations[index] + .shorthand, + validator: + FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value[ + 'object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value[ + 'shorthand']; + + parent.read().add(UpdateRbacOperation( + operationId: state + .operations[ + index] + .id!, + name: name, + slug: slug, + short: + short, + createdBy: state + .operations[ + index] + .createdBy + ?.id, + updatedBy: + id)); + Navigator.pop( + context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + context.read().add( + DeleteRbacOperation( + operationId: state + .operations[index].id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is OperationErrorState) { + return SomethingWentWrong( + message: state.toString(), + onpressed: () { + context.read().add(GetOperations()); + }); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/permission/permission_screen.dart b/lib/screens/superadmin/permission/permission_screen.dart new file mode 100644 index 0000000..28e18c2 --- /dev/null +++ b/lib/screens/superadmin/permission/permission_screen.dart @@ -0,0 +1,283 @@ +import 'dart:math'; +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/global_context.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacPermissionScreen extends StatelessWidget { + final int id; + const RbacPermissionScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + List objects = []; + RBAC? selectedObject; + List operations = []; + List valueItemOperations = []; + List selectedValueItemOperations = []; + final formKey = GlobalKey(); + BuildContext? parent; + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Permissions Screen"), + actions: [ + AddLeading(onPressed: () { + showDialog( + context: NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemOperations = operations.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "object", + decoration: + normalTextFieldStyle("Permission", "Permission"), + items: objects.isEmpty + ? [] + : objects.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedObject = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemOperations = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemOperations, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemOperations + .isNotEmpty) { + int assignerId = id; + int objectId = selectedObject!.id!; + + List opIds = []; + for (var operation in operations) { + selectedValueItemOperations + .forEach((element) { + if (element.label.toLowerCase() == + operation.name?.toLowerCase()) { + opIds.add(operation.id!); + } + }); + } + opIds.forEach((element) { + print(element); + }); + Navigator.pop(context); + parent!.read().add( + AddRbacPermission( + assignerId: assignerId, + objectId: objectId, + operationIds: opIds)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is PermissonLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PermissionLoaded || + state is PermissionErrorState || + state is PermissionAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Added State + if (state is PermissionAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetPermissions()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetPermissions()); + }); + } + } + ////Deleted State + if (state is PermissionDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Permission Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetPermissions()); + }); + } else { + errorAlert(context, "Delete Failed", "Permission Delete Failed", + () { + Navigator.of(context).pop(); + context.read().add(GetPermissions()); + }); + } + } + }, + builder: (context, state) { + parent = context; + if (state is PermissionLoaded) { + objects = state.objects; + operations = state.operations; + if (state.permissions.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.permissions.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Flexible( + child: Text( + "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 1) { + + confirmAlert(context, () { + context.read().add( + DeleteRbacPermission( + permissionId: state.permissions[index].id!)); + }, "Delete?", "Confirm Delete?"); + + } + }, + menuItems: [ + + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Permission available. Please click + to add."); + } + } + if (state is PermissionErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/role/role_screen.dart b/lib/screens/superadmin/role/role_screen.dart new file mode 100644 index 0000000..5c65a71 --- /dev/null +++ b/lib/screens/superadmin/role/role_screen.dart @@ -0,0 +1,373 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleScreen extends StatelessWidget { + final int id; + const RbacRoleScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Role Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Role name *", "Role name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle("Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState!.value['object_name']; + String? slug = + formKey.currentState!.value['slug']; + String? short = formKey + .currentState!.value['shorthand']; + parent.read().add(AddRbacRole( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleLoadedState || + state is RoleErrorState || + state is RoleAddedState || + state is RoleDeletedState || + state is RoleUpdatedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Added State + if (state is RoleAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } + } + ////Updated state + if (state is RoleUpdatedState) { + if (state.response['success']) { + successAlert( + context, "Updated Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } else { + errorAlert(context, "Update Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } + } + ////Deleted State + if (state is RoleDeletedState) { + if (state.success) { + successAlert( + context, "Delete Successfull!", "Role Deleted Successfully", + () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } else { + errorAlert(context, "Delete Failed", "Role Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRoles()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is RoleLoadedState) { + if (state.roles.isNotEmpty) { + return ListView.builder( + padding: + const EdgeInsets.symmetric(vertical: 8, horizontal: 10), + itemCount: state.roles.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar(child: Text('${index+1}'),), + const SizedBox(width: 12,), + Flexible( + child: Text(state.roles[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Update Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: state + .roles[index].name, + name: "object_name", + decoration: + normalTextFieldStyle( + "Role name *", + "Role name "), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .roles[index].slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: state + .roles[index] + .shorthand, + validator: + FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value[ + 'object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value[ + 'shorthand']; + + parent.read().add(UpdateRbacRole( + roleId: state + .roles[ + index] + .id!, + name: name, + slug: slug, + short: + short, + createdBy: state + .roles[ + index] + .createdBy + ?.id, + updatedBy: + id)); + Navigator.pop( + context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + context.read().add( + DeleteRbacRole( + roleId: + state.roles[index].id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () { + context.read().add(GetRoles()); + }); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/role/shared_pop_up_menu.dart b/lib/screens/superadmin/role/shared_pop_up_menu.dart new file mode 100644 index 0000000..3359c56 --- /dev/null +++ b/lib/screens/superadmin/role/shared_pop_up_menu.dart @@ -0,0 +1,21 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; + +PopupMenuItem popMenuItem({String? text, int? value, IconData? icon}) { + return PopupMenuItem( + value: value, + child: Row( + children: [ + Icon( + icon, + ), + const SizedBox( + width: 10, + ), + Text( + text!, + ), + ], + ), + ); +} \ No newline at end of file diff --git a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart new file mode 100644 index 0000000..a354473 --- /dev/null +++ b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart @@ -0,0 +1,289 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:multi_dropdown/models/value_item.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart'; +import 'package:unit2/bloc/role_assignment/role_assignment_bloc.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleAssignment extends StatelessWidget { + final int id; + const RbacRoleAssignment({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final formKey = GlobalKey(); + List roles = []; + List valueItemRoles = []; + List selectedValueItemRoles = []; + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("User Roles Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Select Roles", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label.toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + parent + .read() + .add(AssignRole( + assignerId: id, + roles: rolesId, + )); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleAssignmentLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is AssignedRoleLoaded || + state is RoleAssignmentErrorState || + state is AssignedRoleDeletedState || + state is UserNotExistError || state is AssignedRoleAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////Deleted State + if (state is AssignedRoleDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Role Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedRole()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedRole()); + }); + } + } + + ////Added State + if (state is AssignedRoleAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedRole()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(LoadAssignedRole()); + }); + } + } + }, + builder: (context, state) { + final parent = context; + if (state is AssignedRoleLoaded) { + + roles = state.roles; + if (state.assignedRoles.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: ListView.builder( + padding: const EdgeInsets.symmetric( + vertical: 8, horizontal: 10), + itemCount: state.assignedRoles.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Flexible( + child: Text( + state.assignedRoles[index].role! + .name, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 1) { + confirmAlert(context, () { + context + .read() + .add(DeleteAssignRole( + roleId: state + .assignedRoles[index].id! + )); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const Divider(), + ], + ); + }), + ), + ], + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleAssignmentErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetRoles()); + }); + } + if (state is UserNotExistError) { + return const Center( + child: Text("User Not Exsit"), + ); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/superadmin/role_extend/role_extend_screen.dart b/lib/screens/superadmin/role_extend/role_extend_screen.dart new file mode 100644 index 0000000..670c1d4 --- /dev/null +++ b/lib/screens/superadmin/role_extend/role_extend_screen.dart @@ -0,0 +1,296 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleExtendScreen extends StatelessWidget { + final int id; + const RbacRoleExtendScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> rolesExtend = {}; + List roles = []; + RBAC? selectedRole; + List valueItemRoles = []; + List selectedValueItemRoles = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + elevation: 0, + backgroundColor: primary, + title: const Text("Role Extend"), + actions: [ + AddLeading(onPressed: () { + showDialog( + context: NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Extend"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle( + "Role Extend Main", "Role Extend Main"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Roles Extend", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemRoles.isNotEmpty) { + int roleId = selectedRole!.id!; + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label.toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + Navigator.of(context).pop(); + rolesExtend = {}; + parent.read().add( + AddRoleExtend( + roleId: roleId, + roleExtendsId: rolesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleExtendLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleExtendLoadedState || + state is RoleExtendAddedState || + state is RoleExtendDeletedState || + state is RoleExtendErrorState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleExtendDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Role Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetRoleExtend()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRoleExtend()); + }); + } + } + ////Added State + if (state is RoleExtendAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoleExtend()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoleExtend()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleExtendLoadedState) { + rolesExtend = {}; + roles = state.roles; + + if (state.rolesExtend.isNotEmpty) { + for (var roleExt in state.rolesExtend) { + if (!rolesExtend.keys + .contains(roleExt.roleExtendMain.name!.toLowerCase())) { + rolesExtend.addAll( + {roleExt.roleExtendMain.name!.toLowerCase(): []}); + rolesExtend[roleExt.roleExtendMain.name!.toLowerCase()]! + .add(Content( + id: roleExt.id, + name: roleExt.roleExtendChild.name!)); + } else { + rolesExtend[roleExt.roleExtendMain.name!.toLowerCase()]! + .add(Content( + id: roleExt.id, + name: roleExt.roleExtendChild.name!)); + } + } + } + + if (state.rolesExtend.isNotEmpty) { + return GroupListView( + padding: const EdgeInsets.all(0), + sectionsCount: rolesExtend.keys.toList().length, + countOfItemInSection: (int section) { + return rolesExtend.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(DeleteRoleExtend( + roleExtendId: rolesExtend.values + .toList()[index.section][index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + rolesExtend.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w500, + color: primary), + ), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: second, + title: Text( + rolesExtend.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith(color: Colors.white), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleExtendErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/role_module/role_module_scree.dart b/lib/screens/superadmin/role_module/role_module_scree.dart new file mode 100644 index 0000000..58521bf --- /dev/null +++ b/lib/screens/superadmin/role_module/role_module_scree.dart @@ -0,0 +1,289 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleModuleScreen extends StatelessWidget { + final int id; + const RbacRoleModuleScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> roleModules = {}; + List modules = []; + List roles = []; + RBAC? selectedRole; + List valueItemModules = []; + List selectedValueItemModules = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Role Modules Screen"), + actions: [ + AddLeading(onPressed: () { + showDialog( + context: NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemModules = modules.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemModules = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Modules", + padding: const EdgeInsets.all(8), + options: valueItemModules, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemModules.isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List modulesId = []; + for (var module in modules) { + selectedValueItemModules + .forEach((element) { + if (element.label.toLowerCase() == + module.name?.toLowerCase()) { + modulesId.add(module.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleModule( + assignerId: assignerId, + roleId: roleId, + moduleIds: modulesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleModuleLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleModuleLoadedState || + state is RoleModuleErrorState || + state is RoleModuleDeletedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleModuleDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Role Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetRoleModules()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRoleModules()); + }); + } + } + ////Added State + if (state is RoleModuleAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoleModules()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRoleModules()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleModuleLoadedState) { + modules = state.modules; + roles = state.roles; + roleModules = {}; + if (state.roleModules.isNotEmpty) { + for (var roleMod in state.roleModules) { + if (!roleModules.keys + .contains(roleMod.role!.name!.toLowerCase())) { + roleModules.addAll({roleMod.role!.name!.toLowerCase(): []}); + roleModules[roleMod.role!.name!.toLowerCase()]!.add( + Content(id: roleMod.id!, name: roleMod.module!.name!)); + } else { + roleModules[roleMod.role!.name!.toLowerCase()]!.add( + Content(id: roleMod.id!, name: roleMod.module!.name!)); + } + } + } + + if (state.roleModules.isNotEmpty) { + return GroupListView( + sectionsCount: roleModules.keys.toList().length, + countOfItemInSection: (int section) { + return roleModules.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(DeleteRoleModule( + roleModuleId: roleModules.values + .toList()[index.section][index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + roleModules.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: second, + title: Text( + roleModules.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith(color: Colors.white), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleModuleErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/roles_under/roles_under_screen.dart b/lib/screens/superadmin/roles_under/roles_under_screen.dart new file mode 100644 index 0000000..a085fc5 --- /dev/null +++ b/lib/screens/superadmin/roles_under/roles_under_screen.dart @@ -0,0 +1,294 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleUnderScreen extends StatelessWidget { + final int id; + const RbacRoleUnderScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> rolesUnder = {}; + List roles = []; + RBAC? selectedRole; + List valueItemRoles = []; + List selectedValueItemRoles = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Role Module"), + actions: [ + AddLeading(onPressed: () { + showDialog( + context: NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Under"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle( + "Main Role", "Main Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Roles Under", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: + const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemRoles.isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label.toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleUnder( + roleId: roleId, + roleUnderIds: rolesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleUnderLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleUnderLoadedState || + state is RoleUnderErrorState || + state is RoleUnderDeletedState || + state is RoleUnderAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleUnderDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Role Module Deleted Successfully", () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + ////Added State + if (state is RoleUnderAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleUnderLoadedState) { + rolesUnder = {}; + roles = state.roles; + + if (state.rolesUnder.isNotEmpty) { + for (var roleUnder in state.rolesUnder) { + if (!rolesUnder.keys + .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { + rolesUnder.addAll( + {roleUnder.roleUnderMain.name!.toLowerCase(): []}); + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } else { + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } + } + } + + if (state.rolesUnder.isNotEmpty) { + return GroupListView( + sectionsCount: rolesUnder.keys.toList().length, + countOfItemInSection: (int section) { + return rolesUnder.values.toList()[section].length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + trailing: IconButton( + color: Colors.grey.shade500, + icon: const Icon(Icons.delete), + onPressed: () { + context.read().add(DeleteRoleUnder( + roleUnderId: rolesUnder.values + .toList()[index.section][index.index] + .id)); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + rolesUnder.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w500, + color: primary) + ), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( +tileColor: Colors.white, + dense: true, + title: Text( + rolesUnder.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith(color: primary,fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleUnderErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/stations/stations_screen.dart b/lib/screens/superadmin/stations/stations_screen.dart new file mode 100644 index 0000000..41f8ca3 --- /dev/null +++ b/lib/screens/superadmin/stations/stations_screen.dart @@ -0,0 +1,289 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart'; +import 'package:unit2/model/rbac/rbac_station.dart'; +import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/utils/agency.dart'; +import '../../../theme-data.dart/box_shadow.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/formatters.dart'; +import '../../../utils/global.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacStationScreen extends StatelessWidget { + final int id; + const RbacStationScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final agencyFocusNode = FocusNode(); + List stations = []; + final formKey = GlobalKey(); + Agency selectedAgency; + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Station Screen"), + actions: [ + AddLeading(onPressed: () { + BuildContext parent = context; + // showDialog( + // context: context, + // builder: (BuildContext context) { + // return AlertDialog( + // title: const Text("Add New Station"), + // content: FormBuilder( + // key: formKey, + // child: Column( + // mainAxisSize: MainAxisSize.min, + // children: [ + // FormBuilderTextField( + // name: "object_name", + // decoration: normalTextFieldStyle( + // "Role name *", "Role name "), + // validator: FormBuilderValidators.required( + // errorText: "This field is required"), + // ), + // const SizedBox( + // height: 8, + // ), + // FormBuilderTextField( + // name: "slug", + // decoration: normalTextFieldStyle("Slug ", "Slug"), + // ), + // const SizedBox( + // height: 8, + // ), + // FormBuilderTextField( + // validator: FormBuilderValidators.maxLength(50, + // errorText: "Max characters only 50"), + // name: "shorthand", + // decoration: + // normalTextFieldStyle("Shorthand ", "Shorthand"), + // ), + // const SizedBox( + // height: 12, + // ), + // SizedBox( + // width: double.infinity, + // height: 50, + // child: ElevatedButton( + // style: mainBtnStyle( + // primary, Colors.transparent, second), + // onPressed: () { + // if (formKey.currentState! + // .saveAndValidate()) { + // String name = formKey + // .currentState!.value['object_name']; + // String? slug = + // formKey.currentState!.value['slug']; + // String? short = formKey + // .currentState!.value['shorthand']; + // parent.read().add(AddRbacRole( + // id: id, + // name: name, + // shorthand: short, + // slug: slug)); + // Navigator.pop(context); + // } + // }, + // child: const Text("Add"))), + // ], + // ), + // ), + // ); + // }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) {}, + builder: (context, state) { + final parent = context; + if (state is StationLoadedState) { + stations = state.stations; + if (state.stations.isNotEmpty) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: SearchField( + inputFormatters: [UpperCaseTextFormatter()], + itemHeight: 70, + focusNode: agencyFocusNode, + suggestions: state.agencies + .map((Agency agency) => + SearchFieldListItem(agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, + overflow: TextOverflow.visible, + ), + ))) + .toList(), + searchInputDecoration: + normalTextFieldStyle("Filter", "").copyWith( + prefixIcon: const Icon(Icons.filter_list), + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyFocusNode.unfocus(); + }, + )), + onSuggestionTap: (agency) { + agencyFocusNode.unfocus(); + selectedAgency = agency.item!; + parent.read().add( + FilterStation(agencyId: selectedAgency.id!)); + }, + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + emptyWidget: const Center( + child: Text("No result found..."), + )), + ), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.symmetric( + vertical: 8, horizontal: 10), + itemCount: state.stations.length, + itemBuilder: (BuildContext context, int index) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Flexible( + child: Text( + state.stations[index] + .stationName!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + ], + )), + ], + ), + ), + const SizedBox( + height: 3, + ) + ], + ); + }), + ), + ], + ); + } else { + return Column( + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: SearchField( + + inputFormatters: [UpperCaseTextFormatter()], + itemHeight: 70, + focusNode: agencyFocusNode, + suggestions: state.agencies + .map((Agency agency) => + SearchFieldListItem(agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, + overflow: TextOverflow.visible, + ), + ))) + .toList(), + searchInputDecoration: + normalTextFieldStyle("Filter", "").copyWith( + prefixIcon: const Icon(Icons.filter_list), + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyFocusNode.unfocus(); + }, + )), + onSuggestionTap: (agency) { + agencyFocusNode.unfocus(); + selectedAgency = agency.item!; + parent.read().add( + FilterStation(agencyId: selectedAgency.id!)); + }, + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + emptyWidget: const Center( + child: Text("No result found..."), + )), + ), + const SizedBox( + height: 20, + ), + const EmptyData( + message: + "No Station available. Please click + to add."), + ], + ); + } + } + if (state is StationErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetRoles()); + }); + } + if (state is StationLoadingState) { + return CircularProgressIndicator(); + } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index 2194b21..07539a4 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -7,6 +7,7 @@ import 'package:intl/intl.dart'; import 'package:qr_flutter/qr_flutter.dart'; import 'package:signature/signature.dart'; import 'package:unit2/model/login_data/user_info/user_data.dart'; +import 'package:unit2/screens/unit2/basic-info/components/qr_image.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/text_container.dart'; @@ -115,8 +116,9 @@ class BuildInformation extends StatelessWidget { 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? middlename = userData.employeeInfo == null + ? '' + : userData.employeeInfo!.profile?.middleName?.toUpperCase(); final String sex = userData.employeeInfo!.profile!.sex!.toUpperCase(); final DateTime? bday = userData.employeeInfo!.profile!.birthdate; final uuid = userData.employeeInfo!.uuid; @@ -129,7 +131,7 @@ class BuildInformation extends StatelessWidget { height: 25, ), Text( - "$firstName ${middlename??''} $lastname", + "$firstName ${middlename ?? ''} $lastname", textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -141,27 +143,37 @@ class BuildInformation extends StatelessWidget { ), Text( "${dteFormat2.format(bday!)} | $sex", - style: Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 18), + style: + Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 18), ), const SizedBox( height: 15, ), - QrImage( - data: uuid!, - size: blockSizeVertical * 30, + GestureDetector( + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return QRFullScreenImage(uuid: uuid); + })); + }, + child: QrImage( + data: uuid!, + size: blockSizeVertical * 24, + ), ), const SizedBox( height: 25, ), SizedBox( width: screenWidth * .60, - height: blockSizeVertical * 6, + height: blockSizeVertical * 7, child: SizedBox( child: ElevatedButton.icon( style: mainBtnStyle(third, Colors.transparent, Colors.white54), onPressed: () { - Navigator.push(context, MaterialPageRoute(builder: (BuildContext context){ + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { return const SignaturePad(); })); }, diff --git a/lib/screens/unit2/basic-info/components/qr_image.dart b/lib/screens/unit2/basic-info/components/qr_image.dart new file mode 100644 index 0000000..6cd2d39 --- /dev/null +++ b/lib/screens/unit2/basic-info/components/qr_image.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/src/widgets/framework.dart'; +import 'package:flutter/src/widgets/placeholder.dart'; +import 'package:qr_flutter/qr_flutter.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/utils/global.dart'; + +class QRFullScreenImage extends StatelessWidget { + final String uuid; + const QRFullScreenImage({super.key, required this.uuid}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary,title: const Text("Profile QR Code"),), + body: Center( + child: QrImage( + data: uuid, + size: blockSizeVertical * 50 + ), + ),); + } +} \ No newline at end of file diff --git a/lib/screens/unit2/homepage.dart/components/dashboard.dart b/lib/screens/unit2/homepage.dart/components/dashboard.dart deleted file mode 100644 index 07e0d11..0000000 --- a/lib/screens/unit2/homepage.dart/components/dashboard.dart +++ /dev/null @@ -1,283 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:fluttericon/font_awesome5_icons.dart'; -import 'package:unit2/screens/docsms/index.dart'; -import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; -import 'package:unit2/theme-data.dart/colors.dart'; -import 'package:unit2/utils/global.dart'; -import 'package:unit2/utils/global_context.dart'; -import 'package:unit2/utils/qr_scanner.dart'; -import '../../../../bloc/docsms/docsms_bloc.dart'; - -class DashBoard extends StatelessWidget { - final List roles; - final int userId; - const DashBoard({super.key, required this.roles, required this.userId}); - @override - Widget build(BuildContext context) { - List finishRoles = []; - return Container( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), - height: MediaQuery.of(context).size.height, - ////listview builder - child: ListView.builder( - scrollDirection: Axis.vertical, - shrinkWrap: true, - itemCount: roles.length, - itemBuilder: (BuildContext context, int index) { - //// gridview.count - return roles[index].roles.isNotEmpty - ? SizedBox( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - roles[index].name.toUpperCase(), - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith(fontSize: 12), - ), - const SizedBox( - height: 8, - ), - GridView.count( - shrinkWrap: true, - crossAxisCount: 4, - crossAxisSpacing: 8, - mainAxisSpacing: 10, - physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.symmetric( - vertical: 5, horizontal: 5), - children: roles[index].roles.map((role) { - if (role.role.name!.toLowerCase() == - 'qr code scanner' && - !finishRoles.contains("security")) { - print("1 true"); - finishRoles.add('scanner'); - for (var element in role.role.modules!) { - if (element!.name!.toLowerCase() == 'unit2') { - for (var element in element.objects!) { - if (element!.id == 9 && - element.operations! - .contains("read")) { - return CardLabel( - ontap: () { - PassCheckArguments - passCheckArguments = - PassCheckArguments( - roleId: role.role.id!, - userId: userId); - Navigator.pushNamed( - context, '/pass-check', - arguments: passCheckArguments); - }, - icon: role.icon, - title: "Pass Check", - ); - } - } - } - } - return Container(); - } else if (role.role.name!.toLowerCase() == - 'security guard' && - !finishRoles.contains('scanner')) { - print("2 true"); - finishRoles.add('security'); - for (var element in role.role.modules!) { - if (element!.name!.toLowerCase() == 'unit2') { - for (var element in element.objects!) { - if (element!.id == 9 && - element.operations! - .contains("read")) { - return CardLabel( - ontap: () {}, - icon: role.icon, - title: "Pass Check", - ); - } - } - } - } - return Container( - color: Colors.red, - ); - } else if (role.role.name!.toLowerCase() == - 'field surveyor') { - print("3 true"); - for (var element in role.role.modules!) { - if (element!.name!.toLowerCase() == 'rpass') { - for (var element in element.objects!) { - if (element!.id == 11 && - element.operations! - .contains("read")) { - return CardLabel( - ontap: () { - Navigator.pushNamed( - context, '/passo-home'); - }, - icon: role.icon, - title: "Field Surveyor", - ); - } - } - } - } - return Container(); - } else if (role.role.name!.toLowerCase() == - 'process server') { - print("4 true"); - for (var element in role.role.modules!) { - if (element!.name!.toLowerCase() == - 'document management') { - for (var element in element.objects!) { - if (element!.id == 3 && - element.operations! - .contains("read")) { - return CardLabel( - ontap: () async { - String? qrBarcode = - await qrScanner(); - if (qrBarcode != null) { - Navigator.push( - NavigationService.navigatorKey - .currentContext!, - MaterialPageRoute(builder: - (BuildContext context) { - return BlocProvider( - create: (context) => - DocsmsBloc() - ..add(LoadDocument( - documentId: - qrBarcode)), - child: - const AutoReceiveDocument(), - ); - })); - } - }, - icon: role.icon, - title: "Process Server", - ); - } - } - } - } - return Container(); - } else if (role.role.name!.toLowerCase() == - 'establishment point-person' && - !finishRoles.contains('superadmin')) { - finishRoles.add('establishment point-person'); - for (var element in role.role.modules!) { - print("5 true"); - if (element!.name!.toLowerCase() == 'unit2') { - for (var element in element.objects!) { - if (element!.id == 7 && - element.operations! - .contains("upload")) { - return CardLabel( - ontap: () {}, - icon: FontAwesome5.building, - title: "Establishment", - ); - } - } - } - } - return Container(); - } else if (role.role.name!.toLowerCase() == - 'establishment point-person' && - !finishRoles.contains('superadmin')) { - finishRoles.add('establishment point-person'); - for (var element in role.role.modules!) { - if (element!.name!.toLowerCase() == 'unit2') { - for (var element in element.objects!) { - if (element!.id == 7 && - element.operations! - .contains("upload")) { - return CardLabel( - ontap: () {}, - icon: FontAwesome5.building, - title: "Establishment", - ); - } - } - } - } - return Container(); - } else { - return Wrap(); - } - }).toList()), - const SizedBox( - height: 8, - ) - ], - ), - ) - : Container(); - }), - ); - } -} - -class PassCheckArguments { - final int roleId; - final int userId; - const PassCheckArguments({required this.roleId, required this.userId}); -} - -// ignore: must_be_immutable -class CardLabel extends StatelessWidget { - final String title; - final IconData icon; - final Function()? ontap; - const CardLabel( - {super.key, - required this.icon, - required this.title, - required this.ontap}); - - @override - Widget build(BuildContext context) { - return GestureDetector( - onTap: ontap, - child: Container( - padding: const EdgeInsetsDirectional.fromSTEB(8, 5, 8, 13), - alignment: Alignment.center, - decoration: const BoxDecoration( - color: Colors.white, - boxShadow: [ - BoxShadow(color: Colors.black12, spreadRadius: 2, blurRadius: 3) - ], - borderRadius: BorderRadius.all(Radius.circular(8))), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: Icon( - icon, - size: 20, - weight: 100, - grade: 100, - color: second, - ), - ), - const SizedBox( - height: 5, - ), - Text( - title, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.labelLarge!.copyWith( - fontSize: blockSizeVertical * 1.2, - fontWeight: FontWeight.bold), - ), - ]), - ), - ); - } -} diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart new file mode 100644 index 0000000..6fdb62b --- /dev/null +++ b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard.dart @@ -0,0 +1,588 @@ +import 'package:auto_size_text/auto_size_text.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart'; +import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import './shared_card_label.dart'; + +class DashBoard extends StatefulWidget { + final List cards; + final int userId; + const DashBoard({super.key, required this.cards, required this.userId}); + + @override + State createState() => _DashBoardState(); +} + +List finishRoles = []; +List unit2Cards = []; +List superadminCards = []; +List rpassCards = []; +List docSmsCards = []; +List tempSuperAdminCards = []; +List tempUnit2Cards = []; + +class _DashBoardState extends State { + @override + Widget build(BuildContext context) { + setState(() { + finishRoles.clear(); + unit2Cards.clear(); + superadminCards.clear(); + rpassCards.clear(); + docSmsCards.clear(); + tempSuperAdminCards.clear(); + }); + widget.cards.forEach((e) { + if (e.moduleName == "unit2") { + if (!finishRoles.contains(e.object.name)) { + unit2Cards.add(e); + } + finishRoles.add(e.object.name!); + } + if (e.moduleName == 'superadmin') { + superadminCards.add(e); + } + if (e.moduleName == 'rpass') { + rpassCards.add(e); + } + if (e.moduleName == 'document management') { + docSmsCards.add(e); + } + }); + + if (superadminCards.length > 3) { + tempSuperAdminCards = superadminCards.sublist(0, 4); + } + if (unit2Cards.length > 3) { + tempUnit2Cards = unit2Cards.sublist(0, 4); + } + + return Container( + padding: + const EdgeInsetsDirectional.symmetric(vertical: 24, horizontal: 24), + child: ListView( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ////unit2 module operations + Container( + child: unit2Cards.isEmpty + ? const SizedBox() + : Text( + "Unit2 module operations", + style: Theme.of(context) + .textTheme + .displaySmall! + .copyWith( + fontSize: 16, + color: primary, + fontWeight: FontWeight.w300), + ), + ), + SizedBox( + height: unit2Cards.isEmpty ? 0 : 8, + ), + Container( + child: unit2Cards.isEmpty + ? const SizedBox() + : GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric( + vertical: 5, horizontal: 5), + children: unit2Cards.length > 3 + ? tempUnit2Cards.map(( + e, + ) { + int index = tempUnit2Cards.indexOf(e); + //// if unit2 cards is less then 3 + return Container( + child: index == 3 + ? CardLabel( + icon: FontAwesome5 + .chevron_circle_right, + title: "See More", + ontap: () { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Unit2 Admin Module Operations", + textAlign: + TextAlign.center, + ), + content: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + SizedBox( + height: 200, + width: double + .maxFinite, + child: + GridView.count( + shrinkWrap: + true, + crossAxisCount: + 3, + crossAxisSpacing: + 8, + mainAxisSpacing: + 10, + physics: + const BouncingScrollPhysics(), + padding: const EdgeInsets + .symmetric( + vertical: + 5, + horizontal: + 5), + children: + unit2Cards + .map(( + e, + ) { + int index = + unit2Cards + .indexOf(e); + //// if unit2 cards is less then 3 + return AnimationConfiguration + .staggeredGrid( + position: + index, + columnCount: + 3, + child: + ScaleAnimation( + child: + FadeInAnimation( + child: Container( + child: (e.roleName == 'superadmin' || e.roleName == 'qr code scanner' || e.roleName == 'security guard' || e.roleName == 'establishment point-person' || e.roleName == 'registration in-charge') && e.moduleName == 'unit2' + ? CardLabel( + icon: iconGenerator(name: e.object.name!), + title: e.object.name!.toLowerCase() == 'role based access control' + ? "RBAC" + : e.object.name!.toLowerCase() == "person basic information" + ? "Basic Info" + : e.object.name!, + ontap: () { + if (e.object.name!.toLowerCase() == 'pass check') { + PassCheckArguments passCheckArguments = PassCheckArguments(roleId: 10, userId: widget.userId); + Navigator.pushNamed(context, '/pass-check', arguments: passCheckArguments); + } + if (e.object.name!.toLowerCase() == 'role based access control') { + Navigator.pushNamed(context, '/rbac'); + } + }) + : Container( + color: Colors.black, + )), + ), + ), + ); + }).toList()), + ), + ], + ), + ); + }); + }) + : (e.roleName == 'superadmin' || + e.roleName == + 'qr code scanner' || + e.roleName == + 'security guard' || + e.roleName == + 'establishment point-person' || + e.roleName == + 'registration in-charge') && + e.moduleName == 'unit2' + ? CardLabel( + icon: iconGenerator( + name: e.object.name!), + title: e.object.name! + .toLowerCase() == + 'role based access control' + ? "RBAC" + : e.object.name! + .toLowerCase() == + "person basic information" + ? "Basic Info" + : e.object.name!, + ontap: () { + if (e.object.name! + .toLowerCase() == + 'pass check') { + PassCheckArguments + passCheckArguments = + PassCheckArguments( + roleId: 10, + userId: + widget.userId); + Navigator.pushNamed( + context, '/pass-check', + arguments: + passCheckArguments); + } + if (e.object.name! + .toLowerCase() == + 'role based access control') { + Navigator.pushNamed( + context, '/rbac'); + } + }) + : Container( + color: Colors.black, + )); + }).toList() + : unit2Cards.map(( + e, + ) { + ////if unit2 cards is greater than 3 + return Container( + child: (e.roleName == 'superadmin' || + e.roleName == + 'qr code scanner' || + e.roleName == + 'security guard' || + e.roleName == + 'establishment point-person' || + e.roleName == + 'registration in-charge') && + e.moduleName == 'unit2' + ? CardLabel( + icon: iconGenerator( + name: e.object.name!), + title: e.object.name! + .toLowerCase() == + 'role based access control' + ? "RBAC" + : e.object.name! + .toLowerCase() == + "person basic information" + ? "Basic Info" + : e.object.name!, + ontap: () { + if (e.object.name! + .toLowerCase() == + 'pass check') { + PassCheckArguments + passCheckArguments = + PassCheckArguments( + roleId: 10, + userId: widget.userId); + Navigator.pushNamed( + context, '/pass-check', + arguments: + passCheckArguments); + } + if (e.object.name! + .toLowerCase() == + 'role based access control') { + Navigator.pushNamed( + context, '/rbac'); + } + }) + : Container( + color: Colors.black, + )); + }).toList(), + ), + ), + SizedBox( + height: unit2Cards.isEmpty ? 0 : 24, + ), + Container( + child: superadminCards.isEmpty + ? const SizedBox() + : Text( + "Superadmin module operations", + style: Theme.of(context) + .textTheme + .displaySmall! + .copyWith( + fontSize: 16, + color: primary, + fontWeight: FontWeight.w300), + ), + ), + SizedBox( + height: superadminCards.isEmpty ? 0 : 8, + ), + Container( + child: superadminCards.isEmpty + ? const SizedBox() + : GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric( + vertical: 5, horizontal: 5), + children: superadminCards.length > 3 + //// in superadmincards lenght is greaterthan 3 + ? tempSuperAdminCards.map((e) { + int index = tempSuperAdminCards.indexOf(e); + return Container( + child: index == 3 + ? CardLabel( + icon: FontAwesome5 + .chevron_circle_right, + title: "See More", + ontap: () { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Super Admin Module Operations", + textAlign: + TextAlign.center, + ), + content: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + SizedBox( + height: 480, + width: double + .maxFinite, + child: GridView + .count( + shrinkWrap: + true, + crossAxisCount: + 3, + crossAxisSpacing: + 8, + mainAxisSpacing: + 10, + physics: + const BouncingScrollPhysics(), + padding: const EdgeInsets + .symmetric( + vertical: 5, + horizontal: + 5), + children: + superadminCards + .map( + (e) { + int index = + superadminCards + .indexOf( + e); + return SuperAdminMenu( + id: widget + .userId, + columnCount: + 3, + index: + index, + object: e, + ); + }).toList(), + ), + ), + ], + ), + ); + }); + }) + : SuperAdminMenu( + id: widget.userId, + object: e, + index: index, + columnCount: 3, + )); + }).toList() + //// in superadmincards lenght is lessthan 3 + : superadminCards.map((e) { + int index = tempSuperAdminCards.indexOf(e); + return Container( + child: index == 3 + ? CardLabel( + icon: FontAwesome5 + .chevron_circle_right, + title: "See More", + ontap: () { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Super Admin Module Operations", + textAlign: + TextAlign.center, + ), + content: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + SizedBox( + height: 480, + width: double + .maxFinite, + child: GridView + .count( + shrinkWrap: + true, + crossAxisCount: + 3, + crossAxisSpacing: + 8, + mainAxisSpacing: + 10, + physics: + const BouncingScrollPhysics(), + padding: const EdgeInsets + .symmetric( + vertical: 5, + horizontal: + 5), + children: + superadminCards + .map( + (e) { + return SuperAdminMenu( + id: widget + .userId, + columnCount: + 4, + index: + index, + object: e, + ); + }).toList(), + ), + ), + ], + ), + ); + }); + }) + : SuperAdminMenu( + id: widget.userId, + object: e, + index: index, + columnCount: 4, + )); + }).toList())), + const SizedBox( + height: 24, + ), + Container( + child: rpassCards.isEmpty + ? const SizedBox() + : Text( + "RPAss module operations", + style: Theme.of(context) + .textTheme + .displaySmall! + .copyWith( + fontSize: 16, + color: primary, + fontWeight: FontWeight.w300), + ), + ), + SizedBox( + height: rpassCards.isEmpty ? 0 : 8, + ), + Container( + child: rpassCards.isEmpty + ? const SizedBox() + : GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric( + vertical: 5, horizontal: 5), + children: rpassCards.map((e) { + return Container( + child: (e.roleName == 'field surveyor') && + e.moduleName == 'rpass' + ? CardLabel( + icon: iconGenerator(name: e.object.name!), + title: e.object.name == 'Real Property' + ? "Field Surveyor" + : e.object.name!, + ontap: () { + Navigator.pushNamed( + context, '/passo-home'); + }) + : Container( + color: Colors.black, + )); + }).toList(), + ), + ), + const SizedBox( + height: 24, + ), + Container( + child: docSmsCards.isEmpty + ? const SizedBox() + : Text( + "DocSMS module operations", + style: Theme.of(context) + .textTheme + .displaySmall! + .copyWith( + fontSize: 16, + color: primary, + fontWeight: FontWeight.w300), + ), + ), + const SizedBox( + height: 8, + ), + GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 5), + children: docSmsCards.map((e) { + return Container( + child: (e.roleName == 'process server') && + e.moduleName == 'document management' + ? CardLabel( + icon: iconGenerator(name: e.object.name!), + title: e.object.name == "Document" + ? "Process Server" + : e.object.name!, + ontap: () {}) + : Container( + color: Colors.black, + )); + }).toList(), + ) + ], + ) + ], + ), + ); + } +} + +class PassCheckArguments { + final int roleId; + final int userId; + const PassCheckArguments({required this.roleId, required this.userId}); +} 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 new file mode 100644 index 0000000..ff8e816 --- /dev/null +++ b/lib/screens/unit2/homepage.dart/components/dashboard/dashboard_icon_generator.dart @@ -0,0 +1,66 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:fluttericon/font_awesome_icons.dart'; +import 'package:fluttericon/maki_icons.dart'; +import 'package:fluttericon/modern_pictograms_icons.dart'; +import 'package:fluttericon/octicons_icons.dart'; +import 'package:fluttericon/web_symbols_icons.dart'; + +IconData? iconGenerator({required String name}) { + if (name.toLowerCase() == 'agency') { + return FontAwesome5.building; + } else if (name.toLowerCase() == 'assignable role') { + return FontAwesome5.user_plus; + } else if (name.toLowerCase() == 'role') { + return FontAwesome5.user; + } else if (name.toLowerCase() == 'operation') { + return FontAwesome.export_alt; + } else if (name.toLowerCase() == 'module') { + return Icons.view_module; + } else if (name.toLowerCase() == 'area') { + return FontAwesome5.map_marked; + } else if (name.toLowerCase() == 'object') { + return FontAwesome.box; + } else if (name.toLowerCase() == 'permission') { + return FontAwesome5.door_open; + } else if (name.toLowerCase() == 'station') { + return ModernPictograms.home; + } else if (name.toLowerCase() == 'purok') { + return WebSymbols.list_numbered; + } else if (name.toLowerCase() == 'barangay') { + return Maki.industrial_building; + } else if (name.toLowerCase() == 'role module') { + return FontAwesome5.person_booth; + } else if (name.toLowerCase() == 'module object') { + return FontAwesome5.th_list; + } else if (name.toLowerCase() == 'roles extend') { + return FontAwesome5.external_link_square_alt; + } else if (name.toLowerCase() == 'real property') { + return FontAwesome5.eye; + } else if (name.toLowerCase() == 'document') { + return FontAwesome5.newspaper; + } else if (name.toLowerCase() == 'role based access control') { + return FontAwesome5.tasks; + } else if (name.toLowerCase() == 'pass check') { + return FontAwesome5.qrcode; + } else if (name.toLowerCase() == 'list of persons') { + return FontAwesome5.users; + } else if (name.toLowerCase() == 'person basic information') { + return FontAwesome5.info_circle; + }else if(name.toLowerCase() == "role member"){ + return FontAwesome5.users_cog; + } + + + + + + else if (name.toLowerCase() == 'security location') { + return FontAwesome5.location_arrow; + } + + else { + return null; + } +} diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/shared_card_label.dart b/lib/screens/unit2/homepage.dart/components/dashboard/shared_card_label.dart new file mode 100644 index 0000000..9dd8c3d --- /dev/null +++ b/lib/screens/unit2/homepage.dart/components/dashboard/shared_card_label.dart @@ -0,0 +1,61 @@ +import 'package:auto_size_text/auto_size_text.dart'; +import 'package:flutter/material.dart'; + +import '../../../../../theme-data.dart/colors.dart'; +import '../../../../../utils/global.dart'; + +class CardLabel extends StatelessWidget { + final String title; + final IconData? icon; + final Function()? ontap; + const CardLabel( + {super.key, + required this.icon, + required this.title, + required this.ontap}); + + @override + Widget build(BuildContext context) { + return InkWell( + splashColor: second, + onTap: ontap, + child: Container( + padding: const EdgeInsetsDirectional.fromSTEB(8, 5, 8, 13), + alignment: Alignment.center, + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [ + BoxShadow(color: Colors.black12, spreadRadius: 1, blurRadius: 2) + ], + borderRadius: BorderRadius.all(Radius.circular(8))), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Flexible( + flex: 1, + child: Icon( + icon, + size: 20, + weight: 100, + grade: 100, + color: second, + ), + ), + const Expanded(child: SizedBox()), + Flexible( + flex: 2, + child: AutoSizeText( + minFontSize: 10, + title, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.labelLarge!.copyWith( + fontSize: blockSizeVertical * 1.2, + fontWeight: FontWeight.bold), + ), + ), + ]), + ), + ); + } +} \ 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 new file mode 100644 index 0000000..23d42ca --- /dev/null +++ b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart @@ -0,0 +1,317 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +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/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'; +import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart'; +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/module/module_screen.dart'; +import 'package:unit2/screens/superadmin/object/object_screen.dart'; +import 'package:unit2/screens/superadmin/operation/operation_screen.dart'; +import 'package:unit2/screens/superadmin/permission/permission_screen.dart'; +import 'package:unit2/screens/superadmin/role/role_screen.dart'; +import 'package:unit2/screens/superadmin/role_assignment.dart/role_assignment_screen.dart'; +import 'package:unit2/screens/superadmin/role_extend/role_extend_screen.dart'; +import 'package:unit2/screens/superadmin/roles_under/roles_under_screen.dart'; +import 'package:unit2/screens/superadmin/stations/stations_screen.dart'; +import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import '../../../../superadmin/agency.dart/agency_screen.dart'; +import '../../../../superadmin/module_objects/module_objects_screen.dart'; +import '../../../../superadmin/role_module/role_module_scree.dart'; +import './shared_card_label.dart'; +import 'dashboard_icon_generator.dart'; + +class SuperAdminMenu extends StatelessWidget { + final int id; + final DisplayCard object; + final int index; + final int columnCount; + const SuperAdminMenu( + {super.key, + required this.id, + required this.object, + required this.index, + required this.columnCount}); + + @override + Widget build(BuildContext context) { + final roleAssignmentKey = GlobalKey(); + return AnimationConfiguration.staggeredGrid( + position: index, + columnCount: columnCount, + child: ScaleAnimation( + child: FadeInAnimation( + child: Container( + child: (object.roleName == 'superadmin' || + object.object.name == 'Agency' || + object.object.name == 'Assignable Role' || + object.object.name == 'Role' || + object.object.name == 'Module' || + object.object.name == 'Object' || + object.object.name == 'Operation' || + object.object.name == 'Permission' || + object.object.name == 'Area' || + object.object.name == 'Station' || + object.object.name == 'Purok' || + object.object.name == 'Barangay' || + object.object.name == 'Role Module' || + object.object.name == 'Module Object' || + object.object.name == 'Roles Extend' || + object.object.name == "Role Member") && + object.moduleName == 'superadmin' + ? CardLabel( + icon: iconGenerator(name: object.object.name!), + title: + object.object.name!.toLowerCase() == 'assignable role' + ? "Role Assignment" + : object.object.name!, + ontap: () { + if (object.object.name == 'Role') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => RoleBloc()..add(GetRoles()), + child: RbacRoleScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Operation') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + OperationBloc()..add(GetOperations()), + child: RbacOperationScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Module') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + ModuleBloc()..add(GetModule()), + child: RbacModuleScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Object') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + ObjectBloc()..add(GetObjects()), + child: RbacObjectScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Permission') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + PermissionBloc()..add(GetPermissions()), + child: RbacPermissionScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Module Object') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + ModuleObjectsBloc()..add(GetModuleObjects()), + child: RbacModuleObjectsScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Agency') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + AgencyBloc()..add(GetAgencies()), + child: RbacAgencyScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Role Module') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + RoleModuleBloc()..add(GetRoleModules()), + child: RbacRoleModuleScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Assignable Role') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + RolesUnderBloc()..add(GetRolesUnder()), + child: RbacRoleUnderScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Roles Extend') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + RoleExtendBloc()..add(GetRoleExtend()), + child: RbacRoleExtendScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Station') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => StationBloc() + ..add(const GetStations(agencyId: 1)), + child: RbacStationScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Station') { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => StationBloc() + ..add(const GetStations(agencyId: 1)), + child: RbacStationScreen( + id: id, + ), + ); + })); + } + if (object.object.name == 'Role Member') { + 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( + key: roleAssignmentKey, + 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 (roleAssignmentKey + .currentState! + .saveAndValidate()) { + + String fname = + roleAssignmentKey + .currentState! + .value['firstname']; + String lname = + roleAssignmentKey + .currentState! + .value['lastname']; + Navigator.push(context, + MaterialPageRoute(builder: + (BuildContext + context) { + return BlocProvider( + create: (context) => + RoleAssignmentBloc() + ..add(GetAssignedRoles( + firstname: + fname, + lastname: + lname),),child:RbacRoleAssignment(id:id) ,); + })); + } + }, + style: mainBtnStyle(primary, + Colors.transparent, second), + child: const Text("Submit"), + ), + ) + ], + )), + ); + }); + } + }) + : Container( + color: Colors.black, + )), + ), + ), + ); + } +} diff --git a/lib/screens/unit2/homepage.dart/module-screen.dart b/lib/screens/unit2/homepage.dart/module-screen.dart index e8a9585..a41389a 100644 --- a/lib/screens/unit2/homepage.dart/module-screen.dart +++ b/lib/screens/unit2/homepage.dart/module-screen.dart @@ -1,14 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_zoom_drawer/flutter_zoom_drawer.dart'; -import 'package:fluttericon/font_awesome5_icons.dart'; -import 'package:fluttericon/font_awesome_icons.dart'; -import 'package:fluttericon/rpg_awesome_icons.dart'; -import 'package:fluttericon/typicons_icons.dart'; -import 'package:unit2/screens/unit2/homepage.dart/components/dashboard.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/dashboard.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/utils/text_container.dart'; import '../../../bloc/user/user_bloc.dart'; +import '../../../model/login_data/user_info/module.dart'; import '../../../model/login_data/user_info/role.dart'; import 'components/empty_module.dart'; @@ -20,14 +17,17 @@ class MainScreen extends StatefulWidget { } class _MainScreenState extends State { - List roles = [ - Module(name: 'UniT2 module operations', roles: []), - Module(name: 'DocSms module operations', roles: []), - Module(name: "RPAss module operations",roles:[] ) - ]; + List roles = []; + List cards = []; int? userId; @override Widget build(BuildContext context) { + setState(() { + cards.clear(); + cards=[]; + roles.clear(); + roles = []; + }); return WillPopScope( onWillPop: () async { return Future.value(true); @@ -35,85 +35,63 @@ class _MainScreenState extends State { child: BlocBuilder(builder: (context, state) { if (state is UserLoggedIn) { userId = state.userData!.user!.login!.user!.id; - for (var element in roles) { - element.roles.clear(); - } for (var role in state.userData!.user!.login!.user!.roles!) { Role? getRole = role; - for (var module in role!.modules!) { - if (module!.name!.toLowerCase() == 'unit2') { - IconData iconData = iconGenerator(getRole!.name!); - Roles newRole = Roles(role: getRole, icon: iconData); - roles[0].roles.add(newRole); - } - if (module.name!.toLowerCase() == 'document management') { - IconData iconData = iconGenerator(getRole!.name!); - Roles newRole = Roles(role: getRole, icon: iconData); - roles[1].roles.add(newRole); - } if (module.name!.toLowerCase() == 'rpass') { - IconData iconData = iconGenerator(getRole!.name!); - Roles newRole = Roles(role: getRole, icon: iconData); - roles[2].roles.add(newRole); + roles.add(getRole!); + } + for (var role in roles) { + for (var module in role.modules!) { + for (var object in module!.objects!) { + DisplayCard newCard = DisplayCard( + moduleName: module.name!.toLowerCase(), + object: object!, + roleName: role.name!.toLowerCase()); + cards.add(newCard); } } } + 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, - ), - ), + 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( - userId: userId!, - roles: roles, - ) - : const NoModule(), + ? DashBoard( + userId: userId!, + cards: cards, + ) + : const NoModule(), ); } return Container(); }), ); } +} - IconData iconGenerator(String roleName) { - IconData? iconData; - switch (roleName.toLowerCase()) { - case 'qr code scanner': - iconData = FontAwesome.qrcode; - break; - case 'security guard': - iconData = FontAwesome5.user_shield; - break; - case 'establishment point-person': - iconData = FontAwesome.building_filled; - break; - case 'registration in-charge': - iconData = FontAwesome.user_plus; - break; - case 'process server': - iconData = Typicons.doc_text; - break; - case 'field surveyor': - iconData = RpgAwesome.telescope; - } - return iconData!; - } +class DisplayCard { + final String roleName; + final String moduleName; + final ModuleObject object; + const DisplayCard( + {required this.moduleName, required this.object, required this.roleName}); } class Module { @@ -123,7 +101,7 @@ class Module { } class Roles { - final IconData icon; + final IconData? icon; final Role role; Roles({required this.role, required this.icon}); } diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index c0a0c03..ecd188a 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -1,4 +1,3 @@ -import 'package:barcode_scan2/barcode_scan2.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; @@ -66,7 +65,9 @@ class _UniT2LoginState extends State { gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, ); - Navigator.pushReplacementNamed(context, '/module-screen'); + Navigator.pushReplacementNamed( + NavigationService.navigatorKey.currentContext!, + '/module-screen'); }, () => Navigator.pushReplacementNamed( context, '/module-screen'), @@ -85,8 +86,10 @@ class _UniT2LoginState extends State { Navigator.of(context).pop(); }); } - }if(state is UuidLoaded){ - Navigator.push(context, MaterialPageRoute(builder: (BuildContext context){ + } + if (state is UuidLoaded) { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { return const QRLogin(); })); } @@ -367,15 +370,18 @@ class _UniT2LoginState extends State { if (state is SplashScreen) { return const UniTSplashScreen(); } - if(state is LoginErrorState){ - return SomethingWentWrong(message: state.message, onpressed: () { + if (state is LoginErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { BlocProvider.of( NavigationService.navigatorKey.currentContext!) .add(GetApkVersion()); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); - },); + }, + ); } return Container(); }), diff --git a/lib/screens/unit2/roles/qr_code_scanner.dart/settings_screen.dart b/lib/screens/unit2/roles/qr_code_scanner.dart/settings_screen.dart index 19df2b5..c150df6 100644 --- a/lib/screens/unit2/roles/qr_code_scanner.dart/settings_screen.dart +++ b/lib/screens/unit2/roles/qr_code_scanner.dart/settings_screen.dart @@ -9,7 +9,7 @@ import 'package:fluttericon/modern_pictograms_icons.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:unit2/bloc/role/pass_check/pass_check_bloc.dart'; import 'package:unit2/bloc/user/user_bloc.dart'; -import 'package:unit2/screens/unit2/homepage.dart/components/dashboard.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/dashboard.dart'; import 'package:unit2/screens/unit2/roles/qr_code_scanner.dart/components/custom_switch.dart'; import 'package:unit2/screens/unit2/roles/qr_code_scanner.dart/scan.dart'; import 'package:unit2/utils/text_container.dart'; @@ -40,593 +40,591 @@ class _QRCodeScannerSettingsState extends State { final _formKey = GlobalKey(); @override Widget build(BuildContext context) { - return SafeArea( - child: Scaffold( - appBar: AppBar( - title: const Text(qrScannerTitle), - centerTitle: true, - backgroundColor: primary, + return Scaffold( + appBar: AppBar( + title: const Text(qrScannerTitle), + centerTitle: true, + backgroundColor: primary, + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + indicatorWidget: const SpinKitFadingCircle( + color: Colors.white, ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - indicatorWidget: const SpinKitFadingCircle( - color: Colors.white, - ), - backgroundColor: Colors.black87, - child: BlocBuilder( - builder: (context, state) { - if (state is UserLoggedIn) { - token = state.userData!.user!.login!.token; - checkerId = state.userData!.user!.login!.user!.id; - return BlocConsumer( - listener: (context, state) { - if (state is PassCheckLoadingState) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AssignAreaLoaded || - state is PassCheckErrorState) { - final progress = ProgressHUD.of(context); - progress!.dismiss(); - } - }, - builder: (context, state) { - if (state is AssignAreaLoaded) { - return Container( - height: screenHeight * .90, - padding: const EdgeInsets.symmetric( - horizontal: 42, vertical: 10), - child: FormBuilder( - key: _formKey, - child: Column( - children: [ - Flexible( - child: ListView( - children: [ - const SizedBox( - height: 32, - ), - SvgPicture.asset( - 'assets/svgs/switch.svg', - height: blockSizeVertical * 14, - allowDrawingOutsideViewBox: true, - ), - ListTile( - title: Text( - setQRScannerSettings, - style: Theme.of(context) - .textTheme - .titleLarge! - .copyWith(color: third), - textAlign: TextAlign.center, - ), - ), - Text(includeOtherInputs, - style: Theme.of(context) - .textTheme - .titleMedium), - Text( - includeOtherInputsSubTitle, + backgroundColor: Colors.black87, + child: BlocBuilder( + builder: (context, state) { + if (state is UserLoggedIn) { + token = state.userData!.user!.login!.token; + checkerId = state.userData!.user!.login!.user!.id; + return BlocConsumer( + listener: (context, state) { + if (state is PassCheckLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is AssignAreaLoaded || + state is PassCheckErrorState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + }, + builder: (context, state) { + if (state is AssignAreaLoaded) { + return Container( + height: screenHeight * .90, + padding: const EdgeInsets.symmetric( + horizontal: 42, vertical: 10), + child: FormBuilder( + key: _formKey, + child: Column( + children: [ + Flexible( + child: ListView( + children: [ + const SizedBox( + height: 32, + ), + SvgPicture.asset( + 'assets/svgs/switch.svg', + height: blockSizeVertical * 14, + allowDrawingOutsideViewBox: true, + ), + ListTile( + title: Text( + setQRScannerSettings, style: Theme.of(context) .textTheme - .bodySmall, + .titleLarge! + .copyWith(color: third), + textAlign: TextAlign.center, ), - SizedBox( - child: FittedBox( - child: CostumToggleSwitch( - activeBGColors: [ - Colors.green[800]!, - Colors.red[800]! - ], - initialLabelIndex: - _includeOtherInputs ? 0 : 1, - icons: const [ - Entypo.check, - ModernPictograms.cancel - ], - labels: const ['YES', 'NO'], - onToggle: (value) { - value == 0 - ? _includeOtherInputs = true - : _includeOtherInputs = false; - }, - ), - ), - ), - // Incoming or outgoing - Text(incomingORoutgoing, - style: Theme.of(context) - .textTheme - .titleMedium), - Text( - incomingORoutgoingSubTitle, + ), + Text(includeOtherInputs, style: Theme.of(context) .textTheme - .bodySmall, - ), - FittedBox( + .titleMedium), + Text( + includeOtherInputsSubTitle, + style: Theme.of(context) + .textTheme + .bodySmall, + ), + SizedBox( + child: FittedBox( child: CostumToggleSwitch( activeBGColors: [ - Colors.red[800]!, - Colors.green[800]! + Colors.green[800]!, + Colors.red[800]! ], initialLabelIndex: - scanMode == 'INCOMING' ? 0 : 1, + _includeOtherInputs ? 0 : 1, icons: const [ - Entypo.down_bold, - Entypo.up_bold, - ], - labels: const [ - 'INCOMING', - 'OUTGOING' + Entypo.check, + ModernPictograms.cancel ], + labels: const ['YES', 'NO'], onToggle: (value) { value == 0 - ? scanMode = 'INCOMING' - : scanMode = 'OUTGOING'; + ? _includeOtherInputs = true + : _includeOtherInputs = false; }, ), ), - const SizedBox( - height: 24, - ), - - ////STATION - Container( - child: state.roleId == 41 - ? DropdownButtonFormField( - isExpanded: true, - validator: FormBuilderValidators - .required( - errorText: - fieldIsRequired), - decoration: - normalTextFieldStyle( - "station", "station"), - items: state.assignedArea - .map((station) { - if (station.motherStation) { - return DropdownMenuItem< - dynamic>( - enabled: false, - value: station, - child: Text( - station.stationName - .toUpperCase(), - style: - const TextStyle( - color: Colors - .grey), - ), - ); - } else { - return DropdownMenuItem< - dynamic>( - value: station, - child: Padding( - padding: - const EdgeInsets - .only( - left: 10), - child: Text(station - .stationName), - ), - ); - } - }).toList(), - // value: selectedLevel, - onChanged: (value) async { - assignedArea = value; - }, - ////BARANGAY - ) - : state.roleId == 7 - ? Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - Text( - "Select Barangay", - textAlign: - TextAlign.start, - style: - Theme.of(context) - .textTheme - .titleMedium, - ), - const SizedBox( - height: 12, - ), - DropdownButtonFormField( - isExpanded: true, - decoration: - normalTextFieldStyle( - "Barangay", - "Barangay"), - items: state - .assignedArea - .map((barangay) { - return DropdownMenuItem< - dynamic>( - value: barangay, - child: Padding( - padding: - const EdgeInsets - .only( - left: - 5), - child: Text( - barangay - .brgydesc), - ), - ); - }).toList(), - onChanged: (value) { - assignedArea = - value; - }, - ), - ], - ) - : - ////PUROK - state.roleId == 10 - ? Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - Text( - "Select Purok", - textAlign: - TextAlign - .start, - style: Theme.of( - context) - .textTheme - .titleMedium, - ), - const SizedBox( - height: 12, - ), - DropdownButtonFormField( - isExpanded: true, - decoration: - normalTextFieldStyle( - "Purok", - "Purok"), - items: state - .assignedArea - .map((purok) { - return DropdownMenuItem< - dynamic>( - value: purok, - child: - Padding( - padding: const EdgeInsets - .only( - left: - 5), - child: Text( - purok - .purokdesc), - ), - ); - }).toList(), - onChanged: - (value) { - assignedArea = - value; - }, - ), - ], - ) - : - ////Registration InCharge - state.roleId == 22 - ? Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - Text( - "Select Station", - textAlign: - TextAlign - .start, - style: Theme.of( - context) - .textTheme - .titleMedium, - ), - const SizedBox( - height: 12, - ), - DropdownButtonFormField( - isExpanded: - true, - validator: FormBuilderValidators - .required( - errorText: - fieldIsRequired), - decoration: normalTextFieldStyle( - "station", - "station"), - items: state - .assignedArea - .map( - (station) { - if (station - .motherStation) { - return DropdownMenuItem< - dynamic>( - enabled: - false, - value: - station, - child: - Text( - station - .stationName - .toUpperCase(), - style: - const TextStyle(color: Colors.grey), - ), - ); - } else { - return DropdownMenuItem< - dynamic>( - value: - station, - child: - Padding( - padding: - const EdgeInsets.only(left: 5), - child: - Text(station.stationName), - ), - ); - } - }).toList(), - // value: selectedLevel, - onChanged: - (value) async { - assignedArea = - value; - }, - ), - ], - ) - : ////QR Code Scanner - state.roleId == 13 - ? Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - Text( - "Select Station", - textAlign: - TextAlign - .start, - style: Theme.of( - context) - .textTheme - .titleMedium, - ), - const SizedBox( - height: - 12, - ), - DropdownButtonFormField( - isExpanded: - true, - validator: - FormBuilderValidators.required( - errorText: fieldIsRequired), - decoration: normalTextFieldStyle( - "station", - "station"), - items: state - .assignedArea - .map( - (station) { - if (station - .motherStation) { - return DropdownMenuItem< - dynamic>( - enabled: - false, - value: - station, - child: - Text( - station.stationName.toUpperCase(), - style: const TextStyle(color: Colors.grey), - ), - ); - } else { - return DropdownMenuItem< - dynamic>( - value: - station, - child: - Padding( - padding: const EdgeInsets.only(left: 5), - child: Text(station.stationName), - ), - ); - } - }).toList(), - // value: selectedLevel, - onChanged: - (value) async { - assignedArea = - value; - }, - ), - ], - ) - : - ////Establishment Point-Person - state.roleId == 16 - ? Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - children: [ - Text( - "Select Agency", - textAlign: - TextAlign.start, - style: Theme.of(context) - .textTheme - .titleMedium, - ), - const SizedBox( - height: - 12, - ), - DropdownButtonFormField( - isExpanded: - true, - validator: - FormBuilderValidators.required(errorText: fieldIsRequired), - decoration: normalTextFieldStyle( - "Agency", - "Agency"), - items: state - .assignedArea - .map((agency) { - return DropdownMenuItem( - value: agency, - child: Padding( - padding: const EdgeInsets.only(left: 5), - child: Text(agency.area.name), - ), - ); - }).toList(), - // value: selectedLevel, - onChanged: - (value) async { - assignedArea = - value; - }, - ), - ], - ) - : ////Office Branch Chief - state.roleId == - 17 - ? Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - "Select Station", - textAlign: TextAlign.start, - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox( - height: 12, - ), - DropdownButtonFormField( - isExpanded: true, - validator: FormBuilderValidators.required(errorText: fieldIsRequired), - decoration: normalTextFieldStyle("station", "station"), - items: state.assignedArea.map((station) { - if (station.motherStation) { - return DropdownMenuItem( - enabled: false, - value: station, - child: Text( - station.stationName.toUpperCase(), - style: const TextStyle(color: Colors.grey), - ), - ); - } else { - return DropdownMenuItem( - value: station, - child: Padding( - padding: const EdgeInsets.only(left: 5), - child: Text(station.stationName), - ), - ); - } - }).toList(), - // value: selectedLevel, - onChanged: (value) async { - assignedArea = value; - }, - ), - ], - ) - : Container()) - ], - ), - ), - SizedBox( - width: double.infinity, - height: 60, - child: ElevatedButton( - style: mainBtnStyle(primary, - Colors.transparent, Colors.white54), - child: const Text( - submit, - style: TextStyle(color: Colors.white), ), - onPressed: () { - if (_formKey.currentState! - .saveAndValidate()) { - print(scanMode); - print(_includeOtherInputs); - print(checkerId); - print(assignedArea); - Navigator.push(context, - MaterialPageRoute(builder: - (BuildContext context) { - return BlocProvider< - PassCheckBloc>.value( - value: PassCheckBloc() - ..add(SetScannerSettings( - token: token!, - assignedArea: assignedArea, - checkerId: checkerId!, - entranceExit: scanMode, - includeOtherInputs: - _includeOtherInputs, - roleId: state.roleId)), - child: const QRCodeScanner(), - ); - })); - } - }, + // Incoming or outgoing + Text(incomingORoutgoing, + style: Theme.of(context) + .textTheme + .titleMedium), + Text( + incomingORoutgoingSubTitle, + style: Theme.of(context) + .textTheme + .bodySmall, + ), + FittedBox( + child: CostumToggleSwitch( + activeBGColors: [ + Colors.red[800]!, + Colors.green[800]! + ], + initialLabelIndex: + scanMode == 'INCOMING' ? 0 : 1, + icons: const [ + Entypo.down_bold, + Entypo.up_bold, + ], + labels: const [ + 'INCOMING', + 'OUTGOING' + ], + onToggle: (value) { + value == 0 + ? scanMode = 'INCOMING' + : scanMode = 'OUTGOING'; + }, + ), + ), + const SizedBox( + height: 24, + ), + + ////STATION + Container( + child: state.roleId == 41 + ? DropdownButtonFormField( + isExpanded: true, + validator: FormBuilderValidators + .required( + errorText: + fieldIsRequired), + decoration: + normalTextFieldStyle( + "station", "station"), + items: state.assignedArea + .map((station) { + if (station.motherStation) { + return DropdownMenuItem< + dynamic>( + enabled: false, + value: station, + child: Text( + station.stationName + .toUpperCase(), + style: + const TextStyle( + color: Colors + .grey), + ), + ); + } else { + return DropdownMenuItem< + dynamic>( + value: station, + child: Padding( + padding: + const EdgeInsets + .only( + left: 10), + child: Text(station + .stationName), + ), + ); + } + }).toList(), + // value: selectedLevel, + onChanged: (value) async { + assignedArea = value; + }, + ////BARANGAY + ) + : state.roleId == 7 + ? Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + Text( + "Select Barangay", + textAlign: + TextAlign.start, + style: + Theme.of(context) + .textTheme + .titleMedium, + ), + const SizedBox( + height: 12, + ), + DropdownButtonFormField( + isExpanded: true, + decoration: + normalTextFieldStyle( + "Barangay", + "Barangay"), + items: state + .assignedArea + .map((barangay) { + return DropdownMenuItem< + dynamic>( + value: barangay, + child: Padding( + padding: + const EdgeInsets + .only( + left: + 5), + child: Text( + barangay + .brgydesc), + ), + ); + }).toList(), + onChanged: (value) { + assignedArea = + value; + }, + ), + ], + ) + : + ////PUROK + state.roleId == 10 + ? Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + Text( + "Select Purok", + textAlign: + TextAlign + .start, + style: Theme.of( + context) + .textTheme + .titleMedium, + ), + const SizedBox( + height: 12, + ), + DropdownButtonFormField( + isExpanded: true, + decoration: + normalTextFieldStyle( + "Purok", + "Purok"), + items: state + .assignedArea + .map((purok) { + return DropdownMenuItem< + dynamic>( + value: purok, + child: + Padding( + padding: const EdgeInsets + .only( + left: + 5), + child: Text( + purok + .purokdesc), + ), + ); + }).toList(), + onChanged: + (value) { + assignedArea = + value; + }, + ), + ], + ) + : + ////Registration InCharge + state.roleId == 22 + ? Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + Text( + "Select Station", + textAlign: + TextAlign + .start, + style: Theme.of( + context) + .textTheme + .titleMedium, + ), + const SizedBox( + height: 12, + ), + DropdownButtonFormField( + isExpanded: + true, + validator: FormBuilderValidators + .required( + errorText: + fieldIsRequired), + decoration: normalTextFieldStyle( + "station", + "station"), + items: state + .assignedArea + .map( + (station) { + if (station + .motherStation) { + return DropdownMenuItem< + dynamic>( + enabled: + false, + value: + station, + child: + Text( + station + .stationName + .toUpperCase(), + style: + const TextStyle(color: Colors.grey), + ), + ); + } else { + return DropdownMenuItem< + dynamic>( + value: + station, + child: + Padding( + padding: + const EdgeInsets.only(left: 5), + child: + Text(station.stationName), + ), + ); + } + }).toList(), + // value: selectedLevel, + onChanged: + (value) async { + assignedArea = + value; + }, + ), + ], + ) + : ////QR Code Scanner + state.roleId == 13 + ? Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + Text( + "Select Station", + textAlign: + TextAlign + .start, + style: Theme.of( + context) + .textTheme + .titleMedium, + ), + const SizedBox( + height: + 12, + ), + DropdownButtonFormField( + isExpanded: + true, + validator: + FormBuilderValidators.required( + errorText: fieldIsRequired), + decoration: normalTextFieldStyle( + "station", + "station"), + items: state + .assignedArea + .map( + (station) { + if (station + .motherStation) { + return DropdownMenuItem< + dynamic>( + enabled: + false, + value: + station, + child: + Text( + station.stationName.toUpperCase(), + style: const TextStyle(color: Colors.grey), + ), + ); + } else { + return DropdownMenuItem< + dynamic>( + value: + station, + child: + Padding( + padding: const EdgeInsets.only(left: 5), + child: Text(station.stationName), + ), + ); + } + }).toList(), + // value: selectedLevel, + onChanged: + (value) async { + assignedArea = + value; + }, + ), + ], + ) + : + ////Establishment Point-Person + state.roleId == 16 + ? Column( + crossAxisAlignment: + CrossAxisAlignment + .start, + children: [ + Text( + "Select Agency", + textAlign: + TextAlign.start, + style: Theme.of(context) + .textTheme + .titleMedium, + ), + const SizedBox( + height: + 12, + ), + DropdownButtonFormField( + isExpanded: + true, + validator: + FormBuilderValidators.required(errorText: fieldIsRequired), + decoration: normalTextFieldStyle( + "Agency", + "Agency"), + items: state + .assignedArea + .map((agency) { + return DropdownMenuItem( + value: agency, + child: Padding( + padding: const EdgeInsets.only(left: 5), + child: Text(agency.area.name), + ), + ); + }).toList(), + // value: selectedLevel, + onChanged: + (value) async { + assignedArea = + value; + }, + ), + ], + ) + : ////Office Branch Chief + state.roleId == + 17 + ? Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Select Station", + textAlign: TextAlign.start, + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox( + height: 12, + ), + DropdownButtonFormField( + isExpanded: true, + validator: FormBuilderValidators.required(errorText: fieldIsRequired), + decoration: normalTextFieldStyle("station", "station"), + items: state.assignedArea.map((station) { + if (station.motherStation) { + return DropdownMenuItem( + enabled: false, + value: station, + child: Text( + station.stationName.toUpperCase(), + style: const TextStyle(color: Colors.grey), + ), + ); + } else { + return DropdownMenuItem( + value: station, + child: Padding( + padding: const EdgeInsets.only(left: 5), + child: Text(station.stationName), + ), + ); + } + }).toList(), + // value: selectedLevel, + onChanged: (value) async { + assignedArea = value; + }, + ), + ], + ) + : Container()) + ], + ), + ), + SizedBox( + width: double.infinity, + height: 60, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, Colors.white54), + child: const Text( + submit, + style: TextStyle(color: Colors.white), ), + onPressed: () { + if (_formKey.currentState! + .saveAndValidate()) { + print(scanMode); + print(_includeOtherInputs); + print(checkerId); + print(assignedArea); + Navigator.push(context, + MaterialPageRoute(builder: + (BuildContext context) { + return BlocProvider< + PassCheckBloc>.value( + value: PassCheckBloc() + ..add(SetScannerSettings( + token: token!, + assignedArea: assignedArea, + checkerId: checkerId!, + entranceExit: scanMode, + includeOtherInputs: + _includeOtherInputs, + roleId: state.roleId)), + child: const QRCodeScanner(), + ); + })); + } + }, ), - const SizedBox( - height: 52, - ), - ], - ), + ), + const SizedBox( + height: 52, + ), + ], ), - ); - } - if (state is PassCheckErrorState) { - return SomethingWentWrong( - message: state.message, onpressed: () { - - context.read().add(GetPassCheckAreas(roleId: widget.roleId, userId: widget.userId)); - }); - } - return Container(); - }, - ); - } - return Container(); - }, - ), - )), - ); + ), + ); + } + if (state is PassCheckErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () { + + context.read().add(GetPassCheckAreas(roleId: widget.roleId, userId: widget.userId)); + }); + } + return Container(); + }, + ); + } + return Container(); + }, + ), + )); } } diff --git a/lib/screens/unit2/roles/rbac/add_rbac.dart b/lib/screens/unit2/roles/rbac/add_rbac.dart new file mode 100644 index 0000000..bf7fd3c --- /dev/null +++ b/lib/screens/unit2/roles/rbac/add_rbac.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/src/widgets/framework.dart'; +import 'package:flutter/src/widgets/placeholder.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:unit2/theme-data.dart/box_shadow.dart'; + +import '../../../../theme-data.dart/btn-style.dart'; +import '../../../../theme-data.dart/colors.dart'; +import '../../../../theme-data.dart/form-style.dart'; + +class AddRbac extends StatefulWidget { + +final Function() onpressed; +final GlobalKey formKey; +final String title; + const AddRbac({super.key,required this.title,required this.onpressed, required this.formKey}); + + @override + State createState() => _AddRbacState(); +} + +class _AddRbacState extends State { + final formKey = GlobalKey(); + @override + Widget build(BuildContext context) { + return Container( + decoration: box1(), + child: Column(mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 24,), + const Text("No result found"), + const SizedBox(height: 12,), + TextButton(onPressed: (){ + showDialog(context: context,builder: (BuildContext context) { + return AlertDialog( + title: Text(widget.title), + content: FormBuilder( + key: widget.formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle("Object name *", "Object name "), + validator: FormBuilderValidators.required(errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "shorthand", + decoration: normalTextFieldStyle("Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: widget.onpressed, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }, child: Text(widget.title)) + ], + ), + ); + } +} diff --git a/lib/screens/unit2/roles/rbac/rbac.dart b/lib/screens/unit2/roles/rbac/rbac.dart new file mode 100644 index 0000000..12fe372 --- /dev/null +++ b/lib/screens/unit2/roles/rbac/rbac.dart @@ -0,0 +1,746 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:searchable_paginated_dropdown/searchable_paginated_dropdown.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/rbac/rbac_bloc.dart'; +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/rbac/new_permission.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../../model/profile/basic_information/primary-information.dart'; +import '../../../../sevices/roles/rbac_services.dart'; +import '../../../../theme-data.dart/box_shadow.dart'; +import '../../../../theme-data.dart/form-style.dart'; +import '../../../../utils/alerts.dart'; +import 'add_rbac.dart'; + +class RBACScreen extends StatefulWidget { + const RBACScreen({super.key}); + + @override + State createState() => _RBACScreenState(); +} + +class _RBACScreenState extends State { + ////roles + final roleFocusNode = FocusNode(); + final roleController = TextEditingController(); + RBAC? selectedRole; + + ////modules + final moduleFocusNode = FocusNode(); + final moduleController = TextEditingController(); + RBAC? selectedModule; + +////permissions + final permissionFocusNode = FocusNode(); + final permissionController = TextEditingController(); + List valueItemSelectedPermissions = []; + List valueItemPermission = []; + +////Object + RBAC? selectedObject; + final objectFocusNode = FocusNode(); + final objectController = TextEditingController(); + + ////operations + List operationsId = []; + List newOperations = []; + List valueItemOperation = []; + List selectedValueItemOperation = []; + + String? token; + + ////new permission + List newPermissions = []; + + final formKey = GlobalKey(); + final addRbacFormKey = GlobalKey(); + final newOperationKey = GlobalKey(); + int? selectedWebUserId; + bool showAddOperations = false; + @override + void dispose() { + moduleFocusNode.dispose(); + moduleController.dispose(); + roleFocusNode.dispose(); + roleController.dispose(); + permissionFocusNode.dispose(); + permissionController.dispose(); + objectFocusNode.dispose(); + objectController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + resizeToAvoidBottomInset: false, + appBar: AppBar( + title: const FittedBox( + child: Text("Role Based Access Control"), + ), + backgroundColor: primary, + ), + 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) { + token = state.userData!.user!.login!.token; + return BlocConsumer( + listener: (context, state) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + if (state is RbacScreenSetted || state is RbacErrorState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + if (state is RbacAssignedState) { + if (state.responseStatus['success']) { + successAlert(context, "Assigning Successfull!", + state.responseStatus['message'], () { + Navigator.of(context).pop(); + context.read().add(LoadRbac()); + }); + } else { + errorAlert(context, "Assigning Failed!", + state.responseStatus['message'], () { + Navigator.of(context).pop(); + context.read().add(LoadRbac()); + }); + } + } + }, + builder: (context, state) { + if (state is RbacScreenSetted) { + //// permission value item + valueItemPermission = + state.permission.map((RBACPermission permission) { + return ValueItem( + label: + "${permission.operation?.name} - ${permission.object?.name!}", + value: permission.id.toString()); + }).toList(); + ////value item operation + valueItemOperation = + state.operations.map((RBAC operation) { + return ValueItem( + label: operation.name!, + value: operation.id.toString()); + }).toList(); + return Container( + padding: const EdgeInsets.symmetric( + vertical: 32, horizontal: 34), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const SizedBox( + height: 38, + ), + Flexible( + child: Column( + children: [ + ////users + SearchableDropdownFormField.paginated( + margin: const EdgeInsets.all(0), + trailingIcon: const Padding( + padding: EdgeInsets.only(right: 8), + child: Icon( + Icons.arrow_drop_down, + color: Colors.grey, + )), + hintText: const Padding( + padding: EdgeInsets.only(left: 8), + child: Text( + "Search User", + style: TextStyle( + color: Colors.grey, + fontSize: 16), + )), + searchHintText: "Search User", + backgroundDecoration: (child) { + return SizedBox( + width: double.infinity, + child: Container( + width: double.infinity, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors.grey), + borderRadius: + const BorderRadius.all( + Radius.circular(5))), + child: child, + )); + }, + paginatedRequest: + (int page, String? searchKey) async { + List users = await RbacServices + .instance + .searchUser( + page: page, + name: searchKey ??= "", + token: token!); + return users.map((e) { + String fullname = + "${e.firstName} ${e.lastName}"; + return SearchableDropdownMenuItem< + Profile>( + label: fullname, + child: ListTile( + title: Text(fullname), + subtitle: + Text(e.birthdate.toString()), + ), + onTap: () { + setState(() { + selectedWebUserId = e.webuserId; + }); + }, + ); + }).toList(); + }, + ), + + const SizedBox( + height: 12, + ), + ////Role + StatefulBuilder( + builder: (context, setState) { + return SearchField( + itemHeight: 40, + suggestionsDecoration: box1(), + suggestions: state.role + .map((RBAC role) => + SearchFieldListItem( + role.name!, + item: role, + child: Padding( + padding: + const EdgeInsets + .symmetric( + horizontal: 10), + child: ListTile( + title: Text( + role.name!, + overflow: TextOverflow + .visible, + )), + ))) + .toList(), + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: roleFocusNode, + searchInputDecoration: + normalTextFieldStyle("Role *", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon( + Icons.arrow_drop_down), + onPressed: () { + roleFocusNode.unfocus(); + }, + )), + onSuggestionTap: (role) { + setState(() { + selectedRole = role.item; + roleFocusNode.unfocus(); + }); + }, + ////Add new role + emptyWidget: AddRbac( + formKey: addRbacFormKey, + title: "Add Role", + onpressed: () { + RBAC? newRole; + if (addRbacFormKey.currentState! + .saveAndValidate()) { + newRole = RBAC( + id: null, + name: addRbacFormKey + .currentState + ?.value['object_name'], + slug: addRbacFormKey + .currentState + ?.value['slug'], + shorthand: addRbacFormKey + .currentState + ?.value['shorthand'], + fontawesomeIcon: null, + createdAt: null, + updatedAt: null, + createdBy: null, + updatedBy: null); + } + setState(() { + state.role.insert(0, newRole!); + }); + roleFocusNode.unfocus(); + Navigator.pop(context); + }, + )); + }), + const SizedBox( + height: 12, + ), + // //// Modules + StatefulBuilder( + builder: (context, setState) { + return SearchField( + itemHeight: 40, + suggestionsDecoration: box1(), + suggestions: state.modules + .map((RBAC module) => + SearchFieldListItem( + module.name!, + item: module, + child: Padding( + padding: + const EdgeInsets + .symmetric( + horizontal: 10), + child: ListTile( + title: Text( + module.name!, + overflow: TextOverflow + .visible, + )), + ))) + .toList(), + validator: (module) { + if (module!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: moduleFocusNode, + searchInputDecoration: + normalTextFieldStyle( + "Module *", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon( + Icons.arrow_drop_down), + onPressed: () { + moduleFocusNode.unfocus(); + }, + )), + onSuggestionTap: (module) { + setState(() { + selectedModule = module.item; + moduleFocusNode.unfocus(); + }); + }, + // //// Add new module + + emptyWidget: AddRbac( + formKey: addRbacFormKey, + title: "Add Module", + onpressed: () { + RBAC? newModule; + if (addRbacFormKey.currentState! + .saveAndValidate()) { + newModule = RBAC( + id: null, + name: addRbacFormKey + .currentState + ?.value['object_name'], + slug: addRbacFormKey + .currentState + ?.value['slug'], + shorthand: addRbacFormKey + .currentState + ?.value['shorthand'], + fontawesomeIcon: null, + createdAt: null, + updatedAt: null, + createdBy: null, + updatedBy: null); + } + setState(() { + state.modules + .insert(0, newModule!); + }); + moduleFocusNode.unfocus(); + Navigator.pop(context); + }, + )); + }), + const SizedBox( + height: 12, + ), + //// Permission + + StatefulBuilder( + builder: (context, setState) { + return SizedBox( + width: double.infinity, + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: + BorderRadius.circular(5), + border: Border.all( + color: Colors.grey)), + child: Row( + children: [ + Expanded( + child: MultiSelectDropDown( + onOptionSelected: + (List + selectedOptions) { + setState(() { + valueItemSelectedPermissions = + selectedOptions; + }); + }, + hint: "Permissions", + hintStyle: const TextStyle( + fontSize: 16, + color: Colors.grey), + padding: + const EdgeInsets.all(8), + options: valueItemPermission, + selectionType: + SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: + WrapType.scroll), + dropdownHeight: 300, + optionTextStyle: + const TextStyle( + fontSize: 16), + selectedOptionIcon: + const Icon( + Icons.check_circle), + ), + ), + const SizedBox( + width: 6, + ), + IconButton( + ////Add Permission not the dialog add button + onPressed: () { + final addPermissionFormKey = + GlobalKey(); + showDialog( + context: context, + builder: (BuildContext + context) { + String? objectname; + String? slug; + String? shorthand; + return AlertDialog( + title: Row( + children: [ + Expanded( + child: + Container( + child: !showAddOperations + ? const Text( + "Add new Permission") + : const Text( + "Add new Operation"), + ), + ), + ////close button + IconButton( + onPressed: + () { + setState( + () { + showAddOperations = + false; + }); + Navigator.pop( + context); + }, + icon: const Icon( + Icons + .close)) + ], + ), + content: StatefulBuilder( + builder: (context, + stateSetter) { + return showAddOperations + ////add permission content if choice is in the choices + ? FormBuilder( + key: + newOperationKey, + child: + Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + onChanged: (value) { + objectname = value!; + }, + autovalidateMode: AutovalidateMode.always, + validator: FormBuilderValidators.required(errorText: "This field is required"), + name: "object_name", + decoration: normalTextFieldStyle("Object name *", "Object name "), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + onChanged: (value) { + slug = value!; + }, + name: "slug", + decoration: normalTextFieldStyle("Slug *", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + onChanged: (value) { + shorthand = value!; + }, + name: "shorthand", + decoration: normalTextFieldStyle("Shorthand *", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + /////Add new Operation submit button + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () async { + if (newOperationKey.currentState!.saveAndValidate()) { + RBAC newOperation = RBAC(id: null, name: objectname, slug: slug, shorthand: shorthand, fontawesomeIcon: null, createdAt: null, updatedAt: null, createdBy: null, updatedBy: null); + stateSetter(() { + newOperations.add(newOperation); + valueItemOperation.insert(0, ValueItem(label: newOperation.name!, value: newOperation.name)); + showAddOperations = false; + }); + } + }, + child: const Text("Add"))), + ], + ), + ) + ////add permission content if choice is in the choices + : Form( + key: + addPermissionFormKey, + child: + Column( + mainAxisSize: + MainAxisSize.min, + children: [ + ////Object + SizedBox( + width: double.infinity, + child: + ////Row ofr operation and add operation + Row( + children: [ + ////Operations + Expanded( + child: MultiSelectDropDown( + onOptionSelected: (List selectedOptions) { + stateSetter(() { + ////get operation ids + selectedValueItemOperation = selectedOptions; + }); + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + hintStyle: const TextStyle(fontSize: 16, color: Colors.grey), + padding: const EdgeInsets.all(8), + options: valueItemOperation, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig(wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: const TextStyle(fontSize: 16), + selectedOptionIcon: const Icon(Icons.check_circle), + ), + ), + const SizedBox( + width: 5, + ), + Container( + decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(5)), + child: IconButton( + ////Add Operation beside row button + onPressed: () { + stateSetter(() { + showAddOperations = true; + }); + }, + icon: const Icon(Icons.add)), + ) + ], + )), + const SizedBox( + height: 12, + ), + SearchField( + itemHeight: 40, + suggestionsDecoration: box1(), + suggestions: state.objects + .map((RBAC object) => SearchFieldListItem(object.name!, + item: object, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: ListTile( + title: Text( + object.name!, + overflow: TextOverflow.visible, + )), + ))) + .toList(), + validator: (module) { + if (module!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: objectFocusNode, + searchInputDecoration: normalTextFieldStyle("Object *", "").copyWith( + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + objectFocusNode.unfocus(); + }, + )), + onSuggestionTap: (object) { + stateSetter(() { + selectedObject = object.item; + objectFocusNode.unfocus(); + }); + }, + ////Add new Object + emptyWidget: AddRbac( + formKey: addRbacFormKey, + title: "Add Add Object", + onpressed: () { + if (addRbacFormKey.currentState!.saveAndValidate()) { + RBAC? newObject; + + if (addRbacFormKey.currentState!.saveAndValidate()) { + newObject = RBAC(id: null, name: addRbacFormKey.currentState?.value['object_name'], slug: addRbacFormKey.currentState?.value['slug'], shorthand: addRbacFormKey.currentState?.value['shorthand'], fontawesomeIcon: null, createdAt: null, updatedAt: null, createdBy: null, updatedBy: null); + } + stateSetter(() { + state.objects.insert(0, newObject!); + }); + objectFocusNode.unfocus(); + Navigator.pop(context); + } + }, + )), + const SizedBox( + height: 20, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: () { + ////Add Operation + if (addPermissionFormKey.currentState!.validate()) { + selectedValueItemOperation.forEach((e) { + setState(() { + // state.permission.insert(0, Permission(id: null, object: selectedObject!, operation: RBAC(id: null, name: e.label, slug: null, shorthand: null, fontawesomeIcon: null, createdAt: null, updatedAt: null, createdBy: null, updatedBy: null), createdAt: null, updatedAt: null, createdBy: null, updatedBy: null)); + valueItemPermission.insert(0, ValueItem(label: "${selectedObject!.name} - ${e.label}")); + valueItemPermission = valueItemPermission; + }); + }); + Navigator.pop(context); + setState(() {}); + } + }, + style: mainBtnStyle(primary, Colors.transparent, second), + child: const Text("Submit"), + )) + ], + )); + })); + }); + }, + icon: const Icon(Icons.add)), + ], + ), + ), + ); + }), + const SizedBox( + height: 12, + ), + ], + )), + SizedBox( + height: 50, + width: double.infinity, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + ////existing permission + List permissions = + valueItemSelectedPermissions + .map((e) => + int.parse(e.value!)) + .toList(); + + context.read().add( + AssignedRbac( + assigneeId: + selectedWebUserId!, + assignerId: 63, + newPermissions: [], + permissionId: permissions, + selectedModule: + selectedModule, + selectedRole: selectedRole)); + } + print(valueItemSelectedPermissions + .length); + }, + child: const Text("submit")), + ) + ], + )), + ); + } + if (state is RbacErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } + return Container(); + }, + ); + } + return Container(); + }, + ), + )); + } +} diff --git a/lib/screens/utils/formatters.dart b/lib/screens/utils/formatters.dart new file mode 100644 index 0000000..b9f78bb --- /dev/null +++ b/lib/screens/utils/formatters.dart @@ -0,0 +1 @@ +// TODO Implement this library. \ No newline at end of file diff --git a/lib/sevices/passo/barangay.dart b/lib/sevices/passo/barangay.dart new file mode 100644 index 0000000..24490a1 --- /dev/null +++ b/lib/sevices/passo/barangay.dart @@ -0,0 +1,40 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class BarangayServices { + static final BarangayServices _instance = BarangayServices(); + static BarangayServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(id) async { + String path = Url.instance.getBarangay(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "city_code": id.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => Brgy.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/building/additional_items_services.dart b/lib/sevices/passo/building/additional_items_services.dart index 5215809..b2a4441 100644 --- a/lib/sevices/passo/building/additional_items_services.dart +++ b/lib/sevices/passo/building/additional_items_services.dart @@ -4,50 +4,84 @@ import 'dart:io'; import 'package:unit2/model/passo/additional_items.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; + +import '../../../utils/urls.dart'; class AdditionalItemsServices { static final AdditionalItemsServices _instance = AdditionalItemsServices(); static AdditionalItemsServices get instance => _instance; - Future> getAdditionalItems(tempID) async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/additional_items/?bldgappr_details_id=$tempID')); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => AdditionalItems.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + Future> fetch(tempID) async { + String path = Url.instance.additionalItems(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result.map(((e) => AdditionalItems.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } - Future postAdditionalItems(AdditionalItems items) async { + Future add(AdditionalItems items) async { + String path = Url.instance.additionalItems(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; http.Response? response; try { - response = await http.post( - Uri.parse( - "http://192.168.10.218:8000/api/rptass_app/additional_items/"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(items.toJson())); + response = await Request.instance.postRequest( + param: {}, path: path, body: items.toJson(), headers: headers); } catch (e) { log(e.toString()); } return response; } - Future removeAdditionalItems(id) async { - http.Response response = await http.delete( - Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/additional_items/?id=$id'), - ); - print(id); - if (response.statusCode == 200) { - print(response.body); - return response; - } else { - throw Exception(response.reasonPhrase); + Future remove(id) async { + String path = Url.instance.additionalItems(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id.toString(), + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: params); + print(id); + if (response.statusCode == 200) { + print(response.body); + return response; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } } diff --git a/lib/sevices/passo/building/general_description_services.dart b/lib/sevices/passo/building/general_description_services.dart new file mode 100644 index 0000000..17552c8 --- /dev/null +++ b/lib/sevices/passo/building/general_description_services.dart @@ -0,0 +1,69 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class GeneralDescriptionServices { + static final GeneralDescriptionServices _instance = + GeneralDescriptionServices(); + static GeneralDescriptionServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future fetch(tempID) async { + String path = Url.instance.generalDescription(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('GenDescEdit'); + print(response.body); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = + GeneralDesc.fromJson(dataList[0] as Map); + + return result; + } else { + print(response.reasonPhrase); + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future update(GeneralDesc data, id) async { + String path = Url.instance.generalDescription(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id, + }; + http.Response? response; + try { + print(id); + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + print(response.body); + } catch (e) { + throw e.toString(); + } + return response; + } +} diff --git a/lib/sevices/passo/building/landref_services.dart b/lib/sevices/passo/building/landref_services.dart new file mode 100644 index 0000000..ef90ba5 --- /dev/null +++ b/lib/sevices/passo/building/landref_services.dart @@ -0,0 +1,44 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandRefServices { + static final LandRefServices _instance = LandRefServices(); + static LandRefServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future fetch(tempID) async { + String path = Url.instance.landRef(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('land ref'); + print(response.statusCode); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = LandRef.fromJson(dataList[0] as Map); + + return result; + } else { + print(response.reasonPhrase); + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/building/location_landref_services.dart b/lib/sevices/passo/building/location_landref_services.dart index 6098b76..b916aa8 100644 --- a/lib/sevices/passo/building/location_landref_services.dart +++ b/lib/sevices/passo/building/location_landref_services.dart @@ -4,24 +4,65 @@ import 'dart:io'; import 'package:http/http.dart' as http; import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class LocationLandrefServices { static final LocationLandrefServices _instance = LocationLandrefServices(); static LocationLandrefServices get instance => _instance; - Future bldgLocPutInfo(BldgLoc data, id) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future update(BldgLoc data, id) async { + String path = Url.instance.bldgLocation(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; http.Response? response; try { - response = await http.put(Uri.parse( - // ignore: unnecessary_brace_in_string_interps - "http://192.168.10.218:8000/api/rptass_app/bldgappr_location/?bldgappr_details_id=${id}"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(data.toJson())); + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); } catch (e) { log(e.toString()); } return response; } + + Future fetch(tempID) async { + String path = Url.instance.bldgLocation(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + + print('BldgLocEdit'); + print(response.body); + + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = BldgLoc.fromJson(dataList[0] as Map); + + return result; + } else { + print(response.reasonPhrase); + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } } diff --git a/lib/sevices/passo/building/property_appraisal_services.dart b/lib/sevices/passo/building/property_appraisal_services.dart index 44774c7..2000441 100644 --- a/lib/sevices/passo/building/property_appraisal_services.dart +++ b/lib/sevices/passo/building/property_appraisal_services.dart @@ -2,39 +2,129 @@ import 'dart:convert'; import 'dart:developer'; import 'dart:io'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:unit2/model/passo/property_appraisal.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +import '../../../model/passo/property_appraisal_edit.dart'; class PropertyAppraisalServices { static final PropertyAppraisalServices _instance = PropertyAppraisalServices(); static PropertyAppraisalServices get instance => _instance; - Future> getPropertyAppraisal(tempID) async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/property_appraisal/?bldgappr_details_id=$tempID')); - print('Appraisal'); - print(response.body); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => PropertyAppraisal.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + Future fetch() async { + final tempID = await SharedPreferences.getInstance(); + print('sds'); + print(tempID.getInt('tempid')! - 1); + final id = tempID.getInt('tempid')! - 1; + String path = Url.instance.propertyAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('Appraisal TEMPID'); + print(response.body); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = + PropertyAppraisal.fromJson(dataList[0] as Map); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } - Future postPropertyAppraisal( - PropertyAppraisal appraisal) async { + Future update(PropertyAppraisal appraisal, tempID) async { + String path = Url.instance.propertyAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + print(tempID); http.Response? response; try { - response = await http.post( - Uri.parse( - "http://192.168.10.218:8000/api/rptass_app/property_appraisal/"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(appraisal.toJson())); + response = await Request.instance.putRequest( + path: path, + body: appraisal.toJson(), + headers: headers, + param: params); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future fetchEdit(id) async { + String path = Url.instance.propertyAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('Property_Apraisaledit'); + print(response.statusCode); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = + PropertyAppraisalEdit.fromJson(dataList[0] as Map); + + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future updateAppraisal( + PropertyAppraisalEdit appraisal, tempID) async { + String path = Url.instance.propertyAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID, + }; + print(tempID); + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, + body: appraisal.toJson(), + headers: headers, + param: params); } catch (e) { log(e.toString()); } diff --git a/lib/sevices/passo/building/property_assessment_services.dart b/lib/sevices/passo/building/property_assessment_services.dart index ae98b46..3ac71ca 100644 --- a/lib/sevices/passo/building/property_assessment_services.dart +++ b/lib/sevices/passo/building/property_assessment_services.dart @@ -4,55 +4,152 @@ import 'dart:io'; import 'package:unit2/model/passo/property_assessment.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class PropertyAssessmentServices { static final PropertyAssessmentServices _instance = PropertyAssessmentServices(); static PropertyAssessmentServices get instance => _instance; - Future> getPropertyAssessment(tempID) async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/property_assessment/?bldgappr_details_id=$tempID')); - print('Assessment'); - print(response.statusCode); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => PropertyAssessment.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + Future> fetch(tempID) async { + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('Assessment'); + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => PropertyAssessment.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } - Future postPropertyAssessment( - PropertyAssessment assessment) async { + Future add(PropertyAssessment assessment) async { + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; http.Response? response; + try { - response = await http.post( - Uri.parse( - "http://192.168.10.218:8000/api/rptass_app/property_assessment/"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(assessment.toJson())); + response = await Request.instance.postRequest( + param: {}, path: path, body: assessment.toJson(), headers: headers); } catch (e) { log(e.toString()); } return response; } - Future propertyAssessmentPutInfo( - PropertyAssessment assessment, id) async { - print(id); + Future update(PropertyAssessment assessment, id) async { + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; http.Response? response; try { - response = await http.put(Uri.parse( - // ignore: unnecessary_brace_in_string_interps - "http://192.168.10.218:8000/api/rptass_app/property_assessment/?bldgappr_details_id=${id}"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(assessment.toJson())); + response = await Request.instance.putRequest( + path: path, + body: assessment.toJson(), + headers: headers, + param: params); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future fetchEdit(tempID) async { + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('Assessment'); + print(response.body); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = PropertyAssessmentEdit.fromJson( + dataList[0] as Map); + + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future addEdit(PropertyAssessmentEdit assessment) async { + Map statusResponse = {}; + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: assessment.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future updateEdit( + PropertyAssessmentEdit assessment, id) async { + String path = Url.instance.propertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, + body: assessment.toJson(), + headers: headers, + param: params); } catch (e) { log(e.toString()); } diff --git a/lib/sevices/passo/building/property_info_services.dart b/lib/sevices/passo/building/property_info_services.dart index 5503ad3..ac90a92 100644 --- a/lib/sevices/passo/building/property_info_services.dart +++ b/lib/sevices/passo/building/property_info_services.dart @@ -3,71 +3,134 @@ import 'dart:developer'; import 'dart:io'; import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/model/passo/general_description.dart'; import 'package:unit2/model/passo/land_ref.dart'; import 'package:unit2/model/passo/property_info.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class PropertyInfoService { static final PropertyInfoService _instance = PropertyInfoService(); static PropertyInfoService get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - Future> getpropertyInfo() async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/bldgappr_details/')); - print(response.body); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + Future> fetch() async { + String path = Url.instance.propertyInfo(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; - return result.map(((e) => PropertyInfo.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => PropertyInfo.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } - Future postPropertyInfo(PropertyInfo faas) async { + Future add(PropertyInfo faas) async { + Map statusResponse = {}; + String path = Url.instance.propertyInfo(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; http.Response? response; try { - response = await http.post( - Uri.parse( - "http://192.168.10.218:8000/api/rptass_app/bldgappr_details/"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(faas.toJson())); + response = await Request.instance.postRequest( + param: {}, path: path, body: faas.toJson(), headers: headers); } catch (e) { - log(e.toString()); + throw e.toString(); } return response; } - Future bldgLocPutInfo(BldgLoc data, id) async { + Future update(PropertyInfo data, id) async { + String path = "${Url.instance.propertyInfo()}$id/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; try { - response = await http.put(Uri.parse( - // ignore: unnecessary_brace_in_string_interps - "http://192.168.10.218:8000/api/rptass_app/bldgappr_location/?bldgappr_details_id=${id}"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(data.toJson())); + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: {}); } catch (e) { - log(e.toString()); + throw e.toString(); } return response; } - Future landRefPutInfo(LandRef data, id) async { + Future updateBldg(BldgLoc data, id) async { + String path = Url.instance.bldgLocation(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; http.Response? response; try { - response = await http.put(Uri.parse( - // ignore: unnecessary_brace_in_string_interps - "http://192.168.10.218:8000/api/rptass_app/bldgappr_landref/?bldgappr_details_id=${id}"), - headers: { - HttpHeaders.contentTypeHeader: "application/json", - }, - body: jsonEncode(data.toJson())); + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); } catch (e) { - log(e.toString()); + throw e.toString(); + } + return response; + } + + Future updateLandRef(LandRef data, id) async { + String path = Url.instance.landRef(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + } catch (e) { + throw e.toString(); + } + return response; + } + + Future updateGenDesc(GeneralDesc data, id) async { + String path = Url.instance.generalDescription(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + } catch (e) { + throw e.toString(); } return response; } diff --git a/lib/sevices/passo/building/structural_material_services.dart b/lib/sevices/passo/building/structural_material_services.dart new file mode 100644 index 0000000..0da27f3 --- /dev/null +++ b/lib/sevices/passo/building/structural_material_services.dart @@ -0,0 +1,67 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/model/passo/structureMaterial.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class StrucMaterialServices { + static final StrucMaterialServices _instance = StrucMaterialServices(); + static StrucMaterialServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future update(StructureMaterialsII data, id) async { + String path = Url.instance.structuralMaterials(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future fetch(id) async { + String path = Url.instance.structuralMaterials(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "bldgappr_details_id": id.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + print('StructureMaterialsII'); + print(response.body); + if (response.statusCode == 200) { + final jsonData = jsonDecode(response.body); + final dataList = jsonData['data'] as List; + final result = + StructureMaterials.fromJson(dataList[0] as Map); + + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/class_components_services.dart b/lib/sevices/passo/class_components_services.dart index 2d3e786..8898ed4 100644 --- a/lib/sevices/passo/class_components_services.dart +++ b/lib/sevices/passo/class_components_services.dart @@ -2,20 +2,35 @@ import 'dart:convert'; import 'package:unit2/model/passo/class_components.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class ClassComponentService { static final ClassComponentService _instance = ClassComponentService(); static ClassComponentService get instance => _instance; - Future> getClassComponent() async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/class_components/')); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => ClassComponents.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + Future> fetch() async { + String path = Url.instance.getClassComponents(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => ClassComponents.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } } diff --git a/lib/sevices/passo/land/land_appraisal.dart b/lib/sevices/passo/land/land_appraisal.dart new file mode 100644 index 0000000..065e5ad --- /dev/null +++ b/lib/sevices/passo/land/land_appraisal.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/utils/request.dart'; + +import '../../../utils/urls.dart'; + +class LandAppraisalServices { + static final LandAppraisalServices _instance = LandAppraisalServices(); + static LandAppraisalServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(tempID) async { + String path = Url.instance.getLandAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result.map(((e) => LandAppr.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(LandAppr items) async { + String path = Url.instance.getLandAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: items.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future remove(id) async { + String path = Url.instance.getLandAppraisal(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id.toString(), + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: params); + print(id); + if (response.statusCode == 200) { + print(response.body); + return response; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_boundaries.dart b/lib/sevices/passo/land/land_boundaries.dart new file mode 100644 index 0000000..969d40c --- /dev/null +++ b/lib/sevices/passo/land/land_boundaries.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_property_boundaries.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandBoundariesService { + static final LandBoundariesService _instance = LandBoundariesService(); + static LandBoundariesService get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getLandPropertyBoundaries(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandPropertyBoundaries.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future update(LandPropertyBoundaries data, id) async { + String path = Url.instance.getLandPropertyBoundaries(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + } catch (e) { + log(e.toString()); + } + return response; + } +} diff --git a/lib/sevices/passo/land/land_classification.dart b/lib/sevices/passo/land/land_classification.dart new file mode 100644 index 0000000..198b509 --- /dev/null +++ b/lib/sevices/passo/land/land_classification.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandClassificationService { + static final LandClassificationService _instance = + LandClassificationService(); + static LandClassificationService get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getLandClassification(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandClassification.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_ext.dart b/lib/sevices/passo/land/land_ext.dart new file mode 100644 index 0000000..4d23162 --- /dev/null +++ b/lib/sevices/passo/land/land_ext.dart @@ -0,0 +1,136 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:unit2/model/passo/land_ext.dart'; +import 'package:unit2/model/passo/property_assessment.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/property_assessment_edit.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandExtServices { + static final LandExtServices _instance = LandExtServices(); + static LandExtServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(tempID) async { + String path = Url.instance.getLandExt(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + print('Assessment'); + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandExt.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(LandExt assessment) async { + Map statusResponse = {}; + String path = Url.instance.getLandExt(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: assessment.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future update(LandExt assessment, id) async { + String path = Url.instance.getLandExt(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, + body: assessment.toJson(), + headers: headers, + param: params); + } catch (e) { + log(e.toString()); + } + return response; + } + + // Future fetchEdit(tempID) async { + // http.Response response = await http.get(Uri.parse( + // '$baseUrl${Url.instance.getLandExt()}?bldgappr_details_id=$tempID')); + // print('Assessment'); + // print(response.body); + // if (response.statusCode == 200) { + // final jsonData = jsonDecode(response.body); + // final dataList = jsonData['data'] as List; + // final result = + // LandExtEdit.fromJson(dataList[0] as Map); + + // return result; + // } else { + // throw Exception(response.reasonPhrase); + // } + // } + + // Future addEdit(LandExtEdit assessment) async { + // http.Response? response; + // try { + // response = await http.post( + // Uri.parse("$baseUrl${Url.instance.getLandExt()}"), + // headers: { + // HttpHeaders.contentTypeHeader: "application/json", + // }, + // body: jsonEncode(assessment.toJson())); + // } catch (e) { + // log(e.toString()); + // } + // return response; + // } + + // Future updateEdit( + // LandExtEdit assessment, id) async { + // print(id); + // http.Response? response; + // try { + // response = await http.put(Uri.parse( + // // ignore: unnecessary_brace_in_string_interps + // "$baseUrl${Url.instance.getLandExt()}?bldgappr_details_id=${id}"), + // headers: { + // HttpHeaders.contentTypeHeader: "application/json", + // }, + // body: jsonEncode(assessment.toJson())); + // } catch (e) { + // log(e.toString()); + // } + // return response; + // } +} diff --git a/lib/sevices/passo/land/land_location.dart b/lib/sevices/passo/land/land_location.dart new file mode 100644 index 0000000..8a2fe5b --- /dev/null +++ b/lib/sevices/passo/land/land_location.dart @@ -0,0 +1,58 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:unit2/model/passo/land_property_loc.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandLocationService { + static final LandLocationService _instance = LandLocationService(); + static LandLocationService get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getLandPropertyLoc(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandPropertyLoc.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future update(LandPropertyLoc data, id) async { + String path = Url.instance.getLandPropertyLoc(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": id.toString(), + }; + http.Response? response; + try { + response = await Request.instance.putRequest( + path: path, body: data.toJson(), headers: headers, param: params); + } catch (e) { + log(e.toString()); + } + return response; + } +} diff --git a/lib/sevices/passo/land/land_other_improvements.dart b/lib/sevices/passo/land/land_other_improvements.dart new file mode 100644 index 0000000..d23652a --- /dev/null +++ b/lib/sevices/passo/land/land_other_improvements.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/utils/request.dart'; + +import '../../../utils/urls.dart'; + +class OtherImprovementServices { + static final OtherImprovementServices _instance = OtherImprovementServices(); + static OtherImprovementServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(tempID) async { + String path = Url.instance.getOtherImprovements(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": tempID, + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result.map(((e) => OtherImprovements.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(OtherImprovements items) async { + String path = Url.instance.getOtherImprovements(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: items.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future remove(id) async { + String path = Url.instance.getOtherImprovements(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id, + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + print(id); + if (response.statusCode == 200) { + print(response.body); + return response; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_property_assessment.dart b/lib/sevices/passo/land/land_property_assessment.dart new file mode 100644 index 0000000..d8768bd --- /dev/null +++ b/lib/sevices/passo/land/land_property_assessment.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/land_property_assessment.dart'; +import 'package:unit2/utils/request.dart'; + +import '../../../utils/urls.dart'; + +class LandPropertyAssessmentServices { + static final LandPropertyAssessmentServices _instance = + LandPropertyAssessmentServices(); + static LandPropertyAssessmentServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(tempID) async { + String path = Url.instance.getLandPropertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": tempID.toString(), + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result.map(((e) => LandPropertyAssessment.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(LandPropertyAssessment items) async { + String path = Url.instance.getLandPropertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: items.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future remove(id) async { + String path = Url.instance.getLandPropertyAssessment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id.toString(), + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: params); + print(id); + if (response.statusCode == 200) { + print(response.body); + return response; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_property_owner.dart b/lib/sevices/passo/land/land_property_owner.dart new file mode 100644 index 0000000..83798ab --- /dev/null +++ b/lib/sevices/passo/land/land_property_owner.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:unit2/model/passo/land_property_owner.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandServices { + static final LandServices _instance = LandServices(); + static LandServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getLandOwnerInfo(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandPropertyOwner.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(LandPropertyOwner land) async { + String path = Url.instance.getLandOwnerInfo(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: land.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } +} diff --git a/lib/sevices/passo/land/land_subclassification.dart b/lib/sevices/passo/land/land_subclassification.dart new file mode 100644 index 0000000..031c56e --- /dev/null +++ b/lib/sevices/passo/land/land_subclassification.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_subclassification.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandSubClassificationService { + static final LandSubClassificationService _instance = + LandSubClassificationService(); + static LandSubClassificationService get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(cityCode, classCode) async { + String path = Url.instance.getLandSubClassification(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "city_code": cityCode.toString(), + "classification_id": classCode.toString() + }; + try { + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => LandSubClassification.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_trees_improvements.dart b/lib/sevices/passo/land/land_trees_improvements.dart new file mode 100644 index 0000000..29da425 --- /dev/null +++ b/lib/sevices/passo/land/land_trees_improvements.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/trees_improvements.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class LandTreesImprovementsServices { + static final LandTreesImprovementsServices _instance = + LandTreesImprovementsServices(); + static LandTreesImprovementsServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getTreesImprovements(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => TreesImprovements.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/land_value_adjustment.dart b/lib/sevices/passo/land/land_value_adjustment.dart new file mode 100644 index 0000000..8fda18f --- /dev/null +++ b/lib/sevices/passo/land/land_value_adjustment.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/utils/request.dart'; + +import '../../../utils/urls.dart'; + +class ValueAdjustmentsServices { + static final ValueAdjustmentsServices _instance = ValueAdjustmentsServices(); + static ValueAdjustmentsServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch(tempID) async { + String path = Url.instance.getValueAdjustmentss(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "landappr_details_id": tempID, + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result.map(((e) => ValueAdjustments.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } + + Future add(ValueAdjustments items) async { + String path = Url.instance.getValueAdjustmentss(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + http.Response? response; + try { + response = await Request.instance.postRequest( + param: {}, path: path, body: items.toJson(), headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } + + Future remove(id) async { + String path = Url.instance.getValueAdjustmentss(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map params = { + "id": id, + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + print(id); + if (response.statusCode == 200) { + print(response.body); + return response; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/type_of_location.dart b/lib/sevices/passo/land/type_of_location.dart new file mode 100644 index 0000000..004e6d7 --- /dev/null +++ b/lib/sevices/passo/land/type_of_location.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/type_of_location.dart'; +import 'package:unit2/model/passo/type_of_road.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class TypeOfLocationServices { + static final TypeOfLocationServices _instance = TypeOfLocationServices(); + static TypeOfLocationServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getTypeOfLocation(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + print(response.body); + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => TypeOfLocation.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/land/type_of_road.dart b/lib/sevices/passo/land/type_of_road.dart new file mode 100644 index 0000000..51470ed --- /dev/null +++ b/lib/sevices/passo/land/type_of_road.dart @@ -0,0 +1,37 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/type_of_road.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class TypeOfRoadServices { + static final TypeOfRoadServices _instance = TypeOfRoadServices(); + static TypeOfRoadServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getTypeOfRoad(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + print(response.body); + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => TypeOfRoad.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/memoranda.dart b/lib/sevices/passo/memoranda.dart new file mode 100644 index 0000000..c29a6be --- /dev/null +++ b/lib/sevices/passo/memoranda.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/memoranda.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class MemorandaServices { + static final MemorandaServices _instance = MemorandaServices(); + static MemorandaServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getMemoranda(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => Memoranda.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/municipality.dart b/lib/sevices/passo/municipality.dart new file mode 100644 index 0000000..2bb4850 --- /dev/null +++ b/lib/sevices/passo/municipality.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; + +import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +class MunicipalityServices { + static final MunicipalityServices _instance = MunicipalityServices(); + static MunicipalityServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> fetch() async { + String path = Url.instance.getMunicipality(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + print(response.body); + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => City.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); + } + } +} diff --git a/lib/sevices/passo/signatories_service.dart b/lib/sevices/passo/signatories_service.dart index 76eeba7..1d527f2 100644 --- a/lib/sevices/passo/signatories_service.dart +++ b/lib/sevices/passo/signatories_service.dart @@ -2,23 +2,39 @@ import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:unit2/model/passo/signatories.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class SignatoriesServices { static final SignatoriesServices _instance = SignatoriesServices(); static SignatoriesServices get instance => _instance; - Future> getSignatories() async { - http.Response response = await http.get( - Uri.parse('http://192.168.10.218:8000/api/rptass_app/signatories/')); - print('Signatories'); - print(response.statusCode); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => Signatories.fromJson(e))).toList(); - } else { - print(response.reasonPhrase); - throw Exception(response.reasonPhrase); + Future> fetch() async { + String path = Url.instance.getSignatories(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + + print('Signatories'); + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => Signatories.fromJson(e))).toList(); + } else { + print(response.reasonPhrase); + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } } diff --git a/lib/sevices/passo/unit_construct_services.dart b/lib/sevices/passo/unit_construct_services.dart index 7ef90d5..39794e8 100644 --- a/lib/sevices/passo/unit_construct_services.dart +++ b/lib/sevices/passo/unit_construct_services.dart @@ -2,20 +2,35 @@ import 'dart:convert'; import 'package:unit2/model/passo/unit_construct.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; class UnitConstructService { static final UnitConstructService _instance = UnitConstructService(); static UnitConstructService get instance => _instance; - Future> getUnitConstruct() async { - http.Response response = await http.get(Uri.parse( - 'http://192.168.10.218:8000/api/rptass_app/unitconstruct_values/')); - if (response.statusCode == 200) { - final List result = jsonDecode(response.body)['data']; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; - return result.map(((e) => UnitConstruct.fromJson(e))).toList(); - } else { - throw Exception(response.reasonPhrase); + Future> fetch() async { + String path = Url.instance.getUnitConstruct(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + return result.map(((e) => UnitConstruct.fromJson(e))).toList(); + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw e.toString(); } } } diff --git a/lib/sevices/roles/pass_check_services.dart b/lib/sevices/roles/pass_check_services.dart index 3b076a6..8ff5c22 100644 --- a/lib/sevices/roles/pass_check_services.dart +++ b/lib/sevices/roles/pass_check_services.dart @@ -32,7 +32,7 @@ class PassCheckServices { 'X-Client-Key': xClientKey, 'X-Client-Secret': xClientSecret }; - try { + // try { http.Response response = await Request.instance .getRequest(param: params, headers: headers, path: path); if (response.statusCode == 200) { @@ -133,9 +133,9 @@ class PassCheckServices { statusResponse = assignedArea; } } - } catch (e) { - throw e.toString(); - } + // } catch (e) { + // throw e.toString(); + // } return statusResponse!; } diff --git a/lib/sevices/roles/rbac_operations/agency_services.dart b/lib/sevices/roles/rbac_operations/agency_services.dart new file mode 100644 index 0000000..3f8d713 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/agency_services.dart @@ -0,0 +1,73 @@ +import 'dart:convert'; + +import 'package:unit2/screens/profile/components/other_information/org_membership/add_modal.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +import '../../../model/utils/agency.dart'; +import 'package:http/http.dart' as http; + +class AgencyServices { + static final AgencyServices _instance = AgencyServices(); + static AgencyServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getAgencies() async { + List agencies = []; + String path = Url.instance.agencies(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var element in data['data']) { + Agency newAgency = Agency.fromJson(element); + agencies.add(newAgency); + } + } + } + } catch (e) { + throw e.toString(); + } + return agencies; + } + Future>add({required Agency agency})async{ + Map statusResponse = {}; + String path = Url.instance.postAgencies(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "name":agency.name, + "category_id":agency.category!.id, + "private_entity":agency.privateEntity, + "contact_info":null, + }; + try{ + http.Response response = await Request.instance.postRequest(param: {},path: path, body: body,headers: headers); + if(response.statusCode == 201){ + Map data = jsonDecode(response.body); + statusResponse = data; + }else{ + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + }catch(e){ + throw e.toString(); + } + return statusResponse; + } +} diff --git a/lib/sevices/roles/rbac_operations/module_objects_services.dart b/lib/sevices/roles/rbac_operations/module_objects_services.dart new file mode 100644 index 0000000..87e9890 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/module_objects_services.dart @@ -0,0 +1,98 @@ +import 'dart:convert'; + +import 'package:unit2/model/login_data/user_info/module.dart'; +import 'package:http/http.dart' as http; +import '../../../model/rbac/rbac_rbac.dart'; +import '../../../utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacModuleObjectsServices { + static final RbacModuleObjectsServices _instance = + RbacModuleObjectsServices(); + static RbacModuleObjectsServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + Future> getModuleObjects() async { + List moduleObjects = []; + String path = Url.instance.getModuleObjects(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var modObj in data['data']) { + ModuleObjects newModObj = ModuleObjects.fromJson(modObj); + moduleObjects.add(newModObj); + } + } + } + } catch (e) { + throw e.toString(); + } + return moduleObjects; + } + + ////Add + Future> add({ + required int assignerId, + required int? moduleId, + required List objectsId, + }) async { + String path = Url.instance.getModuleObjects(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "module_id": moduleId, + "objects": objectsId, + "assigner_user_id": assignerId + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deleteRbacModuleObject({required int moduleObjectId}) async { + bool success = false; + String path = "${Url.instance.getModuleObjects()}$moduleObjectId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/module_services.dart b/lib/sevices/roles/rbac_operations/module_services.dart new file mode 100644 index 0000000..76ea4a1 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/module_services.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacModuleServices { + static final RbacModuleServices _instance = RbacModuleServices(); + static RbacModuleServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRbacModule() async { + List modules = []; + String path = Url.instance.getModules(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var rbac in data['data']) { + RBAC newModule = RBAC.fromJson(rbac); + modules.add(newModule); + } + } + } + } catch (e) { + throw e.toString(); + } + + return modules; + } + ////Add + Future> add( + {required String name, + required String? slug, + required String? short, + required int id}) async { + String path = Url.instance.getModules(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "fontawesome_icon":"mobile", + "created_by_id": id, + "updated_by_id": id + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + ////Update + Future> update({ + required int moduleId, + required String name, + required String? slug, + required String? short, + required int? createdBy, + required int updatedBy, + }) async { + String path = "${Url.instance.getModules()}$moduleId/"; + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": createdBy, + "updated_by_id": updatedBy, + "fontawesome_icon":"mobile", + }; + try { + http.Response response = await Request.instance + .putRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deleteRbacModule({required int moduleId}) async { + bool success = false; + String path = "${Url.instance.getModules()}$moduleId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/object_services.dart b/lib/sevices/roles/rbac_operations/object_services.dart new file mode 100644 index 0000000..402b2ac --- /dev/null +++ b/lib/sevices/roles/rbac_operations/object_services.dart @@ -0,0 +1,144 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacObjectServices { + static final RbacObjectServices _instance = RbacObjectServices(); + static RbacObjectServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRbacObjects() async { + List objects = []; + String path = Url.instance.getObject(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var rbac in data['data']) { + RBAC newRbac = RBAC.fromJson(rbac); + objects.add(newRbac); + } + } + } + } catch (e) { + throw e.toString(); + } + + return objects; + } + ////Add + Future> add( + {required String name, + required String? slug, + required String? short, + required int id}) async { + String path = Url.instance.getObject(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": id, + "updated_by_id": id + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + ////Update + Future> update({ + required int objectId, + required String name, + required String? slug, + required String? short, + required int? createdBy, + required int updatedBy, + }) async { + String path = "${Url.instance.getObject()}$objectId/"; + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": createdBy, + "updated_by_id": updatedBy + }; + try { + http.Response response = await Request.instance + .putRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deleteRbacRole({required int objectId}) async { + bool success = false; + String path = "${Url.instance.getObject()}$objectId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/operation_services.dart b/lib/sevices/roles/rbac_operations/operation_services.dart new file mode 100644 index 0000000..f737dc7 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/operation_services.dart @@ -0,0 +1,144 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacOperationServices { + static final RbacOperationServices _instance = RbacOperationServices(); + static RbacOperationServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRbacOperations() async { + List roles = []; + String path = Url.instance.getOperations(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var role in data['data']) { + RBAC newRole = RBAC.fromJson(role); + roles.add(newRole); + } + } + } + } catch (e) { + throw e.toString(); + } + + return roles; + } + ////Add + Future> add( + {required String name, + required String? slug, + required String? short, + required int id}) async { + String path = Url.instance.getOperations(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": id, + "updated_by_id": id + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + ////Update + Future> update({ + required int operationId, + required String name, + required String? slug, + required String? short, + required int? createdBy, + required int updatedBy, + }) async { + String path = "${Url.instance.getRbacOperations()}$operationId/"; + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": createdBy, + "updated_by_id": updatedBy + }; + try { + http.Response response = await Request.instance + .putRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future delete({required int operation}) async { + bool success = false; + String path = "${Url.instance.getRbacOperations()}$operation/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/permission_service.dart b/lib/sevices/roles/rbac_operations/permission_service.dart new file mode 100644 index 0000000..aa49ba5 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/permission_service.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacPermissionServices { + static final RbacPermissionServices _instance = RbacPermissionServices(); + static RbacPermissionServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRbacPermission() async { + List permissions = []; + String path = Url.instance.getPersmissions(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var rbac in data['data']) { + RBACPermission newRbac = RBACPermission.fromJson(rbac); + permissions.add(newRbac); + } + } + } + } catch (e) { + throw e.toString(); + } + + return permissions; + } + + + ////Add + Future> add({ + required int assignerId, + required int? objectId, + required List operationsId, + }) async { + String path = Url.instance.getPersmissions(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "object_id": objectId, + "operations": operationsId, + "assigner_user_id": assignerId + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deletePermission ({required int permissionId}) async { + bool success = false; + String path = "${Url.instance.getPersmissions()}$permissionId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/role_assignment_services.dart b/lib/sevices/roles/rbac_operations/role_assignment_services.dart new file mode 100644 index 0000000..b9d6eae --- /dev/null +++ b/lib/sevices/roles/rbac_operations/role_assignment_services.dart @@ -0,0 +1,137 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/assigned_role.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; + +import 'package:http/http.dart' as http; + +import '../../../model/profile/basic_information/primary-information.dart'; + +class RbacRoleAssignmentServices { + static final RbacRoleAssignmentServices _instance = + RbacRoleAssignmentServices(); + static RbacRoleAssignmentServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getAssignedRoles( + {required String firstname, required String lastname}) async { + List assignedRoles = []; + String path = Url.instance.getRoleAssignment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map param = { + "user__first_name__icontains": firstname, + "user__last_name__icontains": lastname + }; + 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 role in data['data']) { + AssignedRole newRole = AssignedRole.fromJson(role); + assignedRoles.add(newRole); + } + } + } + } catch (e) { + throw e.toString(); + } + return assignedRoles; + } + + Future deleteAssignedRole({required int roleId}) async { + bool success = false; + String path = "${Url.instance.getRoleAssignment()}$roleId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } + ////Add + Future> add({ + required int userId, + required int? assignerId, + required List roles, + }) async { + String path = Url.instance.getRoleAssignment(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "user_id": userId, + "roles": roles, + "assigner_user_id": assignerId, + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future searchUser( + {required int page, required String name, required String lastname}) async { + String path = Url.instance.searchUsers(); + Profile? user; + Map params = { + "profile__last_name__icontains": lastname, + "profile__first_name__icontains": name, + "page": page.toString(), + "is_paginated": "true", + }; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + }; + + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + for(var profile in data['data']) { + int websuerId = profile['webuserid']; + Profile newUser = Profile.fromJson(profile['profile']); + newUser.webuserId = websuerId; + user= newUser; + break; + } + } + + return user; + } + +} diff --git a/lib/sevices/roles/rbac_operations/role_extend_services.dart b/lib/sevices/roles/rbac_operations/role_extend_services.dart new file mode 100644 index 0000000..b5c0fc9 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/role_extend_services.dart @@ -0,0 +1,96 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/role_extend.dart'; +import 'package:unit2/model/rbac/role_under.dart'; +import 'package:http/http.dart' as http; +import '../../../utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacRoleExtendServices { + static final RbacRoleExtendServices _instance = RbacRoleExtendServices(); + static RbacRoleExtendServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRolesExtend() async { + List rolesextend = []; + String path = Url.instance.getRoleExtend(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + // try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var roleExt in data['data']) { + RolesExtend newRoleExtend = RolesExtend.fromJson(roleExt); + rolesextend.add(newRoleExtend); + } + } + } + // } catch (e) { + // throw e.toString(); + // } + return rolesextend; + } + + ////Add + Future> add({ + required int? roleId, + required List rolesExtendsId, + }) async { + String path = Url.instance.getRoleExtend(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "role_main_id": roleId, + "roles_extend": rolesExtendsId, + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future delete({required int roleExtendId}) async { + bool success = false; + String path = "${Url.instance.getRoleExtend()}$roleExtendId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/role_module_services.dart b/lib/sevices/roles/rbac_operations/role_module_services.dart new file mode 100644 index 0000000..27a0779 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/role_module_services.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; + +import 'package:unit2/model/login_data/user_info/module.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/model/rbac/role_module.dart'; +import '../../../model/rbac/rbac_rbac.dart'; +import '../../../utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacRoleModuleServices { + static final RbacRoleModuleServices _instance = + RbacRoleModuleServices(); + static RbacRoleModuleServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRoleModules() async { + List roleModules = []; + String path = Url.instance.getRoleModules(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var roleMod in data['data']) { + RoleModules newRoleMod = RoleModules.fromJson(roleMod); + roleModules.add(newRoleMod); + } + } + } + } catch (e) { + throw e.toString(); + } + return roleModules; + } + + ////Add + Future> add({ + required int assignerId, + required int? roleId, + required List moduleIds, + }) async { + String path = Url.instance.getRoleModules(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "role_id": roleId, + "modules": moduleIds, + "assigner_user_id": assignerId + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deleteRbacRoleModule({required int moduleObjectId}) async { + bool success = false; + String path = "${Url.instance.getRoleModules()}$moduleObjectId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/role_services.dart b/lib/sevices/roles/rbac_operations/role_services.dart new file mode 100644 index 0000000..08a689c --- /dev/null +++ b/lib/sevices/roles/rbac_operations/role_services.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/profile/education_services.dart'; +import 'package:http/http.dart' as http; +import 'package:unit2/utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacRoleServices { + static final RbacRoleServices _instance = RbacRoleServices(); + static RbacRoleServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRbacRoles() async { + List roles = []; + String path = Url.instance.getRbacRoles(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var role in data['data']) { + RBAC newRole = RBAC.fromJson(role); + roles.add(newRole); + } + } + } + } catch (e) { + throw e.toString(); + } + + return roles; + } + +////Add + Future> add( + {required String name, + required String? slug, + required String? short, + required int id}) async { + String path = Url.instance.getRbacRoles(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": id, + "updated_by_id": id + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + ////Update + Future> update({ + required int roleId, + required String name, + required String? slug, + required String? short, + required int? createdBy, + required int updatedBy, + }) async { + String path = "${Url.instance.getRbacRoles()}$roleId/"; + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + String? newSlug = slug?.replaceAll(" ", "-"); + Map body = { + "name": name, + "slug": newSlug?.toLowerCase(), + "shorthand": short, + "created_by_id": createdBy, + "updated_by_id": updatedBy + }; + try { + http.Response response = await Request.instance + .putRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + Future deleteRbacRole({required int roleId}) async { + bool success = false; + String path = "${Url.instance.getRbacRoles()}$roleId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/roles_under_services.dart b/lib/sevices/roles/rbac_operations/roles_under_services.dart new file mode 100644 index 0000000..719dab4 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/roles_under_services.dart @@ -0,0 +1,96 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/role_under.dart'; +import 'package:http/http.dart' as http; +import '../../../utils/request.dart'; +import '../../../utils/urls.dart'; + +class RbacRoleUnderServices { + static final RbacRoleUnderServices _instance = RbacRoleUnderServices(); + static RbacRoleUnderServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getRolesUnder() async { + List rolesUnder = []; + String path = Url.instance.getRolesUnder(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var roleUnd in data['data']) { + RolesUnder newRoleUnder = RolesUnder.fromJson(roleUnd); + rolesUnder.add(newRoleUnder); + } + } + } + } catch (e) { + throw e.toString(); + } + return rolesUnder; + } + + ////Add + Future> add({ + required int? roleId, + required List rolesId, + }) async { + String path = Url.instance.getRolesUnder(); + Map statusResponse = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + Map body = { + "role_main_id": roleId, + "roles_under": rolesId, + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, body: body, headers: headers, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } + + + Future deleteRbacRoleUnder({required int roleUnderId}) async { + bool success = false; + String path = "${Url.instance.getRolesUnder ()}$roleUnderId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + try { + http.Response response = await Request.instance + .deleteRequest(path: path, headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } +} diff --git a/lib/sevices/roles/rbac_operations/station_services.dart b/lib/sevices/roles/rbac_operations/station_services.dart new file mode 100644 index 0000000..9170583 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/station_services.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +import '../../../model/rbac/rbac_station.dart'; +import '../../../model/roles/pass_check/station_assign_area.dart'; +class RbacStationServices{ + static final RbacStationServices _instance = RbacStationServices(); + static RbacStationServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future> getStations({required int agencyId})async{ + List stations = []; + String path = Url.instance.getStation(); + Map param = {"government_agency_id":agencyId.toString()}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + 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 station in data['data']){ + RbacStation area = RbacStation.fromJson(station); + stations.add(area); + } + } + } + }catch(e){ + throw e.toString(); + } + return stations; + } +} \ No newline at end of file diff --git a/lib/sevices/roles/rbac_services.dart b/lib/sevices/roles/rbac_services.dart new file mode 100644 index 0000000..da172e4 --- /dev/null +++ b/lib/sevices/roles/rbac_services.dart @@ -0,0 +1,218 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/utils/request.dart'; + +import '../../model/profile/basic_information/primary-information.dart'; +import '../../model/rbac/new_permission.dart'; +import '../../utils/global.dart'; +import '../../utils/urls.dart'; +import 'package:http/http.dart' as http; + +class RbacServices { + static final RbacServices _instance = RbacServices(); + static RbacServices get instance => _instance; + Future> getModules() async { + List modules = []; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.getModules(); + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((var module) { + print(module); + RBAC newModule = RBAC.fromJson(module); + modules.add(newModule); + }); + } + } catch (e) { + throw e.toString(); + } + return modules; + } + + Future> getObjects() async { + List objects = []; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.getObject(); + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((var object) { + RBAC newObject = RBAC.fromJson(object); + objects.add(newObject); + }); + } + } catch (e) { + throw e.toString(); + } + return objects; + } + + Future> getRole() async { + List roles = []; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.getRoles(); + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((var role) { + RBAC newRole = RBAC.fromJson(role); + roles.add(newRole); + }); + } + } catch (e) { + throw e.toString(); + } + return roles; + } + + Future> getPermission() async { + List permissions = []; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.getPersmissions(); + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((var permission) { + RBACPermission newPermission = RBACPermission.fromJson(permission); + permissions.add(newPermission); + }); + } + } catch (e) { + throw e.toString(); + } + return permissions; + } + + Future> getOperations() async { + List operations = []; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.getOperations(); + try { + http.Response response = await Request.instance + .getRequest(path: path, headers: headers, param: {}); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((var operation) { + RBAC newOperation = RBAC.fromJson(operation); + operations.add(newOperation); + }); + } + } catch (e) { + throw e.toString(); + } + return operations; + } + + Future> searchUser( + {required int page, required String name, required String token}) async { + List users = []; + String path = Url.instance.searchUsers(); + String authtoken = "Token $token"; + Map params = { + "profile__last_name__icontains": name, + "page": page.toString(), + "is_paginated": "true", + }; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'Authorization': authtoken + }; + + http.Response response = await Request.instance + .getRequest(param: params, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + data['data'].forEach((profile) { + int websuerId = profile['webuserid']; + Profile newUsers = Profile.fromJson(profile['profile']); + newUsers.webuserId = websuerId; + users.add(newUsers); + }); + } + + return users; + } + + Future> assignRBAC( + {required int assigneeId, + required int assignerId, + required RBAC? selectedRole, + required RBAC? selectedModule, + required List permissionId, + required List newPermissions}) async { + bool success = false; + String path = Url.instance.assignRbac(); + Map responseStatus = {}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + Map body = { + "assignee_user_id": assigneeId, + "assigner_user_id": assignerId, + "role_id": selectedRole?.id, + "_new_role_name": selectedRole?.name, + "_new_role_slug": selectedRole?.slug, + "_new_role_shorthand": selectedRole?.shorthand, + "module_id": selectedModule?.id, + "_new_module_name": selectedModule?.name, + "_new_module_slug": selectedModule?.slug, + "_new_module_shorthand": selectedModule?.shorthand, + "_new_module_icon": null, + "permission_ids": permissionId, + "_new_permissions": newPermissions, + "assigned_areas": [] + }; + try { + http.Response response = await Request.instance + .postRequest(path: path, param: {}, body: body, headers: headers); + Map data = jsonDecode(response.body); + if (response.statusCode == 201) { + success = true; + String message = data['message']; + responseStatus.addAll({"success": success, "message": message}); + } else { + success = false; + String message = data['message']; + responseStatus.addAll({"success": success, "message": message}); + } + } catch (e) { + throw e.toString(); + } + + return responseStatus; + } +} diff --git a/lib/utils/app_router.dart b/lib/utils/app_router.dart index 9ea6064..27bc4a2 100644 --- a/lib/utils/app_router.dart +++ b/lib/utils/app_router.dart @@ -1,14 +1,19 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; import 'package:unit2/bloc/role/pass_check/pass_check_bloc.dart'; import 'package:unit2/bloc/sos/sos_bloc.dart'; -import 'package:unit2/screens/passo/passo_home.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/screens/passo/passo_dashboard.dart'; +import 'package:unit2/screens/passo/building_home.dart'; import 'package:unit2/screens/sos/index.dart'; -import 'package:unit2/screens/unit2/homepage.dart/components/dashboard.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/dashboard.dart'; import 'package:unit2/screens/unit2/homepage.dart/components/menu.dart'; import 'package:unit2/screens/unit2/login/login.dart'; +import 'package:unit2/screens/unit2/roles/rbac/rbac.dart'; import 'package:unit2/utils/global_context.dart'; +import '../bloc/rbac/rbac_bloc.dart'; import '../bloc/user/user_bloc.dart'; import '../screens/profile/profile.dart'; import '../screens/unit2/basic-info/basic-info.dart'; @@ -70,9 +75,19 @@ class AppRouter { ); }); case '/passo-home': - // BlocProvider.of( NavigationService.navigatorKey.currentContext!).add(LoadLoggedInUser()); - return MaterialPageRoute(builder: (_) { - return const PassoHome(); + return MaterialPageRoute(builder: (BuildContext context) { + return PassoDashBoard(); + }); + // BlocProvider.of( NavigationService.navigatorKey.currentContext!).add(LoadLoggedInUser()); + // return MaterialPageRoute(builder: (_) { + // return const PassoHome(); + // }); + case '/rbac': + return MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (_) => RbacBloc()..add(SetRbacScreen()), + child: const RBACScreen(), + ); }); default: return MaterialPageRoute(builder: (context) { diff --git a/lib/utils/request.dart b/lib/utils/request.dart index 329b3c4..d75fcdc 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.http(host, path!, param), headers: headers) + response = await get(Uri.https(host, path!, param), headers: headers) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { Fluttertoast.showToast( @@ -61,7 +61,7 @@ class Request { Map? param}) async { Response response; try { - response = await post(Uri.http(host, path!, param), + response = await post(Uri.https(host, path!, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { @@ -104,47 +104,8 @@ class Request { required Map? param}) async { Response response; try { - response =await put(Uri.http(host,path,param),headers: headers,body: jsonEncode(body)); - } on TimeoutException catch (_) { - Fluttertoast.showToast( - msg: timeoutError, - toastLength: Toast.LENGTH_LONG, - gravity: ToastGravity.BOTTOM, - backgroundColor: Colors.black, - ); - throw (timeoutError); - } on SocketException catch (_) { - Fluttertoast.showToast( - msg: timeoutError, - toastLength: Toast.LENGTH_LONG, - gravity: ToastGravity.BOTTOM, - backgroundColor: Colors.black, - ); - throw (timeoutError); - } on FormatException catch (_) { - throw const FormatException(formatError); - } on HttpException catch (_) { - throw const HttpException(httpError); - } on Error catch (e) { - debugPrint("post request error: $e"); - Fluttertoast.showToast( - msg: onError, - toastLength: Toast.LENGTH_LONG, - gravity: ToastGravity.BOTTOM, - backgroundColor: Colors.black, - ); - throw (e.toString()); - } - return response; - } - Future patch( - {required String path, - required Map? headers, - required Map? body, - required Map? param}) async { - Response response; - try { - response =await patch(path: host+path, headers: headers,body: body,param: param); + response = await put(Uri.https(host, path, param), + headers: headers, body: jsonEncode(body)); } on TimeoutException catch (_) { Fluttertoast.showToast( msg: timeoutError, @@ -178,6 +139,47 @@ class Request { return response; } + Future patch( + {required String path, + required Map? headers, + required Map? body, + required Map? param}) async { + Response response; + try { + response = await patch( + path: host + path, headers: headers, body: body, param: param); + } on TimeoutException catch (_) { + Fluttertoast.showToast( + msg: timeoutError, + toastLength: Toast.LENGTH_LONG, + gravity: ToastGravity.BOTTOM, + backgroundColor: Colors.black, + ); + throw (timeoutError); + } on SocketException catch (_) { + Fluttertoast.showToast( + msg: timeoutError, + toastLength: Toast.LENGTH_LONG, + gravity: ToastGravity.BOTTOM, + backgroundColor: Colors.black, + ); + throw (timeoutError); + } on FormatException catch (_) { + throw const FormatException(formatError); + } on HttpException catch (_) { + throw const HttpException(httpError); + } on Error catch (e) { + debugPrint("post request error: $e"); + Fluttertoast.showToast( + msg: onError, + toastLength: Toast.LENGTH_LONG, + gravity: ToastGravity.BOTTOM, + backgroundColor: Colors.black, + ); + throw (e.toString()); + } + return response; + } Future deleteRequest( {required String path, @@ -186,7 +188,7 @@ class Request { required Map? param}) async { Response response; try { - response = await delete(Uri.http(host, path, param), + response = await delete(Uri.https(host, path, param), headers: headers, body: jsonEncode(body)) .timeout(Duration(seconds: requestTimeout)); } on TimeoutException catch (_) { diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 7c94dd6..bb5a352 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -5,10 +5,10 @@ class Url { String host() { // return '192.168.10.183:3000'; - // return 'agusandelnorte.gov.ph'; + return 'agusandelnorte.gov.ph'; // return "192.168.10.219:3000"; - // return "192.168.10.241"; - return "192.168.10.221:3004"; + // return "192.168.10.241"; + // return "192.168.10.221:3004"; // return "playweb.agusandelnorte.gov.ph"; // return 'devapi.agusandelnorte.gov.ph:3004'; } @@ -220,6 +220,81 @@ class Url { return "/api/unit2_app/monitoring/pass_check/"; } + String passCheck() { + return "/api/unit2_app/monitoring/pass_check"; + } +////rbac + + String getRbacRoles() { + return "/api/account/auth/roles/"; + } + + String searchUsers() { + return "/api/hrms_app/employee_details/"; + } + + String assignRbac() { + return "/api/account/auth/rbac/"; + } + +////rbac operations + + String getRbacOperations() { + return "/api/account/auth/operations/"; + } + + String getPersmissions() { + return "/api/account/auth/permissionrbac/"; + } + + String getRoles() { + return "/api/account/auth/roles/"; + } + + String getOperations() { + return "/api/account/auth/operations/"; + } + + String getModules() { + return "/api/account/auth/modules/"; + } + + String getObject() { + return "/api/account/auth/objects/"; + } + + String getModuleObjects() { + return "/api/account/auth/moduleobject/"; + } + + String agencies() { + return "/api/jobnet_app/agencies/"; + } + + String postAgencies() { + return "/api/profile_app/agencies/"; + } + + String getRoleModules() { + return "/api/account/auth/rolemodules/"; + } + + String getRolesUnder() { + return "/api/account/auth/rolesunder/"; + } + + String getRoleExtend() { + return "/api/account/auth/rolesextend/"; + } + + String getStation() { + return "/api/hrms_app/station/"; + } + + String getRoleAssignment() { + return "api/account/auth/role_assignment/"; + } + //// location utils path String getCounties() { return "/api/jobnet_app/countries/"; @@ -244,4 +319,114 @@ class Url { String getAddressCategory() { return "/api/jobnet_app/address_categories/"; } + + ////passo path + + String additionalItems() { + return "/api/rptass_app/additional_items/"; + } + + String generalDescription() { + return "/api/rptass_app/bldgappr_gendesc/"; + } + + String landRef() { + return "/api/rptass_app/bldgappr_landref/"; + } + + String bldgLocation() { + return "/api/rptass_app/bldgappr_location/"; + } + + String propertyAppraisal() { + return "/api/rptass_app/property_appraisal/"; + } + + String propertyAssessment() { + return "/api/rptass_app/property_assessment/"; + } + + String propertyInfo() { + return "/api/rptass_app/bldgappr_details/"; + } + + String structuralMaterials() { + return "/api/rptass_app/structural_materials/"; + } + + String getBarangay() { + return "/api/rptass_app/agusan_barangay/"; + } + + String getClassComponents() { + return "/api/rptass_app/class_components/"; + } + + String getMunicipality() { + return "/api/rptass_app/agusan_city/"; + } + + String getSignatories() { + return "/api/rptass_app/signatories/"; + } + + String getUnitConstruct() { + return "/api/rptass_app/unitconstruct_values/"; + } + + String getMemoranda() { + return "/api/rptass_app/bldg_memoranda/"; + } + + String getLandOwnerInfo() { + return "/api/rptass_app/landappr_details/"; + } + + String getLandAppraisal() { + return "/api/rptass_app/landappr/"; + } + + String getLandClassification() { + return "/api/rptass_app/appraisal_classification/"; + } + + String getLandSubClassification() { + return "/api/rptass_app/appraisal_subclassification/"; + } + + String getLandPropertyLoc() { + return "/api/rptass_app/landappr_propertyloc/"; + } + + String getLandPropertyBoundaries() { + return "/api/rptass_app/landappr_prptybounderies/"; + } + + String getOtherImprovements() { + return "/api/rptass_app/landappr_plants_trees/"; + } + + String getTreesImprovements() { + return "/api/rptass_app/appraisal_improvement_price/"; + } + + String getValueAdjustmentss() { + return "/api/rptass_app/landappr_value_adjustment/"; + } + + String getTypeOfRoad() { + return "/api/rptass_app/appraisal_road_type/"; + } + + String getTypeOfLocation() { + return "/api/rptass_app/appraisal_location_type/"; + } + + String getLandPropertyAssessment() { + return "/api/rptass_app/landappr_property_assessment/"; + } + + String getLandExt() { + return '/api/rptass_app/landappr_propertyass_extn/'; + } } diff --git a/lib/widgets/passo/custom_button.dart b/lib/widgets/passo/custom_button.dart index 4823030..1a6d364 100644 --- a/lib/widgets/passo/custom_button.dart +++ b/lib/widgets/passo/custom_button.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; class CustomButton extends StatelessWidget { final VoidCallback onPressed; @@ -13,7 +14,7 @@ class CustomButton extends StatelessWidget { style: ElevatedButton.styleFrom( shape: const CircleBorder(), padding: const EdgeInsets.all(30), - backgroundColor: Colors.red, + backgroundColor: primary, foregroundColor: Colors.white, ), child: icon, diff --git a/lib/widgets/passo/custom_formBuilder_fields.dart b/lib/widgets/passo/custom_formBuilder_fields.dart index 3dc7a25..5adec45 100644 --- a/lib/widgets/passo/custom_formBuilder_fields.dart +++ b/lib/widgets/passo/custom_formBuilder_fields.dart @@ -16,18 +16,30 @@ Widget customTextField(String labelText, String hintText, String keyText) { Widget customDropDownField(String labelText, String hintText, String keyText, List dropdownItems) { + // Create a Set to keep track of unique values + Set uniqueItems = {}; + + // Iterate through the dropdownItems list to filter out duplicates + for (var item in dropdownItems) { + uniqueItems.add(item); + } + + // Convert the Set back to a List to use for DropdownMenuItem + List filteredItems = uniqueItems.toList(); + return Container( margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0), child: FormBuilderDropdown( - name: keyText, - autofocus: false, - decoration: normalTextFieldStyle(labelText, hintText), - items: dropdownItems - .map((items) => DropdownMenuItem( - value: items, - child: Text(items), - )) - .toList()), + name: keyText, + autofocus: false, + decoration: normalTextFieldStyle(labelText, hintText), + items: filteredItems + .map((item) => DropdownMenuItem( + value: item, + child: Text(item), + )) + .toList(), + ), ); } diff --git a/macos/Podfile.lock b/macos/Podfile.lock index d473e2f..9a31980 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -1,4 +1,10 @@ PODS: + - assets_audio_player (0.0.1): + - FlutterMacOS + - assets_audio_player_web (0.0.1): + - FlutterMacOS + - audioplayers_darwin (0.0.1): + - FlutterMacOS - FlutterMacOS (1.0.0) - FMDB (2.7.5): - FMDB/standard (= 2.7.5) @@ -16,6 +22,8 @@ PODS: - FlutterMacOS - platform_device_id_macos (0.0.1): - FlutterMacOS + - rive_common (0.0.1): + - FlutterMacOS - shared_preferences_foundation (0.0.1): - Flutter - FlutterMacOS @@ -24,6 +32,9 @@ PODS: - FMDB (>= 2.7.5) DEPENDENCIES: + - assets_audio_player (from `Flutter/ephemeral/.symlinks/plugins/assets_audio_player/macos`) + - assets_audio_player_web (from `Flutter/ephemeral/.symlinks/plugins/assets_audio_player_web/macos`) + - audioplayers_darwin (from `Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/macos`) - FlutterMacOS (from `Flutter/ephemeral`) - location (from `Flutter/ephemeral/.symlinks/plugins/location/macos`) - modal_progress_hud_nsn (from `Flutter/ephemeral/.symlinks/plugins/modal_progress_hud_nsn/macos`) @@ -31,6 +42,7 @@ DEPENDENCIES: - path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/macos`) - platform_device_id (from `Flutter/ephemeral/.symlinks/plugins/platform_device_id/macos`) - platform_device_id_macos (from `Flutter/ephemeral/.symlinks/plugins/platform_device_id_macos/macos`) + - rive_common (from `Flutter/ephemeral/.symlinks/plugins/rive_common/macos`) - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/macos`) - sqflite (from `Flutter/ephemeral/.symlinks/plugins/sqflite/macos`) @@ -39,6 +51,12 @@ SPEC REPOS: - FMDB EXTERNAL SOURCES: + assets_audio_player: + :path: Flutter/ephemeral/.symlinks/plugins/assets_audio_player/macos + assets_audio_player_web: + :path: Flutter/ephemeral/.symlinks/plugins/assets_audio_player_web/macos + audioplayers_darwin: + :path: Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/macos FlutterMacOS: :path: Flutter/ephemeral location: @@ -53,21 +71,27 @@ EXTERNAL SOURCES: :path: Flutter/ephemeral/.symlinks/plugins/platform_device_id/macos platform_device_id_macos: :path: Flutter/ephemeral/.symlinks/plugins/platform_device_id_macos/macos + rive_common: + :path: Flutter/ephemeral/.symlinks/plugins/rive_common/macos shared_preferences_foundation: :path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/macos sqflite: :path: Flutter/ephemeral/.symlinks/plugins/sqflite/macos SPEC CHECKSUMS: + assets_audio_player: be2578e6f11dd4d183412e97143673c3c4cb2e8a + assets_audio_player_web: 917101123b6db8f73156835c0fa266c11340ff15 + audioplayers_darwin: dcad41de4fbd0099cb3749f7ab3b0cb8f70b810c FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a location: 7cdb0665bd6577d382b0a343acdadbcb7f964775 modal_progress_hud_nsn: 8099d46c2cf9de7af8fe0a3f8f5d2aa32cf956c3 package_info_plus: 02d7a575e80f194102bef286361c6c326e4c29ce - path_provider_foundation: c68054786f1b4f3343858c1e1d0caaded73f0be9 + path_provider_foundation: eaf5b3e458fc0e5fbb9940fb09980e853fe058b8 platform_device_id: 3e414428f45df149bbbfb623e2c0ca27c545b763 platform_device_id_macos: f763bb55f088be804d61b96eb4710b8ab6598e94 - shared_preferences_foundation: 986fc17f3d3251412d18b0265f9c64113a8c2472 + rive_common: fab8476ce8352bf54152a913f393a8696d3dc98c + shared_preferences_foundation: e2dae3258e06f44cc55f49d42024fd8dd03c590c sqflite: a5789cceda41d54d23f31d6de539d65bb14100ea PODFILE CHECKSUM: 353c8bcc5d5b0994e508d035b5431cfe18c1dea7 diff --git a/pubspec.lock b/pubspec.lock index 952f940..eb84854 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -518,6 +518,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" + flutter_custom_selector: + dependency: "direct main" + description: + name: flutter_custom_selector + sha256: "4c42dcd6cc2de1574454f0fc86b324303d1bd30e4bc236d01071525342d51427" + url: "https://pub.dev" + source: hosted + version: "0.0.3" flutter_form_builder: dependency: "direct main" description: @@ -571,6 +579,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.2.0" + flutter_staggered_animations: + dependency: "direct main" + description: + name: flutter_staggered_animations + sha256: "81d3c816c9bb0dca9e8a5d5454610e21ffb068aedb2bde49d2f8d04f75538351" + url: "https://pub.dev" + source: hosted + version: "1.1.1" flutter_svg: dependency: "direct main" description: @@ -661,6 +677,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.1" + group_list_view: + dependency: "direct main" + description: + name: group_list_view + sha256: "58bfc7f4b818abff531c2b202fb18b08abfb503f1621b0e86137a4fa4b6d91dd" + url: "https://pub.dev" + source: hosted + version: "1.1.1" hive: dependency: "direct main" description: @@ -1221,6 +1245,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.3" + search_page: + dependency: "direct main" + description: + name: search_page + sha256: "675239c1ac17f999c37aea7f4c969dc2fc21b58eb61d78180ff0c16112aab49b" + url: "https://pub.dev" + source: hosted + version: "2.3.0" searchable_paginated_dropdown: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 7ff1dce..419cde3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -87,6 +87,11 @@ dependencies: shared_preferences: ^2.0.20 multiselect: ^0.1.0 multi_select_flutter: ^4.1.3 + flutter_custom_selector: ^0.0.3 + flutter_staggered_animations: ^1.1.1 + group_list_view: ^1.1.1 + search_page: ^2.3.0 + dev_dependencies: flutter_test: