diff --git a/lib/bloc/profile/references/references_bloc.dart b/lib/bloc/profile/references/references_bloc.dart index 9041de3..78f089b 100644 --- a/lib/bloc/profile/references/references_bloc.dart +++ b/lib/bloc/profile/references/references_bloc.dart @@ -1,25 +1,209 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; +import 'package:unit2/model/location/address_category.dart'; +import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/location/city.dart'; +import 'package:unit2/model/location/country.dart'; +import 'package:unit2/model/location/region.dart'; import 'package:unit2/sevices/profile/references_services.dart'; +import '../../../model/location/provinces.dart'; import '../../../model/profile/references.dart'; +import '../../../utils/location_utilities.dart'; part 'references_event.dart'; part 'references_state.dart'; - class ReferencesBloc extends Bloc { List references = []; + List globalCountries = []; + List globalRegions = []; + List globalCategories = []; + ReferencesBloc() : super(ReferencesInitial()) { - on((event, emit) async{ + on((event, emit) async { emit(ReferencesLoadingState()); - try{ - List refs = await ReferencesServices.instace.getRefences(event.profileId, event.token); + try { + if(references.isEmpty){ + List refs = await ReferencesServices.instace + .getRefences(event.profileId, event.token); references = refs; emit(ReferencesLoadedState(references: references)); - }catch(e){ + }else{ + emit(ReferencesLoadedState(references: references)); + } + } catch (e) { ReferencesErrorState(message: e.toString()); } +////SHOW FORM FOR ADDING REFERENCES + }); + on((event, emit) async { + emit(ReferencesLoadingState()); + try { + if (globalRegions.isEmpty) { + List regions = await LocationUtils.instance.getRegions(); + globalRegions = regions; + } + if (globalCountries.isEmpty) { + List countries = await LocationUtils.instance.getCountries(); + globalCountries = countries; + } + if (globalCategories.isEmpty) { + List categories = + await LocationUtils.instance.getAddressCategory(); + globalCategories = categories; + } + emit(AddReferenceState( + countries: globalCountries, + regions: globalRegions, + categories: globalCategories)); + } catch (e) { + emit(ReferencesErrorState(message: e.toString())); + } + ////SHOW EDIT FORM + }); + on((event, emit) async { + Region? selectedRegion; + Province? selectedProvince; + CityMunicipality? selectedCity; + AddressCategory? selectedCategory; + Country selectedCountry; + Barangay? selectedBarangay; + try { + if (globalRegions.isEmpty) { + List regions = await LocationUtils.instance.getRegions(); + globalRegions = regions; + } + if (globalCountries.isEmpty) { + List countries = await LocationUtils.instance.getCountries(); + globalCountries = countries; + } + if (globalCategories.isEmpty) { + List categories = + await LocationUtils.instance.getAddressCategory(); + globalCategories = categories; + } +//// checck if address is overseas + bool overseas = + event.personalReference.address!.country!.id! != 175 ? true : false; + selectedCategory = globalCategories.firstWhere((AddressCategory element) => event.personalReference.address!.addressCategory!.id == element.id); + ////if address is not overseas set initial values for address + if (!overseas) { + selectedRegion = globalRegions.firstWhere((Region element) => + event.personalReference.address!.cityMunicipality!.province! + .region!.code == + element.code); + List provinces = await LocationUtils.instance + .getProvinces(regionCode: selectedRegion.code.toString()); + selectedProvince = provinces.firstWhere((Province province) => + event.personalReference.address!.cityMunicipality!.province! + .code == + province.code); + List cities = await LocationUtils.instance + .getCities(code: selectedProvince.code!); + selectedCity = cities.firstWhere((CityMunicipality city) => + event.personalReference.address!.cityMunicipality!.code == + city.code); + List barangays = await LocationUtils.instance.getBarangay(code: selectedCity.code.toString()); + selectedBarangay = barangays.firstWhere((Barangay barangay)=>event.personalReference.address!.barangay!.code == barangay.code); + emit(EditReferenceState( + selectedRegion: selectedRegion, + ref: event.personalReference, + countries: globalCountries, + regions: globalRegions, + barangays: barangays, + categories: globalCategories, + isOverseas: overseas, + provinces: provinces, + selectedProvince: selectedProvince, + cities: cities, + selectedCity: selectedCity, + selectedCategory: selectedCategory, + selectedBarangay: selectedBarangay + )); + } else { + //// if address is overseas set initial value for country + selectedCountry = globalCountries.firstWhere((Country element) => event.personalReference.address!.country!.id == element.id); + emit(EditReferenceState( + selectedCountry: selectedCountry, + selectedCategory: selectedCategory, + selectedRegion: null, + ref: event.personalReference, + countries: globalCountries, + regions: globalRegions, + categories: globalCategories, + isOverseas: overseas)); + } + } catch (e) { + emit(ReferencesErrorState(message: e.toString())); + } + }); + //// CALL THE ERROR STATE EVEN T + on((event, emit) async { + emit(const ReferencesErrorState( + message: "Something went wrong. Please try again")); + //// ADD REFERENCES EVENT + });on((event,emit)async{ + emit(ReferencesLoadingState()); + Map status =await ReferencesServices.instace.update(ref: event.reference, token: event.token, profileId: event.profileId); + if (status['success']) { + PersonalReference ref = PersonalReference.fromJson(status['data']); + references.removeWhere((PersonalReference element)=>element.id == event.reference.id); + references.add(ref); + emit( + ReferenceEditedState(personalRefs: references, response: status)); + } else { + emit( + ReferenceEditedState(personalRefs: references, response: status)); + } + + }); + +//// add reference event + on((event, emit) async { + try { + emit(ReferencesLoadingState()); + Map status = await ReferencesServices.instace + .addReference( + ref: event.reference, + token: event.token, + profileId: event.profileId); + if (status['success']) { + PersonalReference ref = PersonalReference.fromJson(status['data']); + references.add(ref); + emit( + ReferencesAddedState(personalRefs: references, response: status)); + } else { + emit( + ReferencesAddedState(personalRefs: references, response: status)); + } + } catch (e) { + emit(ReferencesErrorState(message: e.toString())); + } + }); + ////LOAD REFERENCE + on((event, emit) { + emit(ReferencesLoadingState()); + references = event.references; + emit(ReferencesLoadedState(references: references)); + + }); + ////DELETE REFERENCE + on((event, emit) async { + try { + final bool success = await ReferencesServices.instace.delete( + profileId: event.profileId, token: event.token, id: event.refId); + if (success) { + event.references.removeWhere( + (PersonalReference element) => element.id == event.refId); + references = event.references; + emit(DeleteReferenceState(references: references, success: success)); + } else { + emit(DeleteReferenceState(references: references, success: success)); + } + } catch (e) { + emit(ReferencesErrorState(message: e.toString())); + } }); } } diff --git a/lib/bloc/profile/references/references_event.dart b/lib/bloc/profile/references/references_event.dart index 4b6737a..584bebb 100644 --- a/lib/bloc/profile/references/references_event.dart +++ b/lib/bloc/profile/references/references_event.dart @@ -14,3 +14,56 @@ class GetReferences extends ReferencesEvent{ @override List get props => [profileId,token]; } + +class ShowAddReferenceForm extends ReferencesEvent{ + +} + +class ShowEditReferenceForm extends ReferencesEvent{ + final PersonalReference personalReference; + const ShowEditReferenceForm({required this.personalReference}); + @override + List get props => [personalReference]; + +} +class CallErrorState extends ReferencesEvent{ + +} + + +class AddReference extends ReferencesEvent{ + final PersonalReference reference; + final String token; + final int profileId; + const AddReference({required this.profileId, required this.reference,required this.token}); + @override + List get props => [profileId,token,reference]; +} +class EditReference extends ReferencesEvent{ + final PersonalReference reference; + final String token; + final int profileId; + const EditReference({required this.profileId, required this.reference,required this.token}); + @override + List get props => [profileId,token,reference]; +} + +class DeleteReference extends ReferencesEvent{ + final Listreferences; + final int profileId; + final String token; + final int refId; + const DeleteReference({required this.profileId, required this.refId, required this.references, required this.token}); + @override + List get props => [profileId,token,refId,references]; +} + +class LoadReferences extends ReferencesEvent{ + final List references; + const LoadReferences({required this.references}); + @override + List get props => [references]; +} + + + diff --git a/lib/bloc/profile/references/references_state.dart b/lib/bloc/profile/references/references_state.dart index 13c2284..207a3fe 100644 --- a/lib/bloc/profile/references/references_state.dart +++ b/lib/bloc/profile/references/references_state.dart @@ -2,28 +2,94 @@ part of 'references_bloc.dart'; abstract class ReferencesState extends Equatable { const ReferencesState(); - + @override List get props => []; } class ReferencesInitial extends ReferencesState {} -class ReferencesLoadedState extends ReferencesState{ +class ReferencesLoadedState extends ReferencesState { final List references; const ReferencesLoadedState({required this.references}); - + @override List get props => [references]; - } -class ReferencesErrorState extends ReferencesState{ + +class ReferencesErrorState extends ReferencesState { final String message; const ReferencesErrorState({required this.message}); - + @override List get props => [message]; } -class ReferencesLoadingState extends ReferencesState{ - + +class ReferencesLoadingState extends ReferencesState {} + +class ReferencesAddedState extends ReferencesState { + final List personalRefs; + final Map response; + const ReferencesAddedState( + {required this.personalRefs, required this.response}); + @override + List get props => [personalRefs, response]; +} +class ReferenceEditedState extends ReferencesState { + final List personalRefs; + final Map response; + const ReferenceEditedState( + {required this.personalRefs, required this.response}); + @override + List get props => [personalRefs, response]; +} + +class EditReferenceState extends ReferencesState { + final List regions; + final List countries; + final List categories; + final List? provinces; + final List? cities; + final List? barangays; + final PersonalReference ref; + final bool isOverseas; + final Region? selectedRegion; + final Province? selectedProvince; + final CityMunicipality? selectedCity; + final AddressCategory selectedCategory; + final Barangay? selectedBarangay; + final Country? selectedCountry; + const EditReferenceState( + { this.barangays, + this.selectedBarangay, + required this.selectedCategory, + this.cities, + this.selectedCity, + this.provinces, + this.selectedProvince, + this.selectedRegion, + this.selectedCountry, + required this.isOverseas, + required this.ref, + required this.categories, + required this.countries, + required this.regions}); + @override + List get props => [regions, countries, categories, isOverseas]; +} + +class AddReferenceState extends ReferencesState { + final List regions; + final List countries; + final List categories; + const AddReferenceState( + {required this.categories, + required this.countries, + required this.regions}); +} + +class DeleteReferenceState extends ReferencesState { + final List references; + final bool success; + const DeleteReferenceState({required this.references, required this.success}); } diff --git a/lib/screens/profile/components/eligibility/add_modal.dart b/lib/screens/profile/components/eligibility/add_modal.dart index 7e7e9fc..561c76b 100644 --- a/lib/screens/profile/components/eligibility/add_modal.dart +++ b/lib/screens/profile/components/eligibility/add_modal.dart @@ -32,7 +32,6 @@ class AddEligibilityScreen extends StatefulWidget { class _AddEligibilityScreenState extends State { final formKey = GlobalKey(); - final provinceKey = GlobalKey(); bool? overseas; DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); Region? selectedRegion; @@ -52,12 +51,12 @@ class _AddEligibilityScreenState extends State { String? license; @override Widget build(BuildContext context) { - //USERBLOC + ////USERBLOC return BlocBuilder( builder: (context, state) { - //LOGGED IN USER STATE + ////LOGGED IN USER STATE if (state is UserLoggedIn) { - //PROFIILE BLOC + ////PROFIILE BLOC token = state.userData!.user!.login!.token; profileId = state.userData!.user!.login!.user!.profileId.toString(); return BlocBuilder( @@ -69,7 +68,7 @@ class _AddEligibilityScreenState extends State { return false; }, builder: (context, state) { - //EDIT ELIGIBILITY STATE + ////ADD ELIGIBILITY STATE if (state is AddEligibilityState) { return ProgressHUD( child: Center( @@ -82,7 +81,7 @@ class _AddEligibilityScreenState extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - //ELIGIBILITIES DROPDOWN + ////ELIGIBILITIES DROPDOWN FormBuilderDropdown( onChanged: (Eligibility? eligibility) { selectedEligibility = eligibility; @@ -109,7 +108,7 @@ class _AddEligibilityScreenState extends State { width: screenWidth, child: Row( children: [ - //LICENSE NUMBER + ////LICENSE NUMBER Flexible( flex: 1, child: FormBuilderTextField( @@ -125,7 +124,7 @@ class _AddEligibilityScreenState extends State { const SizedBox( width: 12, ), - //RATING + ////RATING Flexible( flex: 1, child: FormBuilderTextField( @@ -149,7 +148,7 @@ class _AddEligibilityScreenState extends State { width: screenWidth, child: Row( children: [ - //EXAM DATE + ////EXAM DATE Flexible( flex: 1, child: DateTimePicker( @@ -175,7 +174,7 @@ class _AddEligibilityScreenState extends State { const SizedBox( width: 12, ), - //VALIDITY DATE + ////VALIDITY DATE Flexible( flex: 1, child: DateTimePicker( @@ -211,7 +210,7 @@ class _AddEligibilityScreenState extends State { const SizedBox( height: 12, ), - //OVERSEAS ADDRESS SWITCH + ////OVERSEAS ADDRESS SWITCH Column( children: [ FormBuilderSwitch( @@ -231,15 +230,12 @@ class _AddEligibilityScreenState extends State { const SizedBox( height: 20, ), - //COUNTRY DROPDOWN + ////COUNTRY DROPDOWN SizedBox( child: overseas == true ? FormBuilderDropdown( initialValue: null, - validator: (value) => - value == null - ? 'required' - : null, + validator: FormBuilderValidators.required(errorText: "This field is required"), items: state.countries.map< DropdownMenuItem< Country>>( @@ -264,16 +260,14 @@ class _AddEligibilityScreenState extends State { ) : Column( children: [ - //REGION DROPDOWN + ////REGION DROPDOWN FormBuilderDropdown< Region?>( autovalidateMode: AutovalidateMode .onUserInteraction, - validator: (value) => - value == null - ? 'required' - : null, + validator: FormBuilderValidators.required(errorText: "This field is required"), + //// region onchange onChanged: (Region? region) async { setState(() { @@ -304,7 +298,7 @@ class _AddEligibilityScreenState extends State { const SizedBox( height: 20, ), - //PROVINCE DROPDOWN + ////PROVINCE DROPDOWN SizedBox( height: 70, child: ModalProgressHUD( @@ -358,7 +352,7 @@ class _AddEligibilityScreenState extends State { ), ), - // CityMunicipalities dropdown + //// CityMunicipalities dropdown SizedBox( height: 70, child: ModalProgressHUD( diff --git a/lib/screens/profile/components/eligibility_screen.dart b/lib/screens/profile/components/eligibility_screen.dart index fec9dc2..96e43d5 100644 --- a/lib/screens/profile/components/eligibility_screen.dart +++ b/lib/screens/profile/components/eligibility_screen.dart @@ -86,7 +86,7 @@ class EligibiltyScreen extends StatelessWidget { final progress = ProgressHUD.of(context); progress!.dismiss(); } - //DELETED STATE + ////DELETED STATE if (state is DeletedState) { if (state.success) { successAlert(context, "Deletion Successfull", @@ -105,7 +105,7 @@ class EligibiltyScreen extends StatelessWidget { }); } } - //ADDED STATE + ////ADDED STATE if (state is EligibilityAddedState) { if (state.response['success']) { successAlert(context, "Adding Successfull!", @@ -124,7 +124,7 @@ class EligibiltyScreen extends StatelessWidget { }); } } - //UPDATED STATE + ////UPDATED STATE if (state is EligibilityEditedState) { if (state.response['success']) { successAlert(context, "Update Successfull!", diff --git a/lib/screens/profile/components/reference/add_modal.dart b/lib/screens/profile/components/reference/add_modal.dart new file mode 100644 index 0000000..0060bbc --- /dev/null +++ b/lib/screens/profile/components/reference/add_modal.dart @@ -0,0 +1,548 @@ +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:form_builder_validators/form_builder_validators.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; +import 'package:unit2/bloc/profile/profile_bloc.dart'; +import 'package:unit2/bloc/profile/references/references_bloc.dart'; +import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/location/address_category.dart'; +import 'package:unit2/model/location/barangay.dart'; +import 'package:unit2/model/profile/references.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import '../../../../model/location/city.dart'; +import '../../../../model/location/country.dart'; +import '../../../../model/location/provinces.dart'; +import '../../../../model/location/region.dart'; +import '../../../../theme-data.dart/colors.dart'; +import '../../../../utils/location_utilities.dart'; +import '../../../../utils/text_container.dart'; + +class AddReferenceScreen extends StatefulWidget { + const AddReferenceScreen({super.key}); + + @override + State createState() => _AddReferenceScreenState(); +} + +class _AddReferenceScreenState extends State { + final formKey = GlobalKey(); + String? token; + String? profileId; + bool provinceCall = false; + bool cityCall = false; + bool barangayCall = false; + bool overseas = false; + List? provinces; + List? citymuns; + List? barangays; + List category = ['Permanent', "Residential", "Birthplace"]; + ////seletected + Region? selectedRegion; + Province? selectedProvince; + CityMunicipality? selectedMunicipality; + Barangay? selectedBarangay; + Country? selectedCountry; + AddressCategory? selectedCategory; + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is UserLoggedIn) { + token = state.userData!.user!.login!.token; + profileId = state.userData!.user!.login!.user!.profileId.toString(); + return BlocBuilder( + builder: (context, state) { + if (state is ProfileLoaded) { + return BlocBuilder( + builder: (context, state) { + if (state is AddReferenceState) { + return ProgressHUD( + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 25, horizontal: 18), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const SizedBox(height: 25), + Row( + children: [ + ////LAST NAME + Flexible( + flex: 1, + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Last name *", "Last name *"), + name: "lastname", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + width: 5, + ), + ////FIRST NAME + Flexible( + flex: 1, + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "First name *", "First name *"), + name: "firstname", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + ], + ), + const SizedBox( + height: 8, + ), + Row( + children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Middle name *", "Midlle name *"), + name: "middlename", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + width: 5, + ), + ////CATEGORY + Flexible( + flex: 1, + child: FormBuilderDropdown< + AddressCategory>( + name: 'category', + validator: + FormBuilderValidators.required( + errorText: ""), + decoration: normalTextFieldStyle( + "Category", "Category"), + items: state.categories.map< + DropdownMenuItem< + AddressCategory>>( + (AddressCategory cat) { + return DropdownMenuItem< + AddressCategory>( + value: cat, + child: Text(cat.name!), + ); + }).toList(), + onChanged: (value) { + setState(() { + selectedCategory = value; + }); + }, + ), + ), + ], + ), + const SizedBox( + height: 8, + ), + + ////OVERSEAS ADDRESS + FormBuilderSwitch( + initialValue: overseas, + activeColor: second, + onChanged: (value) { + setState(() { + overseas = value!; + }); + }, + decoration: normalTextFieldStyle("", ''), + name: 'overseas', + title: const Text("Overseas Address?"), + ), + SizedBox( + height: overseas == true ? 8 : 0, + ), + SizedBox( + child: overseas == false + ? Column( + children: [ + const SizedBox( + height: 12, + ), + ////REGION DROPDOWN + FormBuilderDropdown( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + onChanged: + (Region? region) async { + setState(() { + provinceCall = true; + }); + selectedRegion = region; + getProvinces(); + }, + initialValue: null, + decoration: + normalTextFieldStyle( + "Region*", "Region"), + name: 'region', + items: state.regions.map< + DropdownMenuItem< + Region>>( + (Region region) { + return DropdownMenuItem< + Region>( + value: region, + child: Text( + region.description!)); + }).toList(), + ), + const SizedBox( + height: 8, + ), + //// PROVINCE DROPDOWN + SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.transparent, + inAsyncCall: provinceCall, + child: DropdownButtonFormField< + Province?>( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, + value: selectedProvince, + onChanged: + (Province? province) { + setState(() { + cityCall = true; + }); + selectedProvince = + province; + getCities(); + }, + items: provinces == null + ? [] + : provinces!.map< + DropdownMenuItem< + Province>>( + (Province + province) { + return DropdownMenuItem( + value: + province, + child: + FittedBox( + child: Text( + province + .description!), + )); + }).toList(), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), + ), + ), + ////CITY MUNICIPALITY + SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: cityCall, + child: + DropdownButtonFormField< + CityMunicipality>( + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, + onChanged: + (CityMunicipality? + city) { + setState(() { + barangayCall = true; + }); + selectedMunicipality = + city; + getBarangays(); + }, + decoration: + normalTextFieldStyle( + "Municipality*", + "Municipality"), + value: selectedMunicipality, + items: citymuns == null + ? [] + : citymuns!.map< + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { + return DropdownMenuItem( + value: c, + child: Text(c + .description!)); + }).toList(), + ), + ), + ), + //// BARANGAY + SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: barangayCall, + child: + DropdownButtonFormField< + Barangay>( + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, + onChanged: + (Barangay? baragay) { + selectedBarangay = + baragay; + }, + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), + value: selectedBarangay, + items: barangays == null + ? [] + : barangays!.map< + DropdownMenuItem< + Barangay>>( + (Barangay + barangay) { + return DropdownMenuItem( + value: barangay, + child: Text(barangay + .description!)); + }).toList(), + ), + ), + ), + ], + ) + //// COUNTRY DROPDOWN + : SizedBox( + height: 60, + child: FormBuilderDropdown( + initialValue: null, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + items: state.countries.map< + DropdownMenuItem< + Country>>( + (Country country) { + return DropdownMenuItem< + Country>( + value: country, + child: FittedBox( + child: Text( + country.name!))); + }).toList(), + name: 'country', + decoration: normalTextFieldStyle( + "Country*", "Country"), + onChanged: (Country? value) { + selectedCountry = value; + }, + ), + ), + ), + + FormBuilderTextField( + name: "mobile", + decoration: normalTextFieldStyle( + "Tel./Mobile *", "Tel./Mobile"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const Expanded( + child: SizedBox(), + ), + SizedBox( + width: double.infinity, + height: 60, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + child: const Text(submit), + onPressed: () { + + PersonalReference? personalReference; + if (formKey.currentState! + .saveAndValidate()) { + String lastname = formKey + .currentState!.value['lastname']; + String firstname = formKey + .currentState!.value['firstname']; + String middlename = formKey + .currentState! + .value['middlename']; + String mobile = formKey + .currentState!.value['mobile']; + + + Region? region = selectedRegion; + Province? province = Province( + code: selectedProvince?.code, + description: + selectedProvince?.description, + region: region, + psgcCode: + selectedProvince?.psgcCode, + shortname: + selectedProvince?.shortname); + CityMunicipality? city = + CityMunicipality( + code: selectedMunicipality + ?.code, + description: + selectedMunicipality + ?.description, + province: province, + psgcCode: selectedMunicipality + ?.psgcCode, + zipcode: selectedMunicipality + ?.zipcode); + + Address address = Address( + id: null, + addressCategory: selectedCategory, + country: selectedCountry, + barangay: selectedBarangay, + addressClass: null, + cityMunicipality: city); + + if (selectedCountry != null) { + personalReference = + PersonalReference( + id: null, + address: Address( + id: null, + addressCategory: + selectedCategory, + country: selectedCountry, + barangay: null, + cityMunicipality: null, + addressClass: null), + lastName: lastname, + contactNo: mobile, + firstName: firstname, + middleName: middlename); + } else { + personalReference = + PersonalReference( + id: null, + address: address, + lastName: lastname, + contactNo: mobile, + firstName: firstname, + middleName: middlename); + } + + context.read().add( + AddReference( + profileId: + int.parse(profileId!), + reference: personalReference, + token: token!)); + } + }, + ), + ), + const SizedBox( + height: 20, + ), + ], + )), + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + + Future getProvinces() async { + try { + List newProvinces = await LocationUtils.instance + .getProvinces(regionCode: selectedRegion!.code.toString()); + setState(() { + provinces = newProvinces; + selectedProvince = provinces![0]; + provinceCall = false; + cityCall = true; + getCities(); + }); + } catch (e) { + context.read().add(CallErrorState()); + } + } + + Future getCities() async { + try { + List newCities = await LocationUtils.instance + .getCities(code: selectedProvince!.code.toString()); + citymuns = newCities; + setState(() { + selectedMunicipality = newCities[0]; + cityCall = false; + barangayCall = true; + getBarangays(); + }); + } catch (e) { + context.read().add(CallErrorState()); + } + } + + Future getBarangays() async { + try { + List newBarangays = await LocationUtils.instance + .getBarangay(code: selectedMunicipality!.code.toString()); + barangays = newBarangays; + setState(() { + selectedBarangay = newBarangays[0]; + barangayCall = false; + }); + } catch (e) { + context.read().add(CallErrorState()); + } + } +} diff --git a/lib/screens/profile/components/reference/edit_modal.dart b/lib/screens/profile/components/reference/edit_modal.dart new file mode 100644 index 0000000..6c02990 --- /dev/null +++ b/lib/screens/profile/components/reference/edit_modal.dart @@ -0,0 +1,637 @@ +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:form_builder_validators/form_builder_validators.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; +import '../../../../bloc/profile/profile_bloc.dart'; +import '../../../../bloc/profile/references/references_bloc.dart'; +import '../../../../bloc/user/user_bloc.dart'; +import '../../../../model/location/address_category.dart'; +import '../../../../model/location/barangay.dart'; +import '../../../../model/location/city.dart'; +import '../../../../model/location/country.dart'; +import '../../../../model/location/provinces.dart'; +import '../../../../model/location/region.dart'; +import '../../../../model/profile/references.dart'; +import '../../../../theme-data.dart/btn-style.dart'; +import '../../../../theme-data.dart/colors.dart'; +import '../../../../theme-data.dart/form-style.dart'; +import '../../../../utils/location_utilities.dart'; +import '../../../../utils/text_container.dart'; + +class EditReferenceScreen extends StatefulWidget { + const EditReferenceScreen({super.key}); + + @override + State createState() => _EditReferenceScreenState(); +} + +class _EditReferenceScreenState extends State { + final formKey = GlobalKey(); + String? token; + String? profileId; + bool provinceCall = false; + bool cityCall = false; + bool barangayCall = false; + bool overseas = false; + List? provinces; + List? citymuns; + List? barangays; + ////seletected + Region? selectedRegion; + Province? selectedProvince; + CityMunicipality? selectedMunicipality; + Barangay? selectedBarangay; + Country? selectedCountry; + AddressCategory? selectedCategory; + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is UserLoggedIn) { + token = state.userData!.user!.login!.token; + profileId = state.userData!.user!.login!.user!.profileId.toString(); + return BlocBuilder( + builder: (context, state) { + if (state is ProfileLoaded) { + return BlocBuilder( + buildWhen: (previous, current) => false, + builder: (context, state) { + if (state is EditReferenceState) { + overseas = state.isOverseas; + selectedCategory = state.selectedCategory; + ////if not overseas address + //// set initial values + if (!overseas) { + selectedRegion = state.selectedRegion; + provinces = state.provinces; + selectedProvince = state.selectedProvince; + citymuns = state.cities; + selectedMunicipality = state.selectedCity; + barangays = state.barangays; + selectedBarangay = state.selectedBarangay; + } else { + selectedCountry = state.selectedCountry; + } + + return ProgressHUD( + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 25, horizontal: 18), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const SizedBox(height: 25), + Row( + children: [ + ////LAST NAME + Flexible( + flex: 1, + child: FormBuilderTextField( + initialValue: state.ref.lastName, + decoration: normalTextFieldStyle( + "Last name *", "Last name *"), + name: "lastname", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + width: 5, + ), + ////FIRST NAME + Flexible( + flex: 1, + child: FormBuilderTextField( + initialValue: state.ref.firstName, + decoration: normalTextFieldStyle( + "First name *", "First name *"), + name: "firstname", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + ], + ), + const SizedBox( + height: 8, + ), + Row( + children: [ + Flexible( + flex: 1, + child: FormBuilderTextField( + initialValue: state.ref.middleName, + decoration: normalTextFieldStyle( + "Middle name *", "Midlle name *"), + name: "middlename", + validator: + FormBuilderValidators.required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + width: 5, + ), + ////CATEGORY + Flexible( + flex: 1, + child: FormBuilderDropdown< + AddressCategory>( + name: 'category', + validator: + FormBuilderValidators.required( + errorText: ""), + decoration: normalTextFieldStyle( + "Category", "Category"), + items: state.categories.map< + DropdownMenuItem< + AddressCategory>>( + (AddressCategory cat) { + return DropdownMenuItem< + AddressCategory>( + value: cat, + child: Text(cat.name!), + ); + }).toList(), + initialValue: selectedCategory, + onChanged: (value) { + selectedCategory = value; + }, + ), + ), + ], + ), + const SizedBox( + height: 8, + ), + + ////OVERSEAS ADDRESS + StatefulBuilder(builder: (context, setState) { + return Column( + children: [ + FormBuilderSwitch( + initialValue: overseas, + activeColor: second, + onChanged: (value) { + setState(() { + overseas = value!; + }); + }, + decoration: + normalTextFieldStyle("", ''), + name: 'overseas', + title: + const Text("Overseas Address?"), + ), + SizedBox( + height: overseas == true ? 8 : 0, + ), + SizedBox( + child: overseas == false + ? Column( + children: [ + const SizedBox( + height: 12, + ), + ////REGION DROPDOWN + DropdownButtonFormField< + Region?>( + isExpanded: true, + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + onChanged: (Region? + region) async { + setState(() { + provinceCall = true; + + selectedRegion = + region; + }); + //// GET PROVINCES + provinces = await LocationUtils + .instance + .getProvinces( + regionCode: + selectedRegion! + .code + .toString()); + selectedProvince = + provinces![0]; + setState(() { + provinceCall = false; + cityCall = true; + }); + ////GET CITY MUNICIPALITY + citymuns = await LocationUtils + .instance + .getCities( + code: + selectedProvince! + .code!); + selectedMunicipality = + citymuns![0]; + setState(() { + cityCall = false; + barangayCall = true; + }); + //// GET BARANGAYS + barangays = + await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality! + .code!); + selectedBarangay = + barangays![0]; + setState(() { + barangayCall = false; + }); + }, + value: selectedRegion, + decoration: + normalTextFieldStyle( + "Region*", + "Region"), + items: state.regions.map< + DropdownMenuItem< + Region>>( + (Region region) { + return DropdownMenuItem< + Region>( + value: region, + child: Text(region + .description!)); + }).toList(), + ), + const SizedBox( + height: 8, + ), + //// PROVINCE DROPDOWN + SizedBox( + height: 60, + child: ModalProgressHUD( + color: + Colors.transparent, + inAsyncCall: + provinceCall, + child: DropdownButtonFormField< + Province?>( + autovalidateMode: + AutovalidateMode + .onUserInteraction, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, + onChanged: (Province? + province) async { + selectedProvince = + province; + setState(() { + cityCall = true; + }); + //// GET CITIES + citymuns = await LocationUtils + .instance + .getCities( + code: selectedProvince! + .code!); + selectedMunicipality = + citymuns![0]; + setState(() { + cityCall = + false; + barangayCall = + true; + }); + //// GET BARANGAY + barangays = await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality! + .code!); + selectedBarangay = + barangays![0]; + setState(() { + barangayCall = + false; + }); + }, + value: + selectedProvince, + items: provinces == + null + ? [] + : provinces!.map< + DropdownMenuItem< + Province>>((Province + province) { + return DropdownMenuItem( + value: + province, + child: + FittedBox( + child: + Text(province.description!), + )); + }).toList(), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), + ), + ), + ////CITY MUNICIPALITY + SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: cityCall, + child: + DropdownButtonFormField< + CityMunicipality>( + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, + onChanged: + (CityMunicipality? + city) async { + setState(() { + barangayCall = + true; + }); + selectedMunicipality = + city; + //// GET BARANGAYS + barangays = await LocationUtils + .instance + .getBarangay( + code: selectedMunicipality! + .code!); + selectedBarangay = + barangays![0]; + setState(() { + barangayCall = + false; + }); + }, + decoration: + normalTextFieldStyle( + "Municipality*", + "Municipality"), + value: + selectedMunicipality, + items: citymuns == + null + ? [] + : citymuns!.map< + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { + return DropdownMenuItem( + value: c, + child: Text( + c.description!)); + }).toList(), + ), + ), + ), + //// BARANGAY + SizedBox( + height: 60, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: + barangayCall, + child: + DropdownButtonFormField< + Barangay>( + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, + onChanged: (Barangay? + baragay) { + selectedBarangay = + baragay; + }, + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), + value: + selectedBarangay, + items: barangays == + null + ? [] + : barangays!.map< + DropdownMenuItem< + Barangay>>((Barangay + barangay) { + return DropdownMenuItem( + value: + barangay, + child: Text( + barangay + .description!)); + }).toList(), + ), + ), + ), + ], + ) + //// COUNTRY DROPDOWN + : SizedBox( + height: 60, + child: + DropdownButtonFormField< + Country>( + isExpanded: true, + value: selectedCountry, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + items: state.countries.map< + DropdownMenuItem< + Country>>( + (Country country) { + return DropdownMenuItem< + Country>( + value: country, + child: FittedBox( + child: Text( + country + .name!))); + }).toList(), + + decoration: + normalTextFieldStyle( + "Country*", + "Country"), + //// country dropdown + onChanged: + (Country? value) { + selectedCountry = value; + }, + ), + ), + ), + ], + ); + }), + + FormBuilderTextField( + initialValue: state.ref.contactNo, + name: "mobile", + decoration: normalTextFieldStyle( + "Tel./Mobile *", "Tel./Mobile"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const Expanded( + child: SizedBox(), + ), + SizedBox( + width: double.infinity, + height: 60, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + child: const Text(submit), + onPressed: () { + PersonalReference? personalReference; + if (formKey.currentState! + .saveAndValidate()) { + String lastname = formKey + .currentState!.value['lastname']; + String firstname = formKey + .currentState!.value['firstname']; + String middlename = formKey + .currentState! + .value['middlename']; + String mobile = formKey + .currentState!.value['mobile']; + + Region? region = selectedRegion; + Province? province = Province( + code: selectedProvince?.code, + description: + selectedProvince?.description, + region: region, + psgcCode: + selectedProvince?.psgcCode, + shortname: + selectedProvince?.shortname); + CityMunicipality? city = + CityMunicipality( + code: selectedMunicipality + ?.code, + description: + selectedMunicipality + ?.description, + province: province, + psgcCode: selectedMunicipality + ?.psgcCode, + zipcode: selectedMunicipality + ?.zipcode); + + ////IF IS OVERSEAS + if (overseas) { + personalReference = + PersonalReference( + id: state.ref.id, + address: Address( + id: state + .ref.address!.id, + addressCategory: + selectedCategory, + country: + selectedCountry, + barangay: null, + cityMunicipality: null, + addressClass: null), + lastName: lastname, + contactNo: mobile, + firstName: firstname, + middleName: middlename); + } else { + //// IF NOT OVERSEAS + personalReference = + PersonalReference( + id: state.ref.id, + address: Address( + id: state + .ref.address!.id, + addressCategory: + selectedCategory, + country: Country( + id: 175, + code: null, + name: null), + barangay: + selectedBarangay, + cityMunicipality: city, + addressClass: state + .ref + .address + ?.addressClass), + lastName: lastname, + contactNo: mobile, + firstName: firstname, + middleName: middlename); + } + + context.read().add( + EditReference( + profileId: + int.parse(profileId!), + reference: personalReference, + token: token!)); + } + }, + ), + ), + const SizedBox( + height: 20, + ), + ], + )), + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/profile/components/references_screen.dart b/lib/screens/profile/components/references_screen.dart index 1849d9b..b7eb2f4 100644 --- a/lib/screens/profile/components/references_screen.dart +++ b/lib/screens/profile/components/references_screen.dart @@ -1,40 +1,60 @@ +import 'package:app_popup_menu/app_popup_menu.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_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/references.dart'; +import 'package:unit2/screens/profile/components/reference/add_modal.dart'; +import 'package:unit2/screens/profile/components/reference/edit_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/Leadings/close_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; import '../../../bloc/profile/references/references_bloc.dart'; +import '../../../utils/alerts.dart'; class ReferencesScreen extends StatelessWidget { const ReferencesScreen({super.key}); + @override Widget build(BuildContext context) { + int? profileId; + String? token; return Scaffold( appBar: AppBar( - title: const Text(referencesScreenTitle), + title: context.watch().state is AddReferenceState?const Text("Add Personal Reference"):context.watch().state is EditReferenceState?const Text("Edit Personal Reference"):const Text("Personal References"), centerTitle: true, backgroundColor: primary, - actions: [AddLeading(onPressed: () {})], + ////if state is adding or editing state show close button + actions: (context.watch().state is AddReferenceState || context.watch().state is EditReferenceState)? + [ + //// close button + CloseLeading(onPressed: (){ + context.read().add(GetReferences(profileId: profileId!, token: token!)); + }), + ]: + //// if state is loaded state show add button + context.watch().state is ReferencesLoadedState?[ + AddLeading(onPressed: (){ + context.read().add(ShowAddReferenceForm()); + }), + ]:[] ), body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle( - color: Colors.white), + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocBuilder( builder: (context, state) { //userbloc if (state is UserLoggedIn) { + token = state.userData!.user!.login!.token; + profileId = state.userData!.user!.login!.user!.profileId; return BlocBuilder( builder: (context, state) { //profilebloc @@ -42,13 +62,82 @@ class ReferencesScreen extends StatelessWidget { return BlocConsumer( //listener listener: (context, state) { - if(state is ReferencesLoadingState){ - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); + if (state is ReferencesLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); } - if(state is ReferencesLoadedState || state is ReferencesErrorState){ - final progress = ProgressHUD.of(context); - progress!.dismiss(); + if (state is ReferencesLoadedState || + state is AddReferenceState || + state is ReferencesErrorState || + state is DeleteReferenceState || + state is ReferencesAddedState || + state is EditReferenceState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + ////ADDED STATE + if (state is ReferencesAddedState) { + if (state.response['success']) { + successAlert(context, "Adding Successfull!", + state.response['message'], () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.personalRefs)); + }); + } else { + errorAlert(context, "Adding Failed", + "Something went wrong. Please try again.", + () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.personalRefs)); + }); + } + } + ////EDIT REFERENCE STATE + if (state is ReferenceEditedState) { + if (state.response['success']) { + successAlert(context, "Update Successfull!", + state.response['message'], () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.personalRefs)); + }); + } else { + errorAlert(context, "Update Failed", + "Something went wrong. Please try again.", + () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.personalRefs)); + }); + } + } + + ////DELETED STATE + if (state is DeleteReferenceState) { + if (state.success) { + successAlert(context, "Deletion Successfull", + "Eligibility has been deleted successfully", + () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.references)); + }); + } else { + errorAlert(context, "Deletion Failed", + "Error deleting eligibility", () { + Navigator.of(context).pop(); + context.read().add( + LoadReferences( + references: state.references)); + }); + } } }, //builder @@ -56,72 +145,147 @@ class ReferencesScreen extends StatelessWidget { //references bloc if (state is ReferencesLoadedState) { if (state.references.isNotEmpty) { - return ListView.builder( - padding: - const EdgeInsets.symmetric(vertical: 8, horizontal: 10), - itemCount: state.references.length, - itemBuilder: (BuildContext context, int index) { - String fullname = - "${state.references[index].firstName} ${state.references[index].middleName} ${state.references[index].lastName}"; - String addres = - "${state.references[index].address!.cityMunicipality!.description}, ${state.references[index].address!.cityMunicipality!.province!.description}, ${state.references[0].address!.cityMunicipality!.province!.region!.description}"; - String mobile = state.references[index].contactNo.toString(); - return Column( - children: [ - Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, vertical: 8), - decoration: box1(), - child: Row( - children: [ - Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(fullname, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500)), - const Divider(), - const SizedBox( - height: 5, - ), - Text(addres, - style: Theme.of(context) - .textTheme - .titleSmall! - .copyWith( - fontWeight: FontWeight.w500)), - const SizedBox( - height: 8, - ), - Text("${mobileOrPhone.toUpperCase()} : $mobile", - style: Theme.of(context) - .textTheme - .labelMedium!), - ], - ), - ), - IconButton( - onPressed: () {}, - icon: const Icon( - Icons.more_vert, - color: Colors.grey, - )) - ], - ), - ), - const SizedBox( - height: 5, - ), - ], - ); - }); + return ListView.builder( + padding: const EdgeInsets.symmetric( + vertical: 8, horizontal: 10), + itemCount: state.references.length, + itemBuilder: + (BuildContext context, int index) { + String fullname = + "${state.references[index].firstName} ${state.references[index].middleName} ${state.references[index].lastName}"; + String addres = state.references[index] + .address!.country?.id != + 175 + ? "COUNTRY: ${state.references[index].address!.country!.name!.toUpperCase()}" + : "${state.references[index].address?.cityMunicipality?.description}, ${state.references[index].address?.cityMunicipality?.province?.description}, ${state.references[index].address?.cityMunicipality?.province?.region?.description}"; + + String mobile = state + .references[index].contactNo + .toString(); + return Column( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + decoration: box1(), + child: Row( + children: [ + Expanded( + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(fullname.toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight + .w500)), + const Divider(), + const SizedBox( + height: 5, + ), + Text(addres, + style: Theme.of(context) + .textTheme + .titleSmall! + .copyWith( + fontWeight: + FontWeight + .w500)), + const SizedBox( + height: 8, + ), + Text( + "${mobileOrPhone.toUpperCase()} : $mobile", + style: Theme.of(context) + .textTheme + .labelMedium!), + ], + ), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + final progress = + ProgressHUD.of(context); + progress!.showWithText( + "Loading..."); + ////delete eligibilty-= = = = = = = = =>> + if (value == 2) { + confirmAlert(context, () { + context + .read< + ReferencesBloc>() + .add(DeleteReference( + profileId: + profileId!, + refId: state + .references[ + index] + .id!, + references: state + .references, + token: token!)); + }, "Delete?", + "Confirm Delete?"); + } + if (value == 1) { + ////edit reference-= = = = = = = = =>> + context + .read() + .add(ShowEditReferenceForm( + personalReference: + state.references[ + index])); + } + }, + menuItems: [ + popMenuItem( + text: "Edit", + value: 1, + icon: Icons.edit), + popMenuItem( + text: "Delete", + value: 2, + icon: Icons.delete), + popMenuItem( + text: "Attachment", + value: 3, + icon: FontAwesome.attach) + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ) + ], + ), + ), + const SizedBox( + height: 5, + ), + ], + ); + }); } } + if (state is AddReferenceState) { + return const AddReferenceScreen(); + } + if (state is EditReferenceState) { + return const EditReferenceScreen(); + } + if (state is ReferencesErrorState) { + return SomethingWentWrong( + message: state.message, onpressed: () {}); + } return Container(); }, ); @@ -135,5 +299,23 @@ class ReferencesScreen extends StatelessWidget { ), )); } -} + PopupMenuItem popMenuItem({String? text, int? value, IconData? icon}) { + return PopupMenuItem( + value: value, + child: Row( + children: [ + Icon( + icon, + ), + const SizedBox( + width: 10, + ), + Text( + text!, + ), + ], + ), + ); + } +} diff --git a/lib/sevices/profile/references_services.dart b/lib/sevices/profile/references_services.dart index f425f0d..ee215ba 100644 --- a/lib/sevices/profile/references_services.dart +++ b/lib/sevices/profile/references_services.dart @@ -16,7 +16,7 @@ class ReferencesServices{ List references = []; String authToken = "Token $token"; - String path = "${Url.instance.getRefences()}$profileId/"; + String path = "${Url.instance.reference()}$profileId/"; Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': authToken @@ -37,4 +37,100 @@ List references = []; } return references; } -} \ No newline at end of file + Future>addReference({required PersonalReference ref, required String token, required int profileId})async{ + String authToken = "Token $token"; + String path = "${Url.instance.reference()}$profileId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'Authorization': authToken + }; + Map responseStatus ={}; + bool overseas = ref.address!.country !=null?true:false; + Map body = { + "first_name": ref.firstName, + "middle_name": ref.middleName, + "last_name": ref.lastName, + "contact_no":ref.contactNo, + "_addressCatId": ref.address!.addressCategory!.id, + "_areaClass": "Village", + "_citymunCode": overseas?null: ref.address?.cityMunicipality?.code, + "_brgyCode": overseas?null:ref.address?.barangay?.code, + "_countryId": overseas?ref.address!.country!.id:175 + }; + try{ + http.Response response = await Request.instance.postRequest(path: path,body: body,param: {},headers: headers); + if(response.statusCode == 201){ + Map data = jsonDecode(response.body); + responseStatus = data; + }else{ + responseStatus.addAll({'success':false}); + } + return responseStatus; + }catch(e){ + throw e.toString(); + } +} +Future> update({required PersonalReference ref,required String token, required int profileId})async{ + String authToken = "Token $token"; + String path = "${Url.instance.reference()}$profileId/"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'Authorization': authToken + }; + Map responseStatus ={}; + bool overseas = ref.address!.country!.id != 175; + Map body = { + "id":ref.id, + "related_person_id": profileId, + "first_name": ref.firstName, + "middle_name": ref.middleName, + "last_name": ref.lastName, + "contact_no":ref.contactNo, + "_addressCatId": ref.address!.addressCategory!.id, + "_areaClass": "Village", + "_citymunCode": overseas?null: ref.address?.cityMunicipality?.code, + "_brgyCode": overseas?null:ref.address?.barangay?.code, + "_countryId": overseas?ref.address!.country!.id:175 + }; + // try{ + http.Response response = await Request.instance.putRequest(path: path,body: body,param: {},headers: headers); + if(response.statusCode == 200){ + Map data = jsonDecode(response.body); + responseStatus = data; + }else{ + responseStatus.addAll({'success':false}); + } + return responseStatus; + // }catch(e){ + // throw e.toString(); + // } +} + +Futuredelete({required int profileId, required String token, required int id })async{ + bool? success; + String authtoken = "Token $token"; + String path = "${Url.instance.reference()}$profileId/"; + Map params = {"force_mode": "true"}; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'Authorization': authtoken + }; + try{ + http.Response response = await Request.instance.deleteRequest(path: path, headers: headers, body: {"id":id}, param: params); + if(response.statusCode == 200){ + Map data = jsonDecode(response.body); + success=data['success']; + }else{ + success = false; + } + return success!; + }catch(e){ + throw e.toString(); + } + +} + +} + + + diff --git a/lib/sevices/profile/work_history_services.dart b/lib/sevices/profile/work_history_services.dart index bb43770..92906f7 100644 --- a/lib/sevices/profile/work_history_services.dart +++ b/lib/sevices/profile/work_history_services.dart @@ -24,7 +24,7 @@ class WorkHistoryService { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': authToken }; - String path = Url.instance.getWorkHistories() + profileId.toString(); + String path = Url.instance.workhistory() + profileId.toString(); try { http.Response response = await Request.instance .getRequest(path: path, headers: headers, param: {}); @@ -75,7 +75,7 @@ class WorkHistoryService { bool? success; Map params = {"force_mode": "true"}; String authToken = "Token $token"; - String path = "${Url.instance.deleteWorkHistory()}$profileId/"; + String path = "${Url.instance.workhistory()}$profileId/"; Map body = { "id": work.id, "position_id": work.position!.id, @@ -136,7 +136,7 @@ class WorkHistoryService { Future> update({required WorkHistory oldWorkHistory, required WorkHistory newWorkHistory, required String token, required String profileId})async{ Map? statusResponse={}; String authtoken = "Token $token"; - String path = '${Url.instance.updateWorkHistories()}$profileId/'; + String path = '${Url.instance.workhistory()}$profileId/'; Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': authtoken @@ -176,7 +176,7 @@ class WorkHistoryService { //Add work history Future>add({required WorkHistory workHistory, required String token, required int profileId , required bool isPrivate})async{ String authtoken = "Token $token"; - String path = '${Url.instance.addWorkHistory()}$profileId/'; + String path = '${Url.instance.workhistory()}$profileId/'; Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': authtoken diff --git a/lib/utils/location_utilities.dart b/lib/utils/location_utilities.dart index a5678f6..e52c10b 100644 --- a/lib/utils/location_utilities.dart +++ b/lib/utils/location_utilities.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'package:unit2/model/location/address_category.dart'; +import 'package:unit2/model/location/barangay.dart'; import 'package:unit2/model/location/city.dart'; import 'package:unit2/model/location/country.dart'; import 'package:http/http.dart' as http; @@ -8,95 +10,133 @@ import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; import '../model/location/region.dart'; + class LocationUtils { static final LocationUtils _instance = LocationUtils(); static LocationUtils get instance => _instance; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + }; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - }; - - Future>getCountries()async{ - List countries=[]; + Future> getCountries() async { + List countries = []; String path = Url.instance.getCounties(); - - - // try{ - http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers); - if(response.statusCode == 200){ - Map data = jsonDecode(response.body); - if(data['data'] != null){ - data['data'].forEach((var country){ - Country newCOuntry = Country.fromJson(country); - countries.add(newCOuntry); - }); - } - } - // }catch(e){ - // throw(e.toString()); - // } - return countries; - } - - -Future>getRegions()async{ - List regions=[]; - String path = Url.instance.getRegions(); - - - // try{ - http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers); - if(response.statusCode == 200){ - Map data = jsonDecode(response.body); - if(data['data'] != null){ - data['data'].forEach((var region){ - Region newRegion = Region.fromJson(region); - regions.add(newRegion); - }); - } - } - // }catch(e){ - // throw(e.toString()); - // } - return regions; - } - - Future>getProvinces({required String regionCode})async{ - List provinces = []; - String path = Url.instance.getProvinces()+regionCode; try{ - http.Response response = await Request.instance.getRequest(path: path,param:{},headers: headers); + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + if (response.statusCode == 200) { Map data = jsonDecode(response.body); - if(data['data'] != null){ - data['data'].forEach((var province){ + if (data['data'] != null) { + data['data'].forEach((var country) { + Country newCOuntry = Country.fromJson(country); + countries.add(newCOuntry); + }); + } + } + }catch(e){ + throw(e.toString()); + } + return countries; + } + + Future> getRegions() async { + List regions = []; + String path = Url.instance.getRegions(); + + try{ + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var region) { + Region newRegion = Region.fromJson(region); + regions.add(newRegion); + }); + } + } + }catch(e){ + throw(e.toString()); + } + return regions; + } + + Future> getProvinces({required String regionCode}) async { + List provinces = []; + String path = Url.instance.getProvinces() + regionCode; + + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var province) { Province newProvince = Province.fromJson(province); provinces.add(newProvince); }); } - - }catch(e){ - throw(e.toString()); + } catch (e) { + throw (e.toString()); } - return provinces; + return provinces; } - Future>getCities({required String code})async{ + Future> getCities({required String code}) async { List cities = []; - String path = Url.instance.getCities()+code; - try{ - http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers); + String path = Url.instance.getCities() + code; + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); Map data = jsonDecode(response.body); - if(data['data'] != null){ - data['data'].forEach((var city){ + if (data['data'] != null) { + data['data'].forEach((var city) { CityMunicipality cityMun = CityMunicipality.fromJson(city); cities.add(cityMun); }); } - }catch(e){ - throw(e.toString()); + } catch (e) { + throw (e.toString()); } return cities; } -} \ No newline at end of file + + Future> getBarangay({required String code}) async { + List barangays = []; + String path = Url.instance.getBarangays() + code; + try { + http.Response response = await Request.instance + .getRequest(path: path, param: {}, headers: headers); + Map data = jsonDecode(response.body); + if (data['data'] != null) { + data['data'].forEach((var city) { + Barangay barangay = Barangay.fromJson(city); + barangays.add(barangay); + }); + } + } catch (e) { + throw (e.toString()); + } + return barangays; + } + Future>getAddressCategory()async{ + List categories = []; + String path = Url.instance.getAddressCategory(); + try{ + http.Response response = await Request.instance.getRequest(path: path,param: {},headers:headers ); + Map data = jsonDecode(response.body); + if(data['data'] != null){ + data['data'].forEach((var cat){ + categories.add(AddressCategory.fromJson(cat)); + }); + } + categories; + return categories; + }catch(e){ + throw e.toString(); + } + } + + +} diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index e04f450..a7972ea 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -42,7 +42,7 @@ String updateEligibility(){ return "/api/jobnet_app/profile/pds/eligibility/"; } //// work history paths -String getWorkHistories(){ +String workhistory(){ return "/api/jobnet_app/profile/pds/work/"; } String getPositions(){ @@ -51,19 +51,13 @@ String getPositions(){ String getAgencies(){ return "/api/jobnet_app/agencies/"; } -String updateWorkHistories(){ - return "/api/jobnet_app/profile/pds/work/"; -} -String addWorkHistory(){ - return "/api/jobnet_app/profile/pds/work/"; -} + + String getAgencyCategory(){ return "api/jobnet_app/agency_categories/"; } -String deleteWorkHistory(){ - return "/api/jobnet_app/profile/pds/work/"; -} + ////educational background paths String getEducationalBackgrounds(){ @@ -77,7 +71,7 @@ String getLearningAndDevelopments(){ } //// references paths -String getRefences(){ +String reference(){ return "/api/jobnet_app/profile/pds/personal_reference/"; } @@ -106,6 +100,7 @@ String getFamilies(){ return "/api/jobnet_app/profile/pds/family/"; } + // location utils path String getCounties(){ return "/api/jobnet_app/countries/"; @@ -119,4 +114,10 @@ String getFamilies(){ String getCities(){ return "/api/web_app/location/citymun/"; } + String getBarangays(){ + return "/api/web_app/location/barangay/"; + } + String getAddressCategory(){ + return "/api/jobnet_app/address_categories/"; + } } \ No newline at end of file