diff --git a/.gitignore b/.gitignore index 24476c5..434eff9 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,7 @@ migrate_working_dir/ .pub-cache/ .pub/ /build/ +pubspeck.lock # Symbolication related app.*.symbols diff --git a/android/app/build.gradle b/android/app/build.gradle index be52da5..975896b 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -26,7 +26,7 @@ apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { - compileSdkVersion flutter.compileSdkVersion + compileSdkVersion 34 ndkVersion "25.1.8937393" compileOptions { @@ -44,9 +44,10 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.unit2" + applicationId "com.app.rpass" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. + minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c3002df..4cf7608 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,12 +1,16 @@ + package="com.example.unit2" + > + + + +android:usesCleartextTraffic="true" +android:requestLegacyExternalStorage="true"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/bloc/offline/offline_bloc/offline_bloc.dart b/lib/bloc/offline/offline_bloc/offline_bloc.dart new file mode 100644 index 0000000..1fe480f --- /dev/null +++ b/lib/bloc/offline/offline_bloc/offline_bloc.dart @@ -0,0 +1,28 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/utils/global.dart'; + +import '../../../model/offline/offlane_modules.dart'; +import '../../../model/offline/offline_profile.dart'; + +part 'offline_event.dart'; +part 'offline_state.dart'; + +class OfflineBloc extends Bloc { + OfflineBloc() : super(OfflineInitial()) { + on((event, emit) async { + try { + List modules = await OFFLINE!.get('modules'); + List offlineModules = []; + for (var module in modules) { + offlineModules.add(module); + } + OfflineProfile offlineProfile = await OFFLINE!.get('offline_profile'); + emit(OfflineModeState( + offlineModules: offlineModules, offlineProfile: offlineProfile)); + } catch (e) { + emit(OfflineErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/offline/offline_bloc/offline_event.dart b/lib/bloc/offline/offline_bloc/offline_event.dart new file mode 100644 index 0000000..3eb32be --- /dev/null +++ b/lib/bloc/offline/offline_bloc/offline_event.dart @@ -0,0 +1,13 @@ +part of 'offline_bloc.dart'; + +class OfflineEvent extends Equatable { + const OfflineEvent(); + + @override + List get props => []; +} + +class SwitchOffline extends OfflineEvent { + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_bloc/offline_state.dart b/lib/bloc/offline/offline_bloc/offline_state.dart new file mode 100644 index 0000000..2862cf8 --- /dev/null +++ b/lib/bloc/offline/offline_bloc/offline_state.dart @@ -0,0 +1,26 @@ +part of 'offline_bloc.dart'; + +class OfflineState extends Equatable { + const OfflineState(); + + @override + List get props => []; +} + +class OfflineInitial extends OfflineState {} + +class OfflineModeState extends OfflineState { + final OfflineProfile offlineProfile; + final List offlineModules; + const OfflineModeState( + {required this.offlineModules, required this.offlineProfile}); + @override + List get props => [offlineProfile, offlineModules]; +} + +class OfflineLoadingState extends OfflineState {} + +class OfflineErrorState extends OfflineState { + final String message; + const OfflineErrorState({required this.message}); +} diff --git a/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart new file mode 100644 index 0000000..ec30376 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart @@ -0,0 +1,35 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/barangay.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'barangay_admin_event.dart'; +part 'barangay_admin_state.dart'; + +class BarangayAdminBloc extends Bloc { + BarangayAdminBloc() : super(BarangayAdminInitial()) { + List brgy = []; + on((event, emit) async { + brgy = await SQLServices.instance.readAllBarangay(); + + emit(BarangayLoaded(brgy: brgy)); + }); + on((event, emit) async { + brgy = await SQLServices.instance + .readBrgyInSelectedMunicipality(event.cityCode); + + emit(BarangayLoaded(brgy: brgy)); + }); + on((event, emit) async { + await SQLServices.instance.createBarangay( + Brgy( + id: event.id, + barangayId: event.barangayId, + barangayCode: event.barangayCode, + cityCode: event.cityCode, + barangayDescription: event.barangayDescription), + ); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_event.dart b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_event.dart new file mode 100644 index 0000000..757f835 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_event.dart @@ -0,0 +1,48 @@ +part of 'barangay_admin_bloc.dart'; + +class BarangayAdminEvent extends Equatable { + const BarangayAdminEvent(); + + @override + List get props => []; +} + +class AddBarangay extends BarangayAdminEvent { + final int id; + final int barangayId; + final String barangayCode; + final String cityCode; + final String barangayDescription; + + const AddBarangay({ + required this.id, + required this.barangayId, + required this.barangayCode, + required this.cityCode, + required this.barangayDescription, + }); + + @override + List get props => [ + id, + barangayId, + barangayCode, + cityCode, + barangayDescription, + ]; +} + +class LoadBarangay extends BarangayAdminEvent { + const LoadBarangay(); + + @override + List get props => []; +} + +class LoadBarangayInMunicipality extends BarangayAdminEvent { + final String cityCode; + const LoadBarangayInMunicipality({required this.cityCode}); + + @override + List get props => [cityCode]; +} diff --git a/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_state.dart b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_state.dart new file mode 100644 index 0000000..766e360 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_state.dart @@ -0,0 +1,21 @@ +part of 'barangay_admin_bloc.dart'; + +class BarangayAdminState extends Equatable { + const BarangayAdminState(); + + @override + List get props => []; +} + +class BarangayAdminInitial extends BarangayAdminState { + @override + List get props => []; +} + +class BarangayLoaded extends BarangayAdminState { + final List brgy; + + const BarangayLoaded({required this.brgy}); + @override + List get props => [brgy]; +} diff --git a/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart new file mode 100644 index 0000000..b0e27c3 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart @@ -0,0 +1,42 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/class_components _offline.dart'; +import '../../../../../model/passo/class_components.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'class_components_admin_event.dart'; +part 'class_components_admin_state.dart'; + +class ClassComponentsAdminBloc + extends Bloc { + ClassComponentsAdminBloc() : super(ClassComponentsAdminInitial()) { + List classes = []; + on((event, emit) async { + classes = await SQLServices.instance.readAllClassComponents(); + + emit(ClassComponentsAdminLoaded(classes: classes)); + }); + on((event, emit) async { + await SQLServices.instance.createClassComponents( + ClassComponentsOffline( + componentName: event.componentName, + minBaseUnitvalPercent: event.minBaseUnitvalPercent, + maxBaseUnitvalPercent: event.maxBaseUnitvalPercent, + minUnitvalSqrmtr: event.minUnitvalSqrmtr, + maxUnitvalSqrmtr: event.maxUnitvalSqrmtr, + minAddBaseunitval: event.minAddBaseunitval, + maxAddBaseunitval: event.maxAddBaseunitval, + minDeductBaserate: event.minDeductBaserate, + maxDeductBaserate: event.maxDeductBaserate, + minLinearMeter: event.minLinearMeter, + maxLinearMeter: event.maxLinearMeter, + minSpacing: event.minSpacing, + maxSpacing: event.maxSpacing, + roughFinish: event.roughFinish, + highFinish: event.highFinish, + withoutBucc: event.withoutBucc), + ); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_event.dart b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_event.dart new file mode 100644 index 0000000..800b85c --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_event.dart @@ -0,0 +1,73 @@ +part of 'class_components_admin_bloc.dart'; + +class ClassComponentsAdminEvent extends Equatable { + const ClassComponentsAdminEvent(); + + @override + List get props => []; +} + +class AddClassComponents extends ClassComponentsAdminEvent { + final String componentName; + final String minBaseUnitvalPercent; + final String maxBaseUnitvalPercent; + final String minUnitvalSqrmtr; + final String maxUnitvalSqrmtr; + final String minAddBaseunitval; + final String maxAddBaseunitval; + final String minDeductBaserate; + final String maxDeductBaserate; + final String minLinearMeter; + final String maxLinearMeter; + final String minSpacing; + final String maxSpacing; + final String roughFinish; + final String highFinish; + final int withoutBucc; + + const AddClassComponents({ + required this.componentName, + required this.minBaseUnitvalPercent, + required this.maxBaseUnitvalPercent, + required this.minUnitvalSqrmtr, + required this.maxUnitvalSqrmtr, + required this.minAddBaseunitval, + required this.maxAddBaseunitval, + required this.minDeductBaserate, + required this.maxDeductBaserate, + required this.minLinearMeter, + required this.maxLinearMeter, + required this.minSpacing, + required this.maxSpacing, + required this.roughFinish, + required this.highFinish, + required this.withoutBucc, + }); + + @override + List get props => [ + componentName, + minBaseUnitvalPercent, + maxBaseUnitvalPercent, + minUnitvalSqrmtr, + maxUnitvalSqrmtr, + minAddBaseunitval, + maxAddBaseunitval, + minDeductBaserate, + maxDeductBaserate, + minLinearMeter, + maxLinearMeter, + minSpacing, + maxSpacing, + roughFinish, + highFinish, + withoutBucc, + ]; +} + +class LoadClassComponents extends ClassComponentsAdminEvent { + const LoadClassComponents(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_state.dart b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_state.dart new file mode 100644 index 0000000..b08f829 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_state.dart @@ -0,0 +1,21 @@ +part of 'class_components_admin_bloc.dart'; + +class ClassComponentsAdminState extends Equatable { + const ClassComponentsAdminState(); + + @override + List get props => []; +} + +class ClassComponentsAdminInitial extends ClassComponentsAdminState { + @override + List get props => []; +} + +class ClassComponentsAdminLoaded extends ClassComponentsAdminState { + final List classes; + + const ClassComponentsAdminLoaded({required this.classes}); + @override + List get props => [classes]; +} diff --git a/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart new file mode 100644 index 0000000..ecd13a9 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart @@ -0,0 +1,27 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_classification.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_classification_event.dart'; +part 'land_classification_state.dart'; + +class LandClassificationBloc + extends Bloc { + LandClassificationBloc() : super(LandClassificationInitial()) { + List landClassification = []; + on((event, emit) async { + landClassification = + await SQLServices.instance.readAllLandClassification(); + + emit(LandClassificationLoaded(landClassification: landClassification)); + }); + on((event, emit) async { + await SQLServices.instance.createLandClassification(LandClassification( + id: event.id, + classificationCode: event.classificationCode, + description: event.description)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_event.dart b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_event.dart new file mode 100644 index 0000000..0a07ffe --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_event.dart @@ -0,0 +1,34 @@ +part of 'land_classification_bloc.dart'; + +class LandClassificationEvent extends Equatable { + const LandClassificationEvent(); + + @override + List get props => []; +} + +class AddLandClassification extends LandClassificationEvent { + final int id; + final String classificationCode; + final String description; + + const AddLandClassification({ + required this.id, + required this.classificationCode, + required this.description, + }); + + @override + List get props => [ + id, + classificationCode, + description, + ]; +} + +class LoadLandClassification extends LandClassificationEvent { + const LoadLandClassification(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_state.dart b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_state.dart new file mode 100644 index 0000000..52d8921 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_classification/land_classification_state.dart @@ -0,0 +1,18 @@ +part of 'land_classification_bloc.dart'; + +class LandClassificationState extends Equatable { + const LandClassificationState(); + + @override + List get props => []; +} + +class LandClassificationInitial extends LandClassificationState {} + +class LandClassificationLoaded extends LandClassificationState { + final List landClassification; + + const LandClassificationLoaded({required this.landClassification}); + @override + List get props => [landClassification]; +} diff --git a/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart new file mode 100644 index 0000000..bf884b3 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart @@ -0,0 +1,39 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_subclassification.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_subclassification_event.dart'; +part 'land_subclassification_state.dart'; + +class LandSubclassificationBloc + extends Bloc { + LandSubclassificationBloc() : super(LandSubclassificationInitial()) { + List landSubClassification = []; + on((event, emit) async { + landSubClassification = + await SQLServices.instance.readAllLandSubClassification(); + + emit(LandSubClassificationLoaded( + landSubClassification: landSubClassification)); + }); + on((event, emit) async { + landSubClassification = await SQLServices.instance + .readSpecificLandSubClassification(event.cityCode, event.classCode); + + emit(LandSubClassificationLoaded( + landSubClassification: landSubClassification)); + }); + on((event, emit) async { + await SQLServices.instance.createLandSubClassification( + LandSubClassification( + id: event.id, + classificationId: event.classificationId, + cityCode: event.cityCode, + subclassCode: event.subclassCode, + subclassDescription: event.subclassDescription, + baseUnitMarketval: event.baseUnitMarketval)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_event.dart b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_event.dart new file mode 100644 index 0000000..ff1c2c0 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_event.dart @@ -0,0 +1,54 @@ +part of 'land_subclassification_bloc.dart'; + +class LandSubclassificationEvent extends Equatable { + const LandSubclassificationEvent(); + + @override + List get props => []; +} + +class AddLandSubClassification extends LandSubclassificationEvent { + final int id; + final int classificationId; + final String cityCode; + final String subclassCode; + final String subclassDescription; + final String baseUnitMarketval; + + const AddLandSubClassification({ + required this.id, + required this.classificationId, + required this.cityCode, + required this.subclassCode, + required this.subclassDescription, + required this.baseUnitMarketval, + }); + + @override + List get props => [ + id, + classificationId, + cityCode, + subclassCode, + subclassDescription, + baseUnitMarketval, + ]; +} + +class LoadLandSubClassification extends LandSubclassificationEvent { + const LoadLandSubClassification(); + + @override + List get props => []; +} + +class LoadSpecificLandSubClassification extends LandSubclassificationEvent { + final String cityCode; + final int classCode; + + const LoadSpecificLandSubClassification( + {required this.cityCode, required this.classCode}); + + @override + List get props => [cityCode, classCode]; +} diff --git a/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_state.dart b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_state.dart new file mode 100644 index 0000000..69cadc8 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_state.dart @@ -0,0 +1,18 @@ +part of 'land_subclassification_bloc.dart'; + +class LandSubclassificationState extends Equatable { + const LandSubclassificationState(); + + @override + List get props => []; +} + +class LandSubclassificationInitial extends LandSubclassificationState {} + +class LandSubClassificationLoaded extends LandSubclassificationState { + final List landSubClassification; + + const LandSubClassificationLoaded({required this.landSubClassification}); + @override + List get props => [landSubClassification]; +} diff --git a/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart new file mode 100644 index 0000000..4fc10ab --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart @@ -0,0 +1,27 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/memoranda.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'memoranda_admin_event.dart'; +part 'memoranda_admin_state.dart'; + +class MemorandaAdminBloc + extends Bloc { + MemorandaAdminBloc() : super(MemorandaAdminInitial()) { + List memo = []; + on((event, emit) async { + memo = await SQLServices.instance.readAllMemoranda(); + + emit(MemorandaLoaded(memo: memo)); + }); + on((event, emit) async { + await SQLServices.instance.createMemoranda(Memoranda( + id: event.id, + code: event.code, + memoranda: event.memoranda, + )); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_event.dart b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_event.dart new file mode 100644 index 0000000..b44a2de --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_event.dart @@ -0,0 +1,34 @@ +part of 'memoranda_admin_bloc.dart'; + +class MemorandaAdminEvent extends Equatable { + const MemorandaAdminEvent(); + + @override + List get props => []; +} + +class AddMemoranda extends MemorandaAdminEvent { + final int id; + final String code; + final String memoranda; + + const AddMemoranda({ + required this.id, + required this.code, + required this.memoranda, + }); + + @override + List get props => [ + id, + code, + memoranda, + ]; +} + +class LoadMemoranda extends MemorandaAdminEvent { + const LoadMemoranda(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_state.dart b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_state.dart new file mode 100644 index 0000000..eff98cd --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_state.dart @@ -0,0 +1,21 @@ +part of 'memoranda_admin_bloc.dart'; + +class MemorandaAdminState extends Equatable { + const MemorandaAdminState(); + + @override + List get props => []; +} + +class MemorandaAdminInitial extends MemorandaAdminState { + @override + List get props => []; +} + +class MemorandaLoaded extends MemorandaAdminState { + final List memo; + + const MemorandaLoaded({required this.memo}); + @override + List get props => [memo]; +} diff --git a/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart new file mode 100644 index 0000000..e340f5e --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart @@ -0,0 +1,52 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart'; + +part 'municipalities_admin_event.dart'; +part 'municipalities_admin_state.dart'; + +class MunicipalitiesAdminBloc + extends Bloc { + MunicipalitiesAdminBloc() : super(MunicipalitiesAdminInitial()) { + List city = []; + on((event, emit) async { + city = await SQLServices.instance.readAllMunicipalities(); + + emit(MunicipalitiesLoaded(city: city)); + }); + // on((event, emit) async { + // try { + // final result = + // await MunicipalityAdminApiServices.instance.fetch(); + + // // Assuming result is a List of JSON objects, convert them to City objects. + // final cities = + // result.map((json) => City.fromJson(json)).toList(); + + // // Loop through the list of City objects and insert them into the local database. + // for (City city in cities) { + // print(city.cityDescription); + // print(city.cityCode); + // await SQLServices.instance.createMunicipalities(city); + // } + // } catch (e) { + // // Handle any errors that might occur during the API call or database insertion. + // print("Error: $e"); + // } + + // // emit(const LoadMunicipalities()); + // }); + on((event, emit) async { + await SQLServices.instance.createMunicipalities( + City( + id: event.id, + cityCode: event.cityCode, + cityDescription: event.cityDescription, + ), + ); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_event.dart b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_event.dart new file mode 100644 index 0000000..769f5fe --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_event.dart @@ -0,0 +1,41 @@ +part of 'municipalities_admin_bloc.dart'; + +class MunicipalitiesAdminEvent extends Equatable { + const MunicipalitiesAdminEvent(); + + @override + List get props => []; +} + +class AddMunicipality extends MunicipalitiesAdminEvent { + final int id; + final String cityCode; + final String cityDescription; + + const AddMunicipality({ + required this.id, + required this.cityCode, + required this.cityDescription, + }); + + @override + List get props => [ + id, + cityCode, + cityDescription, + ]; +} + +class LoadMunicipalities extends MunicipalitiesAdminEvent { + const LoadMunicipalities(); + + @override + List get props => []; +} + +class MunicipalitiesSyncToDevice extends MunicipalitiesAdminEvent { + const MunicipalitiesSyncToDevice(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_state.dart b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_state.dart new file mode 100644 index 0000000..1910161 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_state.dart @@ -0,0 +1,21 @@ +part of 'municipalities_admin_bloc.dart'; + +class MunicipalitiesAdminState extends Equatable { + const MunicipalitiesAdminState(); + + @override + List get props => []; +} + +class MunicipalitiesAdminInitial extends MunicipalitiesAdminState { + @override + List get props => []; +} + +class MunicipalitiesLoaded extends MunicipalitiesAdminState { + final List city; + + const MunicipalitiesLoaded({required this.city}); + @override + List get props => [city]; +} diff --git a/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart new file mode 100644 index 0000000..42d52be --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart @@ -0,0 +1,32 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/signatories.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'signatories_admin_event.dart'; +part 'signatories_admin_state.dart'; + +class SignatoriesAdminBloc + extends Bloc { + SignatoriesAdminBloc() : super(SignatoriesAdminInitial()) { + List signatories = []; + on((event, emit) async { + signatories = await SQLServices.instance.readAllSignatories(); + + emit(SignatoriesLoaded(signatories: signatories)); + }); + on((event, emit) async { + await SQLServices.instance.createSignatories(Signatories( + id: event.id, + signatoryId: event.signatoryId, + firstname: event.firstname, + middlename: event.middlename, + lastname: event.lastname, + designation: event.designation, + // status: event.status + // genCode: event.genCode + )); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_event.dart b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_event.dart new file mode 100644 index 0000000..134c4d6 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_event.dart @@ -0,0 +1,49 @@ +part of 'signatories_admin_bloc.dart'; + +class SignatoriesAdminEvent extends Equatable { + const SignatoriesAdminEvent(); + + @override + List get props => []; +} + +class AddSignatories extends SignatoriesAdminEvent { + final int id; + final int signatoryId; + final String firstname; + final String middlename; + final String lastname; + final String genCode; + final String designation; + // final String status; + + const AddSignatories({ + required this.id, + required this.signatoryId, + required this.firstname, + required this.middlename, + required this.lastname, + required this.genCode, + required this.designation, + // required this.status + }); + + @override + List get props => [ + id, + signatoryId, + firstname, + middlename, + lastname, + genCode, + designation, + // status + ]; +} + +class LoadSignatories extends SignatoriesAdminEvent { + const LoadSignatories(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_state.dart b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_state.dart new file mode 100644 index 0000000..df9abe7 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/signatories/signatories_admin_state.dart @@ -0,0 +1,21 @@ +part of 'signatories_admin_bloc.dart'; + +class SignatoriesAdminState extends Equatable { + const SignatoriesAdminState(); + + @override + List get props => []; +} + +class SignatoriesAdminInitial extends SignatoriesAdminState { + @override + List get props => []; +} + +class SignatoriesLoaded extends SignatoriesAdminState { + final List signatories; + + const SignatoriesLoaded({required this.signatories}); + @override + List get props => [signatories]; +} diff --git a/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart new file mode 100644 index 0000000..33eac50 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart @@ -0,0 +1,27 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/trees_improvements.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'trees_improvements_event.dart'; +part 'trees_improvements_state.dart'; + +class TreesImprovementsBloc + extends Bloc { + TreesImprovementsBloc() : super(TreesImprovementsInitial()) { + List treesImprovements = []; + on((event, emit) async { + treesImprovements = await SQLServices.instance.readAllTreesImprovements(); + + emit(TreesImprovementsLoaded(treesImprovements: treesImprovements)); + }); + on((event, emit) async { + await SQLServices.instance.createTreesImprovements(TreesImprovements( + id: event.id, + improvement: event.improvement, + pricePerTree: event.pricePerTree, + subclassCode: event.subclassCode)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_event.dart b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_event.dart new file mode 100644 index 0000000..8d2dfa9 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_event.dart @@ -0,0 +1,37 @@ +part of 'trees_improvements_bloc.dart'; + +class TreesImprovementsEvent extends Equatable { + const TreesImprovementsEvent(); + + @override + List get props => []; +} + +class AddTreesImprovements extends TreesImprovementsEvent { + final int id; + final String improvement; + final String pricePerTree; + final dynamic subclassCode; + + const AddTreesImprovements({ + required this.id, + required this.improvement, + required this.pricePerTree, + required this.subclassCode, + }); + + @override + List get props => [ + id, + improvement, + pricePerTree, + subclassCode, + ]; +} + +class LoadTreesImprovements extends TreesImprovementsEvent { + const LoadTreesImprovements(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_state.dart b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_state.dart new file mode 100644 index 0000000..9d9209c --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_state.dart @@ -0,0 +1,18 @@ +part of 'trees_improvements_bloc.dart'; + +class TreesImprovementsState extends Equatable { + const TreesImprovementsState(); + + @override + List get props => []; +} + +class TreesImprovementsInitial extends TreesImprovementsState {} + +class TreesImprovementsLoaded extends TreesImprovementsState { + final List treesImprovements; + + const TreesImprovementsLoaded({required this.treesImprovements}); + @override + List get props => [treesImprovements]; +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart new file mode 100644 index 0000000..82a4f61 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart @@ -0,0 +1,27 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/type_of_location.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'type_of_location_event.dart'; +part 'type_of_location_state.dart'; + +class TypeOfLocationBloc + extends Bloc { + TypeOfLocationBloc() : super(TypeOfLocationInitial()) { + List typeOfLocation = []; + on((event, emit) async { + typeOfLocation = await SQLServices.instance.readAllTypeOfLocation(); + + emit(TypeOfLocationLoaded(typeOfLocation: typeOfLocation)); + }); + on((event, emit) async { + await SQLServices.instance.createTypeOfLocation(TypeOfLocation( + id: event.id, + distanceKm: event.distanceKm, + allRoadTypes: event.allRoadTypes, + localTradingCenter: event.localTradingCenter)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_event.dart b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_event.dart new file mode 100644 index 0000000..c25637e --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_event.dart @@ -0,0 +1,37 @@ +part of 'type_of_location_bloc.dart'; + +class TypeOfLocationEvent extends Equatable { + const TypeOfLocationEvent(); + + @override + List get props => []; +} + +class AddTypeOfLocation extends TypeOfLocationEvent { + final int id; + final String distanceKm; + final String allRoadTypes; + final String localTradingCenter; + + const AddTypeOfLocation({ + required this.id, + required this.distanceKm, + required this.allRoadTypes, + required this.localTradingCenter, + }); + + @override + List get props => [ + id, + distanceKm, + allRoadTypes, + localTradingCenter, + ]; +} + +class LoadTypeOfLocation extends TypeOfLocationEvent { + const LoadTypeOfLocation(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_state.dart b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_state.dart new file mode 100644 index 0000000..9e0884b --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_location/type_of_location_state.dart @@ -0,0 +1,18 @@ +part of 'type_of_location_bloc.dart'; + +class TypeOfLocationState extends Equatable { + const TypeOfLocationState(); + + @override + List get props => []; +} + +class TypeOfLocationInitial extends TypeOfLocationState {} + +class TypeOfLocationLoaded extends TypeOfLocationState { + final List typeOfLocation; + + const TypeOfLocationLoaded({required this.typeOfLocation}); + @override + List get props => [typeOfLocation]; +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart new file mode 100644 index 0000000..565a92c --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart @@ -0,0 +1,26 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/type_of_road.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'type_of_road_event.dart'; +part 'type_of_road_state.dart'; + +class TypeOfRoadBloc extends Bloc { + TypeOfRoadBloc() : super(TypeOfRoadInitial()) { + List typeOfRoad = []; + on((event, emit) async { + typeOfRoad = await SQLServices.instance.readAllTypeOfRoad(); + + emit(TypeOfRoadLoaded(typeOfRoad: typeOfRoad)); + }); + on((event, emit) async { + await SQLServices.instance.createTypeOfRoad(TypeOfRoad( + id: event.id, + roadType: event.roadType, + deduction: event.deduction, + )); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_event.dart b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_event.dart new file mode 100644 index 0000000..54731f8 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_event.dart @@ -0,0 +1,34 @@ +part of 'type_of_road_bloc.dart'; + +class TypeOfRoadEvent extends Equatable { + const TypeOfRoadEvent(); + + @override + List get props => []; +} + +class AddTypeOfRoad extends TypeOfRoadEvent { + final int id; + final String roadType; + final String deduction; + + const AddTypeOfRoad({ + required this.id, + required this.roadType, + required this.deduction, + }); + + @override + List get props => [ + id, + roadType, + deduction, + ]; +} + +class LoadTypeOfRoad extends TypeOfRoadEvent { + const LoadTypeOfRoad(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_state.dart b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_state.dart new file mode 100644 index 0000000..6f389f1 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/type_of_road/type_of_road_state.dart @@ -0,0 +1,18 @@ +part of 'type_of_road_bloc.dart'; + +class TypeOfRoadState extends Equatable { + const TypeOfRoadState(); + + @override + List get props => []; +} + +class TypeOfRoadInitial extends TypeOfRoadState {} + +class TypeOfRoadLoaded extends TypeOfRoadState { + final List typeOfRoad; + + const TypeOfRoadLoaded({required this.typeOfRoad}); + @override + List get props => [typeOfRoad]; +} diff --git a/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart new file mode 100644 index 0000000..6c60e6c --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart @@ -0,0 +1,30 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'unit_construction_admin_event.dart'; +part 'unit_construction_admin_state.dart'; + +class UnitConstructionAdminBloc + extends Bloc { + UnitConstructionAdminBloc() : super(UnitConstructionAdminInitial()) { + List unit = []; + on((event, emit) async { + unit = await SQLServices.instance.readAllUnitConstruct(); + + emit(UnitConstructLoaded(unit: unit)); + }); + on((event, emit) async { + await SQLServices.instance.createUnitConstruction( + UnitConstruct( + id: event.id, + bldgType: event.bldgType, + building: event.building, + unitValue: event.unitValue, + genCode: event.genCode), + ); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_event.dart b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_event.dart new file mode 100644 index 0000000..7b52fcb --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_event.dart @@ -0,0 +1,34 @@ +part of 'unit_construction_admin_bloc.dart'; + +class UnitConstructionAdminEvent extends Equatable { + const UnitConstructionAdminEvent(); + + @override + List get props => []; +} + +class AddUnitConstruct extends UnitConstructionAdminEvent { + final int id; + final String bldgType; + final String building; + final String unitValue; + final String genCode; + + const AddUnitConstruct({ + required this.id, + required this.bldgType, + required this.building, + required this.unitValue, + required this.genCode, + }); + + @override + List get props => [id, bldgType, building, unitValue, genCode]; +} + +class LoadUnitConstruct extends UnitConstructionAdminEvent { + const LoadUnitConstruct(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_state.dart b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_state.dart new file mode 100644 index 0000000..47c950b --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_state.dart @@ -0,0 +1,21 @@ +part of 'unit_construction_admin_bloc.dart'; + +class UnitConstructionAdminState extends Equatable { + const UnitConstructionAdminState(); + + @override + List get props => []; +} + +class UnitConstructionAdminInitial extends UnitConstructionAdminState { + @override + List get props => []; +} + +class UnitConstructLoaded extends UnitConstructionAdminState { + final List unit; + + const UnitConstructLoaded({required this.unit}); + @override + List get props => [unit]; +} diff --git a/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_bloc.dart b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_bloc.dart new file mode 100644 index 0000000..be4159f --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_bloc.dart @@ -0,0 +1,31 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'value_adjustments_event.dart'; +part 'value_adjustments_state.dart'; + +class ValueAdjustmentsBloc + extends Bloc { + ValueAdjustmentsBloc() : super(ValueAdjustmentsInitial()) { + List valueAdjustments = []; + on((event, emit) async { + valueAdjustments = await SQLServices.instance.readAllValueAdjustments(); + + emit(ValueAdjustmentsLoaded(valueAdjustments: valueAdjustments)); + }); + on((event, emit) async { + await SQLServices.instance.createValueAdjustments(ValueAdjustments( + id: event.id, + landapprDetailsId: event.landapprDetailsId, + baseMarketval: event.baseMarketval, + adjustmentFactors: event.adjustmentFactors, + adjustment: event.adjustment, + valueAdjustment: event.valueAdjustment, + marketValue: event.marketValue, + )); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_event.dart b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_event.dart new file mode 100644 index 0000000..196818f --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_event.dart @@ -0,0 +1,46 @@ +part of 'value_adjustments_bloc.dart'; + +class ValueAdjustmentsEvent extends Equatable { + const ValueAdjustmentsEvent(); + + @override + List get props => []; +} + +class AddValueAdjustments extends ValueAdjustmentsEvent { + final int id; + final int landapprDetailsId; + final String baseMarketval; + final String adjustmentFactors; + final String adjustment; + final String valueAdjustment; + final String marketValue; + + const AddValueAdjustments({ + required this.id, + required this.landapprDetailsId, + required this.baseMarketval, + required this.adjustmentFactors, + required this.adjustment, + required this.valueAdjustment, + required this.marketValue, + }); + + @override + List get props => [ + id, + landapprDetailsId, + baseMarketval, + adjustmentFactors, + adjustment, + valueAdjustment, + marketValue, + ]; +} + +class LoadValueAdjustments extends ValueAdjustmentsEvent { + const LoadValueAdjustments(); + + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_state.dart b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_state.dart new file mode 100644 index 0000000..a61fcb4 --- /dev/null +++ b/lib/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_state.dart @@ -0,0 +1,18 @@ +part of 'value_adjustments_bloc.dart'; + +class ValueAdjustmentsState extends Equatable { + const ValueAdjustmentsState(); + + @override + List get props => []; +} + +class ValueAdjustmentsInitial extends ValueAdjustmentsState {} + +class ValueAdjustmentsLoaded extends ValueAdjustmentsState { + final List valueAdjustments; + + const ValueAdjustmentsLoaded({required this.valueAdjustments}); + @override + List get props => [valueAdjustments]; +} diff --git a/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart new file mode 100644 index 0000000..d38753e --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart @@ -0,0 +1,84 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../sevices/offline/offline_passo/building/property_owner_info_service.dart'; + +part 'additional_items_offline_event.dart'; +part 'additional_items_offline_state.dart'; + +class AdditionalItemsOfflineBloc + extends Bloc { + AdditionalItemsOfflineBloc() : super(AdditionalItemsOfflineInitial()) { + List addItems = []; + on((event, emit) async { + emit(AdditionalItemsOfflineInitial()); + try { + emit(AdditionalItemsLoaded(addItem: addItems)); + } catch (e) { + emit(AdditionalItemsErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(AdditionalItemsOfflineInitial()); + List> result = + await SQLServices.instance.getAdditionalItems(event.id); + + if (result.isNotEmpty) { + addItems = result.map((map) => AdditionalItems.fromJson(map)).toList(); + + emit(AdditionalItemsLoaded(addItem: addItems)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + AdditionalItems item = await SQLServices.instance.createAdditionalItems( + AdditionalItems( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + classId: event.classId, + className: event.className, + structType: event.structType, + unitValue: event.unitValue, + baseUnitValue: event.baseUnitValue, + area: event.area, + marketValue: event.marketValue, + depreciationRate: event.depreciationRate, + adjustedMarketVal: event.adjustedMarketVal, + amtDepreciation: event.amtDepreciation, + painted: event.painted == true ? '1' : '0', + secondhand: event.secondhand == true ? '1' : '0', + paintedUnitval: event.paintedUnitval, + secondhandUnitval: event.secondhandUnitval, + actualUse: event.actualUse, + genCode: event.genCode)); + + print(item.toJson()); + + addItems.add(item); + + emit(AdditionalItemsLoaded(addItem: addItems)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowAddItemsScreen()); + }); + on((event, emit) async { + addItems = await SQLServices.instance.readAdditionalItems(); + emit(AdditionalItemsLoaded(addItem: addItems)); + }); + on((event, emit) async { + addItems + .removeWhere(((AdditionalItems element) => element.id == event.id)); + await SQLServices.instance.deleteAdditionalItems(id: event.id); + emit(const AdditionalItemsDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_event.dart b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_event.dart new file mode 100644 index 0000000..e0b5f90 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_event.dart @@ -0,0 +1,134 @@ +part of 'additional_items_offline_bloc.dart'; + +class AdditionalItemsOfflineEvent extends Equatable { + const AdditionalItemsOfflineEvent(); + + @override + List get props => []; +} + +class LoadAdditionalItems extends AdditionalItemsOfflineEvent { + final List items; + + const LoadAdditionalItems({this.items = const []}); + + @override + List get props => [items]; +} + +class LoadAdditionalItemsEdit extends AdditionalItemsOfflineEvent { + final List items; + final int? id; + + const LoadAdditionalItemsEdit({required this.items, this.id}); + + @override + List get props => [items]; +} + +class AddAdditionalItems extends AdditionalItemsOfflineEvent { + final int id; + final int bldgapprDetailsId; + final int classId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String className; + final String structType; + final dynamic unitValue; + final dynamic baseUnitValue; + final dynamic area; + final dynamic marketValue; + final dynamic depreciationRate; + final dynamic adjustedMarketVal; + final dynamic amtDepreciation; + final bool painted; + final bool secondhand; + final dynamic paintedUnitval; + final dynamic secondhandUnitval; + final String actualUse; + final String genCode; + + const AddAdditionalItems({ + required this.id, + required this.bldgapprDetailsId, + required this.classId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.className, + required this.structType, + required this.unitValue, + required this.baseUnitValue, + required this.area, + required this.marketValue, + required this.depreciationRate, + required this.adjustedMarketVal, + required this.amtDepreciation, + required this.painted, + required this.secondhand, + required this.paintedUnitval, + required this.secondhandUnitval, + required this.actualUse, + required this.genCode, + }); + + @override + List get props => [ + id, + bldgapprDetailsId, + classId, + assessedById, + assessedByName, + dateCreated, + dateModified, + className, + structType, + unitValue, + baseUnitValue, + area, + marketValue, + depreciationRate, + adjustedMarketVal, + amtDepreciation, + painted, + secondhand, + paintedUnitval, + secondhandUnitval, + actualUse, + genCode + ]; +} + +class UpdateAdditionalItems extends AdditionalItemsOfflineEvent { + final AdditionalItems addItems; + const UpdateAdditionalItems({required this.addItems}); + @override + List get props => [addItems]; +} + +class FetchAdditionalItems extends AdditionalItemsOfflineEvent { + const FetchAdditionalItems(); + + @override + List get props => []; +} + +class FetchSpecificAdditionalItems extends AdditionalItemsOfflineEvent { + final int id; + const FetchSpecificAdditionalItems({required this.id}); + + @override + List get props => [id]; +} + +class DeleteAdditionalItems extends AdditionalItemsOfflineEvent { + final int id; + const DeleteAdditionalItems({required this.id}); + @override + List get props => [id]; +} + +class ShowAdditionalItems extends AdditionalItemsOfflineEvent {} diff --git a/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_state.dart b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_state.dart new file mode 100644 index 0000000..93864f5 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_state.dart @@ -0,0 +1,46 @@ +part of 'additional_items_offline_bloc.dart'; + +class AdditionalItemsOfflineState extends Equatable { + const AdditionalItemsOfflineState(); + + @override + List get props => []; +} + +class AdditionalItemsOfflineInitial extends AdditionalItemsOfflineState { + @override + List get props => []; +} + +class AdditionalItemsLoaded extends AdditionalItemsOfflineState { + final List addItem; + + const AdditionalItemsLoaded({required this.addItem}); + @override + List get props => [addItem]; +} + +class LoadSpecificAdditionalItems extends AdditionalItemsOfflineState { + final AdditionalItems addItem; + + const LoadSpecificAdditionalItems({required this.addItem}); + @override + List get props => [addItem]; +} + +class ShowAddItemsScreen extends AdditionalItemsOfflineState {} + +class AdditionalItemsErrorState extends AdditionalItemsOfflineState { + const AdditionalItemsErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class AdditionalItemsDeletedState extends AdditionalItemsOfflineState { + final bool success; + const AdditionalItemsDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart new file mode 100644 index 0000000..19fc2fb --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart @@ -0,0 +1,58 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'bldg_appraisal_offline_event.dart'; +part 'bldg_appraisal_offline_state.dart'; + +class BldgAppraisalOfflineBloc + extends Bloc { + BldgAppraisalOfflineBloc() : super(BldgAppraisalOfflineInitial()) { + List appraisal = []; + on((event, emit) async { + await SQLServices.instance.createBldgAppraisal(PropertyAppraisal( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + unitconstructCost: event.unitconstructCost, + buildingCore: event.buildingCore, + unitconstructSubtotal: event.unitconstructSubtotal, + depreciationRate: event.depreciationRate, + depreciationCost: event.depreciationCost, + costAddItems: event.costAddItems, + addItemsSubtotal: event.addItemsSubtotal, + totalpercentDepreciation: event.totalpercentDepreciation, + marketValue: event.marketValue, + totalArea: event.totalArea, + actualUse: event.actualUse, + )); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getBldgAppraisal(event.id); + + if (result.isNotEmpty) { + List appraisalList = + result.map((map) => PropertyAppraisal.fromJson2(map)).toList(); + + // Choose a specific element from locationList + PropertyAppraisal firstAppraisal = appraisalList + .first; // You can change this to select a specific item + + print('appraisal test result'); + print(firstAppraisal.toJson()); + emit(SpecificBldgAppraisalLoaded(appraisal: firstAppraisal)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance.updateAppraisal(event.id, event.appraisal); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_event.dart b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_event.dart new file mode 100644 index 0000000..75e8a31 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_event.dart @@ -0,0 +1,89 @@ +part of 'bldg_appraisal_offline_bloc.dart'; + +class BldgAppraisalOfflineEvent extends Equatable { + const BldgAppraisalOfflineEvent(); + + @override + List get props => []; +} + +class AddBldgAppraisal extends BldgAppraisalOfflineEvent { + final int id; + final int bldgapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String 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; + final String actualUse; + final String genCode; + + const AddBldgAppraisal( + {required this.id, + required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + 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, + required this.totalArea, + required this.actualUse, + required this.genCode}); + + @override + List get props => [ + id, + bldgapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + unitconstructCost, + buildingCore, + unitconstructSubtotal, + depreciationRate, + depreciationCost, + costAddItems, + addItemsSubtotal, + totalpercentDepreciation, + marketValue, + totalArea, + actualUse, + genCode + ]; +} + +class FetchSingleBldgAppraisal extends BldgAppraisalOfflineEvent { + final int id; + const FetchSingleBldgAppraisal({required this.id}); + + @override + List get props => [id]; +} + +class UpdateAppraisal extends BldgAppraisalOfflineEvent { + final PropertyAppraisal appraisal; + final int id; + + const UpdateAppraisal({required this.id, required this.appraisal}); + + @override + List get props => [id, appraisal]; +} diff --git a/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_state.dart b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_state.dart new file mode 100644 index 0000000..0b3b3c7 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_state.dart @@ -0,0 +1,37 @@ +part of 'bldg_appraisal_offline_bloc.dart'; + +class BldgAppraisalOfflineState extends Equatable { + const BldgAppraisalOfflineState(); + + @override + List get props => []; +} + +class BldgAppraisalOfflineInitial extends BldgAppraisalOfflineState { + @override + List get props => []; +} + +class BldgAppraisalOfflineLoaded extends BldgAppraisalOfflineState { + final List appraisal; + + const BldgAppraisalOfflineLoaded({required this.appraisal}); + @override + List get props => [appraisal]; +} + +class LoadSpecificBldgAppraisalOffline extends BldgAppraisalOfflineState { + final PropertyAppraisal appraisal; + + const LoadSpecificBldgAppraisalOffline({required this.appraisal}); + @override + List get props => [appraisal]; +} + +class SpecificBldgAppraisalLoaded extends BldgAppraisalOfflineState { + final PropertyAppraisal appraisal; + + const SpecificBldgAppraisalLoaded({required this.appraisal}); + @override + List get props => [appraisal]; +} diff --git a/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart new file mode 100644 index 0000000..5380953 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart @@ -0,0 +1,70 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/property_assessment.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'bldg_assessment_offline_event.dart'; +part 'bldg_assessment_offline_state.dart'; + +class BldgAssessmentOfflineBloc + extends Bloc { + BldgAssessmentOfflineBloc() : super(BldgAssessmentOfflineInitial()) { + List assessment = []; + on((event, emit) async { + await SQLServices.instance.createBldgAssessment(PropertyAssessment( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + actualUse: event.actualUse, + marketValue: event.marketValue, + assessmentLevel: event.assessmentLevel, + assessedValue: event.assessedValue, + taxable: event.taxable, + exempt: event.exempt, + qtr: event.qtr, + yr: event.yr.toString(), + appraisedbyName: event.appraisedbyName, + appraisedbyDate: event.appraisedbyDate, + recommendapprName: event.recommendapprName, + recommendapprDate: event.recommendapprDate, + approvedbyName: event.approvedbyName, + approvedbyDate: event.approvedbyDate, + memoranda: event.memoranda, + swornstatementNo: event.swornstatementNo, + dateReceived: event.dateReceived, + entryDateAssessment: event.entryDateAssessment, + entryDateBy: event.entryDateBy, + note: event.note, + genCode: event.genCode, + appraisedbyDesignation: event.appraisedbyDesignation, + approvedbyDesignation: event.approvedbyDesignation, + recommendapprDesignation: event.recommendapprDesignation)); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getBldgAssessment(event.id); + + if (result.isNotEmpty) { + List assessmentList = + result.map((map) => PropertyAssessment.fromJson2(map)).toList(); + + // Choose a specific element from locationList + PropertyAssessment firstAssessment = assessmentList + .first; // You can change this to select a specific item + + print('assessment test result'); + print(firstAssessment.toJson()); + emit(SpecificBldgAssessmentLoaded(assessment: firstAssessment)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance.updateAssessment(event.id, event.assessment); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_event.dart b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_event.dart new file mode 100644 index 0000000..44a89d6 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_event.dart @@ -0,0 +1,126 @@ +part of 'bldg_assessment_offline_bloc.dart'; + +class BldgAssessmentOfflineEvent extends Equatable { + const BldgAssessmentOfflineEvent(); + + @override + List get props => []; +} + +class AddBldgAssessment extends BldgAssessmentOfflineEvent { + final int id; + final int bldgapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String actualUse; + final String marketValue; + final String assessmentLevel; + final String assessedValue; + final String taxable; + final String exempt; + final String qtr; + final int yr; + final String appraisedbyName; + final String appraisedbyDate; + final String recommendapprName; + final String recommendapprDate; + final String approvedbyName; + final String approvedbyDate; + final String memoranda; + final String swornstatementNo; + final String dateReceived; + final String entryDateAssessment; + final String entryDateBy; + final String genCode; + final String note; + final String appraisedbyDesignation; + final String recommendapprDesignation; + final String approvedbyDesignation; + + const AddBldgAssessment({ + required this.id, + required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.actualUse, + required this.marketValue, + required this.assessmentLevel, + required this.assessedValue, + required this.taxable, + required this.exempt, + required this.qtr, + required this.yr, + required this.appraisedbyName, + required this.appraisedbyDate, + required this.recommendapprName, + required this.recommendapprDate, + required this.approvedbyName, + required this.approvedbyDate, + required this.memoranda, + required this.swornstatementNo, + required this.dateReceived, + required this.entryDateAssessment, + required this.entryDateBy, + required this.genCode, + required this.note, + required this.appraisedbyDesignation, + required this.recommendapprDesignation, + required this.approvedbyDesignation, + }); + + @override + List get props => [ + id, + bldgapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + actualUse, + marketValue, + assessmentLevel, + assessedValue, + taxable, + exempt, + qtr, + yr, + appraisedbyName, + appraisedbyDate, + recommendapprName, + recommendapprDate, + approvedbyName, + approvedbyDate, + memoranda, + swornstatementNo, + dateReceived, + entryDateAssessment, + entryDateBy, + genCode, + note, + appraisedbyDesignation, + recommendapprDesignation, + approvedbyDesignation, + ]; +} + +class FetchSingleBldgAssessment extends BldgAssessmentOfflineEvent { + final int id; + const FetchSingleBldgAssessment({required this.id}); + + @override + List get props => [id]; +} + +class UpdateBldgAssessment extends BldgAssessmentOfflineEvent { + final PropertyAssessment assessment; + final int id; + + UpdateBldgAssessment({required this.id, required this.assessment}); + + @override + List get props => [id, assessment]; +} diff --git a/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_state.dart b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_state.dart new file mode 100644 index 0000000..5a411ea --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_state.dart @@ -0,0 +1,37 @@ +part of 'bldg_assessment_offline_bloc.dart'; + +class BldgAssessmentOfflineState extends Equatable { + const BldgAssessmentOfflineState(); + + @override + List get props => []; +} + +class BldgAssessmentOfflineInitial extends BldgAssessmentOfflineState { + @override + List get props => []; +} + +class BldgAssessmentOfflineLoaded extends BldgAssessmentOfflineState { + final List assessment; + + const BldgAssessmentOfflineLoaded({required this.assessment}); + @override + List get props => [assessment]; +} + +class LoadSpecificBldgAssessmentOffline extends BldgAssessmentOfflineState { + final PropertyAssessment assessment; + + const LoadSpecificBldgAssessmentOffline({required this.assessment}); + @override + List get props => [assessment]; +} + +class SpecificBldgAssessmentLoaded extends BldgAssessmentOfflineState { + final PropertyAssessment assessment; + + const SpecificBldgAssessmentLoaded({required this.assessment}); + @override + List get props => [assessment]; +} diff --git a/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart new file mode 100644 index 0000000..25ec7cc --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart @@ -0,0 +1,66 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'building_and_structure_event.dart'; +part 'building_and_structure_state.dart'; + +class BuildingAndStructureBloc + extends Bloc { + BuildingAndStructureBloc() : super(BuildingAndStructureOfflineInitial()) { + List bldgAndStructure = []; + on((event, emit) async { + emit(BuildingAndStructureOfflineInitial()); + try { + emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure)); + } catch (e) { + emit(BuildingAndStructureErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(BuildingAndStructureOfflineInitial()); + List> result = + await SQLServices.instance.getBuildingAndStructure(event.id); + + if (result.isNotEmpty) { + bldgAndStructure = + result.map((map) => BldgAndStructure.fromJson(map)).toList(); + + emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + BldgAndStructure item = await SQLServices.instance + .createBuildingAndStructure(event.bldgAndStructure); + + print(item.toJson()); + + bldgAndStructure.add(item); + + emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowBldgAndStructuresScreen()); + }); + on((event, emit) async { + bldgAndStructure = await SQLServices.instance.readBuildingAndStructure(); + emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure)); + }); + on((event, emit) async { + bldgAndStructure + .removeWhere(((BldgAndStructure element) => element.id == event.id)); + await SQLServices.instance.deleteBuildingAndStructure(id: event.id); + emit(const BuildingAndStructureDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_event.dart b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_event.dart new file mode 100644 index 0000000..5d5799a --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_event.dart @@ -0,0 +1,68 @@ +part of 'building_and_structure_bloc.dart'; + +class BuildingAndStructureEvent extends Equatable { + const BuildingAndStructureEvent(); + + @override + List get props => []; +} + +class LoadBuildingAndStructure extends BuildingAndStructureEvent { + final List bldgAndStructure; + + const LoadBuildingAndStructure( + {this.bldgAndStructure = const []}); + + @override + List get props => [bldgAndStructure]; +} + +class LoadBuildingAndStructureEdit extends BuildingAndStructureEvent { + final List bldgAndStructure; + final int? id; + + const LoadBuildingAndStructureEdit({required this.bldgAndStructure, this.id}); + + @override + List get props => [bldgAndStructure]; +} + +class AddBuildingAndStructure extends BuildingAndStructureEvent { + final BldgAndStructure bldgAndStructure; + + const AddBuildingAndStructure({required this.bldgAndStructure}); + + @override + List get props => [bldgAndStructure]; +} + +class UpdateBuildingAndStructure extends BuildingAndStructureEvent { + final BldgAndStructure addItems; + const UpdateBuildingAndStructure({required this.addItems}); + @override + List get props => [addItems]; +} + +class FetchBuildingAndStructure extends BuildingAndStructureEvent { + const FetchBuildingAndStructure(); + + @override + List get props => []; +} + +class FetchSpecificBuildingAndStructure extends BuildingAndStructureEvent { + final int id; + const FetchSpecificBuildingAndStructure({required this.id}); + + @override + List get props => [id]; +} + +class DeleteBuildingAndStructure extends BuildingAndStructureEvent { + final int id; + const DeleteBuildingAndStructure({required this.id}); + @override + List get props => [id]; +} + +class ShowBuildingAndStructure extends BuildingAndStructureEvent {} diff --git a/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_state.dart b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_state.dart new file mode 100644 index 0000000..4917c66 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_state.dart @@ -0,0 +1,46 @@ +part of 'building_and_structure_bloc.dart'; + +class BuildingAndStructureState extends Equatable { + const BuildingAndStructureState(); + + @override + List get props => []; +} + +class BuildingAndStructureOfflineInitial extends BuildingAndStructureState { + @override + List get props => []; +} + +class BuildingAndStructureLoaded extends BuildingAndStructureState { + final List bldgAndStructure; + + const BuildingAndStructureLoaded({required this.bldgAndStructure}); + @override + List get props => [bldgAndStructure]; +} + +class LoadSpecificBuildingAndStructure extends BuildingAndStructureState { + final BldgAndStructure bldgAndStructure; + + const LoadSpecificBuildingAndStructure({required this.bldgAndStructure}); + @override + List get props => [bldgAndStructure]; +} + +class ShowBldgAndStructuresScreen extends BuildingAndStructureState {} + +class BuildingAndStructureErrorState extends BuildingAndStructureState { + const BuildingAndStructureErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class BuildingAndStructureDeletedState extends BuildingAndStructureState { + final bool success; + const BuildingAndStructureDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart b/lib/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart new file mode 100644 index 0000000..cec53be --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart @@ -0,0 +1,65 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/general_description.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +import '../../../../../sevices/offline/offline_passo/building/property_owner_info_service.dart'; + +part 'general_description_event.dart'; +part 'general_description_state.dart'; + +class GeneralDescriptionBloc + extends Bloc { + GeneralDescriptionBloc() : super(GeneralDescriptionInitial()) { + List todos = []; + on((event, emit) async { + await SQLServices.instance.createBldgGeneralDescription(GeneralDesc( + bldgapprDetailsId: event.bldgapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + bldgKind: event.bldgKind, + strucType: event.strucType, + bldgPermit: event.bldgPermit, + dateIssued: event.dateIssued.toString(), + cct: event.cct, + certCompletionIssued: event.certCompletionIssued.toString(), + certOccupancyIssued: event.certOccupancyIssued.toString(), + dateCompleted: event.dateCompleted.toString(), + dateOccupied: event.dateOccupied.toString(), + bldgAge: event.bldgAge, + noStoreys: event.noStoreys, + area1Stfloor: event.area1Stfloor, + area2Ndfloor: event.area2Ndfloor, + area3Rdfloor: event.area3Rdfloor, + area4Thfloor: event.area4Thfloor, + totalFloorArea: event.totalFloorArea, + floorSketch: event.floorSketch, + actualUse: event.actualUse, + unitValue: event.unitValue, + genCode: event.genCode)); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getGeneralDescription(event.id); + + if (result.isNotEmpty) { + List genDescList = + result.map((map) => GeneralDesc.fromJson2(map)).toList(); + + // Choose a specific element from locationList + GeneralDesc firstGenDesc = + genDescList.first; // You can change this to select a specific item + + print('location test result'); + print(firstGenDesc); + emit(SpecificGeneralDescriptionLoaded(gendesc: firstGenDesc)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance + .updateGeneralDescription(event.id, event.gendesc); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/general_description/general_description_event.dart b/lib/bloc/offline/offline_passo/building/general_description/general_description_event.dart new file mode 100644 index 0000000..84b853a --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/general_description/general_description_event.dart @@ -0,0 +1,113 @@ +part of 'general_description_bloc.dart'; + +class GeneralDescriptionEvent extends Equatable { + const GeneralDescriptionEvent(); + + @override + List get props => []; +} + +class AddGendesc extends GeneralDescriptionEvent { + final int id; + final int bldgapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String bldgKind; + final String strucType; + final String bldgPermit; + final String dateIssued; + final String cct; + final String certCompletionIssued; + final String certOccupancyIssued; + final String dateCompleted; + final String dateOccupied; + final String bldgAge; + final String noStoreys; + final String area1Stfloor; + final String area2Ndfloor; + final String area3Rdfloor; + final String area4Thfloor; + final String totalFloorArea; + final dynamic floorSketch; + final String actualUse; + final String unitValue; + final String genCode; + + const AddGendesc( + {required this.id, + required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.bldgKind, + required this.strucType, + required this.bldgPermit, + required this.dateIssued, + required this.cct, + required this.certCompletionIssued, + required this.certOccupancyIssued, + required this.dateCompleted, + required this.dateOccupied, + required this.bldgAge, + required this.noStoreys, + required this.area1Stfloor, + required this.area2Ndfloor, + required this.area3Rdfloor, + required this.area4Thfloor, + required this.totalFloorArea, + required this.floorSketch, + required this.actualUse, + required this.unitValue, + required this.genCode}); + + @override + List get props => [ + id, + bldgapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + bldgKind, + strucType, + bldgPermit, + dateIssued, + cct, + certCompletionIssued, + certOccupancyIssued, + dateCompleted, + dateOccupied, + bldgAge, + noStoreys, + area1Stfloor, + area2Ndfloor, + area3Rdfloor, + area4Thfloor, + totalFloorArea, + floorSketch, + actualUse, + unitValue, + genCode + ]; +} + +class FetchSingleGeneralDescription extends GeneralDescriptionEvent { + final int id; + const FetchSingleGeneralDescription({required this.id}); + + @override + List get props => [id]; +} + +class UpdateGeneralDescription extends GeneralDescriptionEvent { + final GeneralDesc gendesc; + final int id; + + UpdateGeneralDescription({required this.id, required this.gendesc}); + + @override + List get props => [id, gendesc]; +} diff --git a/lib/bloc/offline/offline_passo/building/general_description/general_description_state.dart b/lib/bloc/offline/offline_passo/building/general_description/general_description_state.dart new file mode 100644 index 0000000..3a49f3b --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/general_description/general_description_state.dart @@ -0,0 +1,29 @@ +part of 'general_description_bloc.dart'; + +class GeneralDescriptionState extends Equatable { + const GeneralDescriptionState(); + + @override + List get props => []; +} + +class GeneralDescriptionInitial extends GeneralDescriptionState { + @override + List get props => []; +} + +class LocationLoaded extends GeneralDescriptionState { + final List gendesc; + + const LocationLoaded({required this.gendesc}); + @override + List get props => [gendesc]; +} + +class SpecificGeneralDescriptionLoaded extends GeneralDescriptionState { + final GeneralDesc gendesc; + + const SpecificGeneralDescriptionLoaded({required this.gendesc}); + @override + List get props => [gendesc]; +} diff --git a/lib/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart b/lib/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart new file mode 100644 index 0000000..e17bfde --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart @@ -0,0 +1,83 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +import '../../../../../model/passo/land_ref.dart'; +import '../../../../../model/passo/todo.dart'; +import '../../../../../sevices/offline/offline_passo/building/property_owner_info_service.dart'; + +part 'landref_location_event.dart'; +part 'landref_location_state.dart'; + +class LandrefLocationBloc + extends Bloc { + LandrefLocationBloc() : super(LandrefInitial()) { + List todos = []; + on((event, emit) async { + await SQLServices.instance.createBldgLandRef( + LandRef( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + owner: event.owner, + cloaNo: event.cloaNo, + lotNo: event.lotNo, + tdn: event.tdn, + area: event.area, + surveyNo: event.surveyNo, + blkNo: event.blkNo, + genCode: event.genCode), + ); + }); + + // on((event, emit) async { + // await PropertyOwnerInfoServices.instance.update( + // todo: event.todo, + // ); + // }); + + // on((event, emit) async { + // landref = await PropertyOwnerInfoServices.instance.readAllTodos(); + // emit(LandrefLoaded(landref: landref)); + // }); + + on((event, emit) async { + List> result = + await SQLServices.instance.getLandRef(event.id); + + if (result.isNotEmpty) { + LandRef firstRow = LandRef( + id: result[0]["id"], + bldgapprDetailsId: result[0]["bldgapprDetailsId"], + assessedById: result[0]["assessedById"], + assessedByName: result[0]["assessedByName"], + dateCreated: DateTime.now().toString(), + dateModified: DateTime.now().toString(), + owner: result[0]["owner"], + cloaNo: result[0]["cloaNo"], + lotNo: result[0]["lotNo"], + tdn: result[0]["tdn"], + area: result[0]["area"], + surveyNo: result[0]["surveyNo"], + blkNo: result[0]["blkNo"], + ); + + print('landref test result'); + print(firstRow); + emit(SpecificLandrefLoaded(landref: firstRow)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + await SQLServices.instance.updateLandRef(event.id, event.landRef); + }); + + // on((event, emit) async { + // await PropertyOwnerInfoServices.instance.delete(id: event.id); + // add(const FetchTodos()); + // }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/landref/landref_location_event.dart b/lib/bloc/offline/offline_passo/building/landref/landref_location_event.dart new file mode 100644 index 0000000..fa297fb --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/landref/landref_location_event.dart @@ -0,0 +1,91 @@ +part of 'landref_location_bloc.dart'; + +class LandrefLocationEvent extends Equatable { + const LandrefLocationEvent(); + + @override + List get props => []; +} + +class AddLandRef extends LandrefLocationEvent { + final int id; + final int bldgapprDetailsId; + final String assessedById; + final String assessedByName; + final dynamic owner; + final dynamic cloaNo; + final dynamic lotNo; + final dynamic tdn; + final dynamic area; + final dynamic surveyNo; + final dynamic blkNo; + final String dateCreated; + final String dateModified; + final String genCode; + + const AddLandRef( + {required this.id, + required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.owner, + required this.cloaNo, + required this.lotNo, + required this.tdn, + required this.area, + required this.surveyNo, + required this.blkNo, + required this.dateCreated, + required this.dateModified, + required this.genCode}); + + @override + List get props => [ + id, + bldgapprDetailsId, + assessedById, + assessedByName, + owner, + cloaNo, + lotNo, + tdn, + area, + surveyNo, + blkNo, + dateCreated, + dateModified, + genCode + ]; +} + +class UpdateBldgLandRef extends LandrefLocationEvent { + final LandRef landRef; + final int id; + + UpdateBldgLandRef({required this.id, required this.landRef}); + + @override + List get props => [id, landRef]; +} + +class FetchLanRef extends LandrefLocationEvent { + const FetchLanRef(); + + @override + List get props => []; +} + +class FetchSingleLandref extends LandrefLocationEvent { + final int id; + const FetchSingleLandref({required this.id}); + + @override + List get props => [id]; +} + +// class DeleteTodo extends LandrefLocationEvent { +// final int id; +// const DeleteTodo({required this.id}); +// @override +// List get props => [id]; +// } diff --git a/lib/bloc/offline/offline_passo/building/landref/landref_location_state.dart b/lib/bloc/offline/offline_passo/building/landref/landref_location_state.dart new file mode 100644 index 0000000..4ae7a0d --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/landref/landref_location_state.dart @@ -0,0 +1,29 @@ +part of 'landref_location_bloc.dart'; + +class LandrefLocationState extends Equatable { + const LandrefLocationState(); + + @override + List get props => []; +} + +class LandrefInitial extends LandrefLocationState { + @override + List get props => []; +} + +class LandrefLoaded extends LandrefLocationState { + final List landref; + + const LandrefLoaded({required this.landref}); + @override + List get props => [landref]; +} + +class SpecificLandrefLoaded extends LandrefLocationState { + final LandRef landref; + + const SpecificLandrefLoaded({required this.landref}); + @override + List get props => [landref]; +} diff --git a/lib/bloc/offline/offline_passo/building/location/location_bloc.dart b/lib/bloc/offline/offline_passo/building/location/location_bloc.dart new file mode 100644 index 0000000..6988f95 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/location/location_bloc.dart @@ -0,0 +1,48 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +import '../../../../../model/passo/bldg_loc.dart'; + +part 'location_event.dart'; +part 'location_state.dart'; + +class LocationBloc extends Bloc { + LocationBloc() : super(LocationInitial()) { + List todos = []; + on((event, emit) async { + await SQLServices.instance.createBldglocation(BldgLoc( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + street: event.street, + barangay: event.barangay, + municipality: event.municipality, + province: event.province, + genCode: event.genCode)); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getLocation(event.id); + + if (result.isNotEmpty) { + List locationList = + result.map((map) => BldgLoc.fromJson(map)).toList(); + + // Choose a specific element from locationList + BldgLoc firstLocation = + locationList.first; // You can change this to select a specific item + + print('location test result'); + print(firstLocation); + emit(SpecificLocationLoaded(location: firstLocation)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance.updateLocation(event.id, event.bldgLoc); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/location/location_event.dart b/lib/bloc/offline/offline_passo/building/location/location_event.dart new file mode 100644 index 0000000..f504e2a --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/location/location_event.dart @@ -0,0 +1,81 @@ +part of 'location_bloc.dart'; + +class LocationEvent extends Equatable { + const LocationEvent(); + + @override + List get props => []; +} + +class AddLocation extends LocationEvent { + final int id; + final int bldgapprDetailsId; + final String assessedById; + final String assessedByName; + final String street; + final String barangay; + final String municipality; + final String province; + final String dateCreated; + final String dateModified; + final String genCode; + + const AddLocation( + {required this.id, + required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.street, + required this.barangay, + required this.municipality, + required this.province, + required this.dateCreated, + required this.dateModified, + required this.genCode}); + + @override + List get props => [ + bldgapprDetailsId, + assessedById, + assessedByName, + street, + barangay, + municipality, + province, + dateCreated, + dateModified, + genCode + ]; +} + +class UpdateBldgLoc extends LocationEvent { + final BldgLoc bldgLoc; + final int id; + + UpdateBldgLoc({required this.id, required this.bldgLoc}); + + @override + List get props => [id, bldgLoc]; +} + +class FetchLanRef extends LocationEvent { + const FetchLanRef(); + + @override + List get props => []; +} + +class FetchSingleLocation extends LocationEvent { + final int id; + const FetchSingleLocation({required this.id}); + + @override + List get props => [id]; +} + +// class DeleteTodo extends LocationEvent { +// final int id; +// const DeleteTodo({required this.id}); +// @override +// List get props => [id]; +// } diff --git a/lib/bloc/offline/offline_passo/building/location/location_state.dart b/lib/bloc/offline/offline_passo/building/location/location_state.dart new file mode 100644 index 0000000..ecc13ae --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/location/location_state.dart @@ -0,0 +1,29 @@ +part of 'location_bloc.dart'; + +class LocationState extends Equatable { + const LocationState(); + + @override + List get props => []; +} + +class LocationInitial extends LocationState { + @override + List get props => []; +} + +class LocationLoaded extends LocationState { + final List location; + + const LocationLoaded({required this.location}); + @override + List get props => [location]; +} + +class SpecificLocationLoaded extends LocationState { + final BldgLoc location; + + const SpecificLocationLoaded({required this.location}); + @override + List get props => [location]; +} diff --git a/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart new file mode 100644 index 0000000..74a88b0 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart @@ -0,0 +1,506 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/model/passo/floor_sketch.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import 'package:unit2/sevices/passo/building/building_services.dart'; +import '../../../../../model/offline/offline_profile.dart'; +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/bldg_loc.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../model/passo/general_description.dart'; +import '../../../../../model/passo/land_ref.dart'; +import '../../../../../model/passo/property_assessment.dart'; +import '../../../../../model/passo/property_info.dart'; +import '../../../../../model/passo/structureMaterial.dart'; +import '../../../../../model/passo/todo.dart'; +import '../../../../../model/profile/basic_information/primary-information.dart'; +import '../../../../../sevices/offline/offline_passo/building/property_owner_info_service.dart'; +import 'package:http/http.dart'; + +import 'package:path/path.dart'; +// as http; + +import '../../../../../utils/urls.dart'; +part 'crud_event.dart'; +part 'crud_state.dart'; + +class CrudBloc extends Bloc { + CrudBloc() : super(CrudInitial()) { + List propertyOwner = []; + on((event, emit) async { + try { + PropertyInfo ownerInfo; + ownerInfo = await SQLServices.instance.createBldgOwner( + PropertyInfo( + transCode: event.transCode, + tdn: event.tdn, + pin: event.pin, + fname: event.fname, + mname: event.mname, + lname: event.lname, + bday: event.bday, + address: event.address, + telno: event.telno, + tin: event.tin, + adminUser: event.adminUser, + adminAddress: event.adminAddress, + adminTelno: event.adminTelno, + adminTin: event.adminTin, + faasType: event.faasType, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + genCode: event.genCode), + ); + + propertyOwner.add(ownerInfo); + + emit(PropertyInfoLoaded(propertyInfos: propertyOwner)); + } catch (e) { + emit(PropertyOwnerInfoErrorState(errorMessage: 'Failed to add todo')); + print('Error: $e'); + // You might want to throw or log the error, or take other appropriate actions + + // If you want to rethrow the error, uncomment the following line + // throw e; + } + }); + + on((event, emit) async { + await SQLServices.instance.updateBldgOwner(event.id, event.propertyInfo); + }); + + on((event, emit) async { + emit(PropertyOwnerInfoLoading()); + propertyOwner = await SQLServices.instance.readAllBldgOwner(); + emit(PropertyInfoLoaded(propertyInfos: propertyOwner)); + }); + + // on((event, emit) async { + // Prop todo = await PropertyOwnerInfoServices.instance.readTodo(id: event.id); + // emit(DisplaySpecificTodo(todo: todo)); + // }); + + on((event, emit) async { + await SQLServices.instance.deleteBldgOwner(id: event.id); + // Directly fetch and emit new data rather than triggering another event + try { + emit(PropertyOwnerInfoLoading()); + propertyOwner.clear(); // Clear the current list + propertyOwner = + await SQLServices.instance.readAllBldgOwner(); // Refetch data + emit(PropertyInfoLoaded( + propertyInfos: propertyOwner)); // Emit new state with updated data + } catch (error) { + // emit((error.toString())); // Handle potential errors + print(error.toString()); + } + }); + + Future> _prepareBuildingDetails( + UploadBuildingFaas event, PropertyInfo infos) async { + // Fetch data + List> genDesc = + await SQLServices.instance.getGeneralDescription(infos.id); + List> loc = + await SQLServices.instance.getLocation(infos.id); + List> landRef = + await SQLServices.instance.getLandRef(infos.id); + List> assessment = + await SQLServices.instance.getBldgAssessment(infos.id); + List> strucMat = + await SQLServices.instance.getStructuralMaterials(infos.id); + List> addItems = + await SQLServices.instance.getAdditionalItems(infos.id); + List> bldgStructure = + await SQLServices.instance.getBuildingAndStructure(infos.id); + + // Parse data + GeneralDesc firstGenDesc = GeneralDesc.fromJson2(genDesc.first); + BldgLoc firstLoc = BldgLoc.fromJson2(loc.first); + LandRef firstLandRef = LandRef.fromJson2(landRef.first); + PropertyAssessment firstAssess = + PropertyAssessment.fromJson2(assessment.first); + StructureMaterials firstStructMat = + StructureMaterials.fromJson2(strucMat.first); + + // Prepare details + DateTime dateIssued = DateTime.parse(firstGenDesc.dateIssued!); + final details = { + "assessed_by_id": event.offlineProfile.id.toString(), + "assessed_by_name": event.offlineProfile.firstName, + "date_created": "{{currentTimestamp}}", + "date_modified": "{{currentTimestamp}}", + "trans_code": '08887', + "tdn": infos.tdn, + "pin": infos.pin, + "fname": infos.fname, + "mname": infos.mname, + "lname": infos.lname, + "bday": infos.bday, + "address": infos.address, + "telno": infos.telno, + "tin": infos.tin, + "admin_user": infos.adminUser, + "admin_address": infos.adminAddress, + "admin_telno": infos.adminTelno, + "admin_tin": infos.adminTin, + "faas_type": infos.faasType, + "gen_code": "5TH", + "bldgappr_location.date_created": "{{currentTimestamp}}", + "bldgappr_location.date_modified": "{{currentTimestamp}}", + "bldgappr_location.street": firstLoc.street, + "bldgappr_location.barangay": firstLoc.barangay, + "bldgappr_location.municipality": firstLoc.municipality, + "bldgappr_location.province": firstLoc.province, + "bldgappr_location.gen_code": "5TH", + "bldgappr_landref.date_created": "{{currentTimestamp}}", + "bldgappr_landref.date_modified": "{{currentTimestamp}}", + "bldgappr_landref.owner": firstLandRef.owner, + "bldgappr_landref.cloa_no": firstLandRef.cloaNo, + "bldgappr_landref.lot_no": firstLandRef.lotNo, + "bldgappr_landref.tdn": firstLandRef.tdn, + "bldgappr_landref.area": firstLandRef.area, + "bldgappr_landref.survey_no": firstLandRef.surveyNo, + "bldgappr_landref.blk_no": firstLandRef.blkNo, + "bldgappr_landref.gen_code": "5TH", + "bldgappr_generaldesc.date_created": "{{currentTimestamp}}", + "bldgappr_generaldesc.date_modified": "{{currentTimestamp}}", + "bldgappr_generaldesc.bldg_kind": firstGenDesc.bldgKind, + "bldgappr_generaldesc.struc_type": firstGenDesc.strucType, + "bldgappr_generaldesc.bldg_permit": firstGenDesc.bldgPermit, + "bldgappr_generaldesc.date_issued": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstGenDesc.dateIssued!)), + "bldgappr_generaldesc.cct": null, + "bldgappr_generaldesc.cert_completion_issued": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstGenDesc.certCompletionIssued!)), + "bldgappr_generaldesc.cert_occupancy_issued": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstGenDesc.certOccupancyIssued!)), + "bldgappr_generaldesc.date_completed": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstGenDesc.dateCompleted!)), + "bldgappr_generaldesc.date_occupied": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstGenDesc.dateOccupied!)), + "bldgappr_generaldesc.bldg_age": firstGenDesc.bldgAge, + "bldgappr_generaldesc.no_storeys": firstGenDesc.noStoreys, + "bldgappr_generaldesc.area_1stfloor": firstGenDesc.area1Stfloor, + "bldgappr_generaldesc.area_2ndfloor": firstGenDesc.area2Ndfloor, + "bldgappr_generaldesc.area_3rdfloor": firstGenDesc.area3Rdfloor, + "bldgappr_generaldesc.area_4thfloor": firstGenDesc.area4Thfloor, + "bldgappr_generaldesc.total_floor_area": firstGenDesc.totalFloorArea, + "bldgappr_generaldesc.floor_sketch": null, + "bldgappr_generaldesc.actual_use": firstGenDesc.actualUse, + "bldgappr_generaldesc.unit_value": firstGenDesc.unitValue, + "bldgappr_generaldesc.gen_code": "5TH", + "bldgappr_struct_materials.date_created": "{{currentTimestamp}}", + "bldgappr_struct_materials.date_modified": "{{currentTimestamp}}", + "bldgappr_struct_materials.foundation": firstStructMat.foundation, + "bldgappr_struct_materials.columns": firstStructMat.columns, + "bldgappr_struct_materials.beams": firstStructMat.beams, + "bldgappr_struct_materials.truss_framing": firstStructMat.trussFraming, + "bldgappr_struct_materials.roof": firstStructMat.roof, + "bldgappr_struct_materials.flooring": firstStructMat.flooring, + "bldgappr_struct_materials.walls": firstStructMat.walls, + "bldgappr_struct_materials.others": firstStructMat.others, + "bldgappr_struct_materials.gen_code": "5TH", + "bldgappr_property_assessment.date_created": "{{currentTimestamp}}", + "bldgappr_property_assessment.date_modified": "{{currentTimestamp}}", + "bldgappr_property_assessment.actual_use": firstAssess.actualUse, + "bldgappr_property_assessment.market_value": firstAssess.marketValue, + "bldgappr_property_assessment.assessment_level": + firstAssess.assessmentLevel, + "bldgappr_property_assessment.assessed_value": + firstAssess.assessedValue, + "bldgappr_property_assessment.taxable": firstAssess.taxable, + "bldgappr_property_assessment.exempt": firstAssess.exempt, + "bldgappr_property_assessment.qtr": firstAssess.qtr, + "bldgappr_property_assessment.yr": firstAssess.yr, + "bldgappr_property_assessment.appraisedby_name": + firstAssess.appraisedbyName, + "bldgappr_property_assessment.appraisedby_designation": + firstAssess.appraisedbyDesignation, + "bldgappr_property_assessment.appraisedby_date": + DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstAssess.appraisedbyDate!)), + "bldgappr_property_assessment.recommendappr_name": + firstAssess.recommendapprName, + "bldgappr_property_assessment.recommendappr_designation": + firstAssess.recommendapprDesignation, + "bldgappr_property_assessment.recommendappr_date": + DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstAssess.recommendapprDate!)), + "bldgappr_property_assessment.approvedby_name": + firstAssess.approvedbyName, + "bldgappr_property_assessment.approvedby_designation": + firstAssess.approvedbyDesignation, + "bldgappr_property_assessment.approvedby_date": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstAssess.approvedbyDate!)), + "bldgappr_property_assessment.memoranda": firstAssess.memoranda, + "bldgappr_property_assessment.note": firstAssess.note, + "bldgappr_property_assessment.swornstatement_no": + firstAssess.swornstatementNo, + "bldgappr_property_assessment.date_received": DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstAssess.dateReceived!)), + "bldgappr_property_assessment.entry_date_assessment": + DateFormat("yyyy-MM-dd") + .format(DateTime.parse(firstAssess.entryDateAssessment!)), + "bldgappr_property_assessment.entry_date_by": " ", + "bldgappr_property_assessment.gen_code": "5TH", + "bldgappr_rec_supersededass.date_created": "{{currentTimestamp}}", + "bldgappr_rec_supersededass.date_modified": "{{currentTimestamp}}", + "bldgappr_rec_supersededass.pin": " ", + "bldgappr_rec_supersededass.tdn": " ", + "bldgappr_rec_supersededass.total_assval": "0", + "bldgappr_rec_supersededass.owner": " ", + "bldgappr_rec_supersededass.effectivity_ass": null, + "bldgappr_rec_supersededass.page_no": "0", + "bldgappr_rec_supersededass.total_marketval": "0", + "bldgappr_rec_supersededass.total_area": "0", + "bldgappr_rec_supersededass.rec_assessment": null, + "bldgappr_rec_supersededass.rec_taxmapping": " ", + "bldgappr_rec_supersededass.rec_records": " ", + "bldgappr_rec_supersededass.date": null, + "bldgappr_rec_supersededass.gen_code": "5TH" + }; + + return details; + } + + Future _postAdditionalItems( + Map datas, PropertyInfo infos) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + List> addItems = + await SQLServices.instance.getAdditionalItems(infos.id); + + List addItemsList = + addItems.map((map) => AdditionalItems.fromJson(map)).toList(); + + for (AdditionalItems items in addItemsList) { + // Populate AdditionalItems model here + final addItems = AdditionalItems( + id: 1, + bldgapprDetailsId: datas['data']['id'], + classId: items.classId, + className: items.className, + structType: items.structType, + unitValue: items.unitValue, + baseUnitValue: items.baseUnitValue, + area: items.area, + marketValue: items.marketValue, + depreciationRate: items.depreciationRate, + adjustedMarketVal: items.adjustedMarketVal, + amtDepreciation: items.amtDepreciation, + painted: items.painted, + secondhand: items.secondhand, + paintedUnitval: items.paintedUnitval, + secondhandUnitval: items.secondhandUnitval, + actualUse: items.actualUse, + genCode: "5TH"); + Response addResponse = await post( + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/additional_items/'), + headers: headers, + body: jsonEncode(addItems)); + print(addResponse.body); + } + } + + Future _postBuildingStructures( + Map datas, PropertyInfo infos) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + List> bldgStructures = + await SQLServices.instance.getBuildingAndStructure(infos.id); + + List bldgStructureList = + bldgStructures.map((map) => BldgAndStructure.fromJson(map)).toList(); + for (BldgAndStructure structure in bldgStructureList) { + final bldgStruc = BldgAndStructure( + id: 1, + bldgapprDetailsId: datas['data']['id'], + bldgArea: structure.bldgArea, + bldgType: structure.bldgType, + structType: structure.structType, + description: structure.description, + actualUse: structure.actualUse, + floorCount: structure.floorCount, + unitValue: structure.unitValue, + depRate: structure.depRate, + marketValue: structure.marketValue, + depAmount: structure.depAmount, + adjustedMarketValue: structure.adjustedMarketValue, + genCode: '5TH', + buccPercentage: structure.buccPercentage); + Response response = await post( + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/bldgappr_structure/'), + headers: headers, + body: jsonEncode(bldgStruc)); + print(response.body); + } + } + + Future _postBuildingDetails(Map details) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret + }; + + return await post( + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/bldgappr_details/'), + headers: headers, + body: jsonEncode(details)); + } + + Future _postFloorSketch( + Map details, file) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + // Construct the headers for the request + Map headers = { + 'Content-Type': 'multipart/form-data', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret, + }; + + // Create a MultipartRequest + var request = MultipartRequest( + 'POST', + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/bldgappr_sketch/'), + ); + + // Add the headers to the request + request.headers.addAll(headers); + + // Add JSON data as a field + // Add individual fields to the request + details.forEach((key, value) { + request.fields[key] = value.toString(); + }); + + // Add the floor sketch image file, if it exists + + var fileName = basename(file); + request.files.add( + await MultipartFile.fromPath( + 'floor_sketch', // Field name in the API + file, + filename: fileName, + ), + ); + + // Send the request and get the response + var streamedResponse = await request.send(); + return await Response.fromStream(streamedResponse); + } + + Future _uploadImage(data, infos) async { + // Create a map with the required fields + + List> floorSketch = + await SQLServices.instance.getFloorSketch(infos.id); + + // Parse data + FloorSketch firstFs = FloorSketch.fromJson(floorSketch.first); + var file = File(firstFs.floorSketch!); + Map detailsMap = { + "bldgappr_details_id": data['data']['id'], // int8 NOT NULL + "date_created": DateTime.now().toIso8601String(), // timestamptz NULL + "floor_sketch": firstFs.floorSketch!, // text NULL + "gen_code": "5TH", // varchar(20) NOT NULL + }; + + try { + Response response = await _postFloorSketch(detailsMap, file.path); + print(response.body); + + if (response.statusCode == 201) { + print('Upload successful'); + } else { + print('Upload failed with status: ${response.statusCode}'); + } + } catch (e) { + print('Error: $e'); + } + } + + on((event, emit) async { + emit(UploadBuildingFaasLoading()); + try { + List propertyOwner = + await SQLServices.instance.readAllBldgOwner(); + + for (PropertyInfo infos in propertyOwner) { + if (infos.dateSynced == null) { + final details = await _prepareBuildingDetails(event, infos); + + Response detailsResponse = await _postBuildingDetails(details); + final datas = json.decode(detailsResponse.body); + + print(datas); + + await _postAdditionalItems(datas, infos); + await _postBuildingStructures(datas, infos); + await _uploadImage(datas, infos); + + if (detailsResponse.statusCode == 201) { + final detailsInfo = PropertyInfo( + id: infos.id, + transCode: infos.transCode, + assessedById: infos.assessedById, + assessedByName: infos.assessedByName, + tdn: infos.tdn, + pin: infos.pin, + fname: infos.fname, + mname: infos.mname, + bday: infos.bday, + lname: infos.lname, + address: infos.address, + telno: infos.telno, + tin: infos.tin, + adminUser: infos.adminUser, + adminAddress: infos.adminAddress, + adminTin: infos.adminTin, + adminTelno: infos.adminTelno, + faasType: "Building", + dateSynced: + DateFormat('MM/dd/yyyy hh:mm a').format(DateTime.now())); + + await SQLServices.instance.updateBldgOwner(infos.id, detailsInfo); + } + } + + propertyOwner = await SQLServices.instance.readAllBldgOwner(); + emit(PropertyInfoLoaded(propertyInfos: propertyOwner)); + } + } catch (e) { + print(e.toString()); + emit(PropertyOwnerInfoErrorState(errorMessage: e.toString())); + } + ; + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_event.dart b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_event.dart new file mode 100644 index 0000000..0f42778 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_event.dart @@ -0,0 +1,117 @@ +part of 'crud_bloc.dart'; + +abstract class CrudEvent extends Equatable { + const CrudEvent(); +} + +class AddTodo extends CrudEvent { + final String id; + final String transCode; + final String tdn; + final String pin; + final String fname; + final String mname; + final String lname; + final String bday; + final String address; + final String telno; + final String tin; + final String adminUser; + final String adminAddress; + final String adminTelno; + final String adminTin; + final String faasType; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String genCode; + + const AddTodo( + {required this.id, + required this.transCode, + required this.tdn, + required this.pin, + required this.fname, + required this.mname, + required this.lname, + required this.bday, + required this.address, + required this.telno, + required this.tin, + required this.adminUser, + required this.adminAddress, + required this.adminTelno, + required this.adminTin, + required this.faasType, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.genCode}); + + @override + List get props => [ + id, + transCode, + tdn, + pin, + fname, + mname, + lname, + bday, + address, + telno, + tin, + adminUser, + adminAddress, + adminTelno, + adminTin, + faasType, + assessedById, + assessedByName, + dateCreated, + dateModified, + genCode + ]; +} + +class UpdatePropertyOwnerInfo extends CrudEvent { + final PropertyInfo propertyInfo; + final int id; + + UpdatePropertyOwnerInfo({required this.id, required this.propertyInfo}); + + @override + List get props => [id, propertyInfo]; +} + +class FetchTodos extends CrudEvent { + const FetchTodos(); + + @override + List get props => []; +} + +class UploadBuildingFaas extends CrudEvent { + final OfflineProfile offlineProfile; + const UploadBuildingFaas({required this.offlineProfile}); + + @override + List get props => [offlineProfile]; +} + +class FetchSpecificTodo extends CrudEvent { + final int id; + const FetchSpecificTodo({required this.id}); + + @override + List get props => [id]; +} + +class DeleteTodo extends CrudEvent { + final int id; + const DeleteTodo({required this.id}); + @override + List get props => [id]; +} diff --git a/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_state.dart b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_state.dart new file mode 100644 index 0000000..4da2759 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/owner_info_bloc/crud_state.dart @@ -0,0 +1,43 @@ +part of 'crud_bloc.dart'; + +abstract class CrudState extends Equatable { + const CrudState(); +} + +class CrudInitial extends CrudState { + @override + List get props => []; +} + +class PropertyOwnerInfoLoading extends CrudState { + @override + List get props => []; +} + +class PropertyOwnerInfoErrorState extends CrudState { + final String errorMessage; + const PropertyOwnerInfoErrorState({required this.errorMessage}); + @override + List get props => [errorMessage]; +} + +class PropertyInfoLoaded extends CrudState { + final List propertyInfos; + + const PropertyInfoLoaded({required this.propertyInfos}); + @override + List get props => [propertyInfos]; +} + +class DisplaySpecificTodo extends CrudState { + final Todo todo; + + const DisplaySpecificTodo({required this.todo}); + @override + List get props => [todo]; +} + +class UploadBuildingFaasLoading extends CrudState { + @override + List get props => []; +} diff --git a/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart new file mode 100644 index 0000000..92e505e --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart @@ -0,0 +1,57 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/structural_materials_ii.dart'; +import '../../../../../model/passo/structureMaterial.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'structural_material_offline_event.dart'; +part 'structural_material_offline_state.dart'; + +class StructuralMaterialOfflineBloc extends Bloc { + StructuralMaterialOfflineBloc() : super(StructuralMaterialOfflineInitial()) { + List materials = []; + on((event, emit) async { + await SQLServices.instance.createStructuralMaterials(StructureMaterialsII( + id: event.id, + bldgapprDetailsId: event.bldgapprDetailsId, + foundation: event.foundation!.join(', ').split(', '), + columns: event.columns!.join(', ').split(', '), + beams: event.beams!.join(', ').split(', '), + trussFraming: event.trussFraming!.join(', ').split(', '), + roof: event.roof!.join(', ').split(', '), + flooring: event.flooring!.join(', ').split(', '), + walls: event.walls!.join(', ').split(', '), + others: event.others!.join(', ').split(', '), + genCode: event.genCode, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified)); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getStructuralMaterials(event.id); + + if (result.isNotEmpty) { + List materialList = + result.map((map) => StructureMaterials.fromJson2(map)).toList(); + + // Choose a specific element from locationList + StructureMaterials firstMaterial = + materialList.first; // You can change this to select a specific item + + print('struct mat test result'); + print(firstMaterial); + emit(SpecificStructuralMaterialLoaded(materials: firstMaterial)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance + .updateStructuralMaterial(event.id, event.materials); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_event.dart b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_event.dart new file mode 100644 index 0000000..507fc57 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_event.dart @@ -0,0 +1,80 @@ +part of 'structural_material_offline_bloc.dart'; + +class StructuralMaterialOfflineEvent extends Equatable { + const StructuralMaterialOfflineEvent(); + + @override + List get props => []; +} + +class AddStructuralMaterial extends StructuralMaterialOfflineEvent { + final int id; + final int bldgapprDetailsId; + final List? foundation; + final List? columns; + final List? beams; + final List? trussFraming; + final List? roof; + final List? flooring; + final List? walls; + final List? others; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String genCode; + + const AddStructuralMaterial( + {required this.id, + required this.bldgapprDetailsId, + required this.foundation, + required this.columns, + required this.beams, + required this.trussFraming, + required this.roof, + required this.flooring, + required this.walls, + required this.others, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.genCode}); + + @override + List get props => [ + id, + bldgapprDetailsId, + ...?foundation, + ...?columns, + ...?beams, + ...?trussFraming, + ...?roof, + ...?flooring, + ...?walls, + ...?others, + assessedById, + assessedByName, + dateCreated, + dateModified, + genCode + ]; +} + +class FetchSingleStructuralMaterial extends StructuralMaterialOfflineEvent { + final int id; + const FetchSingleStructuralMaterial({required this.id}); + + @override + List get props => [id]; +} + +class UpdateStructuralMaterials extends StructuralMaterialOfflineEvent { + final StructureMaterialsII materials; + final int id; + + UpdateStructuralMaterials({required this.id, required this.materials}); + + @override + List get props => [id, materials]; +} diff --git a/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_state.dart b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_state.dart new file mode 100644 index 0000000..41ef1f3 --- /dev/null +++ b/lib/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_state.dart @@ -0,0 +1,29 @@ +part of 'structural_material_offline_bloc.dart'; + +class StructuralMaterialOfflineState extends Equatable { + const StructuralMaterialOfflineState(); + + @override + List get props => []; +} + +class StructuralMaterialOfflineInitial extends StructuralMaterialOfflineState { + @override + List get props => []; +} + +class StructuralMaterialLoaded extends StructuralMaterialOfflineState { + final List materials; + + const StructuralMaterialLoaded({required this.materials}); + @override + List get props => [materials]; +} + +class SpecificStructuralMaterialLoaded extends StructuralMaterialOfflineState { + final StructureMaterials materials; + + const SpecificStructuralMaterialLoaded({required this.materials}); + @override + List get props => [materials]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart new file mode 100644 index 0000000..3e6e278 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart @@ -0,0 +1,71 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart'; +import 'package:unit2/model/passo/land_appr.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_appraisal_event.dart'; +part 'land_property_appraisal_state.dart'; + +class LandPropertyAppraisalBloc + extends Bloc { + LandPropertyAppraisalBloc() : super(LandPropertyAppraisalInitial()) { + List landAppr = []; + on((event, emit) async { + emit(LandPropertyAppraisalInitial()); + try { + emit(LandPropertyAppraisalLoaded(landAppr: landAppr)); + } catch (e) { + emit(LandPropertyAppraisalErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(LandPropertyAppraisalInitial()); + List> result = + await SQLServices.instance.getLandPropertyAppraisal(event.id); + + if (result.isNotEmpty) { + landAppr = result.map((map) => LandAppr.fromJson2(map)).toList(); + + emit(LandPropertyAppraisalLoaded(landAppr: landAppr)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + print(event); + LandAppr item = await SQLServices.instance.createLandAppraisal(LandAppr( + landapprDetailsId: event.landapprDetailsId, + classification: event.classification, + subClass: event.subClass, + area: event.area, + unitValue: event.unitValue, + baseMarketval: event.baseMarketval)); + + print('Appraisal'); + print(item.toJson()); + + landAppr.add(item); + + emit(LandPropertyAppraisalLoaded(landAppr: landAppr)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowAddItemsScreen()); + }); + // on((event, emit) async { + // addItems = await SQLServices.instance.readAdditionalItems(); + // emit(AdditionalItemsLoaded(addItem: addItems)); + // }); + on((event, emit) async { + landAppr.removeWhere(((LandAppr element) => element.id == event.id)); + await SQLServices.instance.deleteLandPropertyAppraisal(id: event.id); + emit(const LandPropertyAppraisalDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_event.dart b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_event.dart new file mode 100644 index 0000000..64670f0 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_event.dart @@ -0,0 +1,86 @@ +part of 'land_property_appraisal_bloc.dart'; + +class LandPropertyAppraisalEvent extends Equatable { + const LandPropertyAppraisalEvent(); + + @override + List get props => []; +} + +class LoadLandPropertyAppraisal extends LandPropertyAppraisalEvent { + final List landAppr; + + const LoadLandPropertyAppraisal({this.landAppr = const []}); + + @override + List get props => [landAppr]; +} + +class LoadLandPropertyAppraisalEdit extends LandPropertyAppraisalEvent { + final List landAppr; + final int? id; + + const LoadLandPropertyAppraisalEdit({required this.landAppr, this.id}); + + @override + List get props => [landAppr]; +} + +class AddLandPropertyAppraisal extends LandPropertyAppraisalEvent { + final int landapprDetailsId; + final String classification; + final String subClass; + final String area; + final String unitValue; + final String baseMarketval; + + const AddLandPropertyAppraisal({ + required this.landapprDetailsId, + required this.classification, + required this.subClass, + required this.area, + required this.unitValue, + required this.baseMarketval, + }); + + @override + List get props => [ + landapprDetailsId, + classification, + subClass, + area, + unitValue, + baseMarketval, + ]; +} + +class UpdateLandPropertyAppraisal extends LandPropertyAppraisalEvent { + final LandAppr landAppr; + const UpdateLandPropertyAppraisal({required this.landAppr}); + @override + List get props => [landAppr]; +} + +class FetchLandPropertyAppraisal extends LandPropertyAppraisalEvent { + const FetchLandPropertyAppraisal(); + + @override + List get props => []; +} + +class FetchSpecificLandPropertyAppraisal extends LandPropertyAppraisalEvent { + final int id; + const FetchSpecificLandPropertyAppraisal({required this.id}); + + @override + List get props => [id]; +} + +class DeleteLandPropertyAppraisal extends LandPropertyAppraisalEvent { + final int id; + const DeleteLandPropertyAppraisal({required this.id}); + @override + List get props => [id]; +} + +class ShowAdditionalItems extends LandPropertyAppraisalEvent {} diff --git a/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_state.dart b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_state.dart new file mode 100644 index 0000000..5a63020 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_state.dart @@ -0,0 +1,46 @@ +part of 'land_property_appraisal_bloc.dart'; + +class LandPropertyAppraisalState extends Equatable { + const LandPropertyAppraisalState(); + + @override + List get props => []; +} + +class LandPropertyAppraisalInitial extends LandPropertyAppraisalState { + @override + List get props => []; +} + +class LandPropertyAppraisalLoaded extends LandPropertyAppraisalState { + final List landAppr; + + const LandPropertyAppraisalLoaded({required this.landAppr}); + @override + List get props => [landAppr]; +} + +class LoadSpecificLandPropertyAppraisal extends LandPropertyAppraisalState { + final LandAppr landAppr; + + const LoadSpecificLandPropertyAppraisal({required this.landAppr}); + @override + List get props => [landAppr]; +} + +class ShowAddItemsScreen extends LandPropertyAppraisalState {} + +class LandPropertyAppraisalErrorState extends LandPropertyAppraisalState { + const LandPropertyAppraisalErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class LandPropertyAppraisalDeletedState extends LandPropertyAppraisalState { + final bool success; + const LandPropertyAppraisalDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart new file mode 100644 index 0000000..2d99f77 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart @@ -0,0 +1,72 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_property_assessment.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_assessment_event.dart'; +part 'land_property_assessment_state.dart'; + +class LandPropertyAssessmentBloc + extends Bloc { + LandPropertyAssessmentBloc() : super(LandPropertyAssessmentInitial()) { + List landPropertyAssessment = []; + on((event, emit) async { + emit(LandPropertyAssessmentInitial()); + try { + emit(LandPropertyAssessmentLoaded( + landPropertyAssessment: landPropertyAssessment)); + } catch (e) { + emit(LandPropertyAssessmentErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(LandPropertyAssessmentInitial()); + List> result = + await SQLServices.instance.getLandPropertyAssessment(event.id); + + if (result.isNotEmpty) { + landPropertyAssessment = + result.map((map) => LandPropertyAssessment.fromJson2(map)).toList(); + + emit(LandPropertyAssessmentLoaded( + landPropertyAssessment: landPropertyAssessment)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + LandPropertyAssessment item = await SQLServices.instance + .createLandPropertyAssessment(LandPropertyAssessment( + landapprDetailsId: event.landapprDetailsId, + actualUse: event.actualUse, + marketval: event.marketval, + assessmentLevel: event.assessmentLevel, + assessedValue: event.assessedValue, + totalMarketval: event.totalMarketval, + totalAssessedval: event.totalAssessedval, + )); + + print(item.toJson()); + + landPropertyAssessment.add(item); + + emit(LandPropertyAssessmentLoaded( + landPropertyAssessment: landPropertyAssessment)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowLandPropertyAssessmentcreen()); + }); + on((event, emit) async { + landPropertyAssessment.removeWhere( + ((LandPropertyAssessment element) => element.id == event.id)); + await SQLServices.instance.deleteLandPropertyAssessment(id: event.id); + emit(const LandPropertyAssessmentDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_event.dart b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_event.dart new file mode 100644 index 0000000..4e61c9b --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_event.dart @@ -0,0 +1,91 @@ +part of 'land_property_assessment_bloc.dart'; + +class LandPropertyAssessmentEvent extends Equatable { + const LandPropertyAssessmentEvent(); + + @override + List get props => []; +} + +class LoadLandPropertyAssessment extends LandPropertyAssessmentEvent { + final List landPropertyAssessment; + + const LoadLandPropertyAssessment( + {this.landPropertyAssessment = const []}); + + @override + List get props => [landPropertyAssessment]; +} + +class LoadLandPropertyAssessmentEdit extends LandPropertyAssessmentEvent { + final List landPropertyAssessment; + final int? id; + + const LoadLandPropertyAssessmentEdit( + {required this.landPropertyAssessment, this.id}); + + @override + List get props => [landPropertyAssessment]; +} + +class AddLandPropertyAssessment extends LandPropertyAssessmentEvent { + final int landapprDetailsId; + final String actualUse; + final String marketval; + final String assessmentLevel; + final String assessedValue; + final String totalMarketval; + final String totalAssessedval; + + const AddLandPropertyAssessment({ + required this.landapprDetailsId, + required this.actualUse, + required this.marketval, + required this.assessmentLevel, + required this.assessedValue, + required this.totalMarketval, + required this.totalAssessedval, + }); + + @override + List get props => [ + landapprDetailsId, + actualUse, + marketval, + assessmentLevel, + assessedValue, + totalMarketval, + totalAssessedval, + ]; +} + +class UpdateLandPropertyAssessment extends LandPropertyAssessmentEvent { + final LandPropertyAssessment landPropertyAssessment; + const UpdateLandPropertyAssessment({required this.landPropertyAssessment}); + @override + List get props => [landPropertyAssessment]; +} + +class FetchLandPropertyAssessment extends LandPropertyAssessmentEvent { + const FetchLandPropertyAssessment(); + + @override + List get props => []; +} + +class FetchSpecificLandPropertyAssessment extends LandPropertyAssessmentEvent { + final int id; + const FetchSpecificLandPropertyAssessment({required this.id}); + + @override + List get props => [id]; +} + +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/offline/offline_passo/land/land_property_assessment/land_property_assessment_state.dart b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_state.dart new file mode 100644 index 0000000..5fd09f7 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_state.dart @@ -0,0 +1,47 @@ +part of 'land_property_assessment_bloc.dart'; + +class LandPropertyAssessmentState extends Equatable { + const LandPropertyAssessmentState(); + + @override + List get props => []; +} + +class LandPropertyAssessmentInitial extends LandPropertyAssessmentState { + @override + List get props => []; +} + +class LandPropertyAssessmentLoaded extends LandPropertyAssessmentState { + final List landPropertyAssessment; + + const LandPropertyAssessmentLoaded({required this.landPropertyAssessment}); + @override + List get props => [landPropertyAssessment]; +} + +class LoadSpecificLandPropertyAssessment extends LandPropertyAssessmentState { + final LandPropertyAssessment landPropertyAssessment; + + const LoadSpecificLandPropertyAssessment( + {required this.landPropertyAssessment}); + @override + List get props => [landPropertyAssessment]; +} + +class ShowLandPropertyAssessmentcreen 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/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart new file mode 100644 index 0000000..014bdf2 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart @@ -0,0 +1,55 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_property_boundaries.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_boundaries_event.dart'; +part 'land_property_boundaries_state.dart'; + +class LandPropertyBoundariesBloc + extends Bloc { + LandPropertyBoundariesBloc() : super(LandPropertyBoundariesInitial()) { + List todos = []; + on((event, emit) async { + await SQLServices.instance.createLandPropertyBoundaries( + LandPropertyBoundaries( + id: event.id, + landapprDetailsId: event.landapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + north: event.north, + east: event.east, + south: event.south, + west: event.west, + sketch: event.sketch)); + }); + on((event, emit) async { + List> result = + await SQLServices.instance.getLandPropertyBoundaries(event.id); + + if (result.isNotEmpty) { + List landpropertyboundariesList = + result.map((map) => LandPropertyBoundaries.fromJson(map)).toList(); + + // Choose a specific element from landpropertyboundariesList + LandPropertyBoundaries firstLandPropertyBoundaries = + landpropertyboundariesList + .first; // You can change this to select a specific item + + print('landpropertyboundaries test result'); + print(firstLandPropertyBoundaries); + emit(SpecificLandPropertyBoundariesLoaded( + landpropertyboundaries: firstLandPropertyBoundaries)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance + .updateLandPropertyBoundaries(event.id, event.landPropertyBoundaries); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_event.dart b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_event.dart new file mode 100644 index 0000000..e89773a --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_event.dart @@ -0,0 +1,77 @@ +part of 'land_property_boundaries_bloc.dart'; + +class LandPropertyBoundariesEvent extends Equatable { + const LandPropertyBoundariesEvent(); + + @override + List get props => []; +} + +class AddLandPropertyBoundaries extends LandPropertyBoundariesEvent { + final int id; + final int landapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String north; + final String east; + final String south; + final String west; + final String sketch; + + const AddLandPropertyBoundaries({ + required this.id, + required this.landapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.north, + required this.east, + required this.south, + required this.west, + required this.sketch, + }); + + @override + List get props => [ + id, + landapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + north, + east, + south, + west, + sketch, + ]; +} + +class UpdateLandPropertyBoundaries extends LandPropertyBoundariesEvent { + final LandPropertyBoundaries landPropertyBoundaries; + final int id; + + UpdateLandPropertyBoundaries( + {required this.id, required this.landPropertyBoundaries}); + + @override + List get props => [id, landPropertyBoundaries]; +} + +class FetchLanRef extends LandPropertyBoundariesEvent { + const FetchLanRef(); + + @override + List get props => []; +} + +class FetchSingleLandPropertyBoundaries extends LandPropertyBoundariesEvent { + final int id; + const FetchSingleLandPropertyBoundaries({required this.id}); + + @override + List get props => [id]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_state.dart b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_state.dart new file mode 100644 index 0000000..8e49360 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_state.dart @@ -0,0 +1,30 @@ +part of 'land_property_boundaries_bloc.dart'; + +class LandPropertyBoundariesState extends Equatable { + const LandPropertyBoundariesState(); + + @override + List get props => []; +} + +class LandPropertyBoundariesInitial extends LandPropertyBoundariesState { + @override + List get props => []; +} + +class LandPropertyBoundariesLoaded extends LandPropertyBoundariesState { + final List landpropertyboundaries; + + const LandPropertyBoundariesLoaded({required this.landpropertyboundaries}); + @override + List get props => [landpropertyboundaries]; +} + +class SpecificLandPropertyBoundariesLoaded extends LandPropertyBoundariesState { + final LandPropertyBoundaries landpropertyboundaries; + + const SpecificLandPropertyBoundariesLoaded( + {required this.landpropertyboundaries}); + @override + List get props => [landpropertyboundaries]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart new file mode 100644 index 0000000..57b5375 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart @@ -0,0 +1,58 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_property_loc.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_location_event.dart'; +part 'land_property_location_state.dart'; + +class LandPropertyLocationBloc + extends Bloc { + LandPropertyLocationBloc() : super(LandPropertyLocationInitial()) { + List todos = []; + on((event, emit) async { + await SQLServices.instance.createLandLocation(LandPropertyLoc( + id: event.id, + landapprDetailsId: event.landapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + street: event.street, + municipality: event.municipality, + barangay: event.barangay, + province: event.province, + )); + }); + on((event, emit) async { + // todos = await SQLServices.instance.getLandPropertyOwner(); + // emit(LandPropertyOwnerLoaded(landPropertyOwner: todos)); + }); + + on((event, emit) async { + List> result = + await SQLServices.instance.getLandPropertyLocation(event.id); + + if (result.isNotEmpty) { + List landpropertylocationList = + result.map((map) => LandPropertyLoc.fromJson2(map)).toList(); + + // Choose a specific element from landpropertylocationList + LandPropertyLoc firstLandPropertyLocation = landpropertylocationList + .first; // You can change this to select a specific item + + print('landpropertylocation test result'); + print(firstLandPropertyLocation); + emit(SpecificLandPropertyLocationLoaded( + landpropertylocation: firstLandPropertyLocation)); + } else { + print('No data found.'); + } + }); + on((event, emit) async { + await SQLServices.instance + .updateLandPropertyLocation(event.id, event.landPropertyLocation); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_event.dart b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_event.dart new file mode 100644 index 0000000..8782757 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_event.dart @@ -0,0 +1,81 @@ +part of 'land_property_location_bloc.dart'; + +class LandPropertyLocationEvent extends Equatable { + const LandPropertyLocationEvent(); + + @override + List get props => []; +} + +class AddLandPropertyLocation extends LandPropertyLocationEvent { + final int id; + final int landapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String street; + final String municipality; + final String barangay; + final String province; + + const AddLandPropertyLocation({ + required this.id, + required this.landapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.street, + required this.municipality, + required this.barangay, + required this.province, + }); + + @override + List get props => [ + id, + landapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + street, + municipality, + barangay, + province, + ]; +} + +class UpdateLandPropertyLocation extends LandPropertyLocationEvent { + final LandPropertyLoc landPropertyLocation; + final int id; + + UpdateLandPropertyLocation( + {required this.id, required this.landPropertyLocation}); + + @override + List get props => [id, landPropertyLocation]; +} + +class LoadLandPropertyLocation extends LandPropertyLocationEvent { + const LoadLandPropertyLocation(); + + @override + List get props => []; +} + +class FetchLanRef extends LandPropertyLocationEvent { + const FetchLanRef(); + + @override + List get props => []; +} + +class FetchSingleLandPropertyLocation extends LandPropertyLocationEvent { + final int id; + const FetchSingleLandPropertyLocation({required this.id}); + + @override + List get props => [id]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_state.dart b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_state.dart new file mode 100644 index 0000000..dcdb7d6 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_location/land_property_location_state.dart @@ -0,0 +1,30 @@ +part of 'land_property_location_bloc.dart'; + +class LandPropertyLocationState extends Equatable { + const LandPropertyLocationState(); + + @override + List get props => []; +} + +class LandPropertyLocationInitial extends LandPropertyLocationState { + @override + List get props => []; +} + +class LandPropertyLocationLoaded extends LandPropertyLocationState { + final List landpropertylocation; + + const LandPropertyLocationLoaded({required this.landpropertylocation}); + @override + List get props => [landpropertylocation]; +} + +class SpecificLandPropertyLocationLoaded extends LandPropertyLocationState { + final LandPropertyLoc landpropertylocation; + + const SpecificLandPropertyLocationLoaded( + {required this.landpropertylocation}); + @override + List get props => [landpropertylocation]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart new file mode 100644 index 0000000..911288d --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart @@ -0,0 +1,71 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_owner_event.dart'; +part 'land_property_owner_state.dart'; + +class LandPropertyOwnerBloc + extends Bloc { + LandPropertyOwnerBloc() : super(LandPropertyOwnerInitial()) { + List todos = []; + on((event, emit) async { + try { + await SQLServices.instance.createLandOwner( + LandPropertyOwner( + id: event.id, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + transCode: event.transCode, + tdn: event.tdn, + pin: event.pin, + cloaNo: event.cloaNo, + dated: event.dated, + surveyNo: event.surveyNo, + lotNo: event.lotNo, + blkNo: event.blkNo, + owner: event.owner, + address: event.address, + telno: event.telno, + tin: event.tin, + adminUser: event.adminUser, + adminTelno: event.adminTelno, + adminAddress: event.adminAddress, + adminTin: event.adminTin, + faasType: event.faasType), + ); + } catch (e) { + emit(LandPropertyOwnerInfoErrorState(errorMessage: 'error')); + print('Error: $e'); + // You might want to throw or log the error, or take other appropriate actions + + // If you want to rethrow the error, uncomment the following line + // throw e; + } + }); + + on((event, emit) async { + await SQLServices.instance + .updateLandPropertyOwner(event.id, event.landPropertyOwner); + }); + + on((event, emit) async { + todos = await SQLServices.instance.getLandPropertyOwner(); + emit(LandPropertyOwnerLoaded(landPropertyOwner: todos)); + }); + + // on((event, emit) async { + // Prop todo = await PropertyOwnerInfoServices.instance.readTodo(id: event.id); + // emit(DisplaySpecificTodo(todo: todo)); + // }); + + on((event, emit) async { + await SQLServices.instance.deleteLandPropertyOwner(id: event.id); + add(const LoadLandPropertyOwner()); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_event.dart b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_event.dart new file mode 100644 index 0000000..6d7806b --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_event.dart @@ -0,0 +1,116 @@ +part of 'land_property_owner_bloc.dart'; + +class LandPropertyOwnerEvent extends Equatable { + const LandPropertyOwnerEvent(); + + @override + List get props => []; +} + +class AddLandPropertyOwner extends LandPropertyOwnerEvent { + final int id; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String transCode; + final String tdn; + final String pin; + final String cloaNo; + final String 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; + + const AddLandPropertyOwner( + {required this.id, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.transCode, + required this.tdn, + required this.pin, + required this.cloaNo, + required this.dated, + required this.surveyNo, + required this.lotNo, + required this.blkNo, + required this.owner, + required this.address, + required this.telno, + required this.tin, + required this.adminUser, + required this.adminTelno, + required this.adminAddress, + required this.adminTin, + required this.faasType}); + + @override + List get props => [ + id, + assessedById, + assessedByName, + dateCreated, + dateModified, + transCode, + tdn, + pin, + cloaNo, + dated, + surveyNo, + lotNo, + blkNo, + owner, + address, + telno, + tin, + adminUser, + adminTelno, + adminAddress, + adminTin, + faasType + ]; +} + +class UpdateLandPropertyOwnerInfo extends LandPropertyOwnerEvent { + final LandPropertyOwner landPropertyOwner; + final int id; + + const UpdateLandPropertyOwnerInfo( + {required this.id, required this.landPropertyOwner}); + + @override + List get props => [id, landPropertyOwner]; +} + +class LoadLandPropertyOwner extends LandPropertyOwnerEvent { + const LoadLandPropertyOwner(); + + @override + List get props => []; +} + +class LoadSpecificLandPropertyOwnerInfo extends LandPropertyOwnerEvent { + final int id; + const LoadSpecificLandPropertyOwnerInfo({required this.id}); + + @override + List get props => [id]; +} + +class DeleteLandPropertyOwner extends LandPropertyOwnerEvent { + final int id; + const DeleteLandPropertyOwner({required this.id}); + @override + List get props => [id]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_state.dart b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_state.dart new file mode 100644 index 0000000..666655b --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_state.dart @@ -0,0 +1,39 @@ +part of 'land_property_owner_bloc.dart'; + +class LandPropertyOwnerState extends Equatable { + @override + List get props => []; +} + +class LandPropertyOwnerInitial extends LandPropertyOwnerState { + @override + List get props => []; +} + +class LandPropertyOwnerInfoLoading extends LandPropertyOwnerState { + @override + List get props => []; +} + +class LandPropertyOwnerInfoErrorState extends LandPropertyOwnerState { + String errorMessage; + LandPropertyOwnerInfoErrorState({required this.errorMessage}); + @override + List get props => [errorMessage]; +} + +class LandPropertyOwnerLoaded extends LandPropertyOwnerState { + List landPropertyOwner; + + LandPropertyOwnerLoaded({required this.landPropertyOwner}); + @override + List get props => [landPropertyOwner]; +} + +class LoadSpecificLandPropertyOwner extends LandPropertyOwnerState { + LandPropertyOwner landPropertyOwner; + + LoadSpecificLandPropertyOwner({required this.landPropertyOwner}); + @override + List get props => [landPropertyOwner]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart new file mode 100644 index 0000000..d8d1530 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart @@ -0,0 +1,88 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/passo/land_ext.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'land_property_signature_event.dart'; +part 'land_property_signature_state.dart'; + +class LandPropertySignatureBloc + extends Bloc { + LandPropertySignatureBloc() : super(LandPropertySignatureInitial()) { + List landExt = []; + on((event, emit) async { + try { + print(event.landapprDetailsId); + await SQLServices.instance.createLandPropertySignatories( + LandExt( + id: event.id, + landapprDetailsId: event.landapprDetailsId, + assessedById: event.assessedById, + assessedByName: event.assessedByName, + dateCreated: event.dateCreated, + dateModified: event.dateModified, + taxable: event.taxable, + exempt: event.exempt, + qtr: event.qtr, + yr: event.yr, + appraisedbyName: event.appraisedbyName, + appraisedbyDate: event.appraisedbyDate, + recommendapprName: event.recommendapprName, + recommendapprDate: event.recommendapprDate, + approvedbyName: event.approvedbyName, + approvedbyDate: event.approvedbyDate, + memoranda: event.memoranda, + swornstatementNo: event.swornstatementNo, + dateReceived: event.dateReceived, + entryDateAssessment: event.entryDateAssessment, + entryDateBy: event.entryDateBy, + ), + ); + } catch (e) { + emit(LandPropertySignatureInfoErrorState(errorMessage: 'error')); + print('Error: $e'); + // You might want to throw or log the error, or take other appropriate actions + + // If you want to rethrow the error, uncomment the following line + // throw e; + } + }); + + on((event, emit) async { + await SQLServices.instance + .updateLandPropertySignature(event.id, event.landPropertySignature); + }); + + // on((event, emit) async { + // todos = await SQLServices.instance.getLandPropertySignature(); + // emit(LandPropertySignatureLoaded(landPropertySignature: todos)); + // }); + + on((event, emit) async { + List> result = + await SQLServices.instance.getLandPropertySignature(event.id); + + if (result.isNotEmpty) { + List genDescList = + result.map((map) => LandExt.fromJson2(map)).toList(); + + // Choose a specific element from locationList + LandExt firstLandExt = + genDescList.first; // You can change this to select a specific item + + print('location test result'); + print(firstLandExt); + emit(LoadSpecificLandPropertySignature( + landPropertySignature: firstLandExt)); + } else { + print('No data found.'); + } + }); + + // on((event, emit) async { + // await SQLServices.instance.de(id: event.id); + // add(const LoadLandPropertySignature()); + // }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_event.dart b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_event.dart new file mode 100644 index 0000000..cdae6ef --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_event.dart @@ -0,0 +1,114 @@ +part of 'land_property_signature_bloc.dart'; + +class LandPropertySignatureEvent extends Equatable { + const LandPropertySignatureEvent(); + + @override + List get props => []; +} + +class AddLandPropertySignature extends LandPropertySignatureEvent { + final int id; + final int landapprDetailsId; + final String assessedById; + final String assessedByName; + final String dateCreated; + final String dateModified; + final String taxable; + final String exempt; + final String qtr; + final String yr; + final String appraisedbyName; + final String appraisedbyDate; + final String recommendapprName; + final String recommendapprDate; + final String approvedbyName; + final String approvedbyDate; + final String memoranda; + final String swornstatementNo; + final String dateReceived; + final String entryDateAssessment; + final String entryDateBy; + + const AddLandPropertySignature({ + required this.id, + required this.landapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, + required this.taxable, + required this.exempt, + required this.qtr, + required this.yr, + required this.appraisedbyName, + required this.appraisedbyDate, + required this.recommendapprName, + required this.recommendapprDate, + required this.approvedbyName, + required this.approvedbyDate, + required this.memoranda, + required this.swornstatementNo, + required this.dateReceived, + required this.entryDateAssessment, + required this.entryDateBy, + }); + + @override + List get props => [ + id, + landapprDetailsId, + assessedById, + assessedByName, + dateCreated, + dateModified, + taxable, + exempt, + qtr, + yr, + appraisedbyName, + appraisedbyDate, + recommendapprName, + recommendapprDate, + approvedbyName, + approvedbyDate, + memoranda, + swornstatementNo, + dateReceived, + entryDateAssessment, + entryDateBy, + ]; +} + +class UpdateLandPropertySignatureInfo extends LandPropertySignatureEvent { + final LandExt landPropertySignature; + final int id; + + const UpdateLandPropertySignatureInfo( + {required this.id, required this.landPropertySignature}); + + @override + List get props => [id, landPropertySignature]; +} + +class LoadLandPropertySignature extends LandPropertySignatureEvent { + const LoadLandPropertySignature(); + + @override + List get props => []; +} + +class LoadSpecificLandPropertySignatureInfo extends LandPropertySignatureEvent { + final int id; + const LoadSpecificLandPropertySignatureInfo({required this.id}); + + @override + List get props => [id]; +} + +class DeleteLandPropertySignature extends LandPropertySignatureEvent { + final int id; + const DeleteLandPropertySignature({required this.id}); + @override + List get props => [id]; +} diff --git a/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_state.dart b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_state.dart new file mode 100644 index 0000000..c644a26 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_state.dart @@ -0,0 +1,41 @@ +part of 'land_property_signature_bloc.dart'; + +class LandPropertySignatureState extends Equatable { + const LandPropertySignatureState(); + + @override + List get props => []; +} + +class LandPropertySignatureInitial extends LandPropertySignatureState { + @override + List get props => []; +} + +class LandPropertySignatureInfoLoading extends LandPropertySignatureState { + @override + List get props => []; +} + +class LandPropertySignatureInfoErrorState extends LandPropertySignatureState { + String errorMessage; + LandPropertySignatureInfoErrorState({required this.errorMessage}); + @override + List get props => [errorMessage]; +} + +class LandPropertySignatureLoaded extends LandPropertySignatureState { + List landPropertySignature; + + LandPropertySignatureLoaded({required this.landPropertySignature}); + @override + List get props => [landPropertySignature]; +} + +class LoadSpecificLandPropertySignature extends LandPropertySignatureState { + LandExt landPropertySignature; + + LoadSpecificLandPropertySignature({required this.landPropertySignature}); + @override + List get props => [landPropertySignature]; +} diff --git a/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart new file mode 100644 index 0000000..c5959c3 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart @@ -0,0 +1,75 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart'; + +import '../../../../../model/passo/other_improvements.dart'; +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'other_improvements_event.dart'; +part 'other_improvements_state.dart'; + +class OtherImprovementsBloc + extends Bloc { + OtherImprovementsBloc() : super(OtherImprovementsInitial()) { + List otherImprovements = []; + on((event, emit) async { + emit(OtherImprovementsInitial()); + try { + emit(OtherImprovementsLoaded(otherImprovements: otherImprovements)); + } catch (e) { + emit(OtherImprovementsErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(OtherImprovementsInitial()); + List> result = + await SQLServices.instance.getOtherImprovements(event.id); + + if (result.isNotEmpty) { + otherImprovements = + result.map((map) => OtherImprovements.fromJson2(map)).toList(); + + emit(OtherImprovementsLoaded(otherImprovements: otherImprovements)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + OtherImprovements item = await SQLServices.instance + .createOtherImprovements(OtherImprovements( + landapprDetailsId: event.landapprDetailsId, + kindsOfTrees: event.kindsOfTrees, + subclassAge: event.subclassAge, + quantity: event.quantity, + unitValue: event.unitValue, + baseMarketval: event.baseMarketval, + noOfProductive: event.noOfProductive, + noOfNonproductive: event.noOfNonproductive, + fruitBearing: event.fruitBearing)); + + print(item.toJson()); + + otherImprovements.add(item); + + emit(OtherImprovementsLoaded(otherImprovements: otherImprovements)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowOtherImprovementScreen()); + }); + // on((event, emit) async { + // addItems = await SQLServices.instance.readAdditionalItems(); + // emit(AdditionalItemsLoaded(addItem: addItems)); + // }); + on((event, emit) async { + otherImprovements + .removeWhere(((OtherImprovements element) => element.id == event.id)); + await SQLServices.instance.deleteOtherImprovements(id: event.id); + emit(const OtherImprovementsDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_event.dart b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_event.dart new file mode 100644 index 0000000..ab31f40 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_event.dart @@ -0,0 +1,96 @@ +part of 'other_improvements_bloc.dart'; + +class OtherImprovementsEvent extends Equatable { + const OtherImprovementsEvent(); + + @override + List get props => []; +} + +class LoadOtherImprovements extends OtherImprovementsEvent { + final List otherImprovements; + + const LoadOtherImprovements( + {this.otherImprovements = const []}); + + @override + List get props => [otherImprovements]; +} + +class LoadOtherImprovementsEdit extends OtherImprovementsEvent { + final List otherImprovements; + final int? id; + + const LoadOtherImprovementsEdit({required this.otherImprovements, this.id}); + + @override + List get props => [otherImprovements]; +} + +class AddOtherImprovements extends OtherImprovementsEvent { + 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 String fruitBearing; + + const AddOtherImprovements({ + required this.landapprDetailsId, + required this.kindsOfTrees, + required this.subclassAge, + required this.quantity, + required this.unitValue, + required this.baseMarketval, + required this.noOfProductive, + required this.noOfNonproductive, + required this.fruitBearing, + }); + + @override + List get props => [ + landapprDetailsId, + kindsOfTrees, + subclassAge, + quantity, + unitValue, + baseMarketval, + noOfProductive, + noOfNonproductive, + fruitBearing, + ]; +} + +class UpdateOtherImprovements extends OtherImprovementsEvent { + final OtherImprovements otherImprovements; + const UpdateOtherImprovements({required this.otherImprovements}); + @override + List get props => [otherImprovements]; +} + +class FetchOtherImprovements extends OtherImprovementsEvent { + const FetchOtherImprovements(); + + @override + List get props => []; +} + +class FetchSpecificOtherImprovements extends OtherImprovementsEvent { + final int id; + const FetchSpecificOtherImprovements({required this.id}); + + @override + List get props => [id]; +} + +class DeleteOtherImprovements extends OtherImprovementsEvent { + final int id; + const DeleteOtherImprovements({required this.id}); + @override + List get props => [id]; +} + +class ShowOtherImprovement extends OtherImprovementsEvent {} diff --git a/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_state.dart b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_state.dart new file mode 100644 index 0000000..7ae926e --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/other_improvements/other_improvements_state.dart @@ -0,0 +1,46 @@ +part of 'other_improvements_bloc.dart'; + +class OtherImprovementsState extends Equatable { + const OtherImprovementsState(); + + @override + List get props => []; +} + +class OtherImprovementsInitial extends OtherImprovementsState { + @override + List get props => []; +} + +class OtherImprovementsLoaded extends OtherImprovementsState { + final List otherImprovements; + + const OtherImprovementsLoaded({required this.otherImprovements}); + @override + List get props => [otherImprovements]; +} + +class LoadSpecificOtherImprovements extends OtherImprovementsState { + final OtherImprovements otherImprovements; + + const LoadSpecificOtherImprovements({required this.otherImprovements}); + @override + List get props => [otherImprovements]; +} + +class ShowOtherImprovementScreen extends OtherImprovementsState {} + +class OtherImprovementsErrorState extends OtherImprovementsState { + const OtherImprovementsErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class OtherImprovementsDeletedState extends OtherImprovementsState { + final bool success; + const OtherImprovementsDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart new file mode 100644 index 0000000..0bcae56 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart @@ -0,0 +1,69 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +part 'value_adjustment_event.dart'; +part 'value_adjustment_state.dart'; + +class ValueAdjustmentBloc + extends Bloc { + ValueAdjustmentBloc() : super(ValueAdjustmentInitial()) { + List valueAdjustment = []; + on((event, emit) async { + emit(ValueAdjustmentInitial()); + try { + emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment)); + } catch (e) { + emit(ValueAdjustmentErrorState(e.toString())); + } + }); + on((event, emit) async { + emit(ValueAdjustmentInitial()); + List> result = + await SQLServices.instance.getValueAdjustments(event.id); + + if (result.isNotEmpty) { + valueAdjustment = + result.map((map) => ValueAdjustments.fromJson2(map)).toList(); + + emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment)); + } else { + print('No data found.'); + } + }); + + on((event, emit) async { + try { + ValueAdjustments item = + await SQLServices.instance.createValueAdjustments(ValueAdjustments( + landapprDetailsId: event.landapprDetailsId, + baseMarketval: event.baseMarketval, + adjustmentFactors: event.adjustmentFactors, + adjustment: event.adjustment, + valueAdjustment: event.valueAdjustment, + marketValue: event.marketValue, + )); + + print(item.toJson()); + + valueAdjustment.add(item); + + emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment)); + } catch (e) { + print(e.toString()); + } + }); + on((event, emit) async { + emit(ShowValueAdjustmentcreen()); + }); + on((event, emit) async { + valueAdjustment + .removeWhere(((ValueAdjustments element) => element.id == event.id)); + await SQLServices.instance.deleteValueAdjustment(id: event.id); + emit(const ValueAdjustmentDeletedState(success: true)); + }); + } +} diff --git a/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_event.dart b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_event.dart new file mode 100644 index 0000000..f31daa9 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_event.dart @@ -0,0 +1,88 @@ +part of 'value_adjustment_bloc.dart'; + +class ValueAdjustmentEvent extends Equatable { + const ValueAdjustmentEvent(); + + @override + List get props => []; +} + +class LoadValueAdjustment extends ValueAdjustmentEvent { + final List valueAdjustment; + + const LoadValueAdjustment( + {this.valueAdjustment = const []}); + + @override + List get props => [valueAdjustment]; +} + +class LoadValueAdjustmentEdit extends ValueAdjustmentEvent { + final List valueAdjustment; + final int? id; + + const LoadValueAdjustmentEdit( + {required this.valueAdjustment, required this.id}); + + @override + List get props => [valueAdjustment]; +} + +class AddValueAdjustments extends ValueAdjustmentEvent { + final int landapprDetailsId; + final String baseMarketval; + final String adjustmentFactors; + final String adjustment; + final String valueAdjustment; + final String marketValue; + + const AddValueAdjustments({ + required this.landapprDetailsId, + required this.baseMarketval, + required this.adjustmentFactors, + required this.adjustment, + required this.valueAdjustment, + required this.marketValue, + }); + + @override + List get props => [ + landapprDetailsId, + baseMarketval, + adjustmentFactors, + adjustment, + valueAdjustment, + marketValue, + ]; +} + +class UpdateValueAdjustment extends ValueAdjustmentEvent { + final ValueAdjustments valueAdjustment; + const UpdateValueAdjustment({required this.valueAdjustment}); + @override + List get props => [valueAdjustment]; +} + +class FetchValueAdjustment extends ValueAdjustmentEvent { + const FetchValueAdjustment(); + + @override + List get props => []; +} + +class FetchSpecificValueAdjustment extends ValueAdjustmentEvent { + final int id; + const FetchSpecificValueAdjustment({required this.id}); + + @override + List get props => [id]; +} + +class DeleteValueAdjustment extends ValueAdjustmentEvent { + final int id; + const DeleteValueAdjustment({required this.id}); + @override + List get props => [id]; +} + +class ShowValueAdjustment extends ValueAdjustmentEvent {} diff --git a/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_state.dart b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_state.dart new file mode 100644 index 0000000..95807b6 --- /dev/null +++ b/lib/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_state.dart @@ -0,0 +1,46 @@ +part of 'value_adjustment_bloc.dart'; + +class ValueAdjustmentState extends Equatable { + const ValueAdjustmentState(); + + @override + List get props => []; +} + +class ValueAdjustmentInitial extends ValueAdjustmentState { + @override + List get props => []; +} + +class ValueAdjustmentLoaded extends ValueAdjustmentState { + final List valueAdjustment; + + const ValueAdjustmentLoaded({required this.valueAdjustment}); + @override + List get props => [valueAdjustment]; +} + +class LoadSpecificValueAdjustment extends ValueAdjustmentState { + final ValueAdjustments valueAdjustment; + + const LoadSpecificValueAdjustment({required this.valueAdjustment}); + @override + List get props => [valueAdjustment]; +} + +class ShowValueAdjustmentcreen extends ValueAdjustmentState {} + +class ValueAdjustmentErrorState extends ValueAdjustmentState { + const ValueAdjustmentErrorState(this.error); + final String error; + + @override + List get props => [error]; +} + +class ValueAdjustmentDeletedState extends ValueAdjustmentState { + final bool success; + const ValueAdjustmentDeletedState({required this.success}); + @override + List get props => [success]; +} diff --git a/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart b/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart index e7aa87a..73c2beb 100644 --- a/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart +++ b/lib/bloc/passo/bulding/additional_item/additional_item_bloc.dart @@ -16,11 +16,6 @@ class AdditionalItemBloc on((event, emit) async { emit(AdditionalItemsLoading()); try { - // final tempID = await SharedPreferences.getInstance(); - // print(tempID.getInt('tempid')); - // final additionalItem = await GetAdditionalItems.getAdditionalItems( - // tempID.getInt('tempid')); - emit(AdditionalItemsLoaded(globalAdditionalItems)); } catch (e) { emit(AdditionalItemsErrorState(e.toString())); @@ -42,7 +37,7 @@ class AdditionalItemBloc emit(AdditionalItemsLoaded(globalAdditionalItems)); } else { - emit(AdditionalItemsErrorState('error')); + emit(const AdditionalItemsErrorState('error')); } } catch (e) { emit(AdditionalItemsErrorState(e.toString())); @@ -56,7 +51,7 @@ class AdditionalItemBloc if (response.statusCode == 200) { globalAdditionalItems .removeWhere(((AdditionalItems element) => element.id == event.id)); - emit(AdditionalItemsDeletedState(success: true)); + emit(const AdditionalItemsDeletedState(success: true)); } }); diff --git a/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart index 10a5fdc..ef081b9 100644 --- a/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart +++ b/lib/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart @@ -12,14 +12,14 @@ part 'property_appraisal_state.dart'; class PropertyAppraisalBloc extends Bloc { - PropertyAppraisalBloc() : super(PropertyAppraisalInitial()) { + PropertyAppraisalBloc() : super(PropertyAppraisalLoading()) { List globalPropertyAppraisal = []; on((event, emit) async { emit(PropertyAppraisalLoading()); try { - final appraisal = await PropertyAppraisalServices.instance.fetch(); - print(appraisal); - emit(PropertyAppraisalLoaded(appraisal)); + // final appraisal = await PropertyAppraisalServices.instance.fetch(); + // print(appraisal); + emit(PropertyAppraisalLoaded(PropertyAppraisal())); } catch (e) { emit(PropertyAppraisalErrorState(e.toString())); } diff --git a/lib/bloc/passo/land/land_ext/land_ext_bloc.dart b/lib/bloc/passo/land/land_ext/land_ext_bloc.dart index 7fa7292..1043c2d 100644 --- a/lib/bloc/passo/land/land_ext/land_ext_bloc.dart +++ b/lib/bloc/passo/land/land_ext/land_ext_bloc.dart @@ -42,7 +42,8 @@ class LandExtBloc extends Bloc { }); on((event, emit) async { final tempID = await SharedPreferences.getInstance(); - final tempID2 = tempID.getInt('tempid')! - 1; + final tempID2 = tempID.getInt('landid')! - 1; + http.Response response = (await LandExtServices.instance.update(event.landext, tempID2))!; print('landext'); 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 index 9f9ec3f..0fa5c99 100644 --- 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 @@ -59,6 +59,11 @@ class LandPropertyOwnerInfoBloc print(event.land_loc.id!); print('Land LOc'); print(response.statusCode); + if (response.statusCode == 200) { + emit(ShowLandLocSuccessAlertState()); + } else { + emit(ShowLandLocErrorAlertState()); + } }); on((event, emit) async { @@ -67,6 +72,21 @@ class LandPropertyOwnerInfoBloc .update(event.land_boundaries, event.land_boundaries.id))!; print('Land Boundaries'); print(response.body); + if (response.statusCode == 200) { + emit(ShowLandBoundariesSuccessState()); + } else { + emit(ShowLandBoundariesErrorAlertState()); + } + }); + + on((event, emit) async { + print(event.id); + emit(LandLoading()); + http.Response response = (await LandServices.instance.remove(event.id)); + print(response.statusCode); + if (response.statusCode == 200) { + emit(LandFaasDeletedState(success: true)); + } }); } } 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 index 58820b6..267c75a 100644 --- 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 @@ -58,3 +58,12 @@ class UpdateLandBoundaries extends LandPropertyOwnerInfoEvent { @override List get props => [land_boundaries]; } + +class DeleteLandFaas extends LandPropertyOwnerInfoEvent { + final int id; + + const DeleteLandFaas({required this.id}); + + @override + List get props => [id]; +} 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 index a519420..360e5bb 100644 --- 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 @@ -24,3 +24,18 @@ class LandErrorState extends LandPropertyOwnerInfoState { @override List get props => [error]; } + +class LandFaasDeletedState extends LandPropertyOwnerInfoState { + final bool success; + const LandFaasDeletedState({required this.success}); + @override + List get props => [success]; +} + +class ShowLandLocErrorAlertState extends LandPropertyOwnerInfoState {} + +class ShowLandBoundariesErrorAlertState extends LandPropertyOwnerInfoState {} + +class ShowLandLocSuccessAlertState extends LandPropertyOwnerInfoState {} + +class ShowLandBoundariesSuccessState extends LandPropertyOwnerInfoState {} diff --git a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart index c02604d..9cbcc07 100644 --- a/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart +++ b/lib/bloc/profile/learningDevelopment/learning_development_bloc.dart @@ -51,10 +51,13 @@ class LearningDevelopmentBloc attachmentCategories = await AttachmentServices.instance.getCategories(); } - List learnings = await LearningDevelopmentServices + if(learningsAndDevelopments.isEmpty){ + List learnings = await LearningDevelopmentServices .instance .getLearningDevelopments(event.profileId, event.token); learningsAndDevelopments = learnings; + } + emit(LearningDevelopmentLoadedState( learningsAndDevelopment: learningsAndDevelopments,attachmentCategory: attachmentCategories)); } catch (e) { diff --git a/lib/bloc/profile/profile_bloc.dart b/lib/bloc/profile/profile_bloc.dart index 6600285..dbe1e4c 100644 --- a/lib/bloc/profile/profile_bloc.dart +++ b/lib/bloc/profile/profile_bloc.dart @@ -64,6 +64,7 @@ class ProfileBloc extends Bloc { primaryBasicInformation: globalCurrentProfile!)); } else { currentProfileInformation = event.primaryBasicInformation; + globalCurrentProfile = currentProfileInformation; emit(BasicInformationProfileLoaded( primaryBasicInformation: currentProfileInformation!)); } @@ -108,7 +109,7 @@ class ProfileBloc extends Bloc { 0, ProfileOtherInfo(id: null, name: "NONE", description: null)); } emit(BasicInformationEditingState( - primaryInformation: currentProfileInformation!, + primaryInformation: globalCurrentProfile!, extensions: nameExtensions, sexes: sexes, bloodTypes: bloodType, diff --git a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart index fece6bc..936e2d1 100644 --- a/lib/bloc/rbac/rbac_operations/agency/agency_event.dart +++ b/lib/bloc/rbac/rbac_operations/agency/agency_event.dart @@ -13,9 +13,12 @@ class GetAgencies extends AgencyEvent{ class AddAgency extends AgencyEvent{ final Agency agency; const AddAgency({required this.agency}); + List get props => [agency + ]; } class GetEstPointPersonAgencies extends AgencyEvent{ final List? assignedAreas; const GetEstPointPersonAgencies({required this.assignedAreas}); + } diff --git a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart index b302617..925e294 100644 --- a/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/assign_area/assign_area_bloc.dart @@ -60,7 +60,7 @@ class AssignAreaBloc extends Bloc { } }); on((event, emit) async { - // try { + try { emit(AssignAreaLoadingState()); Map response = await RbacAssignedAreaServices.instance .add( @@ -77,11 +77,6 @@ class AssignAreaBloc extends Bloc { break; } } - // newAssignArea = userAssignedAreas.firstWhere((var element) { - // return element.assignedRole?.role?.id == event.roleId && - // element.assignedRole?.user?.id == event.userId; - // }); - if (newAssignArea?.assignedArea != null) { userAssignedAreas.removeWhere((element) => element.assignedRole!.role!.id == event.roleId && @@ -120,8 +115,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); //// purok } if (event.areaTypeId == 2) { @@ -149,8 +144,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////statiom if (event.areaTypeId == 4) { @@ -200,8 +195,8 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } ////agency if (event.areaTypeId == 3) { @@ -231,16 +226,16 @@ class AssignAreaBloc extends Bloc { newAreas.add(newArea); } } - newAssignArea?.assignedArea = newAreas; - userAssignedAreas.add(newAssignArea!); + newAssignArea.assignedArea = newAreas; + userAssignedAreas.add(newAssignArea); } emit(AssignAreaAddedState(response: response)); } else { emit(AssignAreaAddedState(response: response)); } - // } catch (e) { - // emit(AssignAreaErorState(message: e.toString())); - // } + } catch (e) { + emit(AssignAreaErorState(message: e.toString())); + } }); on((event, emit) async { emit(AssignedAreaLoadedState( diff --git a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart index f401b3b..4622f0b 100644 --- a/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/module_objects/module_objects_bloc.dart @@ -66,7 +66,7 @@ class ModuleObjectsBloc extends Bloc { emit(ModuleObjectLoadingState()); try { bool success = await RbacModuleObjectsServices.instance - .deleteRbacModuleObject(moduleObjectId: event.moduleObjectId); + .delete(moduleObjectId: event.moduleObjectId); if (success) { moduleObjects .removeWhere((element) => element.id == event.moduleObjectId); diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart new file mode 100644 index 0000000..145be4c --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart @@ -0,0 +1,82 @@ +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/permission_assignment.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/sevices/roles/rbac_operations/permission_assignment_services.dart'; +import 'package:unit2/sevices/roles/rbac_operations/permission_service.dart'; +import 'package:unit2/sevices/roles/rbac_operations/role_services.dart'; + +part 'permission_assignment_event.dart'; +part 'permission_assignment_state.dart'; + +class PermissionAssignmentBloc + extends Bloc { + PermissionAssignmentBloc() : super(PermissionAssignmentInitial()) { + List permissionAssignments = []; + List permissions = []; + List roles = []; + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + if (permissionAssignments.isEmpty) { + permissionAssignments = await RbacPermissionAssignmentServices + .instance + .getPermissionAssignment(); + } + if (permissions.isEmpty) { + permissions = + await RbacPermissionServices.instance.getRbacPermission(); + } + if (roles.isEmpty) { + roles = await RbacRoleServices.instance.getRbacRoles(); + } + emit(PermissionAssignmentLoadedState( + permissionAssignments: permissionAssignments, + permissions: permissions, + roles: roles)); + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + Map statusResponse = + await RbacPermissionAssignmentServices.instance + .addPermissionAssignment( + assignerId: event.assignerId, + opsId: event.opsId, + roleId: event.roleId); + if (statusResponse['success']) { + if (statusResponse['data'] != null) { + for (var rbac in statusResponse['data']) { + PermissionAssignment permissionAssignment = + PermissionAssignment.fromJson(rbac); + permissionAssignments.add(permissionAssignment); + } + } + emit(PermissionAssignmentAddedState(status: statusResponse)); + } else { + emit(PermissionAssignmentAddedState(status: statusResponse)); + } + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + on((event, emit) async { + try { + emit(PermissionAssignmentLoadingScreen()); + bool success = await RbacPermissionAssignmentServices.instance + .deletePermissionAssignment(id: event.id); + if (success) { + permissionAssignments + .removeWhere((element) => element.id == event.id); + } + emit(PermissionAssignmentDeletedState(success: success)); + } catch (e) { + emit(PermissionAssignmentErrorState(message: e.toString())); + } + }); + } +} diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart new file mode 100644 index 0000000..e2d13fc --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_event.dart @@ -0,0 +1,28 @@ +part of 'permission_assignment_bloc.dart'; + +class PermissionAssignmentEvent extends Equatable { + const PermissionAssignmentEvent(); + + @override + List get props => []; +} + +class GetPermissionAssignments extends PermissionAssignmentEvent{ + +} +class DeletePermissionAssignment extends PermissionAssignmentEvent{ + final int id; + const DeletePermissionAssignment({required this.id}); + @override + List get props => [id]; +} + +class AddPersmissionAssignment extends PermissionAssignmentEvent{ + final int assignerId; + final List opsId; + final int roleId; + const AddPersmissionAssignment({required this.assignerId, required this.opsId, required this.roleId}); + @override + List get props => [assignerId,opsId,roleId]; + +} diff --git a/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart new file mode 100644 index 0000000..4100b58 --- /dev/null +++ b/lib/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_state.dart @@ -0,0 +1,45 @@ +part of 'permission_assignment_bloc.dart'; + +class PermissionAssignmentState extends Equatable { + const PermissionAssignmentState(); + + @override + List get props => []; +} + +class PermissionAssignmentInitial extends PermissionAssignmentState {} + +class PermissionAssignmentLoadingScreen extends PermissionAssignmentState {} + +class PermissionAssignmentLoadedState extends PermissionAssignmentState { + final List permissionAssignments; + final List permissions; + final List roles; + const PermissionAssignmentLoadedState( + {required this.permissionAssignments, + required this.permissions, + required this.roles}); + @override + List get props => [permissionAssignments, permissions, roles]; +} + +class PermissionAssignmentErrorState extends PermissionAssignmentState { + final String message; + const PermissionAssignmentErrorState({required this.message}); + @override + List get props => [message]; +} + +class PermissionAssignmentDeletedState extends PermissionAssignmentState { + final bool success; + const PermissionAssignmentDeletedState({required this.success}); + @override + List get props => [success]; +} + +class PermissionAssignmentAddedState extends PermissionAssignmentState { + final Map status; + const PermissionAssignmentAddedState({required this.status}); + @override + List get props => [status]; +} diff --git a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart index 3f52bd4..36ace5d 100644 --- a/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart @@ -11,7 +11,7 @@ part 'role_module_state.dart'; class RoleModuleBloc extends Bloc { RoleModuleBloc() : super(RoleModuleInitial()) { List roleModules = []; - List roles = []; + List roles = []; List modules = []; on((event, emit) async { emit(RoleModuleLoadingState()); @@ -19,18 +19,19 @@ class RoleModuleBloc extends Bloc { if (roleModules.isEmpty) { roleModules = await RbacRoleModuleServices.instance.getRoleModules(); } - if (modules.isEmpty) { + if (modules.isEmpty) { modules = await RbacModuleServices.instance.getRbacModule(); } - if (roles.isEmpty) { + if (roles.isEmpty) { roles = await RbacRoleServices.instance.getRbacRoles(); } - emit(RoleModuleLoadedState(roleModules: roleModules,modules: modules,roles: roles)); + emit(RoleModuleLoadedState( + roleModules: roleModules, modules: modules, roles: roles)); } catch (e) { emit(RoleModuleErrorState(message: e.toString())); } }); - on((event, emit) async { + on((event, emit) async { try { emit(RoleModuleLoadingState()); Map statusResponse = @@ -40,9 +41,12 @@ class RoleModuleBloc extends Bloc { moduleIds: event.moduleIds); if (statusResponse['success']) { + List ids = roleModules.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RoleModules newRoleModule = RoleModules.fromJson(roleMod); - roleModules.add(newRoleModule); + if (!ids.contains(newRoleModule.id)) { + roleModules.add(newRoleModule); + } emit(RoleModuleAddedState(response: statusResponse)); }); } else { diff --git a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart index f8fc508..ba17ba3 100644 --- a/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart +++ b/lib/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart @@ -36,11 +36,14 @@ class RolesUnderBloc extends Bloc { .add(roleId: event.roleId, rolesId: event.roleUnderIds); if (statusResponse['success']) { + List ids = rolesUnder.map((e) => e.id).toList(); statusResponse['data'].forEach((var roleMod) { RolesUnder newRoleUnder = RolesUnder.fromJson(roleMod); - rolesUnder.add(newRoleUnder); - emit(RoleUnderAddedState(response: statusResponse)); + if (!ids.contains(newRoleUnder.id)) { + rolesUnder.add(newRoleUnder); + } }); + emit(RoleUnderAddedState(response: statusResponse)); } else { emit(RoleUnderAddedState(response: statusResponse)); } diff --git a/lib/bloc/user/user_bloc.dart b/lib/bloc/user/user_bloc.dart index da677e9..3f686ad 100644 --- a/lib/bloc/user/user_bloc.dart +++ b/lib/bloc/user/user_bloc.dart @@ -8,6 +8,8 @@ import 'package:unit2/model/login_data/user_info/assigned_area.dart'; import 'package:unit2/model/login_data/user_info/role.dart'; import 'package:unit2/model/login_data/user_info/user_data.dart'; import 'package:unit2/model/login_data/version_info.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; import 'package:unit2/screens/unit2/login/functions/get_app_version.dart'; import 'package:unit2/sevices/login_service/auth_service.dart'; import 'package:unit2/utils/global.dart'; @@ -15,6 +17,7 @@ import '../../utils/scanner.dart'; import '../../utils/text_container.dart'; part 'user_event.dart'; part 'user_state.dart'; + class UserBloc extends Bloc { UserData? _userData; VersionInfo? _versionInfo; @@ -38,15 +41,15 @@ class UserBloc extends Bloc { String apkVersion = await getAppVersion(); _apkVersion = apkVersion; final String? saved = CREDENTIALS?.get('saved'); - username = CREDENTIALS?.get('username'); - password = CREDENTIALS?.get('password'); - if(apkVersion != _versionInfo!.id ){ - emit(VersionLoaded( + username = CREDENTIALS?.get('username'); + password = CREDENTIALS?.get('password'); + if (apkVersion != _versionInfo!.id) { + emit(VersionLoaded( versionInfo: _versionInfo, apkVersion: _apkVersion, username: event.username, password: event.password)); - }else if (saved != null) { + } else if (saved != null) { save = true; add(UserLogin(username: username, password: password)); } else { @@ -57,9 +60,14 @@ class UserBloc extends Bloc { password: event.password)); } } catch (e) { - emit(UserError( - message: e.toString(), - )); + bool? offlineAvalable = await OFFLINE!.get('offline'); + if (offlineAvalable == true) { + emit(ErrorWithOfflineMode()); + } else { + emit(UserError( + message: e.toString(), + )); + } } }); ////Loading the current version of the app @@ -76,50 +84,95 @@ class UserBloc extends Bloc { on((event, emit) async { username = event.username; password = event.password; + bool? availableOffline; + List offlineCards = []; try { - Map response = await AuthService.instance - .webLogin(username: event.username, password: event.password); - if (response['status'] == true) { - UserData userData = UserData.fromJson(response['data']); - Role? estPointPerson; - if (userData.user?.login?.user?.roles != null && - userData.user!.login!.user!.roles!.isNotEmpty) { - userData.user!.login!.user!.roles!.forEach((element) { - if (element!.name!.toLowerCase() == 'establishment point-person') { - estPointPerson = element; - } - }); - if (estPointPerson != null && - estPointPerson!.assignedArea!.isNotEmpty) { - estPointPerson!.assignedArea!.forEach((element) { - establishmentPointPersonAssignedAreas.add(element!); + Map response = await AuthService.instance + .webLogin(username: event.username, password: event.password); + if (response['status'] == true) { + UserData userData = UserData.fromJson(response['data']); + Role? estPointPerson; + if (userData.user?.login?.user?.roles != null && + userData.user!.login!.user!.roles!.isNotEmpty) { + userData.user!.login!.user!.roles!.forEach((element) { + if (element!.name!.toLowerCase() == + 'establishment point-person') { + estPointPerson = element; + } }); + if (estPointPerson != null && + estPointPerson!.assignedArea!.isNotEmpty) { + estPointPerson!.assignedArea!.forEach((element) { + establishmentPointPersonAssignedAreas.add(element!); + }); + } } - } + ////Check offline availabilty + for (var role in userData.user!.login!.user!.roles!) { + if (role!.name!.toLowerCase() == 'field surveyor') { + availableOffline = true; + OfflineModules newOfflineModule = OfflineModules( + moduleName: role.modules!.first!.name!, + object: role.modules!.first!.objects!.first!, + roleName: role.name!, + roleId: role.id!); - emit(UserLoggedIn( - estPersonAssignedArea: establishmentPointPersonAssignedAreas, - userData: userData, - success: true, - message: response['message'], - savedCredentials: save)); - } else { - emit(UserLoggedIn( - estPersonAssignedArea: establishmentPointPersonAssignedAreas, - userData: null, - success: false, - message: response['message'], - savedCredentials: save)); - } - } - on TimeoutException catch (_) { + offlineCards.add(newOfflineModule); + OfflineProfile offlineProfile = OfflineProfile( + webuserId: userData.employeeInfo?.profile?.webuserId, + id: userData.employeeInfo?.profile?.id, + lastName: userData.employeeInfo?.profile?.lastName, + firstName: userData.employeeInfo?.profile?.lastName, + middleName: userData.employeeInfo?.profile?.middleName, + nameExtension: userData.employeeInfo?.profile?.nameExtension, + sex: userData.employeeInfo?.profile?.sex, + birthdate: userData.employeeInfo?.profile?.birthdate, + civilStatus: civilStatus, + bloodType: bloodType, + heightM: userData.employeeInfo?.profile?.heightM, + weightKg: userData.employeeInfo?.profile?.weightKg, + photoPath: userData.employeeInfo?.profile?.photoPath, + esigPath: userData.employeeInfo?.profile?.esigPath, + maidenName: userData.employeeInfo?.profile?.maidenName, + deceased: userData.employeeInfo?.profile?.deceased, + uuidQrcode: userData.employeeInfo?.profile?.uuidQrcode, + titlePrefix: userData.employeeInfo?.profile?.titlePrefix, + titleSuffix: userData.employeeInfo?.profile?.titleSuffix, + showTitleId: userData.employeeInfo?.profile?.showTitleId, + ethnicity: userData.employeeInfo?.profile?.ethnicity, + disability: userData.employeeInfo?.profile?.disability, + gender: userData.employeeInfo?.profile?.gender, + religion: userData.employeeInfo?.profile?.religion, + ip: userData.employeeInfo?.profile?.ip); + await OFFLINE!.put("offline_profile", offlineProfile); + break; + } + } + await OFFLINE!.put('modules', offlineCards); + await OFFLINE!.put('offline', availableOffline); + globalOfflineAvailable = availableOffline; + emit(UserLoggedIn( + estPersonAssignedArea: establishmentPointPersonAssignedAreas, + userData: userData, + success: true, + message: response['message'], + savedCredentials: save)); + } else { + emit(UserLoggedIn( + estPersonAssignedArea: establishmentPointPersonAssignedAreas, + userData: null, + success: false, + message: response['message'], + savedCredentials: save)); + } + } on TimeoutException catch (_) { emit(InternetTimeout(message: timeoutError)); } on SocketException catch (_) { emit(InternetTimeout(message: timeoutError)); } on Error catch (e) { emit(LoginErrorState(message: e.toString())); - }catch(e){ - emit(LoginErrorState(message: e.toString())); + } catch (e) { + emit(LoginErrorState(message: e.toString())); } }); on((event, emit) async { diff --git a/lib/bloc/user/user_event.dart b/lib/bloc/user/user_event.dart index be22335..20869b7 100644 --- a/lib/bloc/user/user_event.dart +++ b/lib/bloc/user/user_event.dart @@ -6,11 +6,11 @@ abstract class UserEvent extends Equatable { } class GetApkVersion extends UserEvent { - final String username; - final String password; + final String? username; + final String? password; GetApkVersion({required this.password, required this.username}); @override - List get props => [username,password]; + List get props => []; } class UserLogin extends UserEvent { @@ -28,15 +28,15 @@ class LoadLoggedInUser extends UserEvent { class GetUuid extends UserEvent { GetUuid(); } -class LoadUuid extends UserEvent{ + +class LoadUuid extends UserEvent { LoadUuid(); } - class LoadVersion extends UserEvent { final String? username; final String? password; - LoadVersion({this.password,this.username}); + LoadVersion({this.password, this.username}); } class UuidLogin extends UserEvent { diff --git a/lib/bloc/user/user_state.dart b/lib/bloc/user/user_state.dart index c63fbf7..fe965c2 100644 --- a/lib/bloc/user/user_state.dart +++ b/lib/bloc/user/user_state.dart @@ -1,43 +1,47 @@ part of 'user_bloc.dart'; abstract class UserState extends Equatable { - @override List get props => []; } class UserInitial extends UserState { UserInitial(); - @override + @override List get props => []; } class UserLoading extends UserState { final String? message; - UserLoading({this.message}); + UserLoading({this.message}); @override List get props => [message!]; } class SplashScreen extends UserState { - @override List get props => []; } class UserError extends UserState { final String? message; - UserError({this.message}); + UserError({this.message}); @override List get props => []; } -class UserLoggedIn extends UserState{ + +class UserLoggedIn extends UserState { final List? estPersonAssignedArea; final UserData? userData; final String? message; final bool? success; final bool? savedCredentials; - UserLoggedIn({this.userData,this.message,this.success,this.savedCredentials, required this.estPersonAssignedArea}); + UserLoggedIn( + {this.userData, + this.message, + this.success, + this.savedCredentials, + required this.estPersonAssignedArea}); } class VersionLoaded extends UserState { @@ -45,29 +49,34 @@ class VersionLoaded extends UserState { final String? apkVersion; final String? username; final String? password; - VersionLoaded({this.versionInfo,this.apkVersion, this.password,this.username}); + VersionLoaded( + {this.versionInfo, this.apkVersion, this.password, this.username}); @override List get props => [versionInfo!]; } -class UuidLoaded extends UserState{ + +class UuidLoaded extends UserState { final String uuid; UuidLoaded({required this.uuid}); - @override + @override List get props => [uuid]; } -class InternetTimeout extends UserState{ +class InternetTimeout extends UserState { final String message; InternetTimeout({required this.message}); @override List get props => [message]; } -class InvalidCredentials extends UserState{ - final String message ; - InvalidCredentials ({required this.message}); +class InvalidCredentials extends UserState { + final String message; + InvalidCredentials({required this.message}); } -class LoginErrorState extends UserState{ + +class LoginErrorState extends UserState { final String message; LoginErrorState({required this.message}); } + +class ErrorWithOfflineMode extends UserState {} diff --git a/lib/main.dart b/lib/main.dart index d88fa6c..fddedb9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,6 +4,10 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:unit2/bloc/profile/profile_bloc.dart'; import 'package:unit2/bloc/user/user_bloc.dart'; +import 'package:unit2/model/login_data/user_info/module.dart'; +import 'package:unit2/model/login_data/user_info/module_object.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; import 'package:unit2/utils/app_router.dart'; import 'package:unit2/utils/global_context.dart'; import 'package:path_provider/path_provider.dart' as path_provider; @@ -12,10 +16,17 @@ import './utils/global.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); var appDirectory = await path_provider.getApplicationDocumentsDirectory(); + await Hive.initFlutter(appDirectory.path); + Hive.registerAdapter(OfflineProfileAdapter()); + Hive.registerAdapter(ModuleAdapter()); + Hive.registerAdapter(ModuleObjectAdapter()); + Hive.registerAdapter(OfflineModulesAdapter()); CREDENTIALS = await Hive.openBox('credentials'); SOS = await Hive.openBox('soscontacts'); - SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]) + OFFLINE = await Hive.openBox('offline'); + + SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]) .then((_) { runApp(MyApp()); }); diff --git a/lib/model/login_data/user_info/module.dart b/lib/model/login_data/user_info/module.dart index a72f278..f3762a8 100644 --- a/lib/model/login_data/user_info/module.dart +++ b/lib/model/login_data/user_info/module.dart @@ -1,4 +1,8 @@ -class Module { +import 'package:hive/hive.dart'; +import 'package:unit2/model/login_data/user_info/module_object.dart'; +part 'module.g.dart'; +@HiveType(typeId: 1) +class Module extends HiveObject { Module({ this.id, this.icon, @@ -6,11 +10,15 @@ class Module { this.slug, this.objects, }); - + @HiveField(0) int? id; + @HiveField(1) String? icon; + @HiveField(2) String? name; + @HiveField(3) String? slug; + @HiveField(4) List? objects; factory Module.fromJson(Map json) => Module( @@ -35,34 +43,3 @@ class Module { }; } -class ModuleObject { - ModuleObject({ - this.id, - this.name, - this.slug, - this.operations, - }); - - int? id; - String? name; - String? slug; - List? operations; - - factory ModuleObject.fromJson(Map json) => ModuleObject( - 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/login_data/user_info/module.g.dart b/lib/model/login_data/user_info/module.g.dart new file mode 100644 index 0000000..3a906b8 --- /dev/null +++ b/lib/model/login_data/user_info/module.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'module.dart'; + +// ************************************************************************** +// TypeAdapterGenerator +// ************************************************************************** + +class ModuleAdapter extends TypeAdapter { + @override + final int typeId = 1; + + @override + Module read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return Module( + id: fields[0] as int?, + icon: fields[1] as String?, + name: fields[2] as String?, + slug: fields[3] as String?, + objects: (fields[4] as List?)?.cast(), + ); + } + + @override + void write(BinaryWriter writer, Module obj) { + writer + ..writeByte(5) + ..writeByte(0) + ..write(obj.id) + ..writeByte(1) + ..write(obj.icon) + ..writeByte(2) + ..write(obj.name) + ..writeByte(3) + ..write(obj.slug) + ..writeByte(4) + ..write(obj.objects); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ModuleAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} diff --git a/lib/model/login_data/user_info/module_object.dart b/lib/model/login_data/user_info/module_object.dart new file mode 100644 index 0000000..4d36c15 --- /dev/null +++ b/lib/model/login_data/user_info/module_object.dart @@ -0,0 +1,37 @@ +import 'package:hive/hive.dart'; +part 'module_object.g.dart'; +@HiveType(typeId: 2) +class ModuleObject extends HiveObject { + ModuleObject({ + this.id, + this.name, + this.slug, + this.operations, + }); + @HiveField(0) + int? id; + @HiveField(1) + String? name; + @HiveField(2) + String? slug; + @HiveField(3) + List? operations; + + factory ModuleObject.fromJson(Map json) => ModuleObject( + 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)), + }; +} diff --git a/lib/model/login_data/user_info/module_object.g.dart b/lib/model/login_data/user_info/module_object.g.dart new file mode 100644 index 0000000..c20151b --- /dev/null +++ b/lib/model/login_data/user_info/module_object.g.dart @@ -0,0 +1,50 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'module_object.dart'; + +// ************************************************************************** +// TypeAdapterGenerator +// ************************************************************************** + +class ModuleObjectAdapter extends TypeAdapter { + @override + final int typeId = 2; + + @override + ModuleObject read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return ModuleObject( + id: fields[0] as int?, + name: fields[1] as String?, + slug: fields[2] as String?, + operations: (fields[3] as List?)?.cast(), + ); + } + + @override + void write(BinaryWriter writer, ModuleObject obj) { + writer + ..writeByte(4) + ..writeByte(0) + ..write(obj.id) + ..writeByte(1) + ..write(obj.name) + ..writeByte(2) + ..write(obj.slug) + ..writeByte(3) + ..write(obj.operations); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ModuleObjectAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} diff --git a/lib/model/offline/offlane_modules.dart b/lib/model/offline/offlane_modules.dart new file mode 100644 index 0000000..fd25a6d --- /dev/null +++ b/lib/model/offline/offlane_modules.dart @@ -0,0 +1,18 @@ +import 'package:hive/hive.dart'; +import 'package:unit2/model/login_data/user_info/module.dart'; + +import '../login_data/user_info/module_object.dart'; +part 'offlane_modules.g.dart'; +@HiveType(typeId: 4) +class OfflineModules { + @HiveField(0) + final String roleName; + @HiveField(1) + final String moduleName; + @HiveField(2) + final ModuleObject object; + @HiveField(3) + final int roleId; + const OfflineModules( + {required this.moduleName, required this.object, required this.roleName,required this.roleId}); +} \ No newline at end of file diff --git a/lib/model/offline/offlane_modules.g.dart b/lib/model/offline/offlane_modules.g.dart new file mode 100644 index 0000000..55434b0 --- /dev/null +++ b/lib/model/offline/offlane_modules.g.dart @@ -0,0 +1,50 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'offlane_modules.dart'; + +// ************************************************************************** +// TypeAdapterGenerator +// ************************************************************************** + +class OfflineModulesAdapter extends TypeAdapter { + @override + final int typeId = 4; + + @override + OfflineModules read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return OfflineModules( + moduleName: fields[1] as String, + object: fields[2] as ModuleObject, + roleName: fields[0] as String, + roleId: fields[3] as int, + ); + } + + @override + void write(BinaryWriter writer, OfflineModules obj) { + writer + ..writeByte(4) + ..writeByte(0) + ..write(obj.roleName) + ..writeByte(1) + ..write(obj.moduleName) + ..writeByte(2) + ..write(obj.object) + ..writeByte(3) + ..write(obj.roleId); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is OfflineModulesAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} diff --git a/lib/model/offline/offline_profile.dart b/lib/model/offline/offline_profile.dart new file mode 100644 index 0000000..1dd0575 --- /dev/null +++ b/lib/model/offline/offline_profile.dart @@ -0,0 +1,145 @@ +import 'package:hive/hive.dart'; + +import 'dart:convert'; + +import 'package:unit2/model/profile/family_backround.dart'; +part 'offline_profile.g.dart'; +OfflineProfile primaryInformationFromJson(String str) => OfflineProfile.fromJson(json.decode(str)); + +String primaryInformationToJson(OfflineProfile data) => json.encode(data.toJson()); +@HiveType(typeId: 0) +class OfflineProfile extends HiveObject { + @HiveField(0) + int? webuserId; + @HiveField(1) + int? id; + @HiveField(2) + String? lastName; + @HiveField(3) + String? firstName; + @HiveField(4) + String? middleName; + @HiveField(5) + String? nameExtension; + @HiveField(6) + String? sex; + @HiveField(7) + DateTime? birthdate; + @HiveField(8) + String? civilStatus; + @HiveField(9) + String? bloodType; + @HiveField(10) + double? heightM; + @HiveField(11) + double? weightKg; + @HiveField(12) + String? photoPath; + @HiveField(13) + String? esigPath; + @HiveField(14) + MaidenName? maidenName; + @HiveField(15) + bool? deceased; + @HiveField(16) + String? uuidQrcode; + @HiveField(17) + String? titlePrefix; + @HiveField(18) + String? titleSuffix; + @HiveField(19) + bool? showTitleId; + @HiveField(20) + String? ethnicity; + @HiveField(21) + String? disability; + @HiveField(22) + String? gender; + @HiveField(23) + String? religion; + @HiveField(24) + String? ip; + + OfflineProfile({ + required this.webuserId, + required this.id, + required this.lastName, + required this.firstName, + required this.middleName, + required this.nameExtension, + required this.sex, + required this.birthdate, + required this.civilStatus, + required this.bloodType, + required this.heightM, + required this.weightKg, + required this.photoPath, + required this.esigPath, + required this.maidenName, + required this.deceased, + required this.uuidQrcode, + required this.titlePrefix, + required this.titleSuffix, + required this.showTitleId, + required this.ethnicity, + required this.disability, + required this.gender, + required this.religion, + required this.ip, + }); + + factory OfflineProfile.fromJson(Map json) => OfflineProfile( + 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:json['birthdate'] ==null?null: DateTime.parse(json["birthdate"]), + civilStatus: json["civil_status"], + bloodType: json["blood_type"], + heightM: json["height_m"]?.toDouble(), + weightKg: json["weight_kg"]?.toDouble(), + photoPath: json["photo_path"], + esigPath: json["esig_path"], + maidenName: json["maiden_name"]==null?null:MaidenName.fromJson(json["maiden_name"]), + deceased: json["deceased"], + uuidQrcode: json["uuid_qrcode"], + titlePrefix: json["title_prefix"], + titleSuffix: json["title_suffix"], + showTitleId: json["show_title_id"], + ethnicity: json["ethnicity"]== null?null:json["ethnicity"]['name'], + disability: json["disability"] == null?null:json['disability']['name'], + gender: json["gender"] == null?null:json['gender']['name'], + religion: json["religion"] == null?null:json['religion']['name'], + ip: json["ip"]==null?null:json['ip']['name'], + ); + + Map toJson() => { + "id": id, + "last_name": lastName, + "first_name": firstName, + "middle_name": middleName, + "name_extension": nameExtension, + "sex": sex, + "birthdate": "${birthdate?.year.toString().padLeft(4, '0')}-${birthdate?.month.toString().padLeft(2, '0')}-${birthdate?.day.toString().padLeft(2, '0')}", + "civil_status": civilStatus, + "blood_type": bloodType, + "height_m": heightM, + "weight_kg": weightKg, + "photo_path": photoPath, + "esig_path": esigPath, + "maiden_name": maidenName, + "deceased": deceased, + "uuid_qrcode": uuidQrcode, + "title_prefix": titlePrefix, + "title_suffix": titleSuffix, + "show_title_id": showTitleId, + "ethnicity": ethnicity, + "disability": disability, + "gender": gender, + "religion": religion, + "ip": ip, + }; +} diff --git a/lib/model/offline/offline_profile.g.dart b/lib/model/offline/offline_profile.g.dart new file mode 100644 index 0000000..57c2d7a --- /dev/null +++ b/lib/model/offline/offline_profile.g.dart @@ -0,0 +1,113 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'offline_profile.dart'; + +// ************************************************************************** +// TypeAdapterGenerator +// ************************************************************************** + +class OfflineProfileAdapter extends TypeAdapter { + @override + final int typeId = 0; + + @override + OfflineProfile read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return OfflineProfile( + webuserId: fields[0] as int?, + id: fields[1] as int?, + lastName: fields[2] as String?, + firstName: fields[3] as String?, + middleName: fields[4] as String?, + nameExtension: fields[5] as String?, + sex: fields[6] as String?, + birthdate: fields[7] as DateTime?, + civilStatus: fields[8] as String?, + bloodType: fields[9] as String?, + heightM: fields[10] as double?, + weightKg: fields[11] as double?, + photoPath: fields[12] as String?, + esigPath: fields[13] as String?, + maidenName: fields[14] as MaidenName?, + deceased: fields[15] as bool?, + uuidQrcode: fields[16] as String?, + titlePrefix: fields[17] as String?, + titleSuffix: fields[18] as String?, + showTitleId: fields[19] as bool?, + ethnicity: fields[20] as String?, + disability: fields[21] as String?, + gender: fields[22] as String?, + religion: fields[23] as String?, + ip: fields[24] as String?, + ); + } + + @override + void write(BinaryWriter writer, OfflineProfile obj) { + writer + ..writeByte(25) + ..writeByte(0) + ..write(obj.webuserId) + ..writeByte(1) + ..write(obj.id) + ..writeByte(2) + ..write(obj.lastName) + ..writeByte(3) + ..write(obj.firstName) + ..writeByte(4) + ..write(obj.middleName) + ..writeByte(5) + ..write(obj.nameExtension) + ..writeByte(6) + ..write(obj.sex) + ..writeByte(7) + ..write(obj.birthdate) + ..writeByte(8) + ..write(obj.civilStatus) + ..writeByte(9) + ..write(obj.bloodType) + ..writeByte(10) + ..write(obj.heightM) + ..writeByte(11) + ..write(obj.weightKg) + ..writeByte(12) + ..write(obj.photoPath) + ..writeByte(13) + ..write(obj.esigPath) + ..writeByte(14) + ..write(obj.maidenName) + ..writeByte(15) + ..write(obj.deceased) + ..writeByte(16) + ..write(obj.uuidQrcode) + ..writeByte(17) + ..write(obj.titlePrefix) + ..writeByte(18) + ..write(obj.titleSuffix) + ..writeByte(19) + ..write(obj.showTitleId) + ..writeByte(20) + ..write(obj.ethnicity) + ..writeByte(21) + ..write(obj.disability) + ..writeByte(22) + ..write(obj.gender) + ..writeByte(23) + ..write(obj.religion) + ..writeByte(24) + ..write(obj.ip); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is OfflineProfileAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} diff --git a/lib/model/passo/additional_items.dart b/lib/model/passo/additional_items.dart index 9f89494..ca22c52 100644 --- a/lib/model/passo/additional_items.dart +++ b/lib/model/passo/additional_items.dart @@ -2,7 +2,6 @@ // // final additionalItems = additionalItemsFromJson(jsonString); -import 'package:meta/meta.dart'; import 'dart:convert'; AdditionalItems additionalItemsFromJson(String str) => @@ -24,52 +23,93 @@ class AdditionalItems { final dynamic depreciationRate; final dynamic adjustedMarketVal; final dynamic amtDepreciation; - final bool painted; - final bool secondhand; + final String painted; + final String secondhand; final dynamic paintedUnitval; final dynamic secondhandUnitval; final String actualUse; + final String genCode; - AdditionalItems({ - required this.id, - required this.bldgapprDetailsId, - required this.classId, - required this.className, - required this.structType, - required this.unitValue, - required this.baseUnitValue, - required this.area, - required this.marketValue, - required this.depreciationRate, - required this.adjustedMarketVal, - required this.amtDepreciation, - required this.painted, - required this.secondhand, - required this.paintedUnitval, - required this.secondhandUnitval, - required this.actualUse, - }); + AdditionalItems( + {required this.id, + required this.bldgapprDetailsId, + required this.classId, + required this.className, + required this.structType, + required this.unitValue, + required this.baseUnitValue, + required this.area, + required this.marketValue, + required this.depreciationRate, + required this.adjustedMarketVal, + required this.amtDepreciation, + required this.painted, + required this.secondhand, + required this.paintedUnitval, + required this.secondhandUnitval, + required this.actualUse, + required this.genCode}); + + AdditionalItems copy( + {int? id, + int? bldgapprDetailsId, + int? classId, + String? className, + String? structType, + dynamic unitValue, + dynamic baseUnitValue, + dynamic area, + dynamic marketValue, + dynamic depreciationRate, + dynamic adjustedMarketVal, + dynamic amtDepreciation, + String? painted, + String? secondhand, + dynamic paintedUnitval, + dynamic secondhandUnitval, + String? actualUse, + String? genCode}) { + return AdditionalItems( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + classId: classId ?? this.classId, + className: className ?? this.className, + structType: structType ?? this.structType, + unitValue: unitValue ?? this.unitValue, + baseUnitValue: baseUnitValue ?? this.baseUnitValue, + area: area ?? this.area, + marketValue: marketValue ?? this.marketValue, + depreciationRate: depreciationRate ?? this.depreciationRate, + adjustedMarketVal: adjustedMarketVal ?? this.adjustedMarketVal, + amtDepreciation: amtDepreciation ?? this.amtDepreciation, + painted: painted ?? this.painted, + secondhand: secondhand ?? this.secondhand, + paintedUnitval: paintedUnitval ?? this.paintedUnitval, + secondhandUnitval: secondhandUnitval ?? this.secondhandUnitval, + actualUse: actualUse ?? this.actualUse, + genCode: genCode ?? this.genCode); + } factory AdditionalItems.fromJson(Map json) => AdditionalItems( - id: json["id"], - bldgapprDetailsId: json["bldgappr_details_id"], - classId: json["class_id"], - className: json["class_name"], - structType: json["struct_type"], - unitValue: json["unit_value"], - baseUnitValue: json["base_unit_value"], - area: json["area"], - marketValue: json["market_value"], - depreciationRate: json["depreciation_rate"], - adjustedMarketVal: json["adjusted_market_val"], - amtDepreciation: json["amt_depreciation"], - painted: json["painted"], - secondhand: json["secondhand"], - paintedUnitval: json["painted_unitval"], - secondhandUnitval: json["secondhand_unitval"], - actualUse: json["actual_use"], - ); + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + classId: json["classId"], + className: json["className"], + structType: json["structType"], + unitValue: json["unitValue"], + baseUnitValue: json["baseUnitValue"], + area: json["area"], + marketValue: json["marketValue"], + depreciationRate: json["depreciationRate"], + adjustedMarketVal: json["adjustedMarketVal"], + amtDepreciation: json["amtDepreciation"], + painted: json["painted"], + secondhand: json["secondhand"], + paintedUnitval: json["paintedUnitval"], + secondhandUnitval: json["secondhandUnitval"], + actualUse: json["actualUse"], + genCode: json["gen_code"]); Map toJson() => { "id": id, @@ -89,5 +129,6 @@ class AdditionalItems { "painted_unitval": paintedUnitval, "secondhand_unitval": secondhandUnitval, "actual_use": actualUse, + "gen_code": genCode }; } diff --git a/lib/model/passo/barangay.dart b/lib/model/passo/barangay.dart index 6dacfa1..9b2e754 100644 --- a/lib/model/passo/barangay.dart +++ b/lib/model/passo/barangay.dart @@ -9,29 +9,61 @@ Brgy barangayFromJson(String str) => Brgy.fromJson(json.decode(str)); String barangayToJson(Brgy data) => json.encode(data.toJson()); class Brgy { + final int? id; final int? barangayId; final String? barangayCode; final String? cityCode; final String? barangayDescription; + final String? genCode; - Brgy({ - this.barangayId, - this.barangayCode, - this.cityCode, - this.barangayDescription, - }); + Brgy( + {this.id, + this.barangayId, + this.barangayCode, + this.cityCode, + this.barangayDescription, + this.genCode}); + + Brgy copy( + {int? id, + int? barangayId, + String? barangayCode, + String? cityCode, + String? barangayDescription, + String? genCode}) { + return Brgy( + id: id ?? this.id, + barangayId: barangayId ?? this.barangayId, + barangayCode: barangayCode ?? this.barangayCode, + cityCode: cityCode ?? this.cityCode, + barangayDescription: barangayDescription ?? this.barangayDescription, + genCode: genCode ?? this.genCode); + } factory Brgy.fromJson(Map json) => Brgy( + id: json["id"], barangayId: json["barangay_id"], barangayCode: json["barangay_code"], cityCode: json["city_code"], barangayDescription: json["barangay_description"], + genCode: json["gen_code"], + ); + + factory Brgy.fromJson2(Map json) => Brgy( + id: json["id"], + barangayId: json["barangayId"], + barangayCode: json["barangayCode"], + cityCode: json["cityCode"], + barangayDescription: json["barangayDescription"], + genCode: json["gen_code"], ); Map toJson() => { + "id": id, "barangay_id": barangayId, "barangay_code": barangayCode, "city_code": cityCode, "barangay_description": barangayDescription, + "gen_code": genCode, }; } diff --git a/lib/model/passo/bldg_loc.dart b/lib/model/passo/bldg_loc.dart index 06714fb..4911fff 100644 --- a/lib/model/passo/bldg_loc.dart +++ b/lib/model/passo/bldg_loc.dart @@ -13,12 +13,13 @@ class BldgLoc { final int? bldgapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final dynamic street; final dynamic barangay; final dynamic municipality; final dynamic province; + final String? genCode; BldgLoc({ this.id, @@ -31,23 +32,61 @@ class BldgLoc { this.barangay, this.municipality, this.province, + this.genCode, }); + BldgLoc copy( + {int? id, + int? bldgapprDetailsId, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + dynamic street, + dynamic barangay, + dynamic municipality, + dynamic province, + String? genCode}) { + return BldgLoc( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + street: street ?? this.street, + barangay: barangay ?? this.barangay, + municipality: municipality ?? this.municipality, + province: province ?? this.province, + genCode: genCode ?? this.genCode); + } + 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"]), + dateCreated: json["date_created"], + dateModified: json["date_modified"], street: json["street"], barangay: json["barangay"], municipality: json["municipality"], province: json["province"], + genCode: json["gen_code"], + ); + + factory BldgLoc.fromJson2(Map json) => BldgLoc( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + street: json["street"], + barangay: json["barangay"], + municipality: json["municipality"], + province: json["province"], + genCode: json["gen_code"], ); Map toJson() => { @@ -55,11 +94,12 @@ class BldgLoc { "bldgappr_details_id": bldgapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "street": street, "barangay": barangay, "municipality": municipality, "province": province, + "gen_code": genCode, }; } diff --git a/lib/model/passo/building_and_structure.dart b/lib/model/passo/building_and_structure.dart new file mode 100644 index 0000000..910e818 --- /dev/null +++ b/lib/model/passo/building_and_structure.dart @@ -0,0 +1,119 @@ +// To parse this JSON data, do +// +// final bldgAndStructure = bldgAndStructureFromJson(jsonString); + +import 'dart:convert'; + +BldgAndStructure bldgAndStructureFromJson(String str) => + BldgAndStructure.fromJson(json.decode(str)); + +String bldgAndStructureToJson(BldgAndStructure data) => + json.encode(data.toJson()); + +class BldgAndStructure { + final int? id; + final int? bldgapprDetailsId; + final String? bldgType; + final String? structType; + final String? description; + final String? actualUse; + final String? floorCount; + final String? bldgArea; + final String? unitValue; + final String? buccPercentage; + final String? depRate; + final String? marketValue; + final String? depAmount; + final String? adjustedMarketValue; + final String? genCode; + + BldgAndStructure({ + this.id, + this.bldgapprDetailsId, + this.bldgType, + this.structType, + this.description, + this.actualUse, + this.floorCount, + this.bldgArea, + this.unitValue, + this.buccPercentage, + this.depRate, + this.marketValue, + this.depAmount, + this.adjustedMarketValue, + this.genCode, + }); + + BldgAndStructure copy({ + int? id, + int? bldgapprDetailsId, + String? bldgType, + String? structType, + String? description, + String? actualUse, + String? floorCount, + String? bldgArea, + String? unitValue, + String? buccPercentage, + String? depRate, + String? marketValue, + String? depAmount, + String? adjustedMarketValue, + String? genCode, + }) => + BldgAndStructure( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + bldgType: bldgType ?? this.bldgType, + structType: structType ?? this.structType, + description: description ?? this.description, + actualUse: actualUse ?? this.actualUse, + floorCount: floorCount ?? this.floorCount, + bldgArea: bldgArea ?? this.bldgArea, + unitValue: unitValue ?? this.unitValue, + buccPercentage: buccPercentage ?? this.buccPercentage, + depRate: depRate ?? this.depRate, + marketValue: marketValue ?? this.marketValue, + depAmount: depAmount ?? this.depAmount, + adjustedMarketValue: adjustedMarketValue ?? this.adjustedMarketValue, + genCode: genCode ?? this.genCode, + ); + + factory BldgAndStructure.fromJson(Map json) => + BldgAndStructure( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + bldgType: json["bldgType"], + structType: json["structType"], + description: json["description"], + actualUse: json["actualUse"], + floorCount: json["floorCount"], + bldgArea: json["bldgArea"], + unitValue: json["unitValue"], + buccPercentage: json["buccPercentage"], + depRate: json["depRate"], + marketValue: json["marketValue"], + depAmount: json["depAmount"], + adjustedMarketValue: json["adjustedMarketValue"], + genCode: json["gen_code"], + ); + + Map toJson() => { + "id": id, + "bldgappr_details_id": bldgapprDetailsId, + "bldg_type": bldgType, + "struct_type": structType, + "description": description, + "actual_use": actualUse, + "floor_count": floorCount, + "bldg_area": bldgArea, + "unit_value": unitValue, + "bucc_percentage": buccPercentage, + "dep_rate": depRate, + "market_value": marketValue, + "dep_amount": depAmount, + "adjusted_market_value": adjustedMarketValue, + "gen_code": genCode, + }; +} diff --git a/lib/model/passo/building_details.dart b/lib/model/passo/building_details.dart new file mode 100644 index 0000000..b1f6e04 --- /dev/null +++ b/lib/model/passo/building_details.dart @@ -0,0 +1,850 @@ +// To parse this JSON data, do +// +// final buildingDetails = buildingDetailsFromJson(jsonString); + +import 'dart:convert'; + +BuildingDetails buildingDetailsFromJson(String str) => + BuildingDetails.fromJson(json.decode(str)); + +String buildingDetailsToJson(BuildingDetails data) => + json.encode(data.toJson()); + +class BuildingDetails { + final String? assessedById; + final String? assessedByName; + final String? dateCreated; + final String? dateModified; + final String? transCode; + final String? tdn; + final String? pin; + 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; + final String? genCode; + final String? bldgapprLocationDateCreated; + final String? bldgapprLocationDateModified; + final dynamic bldgapprLocationStreet; + final dynamic bldgapprLocationBarangay; + final dynamic bldgapprLocationMunicipality; + final dynamic bldgapprLocationProvince; + final String? bldgapprLocationGenCode; + final String? bldgapprLandrefDateCreated; + final String? bldgapprLandrefDateModified; + final dynamic bldgapprLandrefOwner; + final dynamic bldgapprLandrefCloaNo; + final dynamic bldgapprLandrefLotNo; + final dynamic bldgapprLandrefTdn; + final dynamic bldgapprLandrefArea; + final dynamic bldgapprLandrefSurveyNo; + final dynamic bldgapprLandrefBlkNo; + final String? bldgapprLandrefGenCode; + final String? bldgapprGeneraldescDateCreated; + final String? bldgapprGeneraldescDateModified; + final dynamic bldgapprGeneraldescBldgKind; + final dynamic bldgapprGeneraldescStrucType; + final dynamic bldgapprGeneraldescBldgPermit; + final dynamic bldgapprGeneraldescDateIssued; + final dynamic bldgapprGeneraldescCct; + final dynamic bldgapprGeneraldescCertCompletionIssued; + final dynamic bldgapprGeneraldescCertOccupancyIssued; + final dynamic bldgapprGeneraldescDateCompleted; + final dynamic bldgapprGeneraldescDateOccupied; + final dynamic bldgapprGeneraldescBldgAge; + final dynamic bldgapprGeneraldescNoStoreys; + final dynamic bldgapprGeneraldescArea1Stfloor; + final dynamic bldgapprGeneraldescArea2Ndfloor; + final dynamic bldgapprGeneraldescArea3Rdfloor; + final dynamic bldgapprGeneraldescArea4Thfloor; + final dynamic bldgapprGeneraldescTotalFloorArea; + final dynamic bldgapprGeneraldescFloorSketch; + final dynamic bldgapprGeneraldescActualUse; + final dynamic bldgapprGeneraldescUnitValue; + final String? bldgapprGeneraldescGenCode; + final String? bldgapprStructMaterialsDateCreated; + final String? bldgapprStructMaterialsDateModified; + final dynamic bldgapprStructMaterialsFoundation; + final dynamic bldgapprStructMaterialsColumns; + final dynamic bldgapprStructMaterialsBeams; + final dynamic bldgapprStructMaterialsTrussFraming; + final dynamic bldgapprStructMaterialsRoof; + final dynamic bldgapprStructMaterialsFlooring; + final dynamic bldgapprStructMaterialsWalls; + final dynamic bldgapprStructMaterialsOthers; + final String? bldgapprStructMaterialsGenCode; + final String? bldgapprPropertyAssessmentDateCreated; + final String? bldgapprPropertyAssessmentDateModified; + final dynamic bldgapprPropertyAssessmentActualUse; + final dynamic bldgapprPropertyAssessmentMarketValue; + final dynamic bldgapprPropertyAssessmentAssessmentLevel; + final dynamic bldgapprPropertyAssessmentAssessedValue; + final dynamic bldgapprPropertyAssessmentTaxable; + final dynamic bldgapprPropertyAssessmentExempt; + final dynamic bldgapprPropertyAssessmentQtr; + final dynamic bldgapprPropertyAssessmentYr; + final dynamic bldgapprPropertyAssessmentAppraisedbyName; + final dynamic bldgapprPropertyAssessmentAppraisedbyDate; + final dynamic bldgapprPropertyAssessmentRecommendapprName; + final dynamic bldgapprPropertyAssessmentRecommendapprDate; + final dynamic bldgapprPropertyAssessmentApprovedbyName; + final dynamic bldgapprPropertyAssessmentApprovedbyDate; + final dynamic bldgapprPropertyAssessmentMemoranda; + final dynamic bldgapprPropertyAssessmentSwornstatementNo; + final dynamic bldgapprPropertyAssessmentDateReceived; + final dynamic bldgapprPropertyAssessmentEntryDateAssessment; + final dynamic bldgapprPropertyAssessmentEntryDateBy; + final String? bldgapprPropertyAssessmentGenCode; + final String? bldgapprRecSupersededassDateCreated; + final String? bldgapprRecSupersededassDateModified; + final dynamic bldgapprRecSupersededassPin; + final dynamic bldgapprRecSupersededassTdn; + final dynamic bldgapprRecSupersededassTotalAssval; + final dynamic bldgapprRecSupersededassOwner; + final dynamic bldgapprRecSupersededassEffectivityAss; + final dynamic bldgapprRecSupersededassPageNo; + final dynamic bldgapprRecSupersededassTotalMarketval; + final dynamic bldgapprRecSupersededassTotalArea; + final dynamic bldgapprRecSupersededassRecAssessment; + final dynamic bldgapprRecSupersededassRecTaxmapping; + final dynamic bldgapprRecSupersededassRecRecords; + final dynamic bldgapprRecSupersededassDate; + final String? bldgapprRecSupersededassGenCode; + + BuildingDetails({ + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.transCode, + this.tdn, + this.pin, + this.owner, + this.address, + this.telno, + this.tin, + this.adminUser, + this.adminAddress, + this.adminTelno, + this.adminTin, + this.faasType, + this.genCode, + this.bldgapprLocationDateCreated, + this.bldgapprLocationDateModified, + this.bldgapprLocationStreet, + this.bldgapprLocationBarangay, + this.bldgapprLocationMunicipality, + this.bldgapprLocationProvince, + this.bldgapprLocationGenCode, + this.bldgapprLandrefDateCreated, + this.bldgapprLandrefDateModified, + this.bldgapprLandrefOwner, + this.bldgapprLandrefCloaNo, + this.bldgapprLandrefLotNo, + this.bldgapprLandrefTdn, + this.bldgapprLandrefArea, + this.bldgapprLandrefSurveyNo, + this.bldgapprLandrefBlkNo, + this.bldgapprLandrefGenCode, + this.bldgapprGeneraldescDateCreated, + this.bldgapprGeneraldescDateModified, + this.bldgapprGeneraldescBldgKind, + this.bldgapprGeneraldescStrucType, + this.bldgapprGeneraldescBldgPermit, + this.bldgapprGeneraldescDateIssued, + this.bldgapprGeneraldescCct, + this.bldgapprGeneraldescCertCompletionIssued, + this.bldgapprGeneraldescCertOccupancyIssued, + this.bldgapprGeneraldescDateCompleted, + this.bldgapprGeneraldescDateOccupied, + this.bldgapprGeneraldescBldgAge, + this.bldgapprGeneraldescNoStoreys, + this.bldgapprGeneraldescArea1Stfloor, + this.bldgapprGeneraldescArea2Ndfloor, + this.bldgapprGeneraldescArea3Rdfloor, + this.bldgapprGeneraldescArea4Thfloor, + this.bldgapprGeneraldescTotalFloorArea, + this.bldgapprGeneraldescFloorSketch, + this.bldgapprGeneraldescActualUse, + this.bldgapprGeneraldescUnitValue, + this.bldgapprGeneraldescGenCode, + this.bldgapprStructMaterialsDateCreated, + this.bldgapprStructMaterialsDateModified, + this.bldgapprStructMaterialsFoundation, + this.bldgapprStructMaterialsColumns, + this.bldgapprStructMaterialsBeams, + this.bldgapprStructMaterialsTrussFraming, + this.bldgapprStructMaterialsRoof, + this.bldgapprStructMaterialsFlooring, + this.bldgapprStructMaterialsWalls, + this.bldgapprStructMaterialsOthers, + this.bldgapprStructMaterialsGenCode, + this.bldgapprPropertyAssessmentDateCreated, + this.bldgapprPropertyAssessmentDateModified, + this.bldgapprPropertyAssessmentActualUse, + this.bldgapprPropertyAssessmentMarketValue, + this.bldgapprPropertyAssessmentAssessmentLevel, + this.bldgapprPropertyAssessmentAssessedValue, + this.bldgapprPropertyAssessmentTaxable, + this.bldgapprPropertyAssessmentExempt, + this.bldgapprPropertyAssessmentQtr, + this.bldgapprPropertyAssessmentYr, + this.bldgapprPropertyAssessmentAppraisedbyName, + this.bldgapprPropertyAssessmentAppraisedbyDate, + this.bldgapprPropertyAssessmentRecommendapprName, + this.bldgapprPropertyAssessmentRecommendapprDate, + this.bldgapprPropertyAssessmentApprovedbyName, + this.bldgapprPropertyAssessmentApprovedbyDate, + this.bldgapprPropertyAssessmentMemoranda, + this.bldgapprPropertyAssessmentSwornstatementNo, + this.bldgapprPropertyAssessmentDateReceived, + this.bldgapprPropertyAssessmentEntryDateAssessment, + this.bldgapprPropertyAssessmentEntryDateBy, + this.bldgapprPropertyAssessmentGenCode, + this.bldgapprRecSupersededassDateCreated, + this.bldgapprRecSupersededassDateModified, + this.bldgapprRecSupersededassPin, + this.bldgapprRecSupersededassTdn, + this.bldgapprRecSupersededassTotalAssval, + this.bldgapprRecSupersededassOwner, + this.bldgapprRecSupersededassEffectivityAss, + this.bldgapprRecSupersededassPageNo, + this.bldgapprRecSupersededassTotalMarketval, + this.bldgapprRecSupersededassTotalArea, + this.bldgapprRecSupersededassRecAssessment, + this.bldgapprRecSupersededassRecTaxmapping, + this.bldgapprRecSupersededassRecRecords, + this.bldgapprRecSupersededassDate, + this.bldgapprRecSupersededassGenCode, + }); + + BuildingDetails copyWith({ + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? transCode, + String? tdn, + String? pin, + String? owner, + String? address, + String? telno, + String? tin, + String? adminUser, + String? adminAddress, + String? adminTelno, + String? adminTin, + String? faasType, + String? genCode, + String? bldgapprLocationDateCreated, + String? bldgapprLocationDateModified, + dynamic bldgapprLocationStreet, + dynamic bldgapprLocationBarangay, + dynamic bldgapprLocationMunicipality, + dynamic bldgapprLocationProvince, + String? bldgapprLocationGenCode, + String? bldgapprLandrefDateCreated, + String? bldgapprLandrefDateModified, + dynamic bldgapprLandrefOwner, + dynamic bldgapprLandrefCloaNo, + dynamic bldgapprLandrefLotNo, + dynamic bldgapprLandrefTdn, + dynamic bldgapprLandrefArea, + dynamic bldgapprLandrefSurveyNo, + dynamic bldgapprLandrefBlkNo, + String? bldgapprLandrefGenCode, + String? bldgapprGeneraldescDateCreated, + String? bldgapprGeneraldescDateModified, + dynamic bldgapprGeneraldescBldgKind, + dynamic bldgapprGeneraldescStrucType, + dynamic bldgapprGeneraldescBldgPermit, + dynamic bldgapprGeneraldescDateIssued, + dynamic bldgapprGeneraldescCct, + dynamic bldgapprGeneraldescCertCompletionIssued, + dynamic bldgapprGeneraldescCertOccupancyIssued, + dynamic bldgapprGeneraldescDateCompleted, + dynamic bldgapprGeneraldescDateOccupied, + dynamic bldgapprGeneraldescBldgAge, + dynamic bldgapprGeneraldescNoStoreys, + dynamic bldgapprGeneraldescArea1Stfloor, + dynamic bldgapprGeneraldescArea2Ndfloor, + dynamic bldgapprGeneraldescArea3Rdfloor, + dynamic bldgapprGeneraldescArea4Thfloor, + dynamic bldgapprGeneraldescTotalFloorArea, + dynamic bldgapprGeneraldescFloorSketch, + dynamic bldgapprGeneraldescActualUse, + dynamic bldgapprGeneraldescUnitValue, + String? bldgapprGeneraldescGenCode, + String? bldgapprStructMaterialsDateCreated, + String? bldgapprStructMaterialsDateModified, + dynamic bldgapprStructMaterialsFoundation, + dynamic bldgapprStructMaterialsColumns, + dynamic bldgapprStructMaterialsBeams, + dynamic bldgapprStructMaterialsTrussFraming, + dynamic bldgapprStructMaterialsRoof, + dynamic bldgapprStructMaterialsFlooring, + dynamic bldgapprStructMaterialsWalls, + dynamic bldgapprStructMaterialsOthers, + String? bldgapprStructMaterialsGenCode, + String? bldgapprPropertyAssessmentDateCreated, + String? bldgapprPropertyAssessmentDateModified, + dynamic bldgapprPropertyAssessmentActualUse, + dynamic bldgapprPropertyAssessmentMarketValue, + dynamic bldgapprPropertyAssessmentAssessmentLevel, + dynamic bldgapprPropertyAssessmentAssessedValue, + dynamic bldgapprPropertyAssessmentTaxable, + dynamic bldgapprPropertyAssessmentExempt, + dynamic bldgapprPropertyAssessmentQtr, + dynamic bldgapprPropertyAssessmentYr, + dynamic bldgapprPropertyAssessmentAppraisedbyName, + dynamic bldgapprPropertyAssessmentAppraisedbyDate, + dynamic bldgapprPropertyAssessmentRecommendapprName, + dynamic bldgapprPropertyAssessmentRecommendapprDate, + dynamic bldgapprPropertyAssessmentApprovedbyName, + dynamic bldgapprPropertyAssessmentApprovedbyDate, + dynamic bldgapprPropertyAssessmentMemoranda, + dynamic bldgapprPropertyAssessmentSwornstatementNo, + dynamic bldgapprPropertyAssessmentDateReceived, + dynamic bldgapprPropertyAssessmentEntryDateAssessment, + dynamic bldgapprPropertyAssessmentEntryDateBy, + String? bldgapprPropertyAssessmentGenCode, + String? bldgapprRecSupersededassDateCreated, + String? bldgapprRecSupersededassDateModified, + dynamic bldgapprRecSupersededassPin, + dynamic bldgapprRecSupersededassTdn, + dynamic bldgapprRecSupersededassTotalAssval, + dynamic bldgapprRecSupersededassOwner, + dynamic bldgapprRecSupersededassEffectivityAss, + dynamic bldgapprRecSupersededassPageNo, + dynamic bldgapprRecSupersededassTotalMarketval, + dynamic bldgapprRecSupersededassTotalArea, + dynamic bldgapprRecSupersededassRecAssessment, + dynamic bldgapprRecSupersededassRecTaxmapping, + dynamic bldgapprRecSupersededassRecRecords, + dynamic bldgapprRecSupersededassDate, + String? bldgapprRecSupersededassGenCode, + }) => + BuildingDetails( + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + transCode: transCode ?? this.transCode, + tdn: tdn ?? this.tdn, + pin: pin ?? this.pin, + owner: owner ?? this.owner, + address: address ?? this.address, + telno: telno ?? this.telno, + tin: tin ?? this.tin, + adminUser: adminUser ?? this.adminUser, + adminAddress: adminAddress ?? this.adminAddress, + adminTelno: adminTelno ?? this.adminTelno, + adminTin: adminTin ?? this.adminTin, + faasType: faasType ?? this.faasType, + genCode: genCode ?? this.genCode, + bldgapprLocationDateCreated: + bldgapprLocationDateCreated ?? this.bldgapprLocationDateCreated, + bldgapprLocationDateModified: + bldgapprLocationDateModified ?? this.bldgapprLocationDateModified, + bldgapprLocationStreet: + bldgapprLocationStreet ?? this.bldgapprLocationStreet, + bldgapprLocationBarangay: + bldgapprLocationBarangay ?? this.bldgapprLocationBarangay, + bldgapprLocationMunicipality: + bldgapprLocationMunicipality ?? this.bldgapprLocationMunicipality, + bldgapprLocationProvince: + bldgapprLocationProvince ?? this.bldgapprLocationProvince, + bldgapprLocationGenCode: + bldgapprLocationGenCode ?? this.bldgapprLocationGenCode, + bldgapprLandrefDateCreated: + bldgapprLandrefDateCreated ?? this.bldgapprLandrefDateCreated, + bldgapprLandrefDateModified: + bldgapprLandrefDateModified ?? this.bldgapprLandrefDateModified, + bldgapprLandrefOwner: bldgapprLandrefOwner ?? this.bldgapprLandrefOwner, + bldgapprLandrefCloaNo: + bldgapprLandrefCloaNo ?? this.bldgapprLandrefCloaNo, + bldgapprLandrefLotNo: bldgapprLandrefLotNo ?? this.bldgapprLandrefLotNo, + bldgapprLandrefTdn: bldgapprLandrefTdn ?? this.bldgapprLandrefTdn, + bldgapprLandrefArea: bldgapprLandrefArea ?? this.bldgapprLandrefArea, + bldgapprLandrefSurveyNo: + bldgapprLandrefSurveyNo ?? this.bldgapprLandrefSurveyNo, + bldgapprLandrefBlkNo: bldgapprLandrefBlkNo ?? this.bldgapprLandrefBlkNo, + bldgapprLandrefGenCode: + bldgapprLandrefGenCode ?? this.bldgapprLandrefGenCode, + bldgapprGeneraldescDateCreated: bldgapprGeneraldescDateCreated ?? + this.bldgapprGeneraldescDateCreated, + bldgapprGeneraldescDateModified: bldgapprGeneraldescDateModified ?? + this.bldgapprGeneraldescDateModified, + bldgapprGeneraldescBldgKind: + bldgapprGeneraldescBldgKind ?? this.bldgapprGeneraldescBldgKind, + bldgapprGeneraldescStrucType: + bldgapprGeneraldescStrucType ?? this.bldgapprGeneraldescStrucType, + bldgapprGeneraldescBldgPermit: + bldgapprGeneraldescBldgPermit ?? this.bldgapprGeneraldescBldgPermit, + bldgapprGeneraldescDateIssued: + bldgapprGeneraldescDateIssued ?? this.bldgapprGeneraldescDateIssued, + bldgapprGeneraldescCct: + bldgapprGeneraldescCct ?? this.bldgapprGeneraldescCct, + bldgapprGeneraldescCertCompletionIssued: + bldgapprGeneraldescCertCompletionIssued ?? + this.bldgapprGeneraldescCertCompletionIssued, + bldgapprGeneraldescCertOccupancyIssued: + bldgapprGeneraldescCertOccupancyIssued ?? + this.bldgapprGeneraldescCertOccupancyIssued, + bldgapprGeneraldescDateCompleted: bldgapprGeneraldescDateCompleted ?? + this.bldgapprGeneraldescDateCompleted, + bldgapprGeneraldescDateOccupied: bldgapprGeneraldescDateOccupied ?? + this.bldgapprGeneraldescDateOccupied, + bldgapprGeneraldescBldgAge: + bldgapprGeneraldescBldgAge ?? this.bldgapprGeneraldescBldgAge, + bldgapprGeneraldescNoStoreys: + bldgapprGeneraldescNoStoreys ?? this.bldgapprGeneraldescNoStoreys, + bldgapprGeneraldescArea1Stfloor: bldgapprGeneraldescArea1Stfloor ?? + this.bldgapprGeneraldescArea1Stfloor, + bldgapprGeneraldescArea2Ndfloor: bldgapprGeneraldescArea2Ndfloor ?? + this.bldgapprGeneraldescArea2Ndfloor, + bldgapprGeneraldescArea3Rdfloor: bldgapprGeneraldescArea3Rdfloor ?? + this.bldgapprGeneraldescArea3Rdfloor, + bldgapprGeneraldescArea4Thfloor: bldgapprGeneraldescArea4Thfloor ?? + this.bldgapprGeneraldescArea4Thfloor, + bldgapprGeneraldescTotalFloorArea: bldgapprGeneraldescTotalFloorArea ?? + this.bldgapprGeneraldescTotalFloorArea, + bldgapprGeneraldescFloorSketch: bldgapprGeneraldescFloorSketch ?? + this.bldgapprGeneraldescFloorSketch, + bldgapprGeneraldescActualUse: + bldgapprGeneraldescActualUse ?? this.bldgapprGeneraldescActualUse, + bldgapprGeneraldescUnitValue: + bldgapprGeneraldescUnitValue ?? this.bldgapprGeneraldescUnitValue, + bldgapprGeneraldescGenCode: + bldgapprGeneraldescGenCode ?? this.bldgapprGeneraldescGenCode, + bldgapprStructMaterialsDateCreated: + bldgapprStructMaterialsDateCreated ?? + this.bldgapprStructMaterialsDateCreated, + bldgapprStructMaterialsDateModified: + bldgapprStructMaterialsDateModified ?? + this.bldgapprStructMaterialsDateModified, + bldgapprStructMaterialsFoundation: bldgapprStructMaterialsFoundation ?? + this.bldgapprStructMaterialsFoundation, + bldgapprStructMaterialsColumns: bldgapprStructMaterialsColumns ?? + this.bldgapprStructMaterialsColumns, + bldgapprStructMaterialsBeams: + bldgapprStructMaterialsBeams ?? this.bldgapprStructMaterialsBeams, + bldgapprStructMaterialsTrussFraming: + bldgapprStructMaterialsTrussFraming ?? + this.bldgapprStructMaterialsTrussFraming, + bldgapprStructMaterialsRoof: + bldgapprStructMaterialsRoof ?? this.bldgapprStructMaterialsRoof, + bldgapprStructMaterialsFlooring: bldgapprStructMaterialsFlooring ?? + this.bldgapprStructMaterialsFlooring, + bldgapprStructMaterialsWalls: + bldgapprStructMaterialsWalls ?? this.bldgapprStructMaterialsWalls, + bldgapprStructMaterialsOthers: + bldgapprStructMaterialsOthers ?? this.bldgapprStructMaterialsOthers, + bldgapprStructMaterialsGenCode: bldgapprStructMaterialsGenCode ?? + this.bldgapprStructMaterialsGenCode, + bldgapprPropertyAssessmentDateCreated: + bldgapprPropertyAssessmentDateCreated ?? + this.bldgapprPropertyAssessmentDateCreated, + bldgapprPropertyAssessmentDateModified: + bldgapprPropertyAssessmentDateModified ?? + this.bldgapprPropertyAssessmentDateModified, + bldgapprPropertyAssessmentActualUse: + bldgapprPropertyAssessmentActualUse ?? + this.bldgapprPropertyAssessmentActualUse, + bldgapprPropertyAssessmentMarketValue: + bldgapprPropertyAssessmentMarketValue ?? + this.bldgapprPropertyAssessmentMarketValue, + bldgapprPropertyAssessmentAssessmentLevel: + bldgapprPropertyAssessmentAssessmentLevel ?? + this.bldgapprPropertyAssessmentAssessmentLevel, + bldgapprPropertyAssessmentAssessedValue: + bldgapprPropertyAssessmentAssessedValue ?? + this.bldgapprPropertyAssessmentAssessedValue, + bldgapprPropertyAssessmentTaxable: bldgapprPropertyAssessmentTaxable ?? + this.bldgapprPropertyAssessmentTaxable, + bldgapprPropertyAssessmentExempt: bldgapprPropertyAssessmentExempt ?? + this.bldgapprPropertyAssessmentExempt, + bldgapprPropertyAssessmentQtr: + bldgapprPropertyAssessmentQtr ?? this.bldgapprPropertyAssessmentQtr, + bldgapprPropertyAssessmentYr: + bldgapprPropertyAssessmentYr ?? this.bldgapprPropertyAssessmentYr, + bldgapprPropertyAssessmentAppraisedbyName: + bldgapprPropertyAssessmentAppraisedbyName ?? + this.bldgapprPropertyAssessmentAppraisedbyName, + bldgapprPropertyAssessmentAppraisedbyDate: + bldgapprPropertyAssessmentAppraisedbyDate ?? + this.bldgapprPropertyAssessmentAppraisedbyDate, + bldgapprPropertyAssessmentRecommendapprName: + bldgapprPropertyAssessmentRecommendapprName ?? + this.bldgapprPropertyAssessmentRecommendapprName, + bldgapprPropertyAssessmentRecommendapprDate: + bldgapprPropertyAssessmentRecommendapprDate ?? + this.bldgapprPropertyAssessmentRecommendapprDate, + bldgapprPropertyAssessmentApprovedbyName: + bldgapprPropertyAssessmentApprovedbyName ?? + this.bldgapprPropertyAssessmentApprovedbyName, + bldgapprPropertyAssessmentApprovedbyDate: + bldgapprPropertyAssessmentApprovedbyDate ?? + this.bldgapprPropertyAssessmentApprovedbyDate, + bldgapprPropertyAssessmentMemoranda: + bldgapprPropertyAssessmentMemoranda ?? + this.bldgapprPropertyAssessmentMemoranda, + bldgapprPropertyAssessmentSwornstatementNo: + bldgapprPropertyAssessmentSwornstatementNo ?? + this.bldgapprPropertyAssessmentSwornstatementNo, + bldgapprPropertyAssessmentDateReceived: + bldgapprPropertyAssessmentDateReceived ?? + this.bldgapprPropertyAssessmentDateReceived, + bldgapprPropertyAssessmentEntryDateAssessment: + bldgapprPropertyAssessmentEntryDateAssessment ?? + this.bldgapprPropertyAssessmentEntryDateAssessment, + bldgapprPropertyAssessmentEntryDateBy: + bldgapprPropertyAssessmentEntryDateBy ?? + this.bldgapprPropertyAssessmentEntryDateBy, + bldgapprPropertyAssessmentGenCode: bldgapprPropertyAssessmentGenCode ?? + this.bldgapprPropertyAssessmentGenCode, + bldgapprRecSupersededassDateCreated: + bldgapprRecSupersededassDateCreated ?? + this.bldgapprRecSupersededassDateCreated, + bldgapprRecSupersededassDateModified: + bldgapprRecSupersededassDateModified ?? + this.bldgapprRecSupersededassDateModified, + bldgapprRecSupersededassPin: + bldgapprRecSupersededassPin ?? this.bldgapprRecSupersededassPin, + bldgapprRecSupersededassTdn: + bldgapprRecSupersededassTdn ?? this.bldgapprRecSupersededassTdn, + bldgapprRecSupersededassTotalAssval: + bldgapprRecSupersededassTotalAssval ?? + this.bldgapprRecSupersededassTotalAssval, + bldgapprRecSupersededassOwner: + bldgapprRecSupersededassOwner ?? this.bldgapprRecSupersededassOwner, + bldgapprRecSupersededassEffectivityAss: + bldgapprRecSupersededassEffectivityAss ?? + this.bldgapprRecSupersededassEffectivityAss, + bldgapprRecSupersededassPageNo: bldgapprRecSupersededassPageNo ?? + this.bldgapprRecSupersededassPageNo, + bldgapprRecSupersededassTotalMarketval: + bldgapprRecSupersededassTotalMarketval ?? + this.bldgapprRecSupersededassTotalMarketval, + bldgapprRecSupersededassTotalArea: bldgapprRecSupersededassTotalArea ?? + this.bldgapprRecSupersededassTotalArea, + bldgapprRecSupersededassRecAssessment: + bldgapprRecSupersededassRecAssessment ?? + this.bldgapprRecSupersededassRecAssessment, + bldgapprRecSupersededassRecTaxmapping: + bldgapprRecSupersededassRecTaxmapping ?? + this.bldgapprRecSupersededassRecTaxmapping, + bldgapprRecSupersededassRecRecords: + bldgapprRecSupersededassRecRecords ?? + this.bldgapprRecSupersededassRecRecords, + bldgapprRecSupersededassDate: + bldgapprRecSupersededassDate ?? this.bldgapprRecSupersededassDate, + bldgapprRecSupersededassGenCode: bldgapprRecSupersededassGenCode ?? + this.bldgapprRecSupersededassGenCode, + ); + + factory BuildingDetails.fromJson(Map json) => + BuildingDetails( + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"], + dateModified: json["date_modified"], + transCode: json["trans_code"], + tdn: json["tdn"], + pin: json["pin"], + 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"], + genCode: json["gen_code"], + bldgapprLocationDateCreated: json["bldgappr_location.date_created"], + bldgapprLocationDateModified: json["bldgappr_location.date_modified"], + bldgapprLocationStreet: json["bldgappr_location.street"], + bldgapprLocationBarangay: json["bldgappr_location.barangay"], + bldgapprLocationMunicipality: json["bldgappr_location.municipality"], + bldgapprLocationProvince: json["bldgappr_location.province"], + bldgapprLocationGenCode: json["bldgappr_location.gen_code"], + bldgapprLandrefDateCreated: json["bldgappr_landref.date_created"], + bldgapprLandrefDateModified: json["bldgappr_landref.date_modified"], + bldgapprLandrefOwner: json["bldgappr_landref.owner"], + bldgapprLandrefCloaNo: json["bldgappr_landref.cloa_no"], + bldgapprLandrefLotNo: json["bldgappr_landref.lot_no"], + bldgapprLandrefTdn: json["bldgappr_landref.tdn"], + bldgapprLandrefArea: json["bldgappr_landref.area"], + bldgapprLandrefSurveyNo: json["bldgappr_landref.survey_no"], + bldgapprLandrefBlkNo: json["bldgappr_landref.blk_no"], + bldgapprLandrefGenCode: json["bldgappr_landref.gen_code"], + bldgapprGeneraldescDateCreated: + json["bldgappr_generaldesc.date_created"], + bldgapprGeneraldescDateModified: + json["bldgappr_generaldesc.date_modified"], + bldgapprGeneraldescBldgKind: json["bldgappr_generaldesc.bldg_kind"], + bldgapprGeneraldescStrucType: json["bldgappr_generaldesc.struc_type"], + bldgapprGeneraldescBldgPermit: json["bldgappr_generaldesc.bldg_permit"], + bldgapprGeneraldescDateIssued: json["bldgappr_generaldesc.date_issued"], + bldgapprGeneraldescCct: json["bldgappr_generaldesc.cct"], + bldgapprGeneraldescCertCompletionIssued: + json["bldgappr_generaldesc.cert_completion_issued"], + bldgapprGeneraldescCertOccupancyIssued: + json["bldgappr_generaldesc.cert_occupancy_issued"], + bldgapprGeneraldescDateCompleted: + json["bldgappr_generaldesc.date_completed"], + bldgapprGeneraldescDateOccupied: + json["bldgappr_generaldesc.date_occupied"], + bldgapprGeneraldescBldgAge: json["bldgappr_generaldesc.bldg_age"], + bldgapprGeneraldescNoStoreys: json["bldgappr_generaldesc.no_storeys"], + bldgapprGeneraldescArea1Stfloor: + json["bldgappr_generaldesc.area_1stfloor"], + bldgapprGeneraldescArea2Ndfloor: + json["bldgappr_generaldesc.area_2ndfloor"], + bldgapprGeneraldescArea3Rdfloor: + json["bldgappr_generaldesc.area_3rdfloor"], + bldgapprGeneraldescArea4Thfloor: + json["bldgappr_generaldesc.area_4thfloor"], + bldgapprGeneraldescTotalFloorArea: + json["bldgappr_generaldesc.total_floor_area"], + bldgapprGeneraldescFloorSketch: + json["bldgappr_generaldesc.floor_sketch"], + bldgapprGeneraldescActualUse: json["bldgappr_generaldesc.actual_use"], + bldgapprGeneraldescUnitValue: json["bldgappr_generaldesc.unit_value"], + bldgapprGeneraldescGenCode: json["bldgappr_generaldesc.gen_code"], + bldgapprStructMaterialsDateCreated: + json["bldgappr_struct_materials.date_created"], + bldgapprStructMaterialsDateModified: + json["bldgappr_struct_materials.date_modified"], + bldgapprStructMaterialsFoundation: + json["bldgappr_struct_materials.foundation"], + bldgapprStructMaterialsColumns: + json["bldgappr_struct_materials.columns"], + bldgapprStructMaterialsBeams: json["bldgappr_struct_materials.beams"], + bldgapprStructMaterialsTrussFraming: + json["bldgappr_struct_materials.truss_framing"], + bldgapprStructMaterialsRoof: json["bldgappr_struct_materials.roof"], + bldgapprStructMaterialsFlooring: + json["bldgappr_struct_materials.flooring"], + bldgapprStructMaterialsWalls: json["bldgappr_struct_materials.walls"], + bldgapprStructMaterialsOthers: json["bldgappr_struct_materials.others"], + bldgapprStructMaterialsGenCode: + json["bldgappr_struct_materials.gen_code"], + bldgapprPropertyAssessmentDateCreated: + json["bldgappr_property_assessment.date_created"], + bldgapprPropertyAssessmentDateModified: + json["bldgappr_property_assessment.date_modified"], + bldgapprPropertyAssessmentActualUse: + json["bldgappr_property_assessment.actual_use"], + bldgapprPropertyAssessmentMarketValue: + json["bldgappr_property_assessment.market_value"], + bldgapprPropertyAssessmentAssessmentLevel: + json["bldgappr_property_assessment.assessment_level"], + bldgapprPropertyAssessmentAssessedValue: + json["bldgappr_property_assessment.assessed_value"], + bldgapprPropertyAssessmentTaxable: + json["bldgappr_property_assessment.taxable"], + bldgapprPropertyAssessmentExempt: + json["bldgappr_property_assessment.exempt"], + bldgapprPropertyAssessmentQtr: json["bldgappr_property_assessment.qtr"], + bldgapprPropertyAssessmentYr: json["bldgappr_property_assessment.yr"], + bldgapprPropertyAssessmentAppraisedbyName: + json["bldgappr_property_assessment.appraisedby_name"], + bldgapprPropertyAssessmentAppraisedbyDate: + json["bldgappr_property_assessment.appraisedby_date"], + bldgapprPropertyAssessmentRecommendapprName: + json["bldgappr_property_assessment.recommendappr_name"], + bldgapprPropertyAssessmentRecommendapprDate: + json["bldgappr_property_assessment.recommendappr_date"], + bldgapprPropertyAssessmentApprovedbyName: + json["bldgappr_property_assessment.approvedby_name"], + bldgapprPropertyAssessmentApprovedbyDate: + json["bldgappr_property_assessment.approvedby_date"], + bldgapprPropertyAssessmentMemoranda: + json["bldgappr_property_assessment.memoranda"], + bldgapprPropertyAssessmentSwornstatementNo: + json["bldgappr_property_assessment.swornstatement_no"], + bldgapprPropertyAssessmentDateReceived: + json["bldgappr_property_assessment.date_received"], + bldgapprPropertyAssessmentEntryDateAssessment: + json["bldgappr_property_assessment.entry_date_assessment"], + bldgapprPropertyAssessmentEntryDateBy: + json["bldgappr_property_assessment.entry_date_by"], + bldgapprPropertyAssessmentGenCode: + json["bldgappr_property_assessment.gen_code"], + bldgapprRecSupersededassDateCreated: + json["bldgappr_rec_supersededass.date_created"], + bldgapprRecSupersededassDateModified: + json["bldgappr_rec_supersededass.date_modified"], + bldgapprRecSupersededassPin: json["bldgappr_rec_supersededass.pin"], + bldgapprRecSupersededassTdn: json["bldgappr_rec_supersededass.tdn"], + bldgapprRecSupersededassTotalAssval: + json["bldgappr_rec_supersededass.total_assval"], + bldgapprRecSupersededassOwner: json["bldgappr_rec_supersededass.owner"], + bldgapprRecSupersededassEffectivityAss: + json["bldgappr_rec_supersededass.effectivity_ass"], + bldgapprRecSupersededassPageNo: + json["bldgappr_rec_supersededass.page_no"], + bldgapprRecSupersededassTotalMarketval: + json["bldgappr_rec_supersededass.total_marketval"], + bldgapprRecSupersededassTotalArea: + json["bldgappr_rec_supersededass.total_area"], + bldgapprRecSupersededassRecAssessment: + json["bldgappr_rec_supersededass.rec_assessment"], + bldgapprRecSupersededassRecTaxmapping: + json["bldgappr_rec_supersededass.rec_taxmapping"], + bldgapprRecSupersededassRecRecords: + json["bldgappr_rec_supersededass.rec_records"], + bldgapprRecSupersededassDate: json["bldgappr_rec_supersededass.date"], + bldgapprRecSupersededassGenCode: + json["bldgappr_rec_supersededass.gen_code"], + ); + + Map toJson() => { + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated, + "date_modified": dateModified, + "trans_code": transCode, + "tdn": tdn, + "pin": pin, + "owner": owner, + "address": address, + "telno": telno, + "tin": tin, + "admin_user": adminUser, + "admin_address": adminAddress, + "admin_telno": adminTelno, + "admin_tin": adminTin, + "faas_type": faasType, + "gen_code": genCode, + "bldgappr_location.date_created": bldgapprLocationDateCreated, + "bldgappr_location.date_modified": bldgapprLocationDateModified, + "bldgappr_location.street": bldgapprLocationStreet, + "bldgappr_location.barangay": bldgapprLocationBarangay, + "bldgappr_location.municipality": bldgapprLocationMunicipality, + "bldgappr_location.province": bldgapprLocationProvince, + "bldgappr_location.gen_code": bldgapprLocationGenCode, + "bldgappr_landref.date_created": bldgapprLandrefDateCreated, + "bldgappr_landref.date_modified": bldgapprLandrefDateModified, + "bldgappr_landref.owner": bldgapprLandrefOwner, + "bldgappr_landref.cloa_no": bldgapprLandrefCloaNo, + "bldgappr_landref.lot_no": bldgapprLandrefLotNo, + "bldgappr_landref.tdn": bldgapprLandrefTdn, + "bldgappr_landref.area": bldgapprLandrefArea, + "bldgappr_landref.survey_no": bldgapprLandrefSurveyNo, + "bldgappr_landref.blk_no": bldgapprLandrefBlkNo, + "bldgappr_landref.gen_code": bldgapprLandrefGenCode, + "bldgappr_generaldesc.date_created": bldgapprGeneraldescDateCreated, + "bldgappr_generaldesc.date_modified": bldgapprGeneraldescDateModified, + "bldgappr_generaldesc.bldg_kind": bldgapprGeneraldescBldgKind, + "bldgappr_generaldesc.struc_type": bldgapprGeneraldescStrucType, + "bldgappr_generaldesc.bldg_permit": bldgapprGeneraldescBldgPermit, + "bldgappr_generaldesc.date_issued": bldgapprGeneraldescDateIssued, + "bldgappr_generaldesc.cct": bldgapprGeneraldescCct, + "bldgappr_generaldesc.cert_completion_issued": + bldgapprGeneraldescCertCompletionIssued, + "bldgappr_generaldesc.cert_occupancy_issued": + bldgapprGeneraldescCertOccupancyIssued, + "bldgappr_generaldesc.date_completed": bldgapprGeneraldescDateCompleted, + "bldgappr_generaldesc.date_occupied": bldgapprGeneraldescDateOccupied, + "bldgappr_generaldesc.bldg_age": bldgapprGeneraldescBldgAge, + "bldgappr_generaldesc.no_storeys": bldgapprGeneraldescNoStoreys, + "bldgappr_generaldesc.area_1stfloor": bldgapprGeneraldescArea1Stfloor, + "bldgappr_generaldesc.area_2ndfloor": bldgapprGeneraldescArea2Ndfloor, + "bldgappr_generaldesc.area_3rdfloor": bldgapprGeneraldescArea3Rdfloor, + "bldgappr_generaldesc.area_4thfloor": bldgapprGeneraldescArea4Thfloor, + "bldgappr_generaldesc.total_floor_area": + bldgapprGeneraldescTotalFloorArea, + "bldgappr_generaldesc.floor_sketch": bldgapprGeneraldescFloorSketch, + "bldgappr_generaldesc.actual_use": bldgapprGeneraldescActualUse, + "bldgappr_generaldesc.unit_value": bldgapprGeneraldescUnitValue, + "bldgappr_generaldesc.gen_code": bldgapprGeneraldescGenCode, + "bldgappr_struct_materials.date_created": + bldgapprStructMaterialsDateCreated, + "bldgappr_struct_materials.date_modified": + bldgapprStructMaterialsDateModified, + "bldgappr_struct_materials.foundation": + bldgapprStructMaterialsFoundation, + "bldgappr_struct_materials.columns": bldgapprStructMaterialsColumns, + "bldgappr_struct_materials.beams": bldgapprStructMaterialsBeams, + "bldgappr_struct_materials.truss_framing": + bldgapprStructMaterialsTrussFraming, + "bldgappr_struct_materials.roof": bldgapprStructMaterialsRoof, + "bldgappr_struct_materials.flooring": bldgapprStructMaterialsFlooring, + "bldgappr_struct_materials.walls": bldgapprStructMaterialsWalls, + "bldgappr_struct_materials.others": bldgapprStructMaterialsOthers, + "bldgappr_struct_materials.gen_code": bldgapprStructMaterialsGenCode, + "bldgappr_property_assessment.date_created": + bldgapprPropertyAssessmentDateCreated, + "bldgappr_property_assessment.date_modified": + bldgapprPropertyAssessmentDateModified, + "bldgappr_property_assessment.actual_use": + bldgapprPropertyAssessmentActualUse, + "bldgappr_property_assessment.market_value": + bldgapprPropertyAssessmentMarketValue, + "bldgappr_property_assessment.assessment_level": + bldgapprPropertyAssessmentAssessmentLevel, + "bldgappr_property_assessment.assessed_value": + bldgapprPropertyAssessmentAssessedValue, + "bldgappr_property_assessment.taxable": + bldgapprPropertyAssessmentTaxable, + "bldgappr_property_assessment.exempt": bldgapprPropertyAssessmentExempt, + "bldgappr_property_assessment.qtr": bldgapprPropertyAssessmentQtr, + "bldgappr_property_assessment.yr": bldgapprPropertyAssessmentYr, + "bldgappr_property_assessment.appraisedby_name": + bldgapprPropertyAssessmentAppraisedbyName, + "bldgappr_property_assessment.appraisedby_date": + bldgapprPropertyAssessmentAppraisedbyDate, + "bldgappr_property_assessment.recommendappr_name": + bldgapprPropertyAssessmentRecommendapprName, + "bldgappr_property_assessment.recommendappr_date": + bldgapprPropertyAssessmentRecommendapprDate, + "bldgappr_property_assessment.approvedby_name": + bldgapprPropertyAssessmentApprovedbyName, + "bldgappr_property_assessment.approvedby_date": + bldgapprPropertyAssessmentApprovedbyDate, + "bldgappr_property_assessment.memoranda": + bldgapprPropertyAssessmentMemoranda, + "bldgappr_property_assessment.swornstatement_no": + bldgapprPropertyAssessmentSwornstatementNo, + "bldgappr_property_assessment.date_received": + bldgapprPropertyAssessmentDateReceived, + "bldgappr_property_assessment.entry_date_assessment": + bldgapprPropertyAssessmentEntryDateAssessment, + "bldgappr_property_assessment.entry_date_by": + bldgapprPropertyAssessmentEntryDateBy, + "bldgappr_property_assessment.gen_code": + bldgapprPropertyAssessmentGenCode, + "bldgappr_rec_supersededass.date_created": + bldgapprRecSupersededassDateCreated, + "bldgappr_rec_supersededass.date_modified": + bldgapprRecSupersededassDateModified, + "bldgappr_rec_supersededass.pin": bldgapprRecSupersededassPin, + "bldgappr_rec_supersededass.tdn": bldgapprRecSupersededassTdn, + "bldgappr_rec_supersededass.total_assval": + bldgapprRecSupersededassTotalAssval, + "bldgappr_rec_supersededass.owner": bldgapprRecSupersededassOwner, + "bldgappr_rec_supersededass.effectivity_ass": + bldgapprRecSupersededassEffectivityAss, + "bldgappr_rec_supersededass.page_no": bldgapprRecSupersededassPageNo, + "bldgappr_rec_supersededass.total_marketval": + bldgapprRecSupersededassTotalMarketval, + "bldgappr_rec_supersededass.total_area": + bldgapprRecSupersededassTotalArea, + "bldgappr_rec_supersededass.rec_assessment": + bldgapprRecSupersededassRecAssessment, + "bldgappr_rec_supersededass.rec_taxmapping": + bldgapprRecSupersededassRecTaxmapping, + "bldgappr_rec_supersededass.rec_records": + bldgapprRecSupersededassRecRecords, + "bldgappr_rec_supersededass.date": bldgapprRecSupersededassDate, + "bldgappr_rec_supersededass.gen_code": bldgapprRecSupersededassGenCode, + }; +} diff --git a/lib/model/passo/city.dart b/lib/model/passo/city.dart index eb22f22..fc0057f 100644 --- a/lib/model/passo/city.dart +++ b/lib/model/passo/city.dart @@ -9,21 +9,40 @@ City cityFromJson(String str) => City.fromJson(json.decode(str)); String cityToJson(City data) => json.encode(data.toJson()); class City { + final int? id; final String? cityCode; final String? cityDescription; + final String? genCode; - City({ - this.cityCode, - this.cityDescription, - }); + City({this.id, this.cityCode, this.cityDescription, this.genCode}); + + City copy( + {int? id, String? cityCode, String? cityDescription, String? genCode}) { + return City( + id: id ?? this.id, + cityCode: cityCode ?? this.cityCode, + cityDescription: cityDescription ?? this.cityDescription, + genCode: genCode ?? this.genCode, + ); + } factory City.fromJson(Map json) => City( + id: json["id"], cityCode: json["city_code"], cityDescription: json["city_description"], + genCode: json["gen_code"], ); + factory City.fromJson2(Map json) => City( + id: json["id"], + cityCode: json["cityCode"], + cityDescription: json["cityDescription"], + genCode: json["genCode"]); + Map toJson() => { + "id": id, "city_code": cityCode, "city_description": cityDescription, + "gen_code": genCode }; } diff --git a/lib/model/passo/class_components _offline.dart b/lib/model/passo/class_components _offline.dart new file mode 100644 index 0000000..b4c537e --- /dev/null +++ b/lib/model/passo/class_components _offline.dart @@ -0,0 +1,162 @@ +// To parse this JSON data, do +// +// final classComponents = classComponentsFromJson(jsonString); + +import 'dart:convert'; + +ClassComponentsOffline classComponentsFromJson(String str) => + ClassComponentsOffline.fromJson(json.decode(str)); + +String classComponentsToJson(ClassComponentsOffline data) => + json.encode(data.toJson()); + +class ClassComponentsOffline { + final int? id; + final String? componentName; + final String? minBaseUnitvalPercent; + final String? maxBaseUnitvalPercent; + final String? minUnitvalSqrmtr; + final String? maxUnitvalSqrmtr; + final String? minAddBaseunitval; + final String? maxAddBaseunitval; + final String? minDeductBaserate; + final String? maxDeductBaserate; + final String? minLinearMeter; + final String? maxLinearMeter; + final String? minSpacing; + final String? maxSpacing; + final String? roughFinish; + final String? highFinish; + final int? withoutBucc; + // final String? genCode; + + ClassComponentsOffline({ + this.id, + this.componentName, + this.minBaseUnitvalPercent, + this.maxBaseUnitvalPercent, + this.minUnitvalSqrmtr, + this.maxUnitvalSqrmtr, + this.minAddBaseunitval, + this.maxAddBaseunitval, + this.minDeductBaserate, + this.maxDeductBaserate, + this.minLinearMeter, + this.maxLinearMeter, + this.minSpacing, + this.maxSpacing, + this.roughFinish, + this.highFinish, + this.withoutBucc, + // this.genCode + }); + + ClassComponentsOffline copy({ + int? id, + String? componentName, + String? minBaseUnitvalPercent, + String? maxBaseUnitvalPercent, + String? minUnitvalSqrmtr, + String? maxUnitvalSqrmtr, + String? minAddBaseunitval, + String? maxAddBaseunitval, + String? minDeductBaserate, + String? maxDeductBaserate, + String? minLinearMeter, + String? maxLinearMeter, + String? minSpacing, + String? maxSpacing, + String? roughFinish, + String? highFinish, + int? withoutBucc, + // String? genCode, + }) { + return ClassComponentsOffline( + id: id ?? this.id, + componentName: componentName ?? this.componentName, + minBaseUnitvalPercent: + minBaseUnitvalPercent ?? this.minBaseUnitvalPercent, + maxBaseUnitvalPercent: + maxBaseUnitvalPercent ?? this.maxBaseUnitvalPercent, + minUnitvalSqrmtr: minUnitvalSqrmtr ?? this.minUnitvalSqrmtr, + maxUnitvalSqrmtr: maxUnitvalSqrmtr ?? this.maxUnitvalSqrmtr, + minAddBaseunitval: minAddBaseunitval ?? this.minAddBaseunitval, + maxAddBaseunitval: maxAddBaseunitval ?? this.maxAddBaseunitval, + minDeductBaserate: minDeductBaserate ?? this.minDeductBaserate, + maxDeductBaserate: maxDeductBaserate ?? this.maxDeductBaserate, + minLinearMeter: minLinearMeter ?? this.minLinearMeter, + maxLinearMeter: maxLinearMeter ?? this.maxLinearMeter, + minSpacing: minSpacing ?? this.minSpacing, + maxSpacing: maxSpacing ?? this.maxSpacing, + roughFinish: roughFinish ?? this.roughFinish, + highFinish: highFinish ?? this.highFinish, + withoutBucc: withoutBucc ?? this.withoutBucc, + // genCode: genCode ?? this.genCode, + ); + } + + factory ClassComponentsOffline.fromJson(Map json) => + ClassComponentsOffline( + id: json["id"], + componentName: json["component_name"], + minBaseUnitvalPercent: json["min_base_unitval_percent"], + maxBaseUnitvalPercent: json["max_base_unitval_percent"], + minUnitvalSqrmtr: json["min_unitval_sqrmtr"], + maxUnitvalSqrmtr: json["max_unitval_sqrmtr"], + minAddBaseunitval: json["min_add_baseunitval"], + maxAddBaseunitval: json["max_add_baseunitval"], + minDeductBaserate: json["min_deduct_baserate"], + maxDeductBaserate: json["max_deduct_baserate"], + minLinearMeter: json["min_linear_meter"], + maxLinearMeter: json["max_linear_meter"], + minSpacing: json["min_spacing"], + maxSpacing: json["max_spacing"], + roughFinish: json["rough_finish"], + highFinish: json["high_finish"], + withoutBucc: json["without_bucc"], + // genCode: json["gen_code"], + ); + + factory ClassComponentsOffline.fromJson2(Map json) => + ClassComponentsOffline( + id: json["id"], + componentName: json["componentName"], + minBaseUnitvalPercent: json["minBaseUnitvalPercent"], + maxBaseUnitvalPercent: json["maxBaseUnitvalPercent"], + minUnitvalSqrmtr: json["minUnitvalSqrmtr"], + maxUnitvalSqrmtr: json["maxUnitvalSqrmtr"], + minAddBaseunitval: json["minAddBaseunitval"], + maxAddBaseunitval: json["maxAddBaseunitval"], + minDeductBaserate: json["minDeductBaserate"], + maxDeductBaserate: json["maxDeductBaserate"], + minLinearMeter: json["minLinearMeter"], + maxLinearMeter: json["maxLinearMeter"], + minSpacing: json["minSpacing"], + maxSpacing: json["maxSpacing"], + roughFinish: json["roughFinish"], + highFinish: json["highFinish"], + withoutBucc: json["withoutBucc"], + // genCode: json["genCode"] + ); + + Map toJson() => { + "id": id, + "component_name": componentName, + "min_base_unitval_percent": minBaseUnitvalPercent, + "max_base_unitval_percent": maxBaseUnitvalPercent, + "min_unitval_sqrmtr": minUnitvalSqrmtr, + "max_unitval_sqrmtr": maxUnitvalSqrmtr, + "min_add_baseunitval": minAddBaseunitval, + "max_add_baseunitval": maxAddBaseunitval, + "min_deduct_baserate": minDeductBaserate, + "max_deduct_baserate": maxDeductBaserate, + "min_linear_meter": minLinearMeter, + "max_linear_meter": maxLinearMeter, + "min_spacing": minSpacing, + "max_spacing": maxSpacing, + "rough_finish": roughFinish, + "high_finish": highFinish, + "without_bucc": withoutBucc, + // "gen_code": genCode + }; +} diff --git a/lib/model/passo/class_components.dart b/lib/model/passo/class_components.dart index b9ce05b..bba98aa 100644 --- a/lib/model/passo/class_components.dart +++ b/lib/model/passo/class_components.dart @@ -2,7 +2,6 @@ // // final classComponents = classComponentsFromJson(jsonString); -import 'package:meta/meta.dart'; import 'dart:convert'; ClassComponents classComponentsFromJson(String str) => @@ -29,6 +28,7 @@ class ClassComponents { final String roughFinish; final String highFinish; final bool withoutBucc; + // final String genCode; ClassComponents({ required this.id, @@ -48,6 +48,7 @@ class ClassComponents { required this.roughFinish, required this.highFinish, required this.withoutBucc, + // required this.genCode, }); factory ClassComponents.fromJson(Map json) => @@ -69,6 +70,7 @@ class ClassComponents { roughFinish: json["rough_finish"], highFinish: json["high_finish"], withoutBucc: json["without_bucc"], + // genCode: json["gen_code"] ); Map toJson() => { @@ -89,5 +91,6 @@ class ClassComponents { "rough_finish": roughFinish, "high_finish": highFinish, "without_bucc": withoutBucc, + // "gen_code": genCode, }; } diff --git a/lib/model/passo/floor_sketch.dart b/lib/model/passo/floor_sketch.dart new file mode 100644 index 0000000..718a023 --- /dev/null +++ b/lib/model/passo/floor_sketch.dart @@ -0,0 +1,64 @@ +// To parse this JSON data, do +// +// final floorSketch = floorSketchFromJson(jsonString); + +import 'dart:convert'; + +FloorSketch floorSketchFromJson(String str) => + FloorSketch.fromJson(json.decode(str)); + +String floorSketchToJson(FloorSketch data) => json.encode(data.toJson()); + +class FloorSketch { + final int? bldgapprDetailsId; + final String? dateCreated; + final String? floorSketch; + final String? genCode; + + FloorSketch({ + this.bldgapprDetailsId, + this.dateCreated, + this.floorSketch, + this.genCode, + }); + + FloorSketch copy( + {int? bldgapprDetailsId, + String? dateCreated, + String? floorSketch, + String? genCode}) { + return FloorSketch( + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + dateCreated: dateCreated ?? this.dateCreated, + floorSketch: floorSketch ?? this.floorSketch, + genCode: genCode ?? this.genCode, + ); + } + + FloorSketch copyWith({ + int? bldgapprDetailsId, + String? dateCreated, + String? floorSketch, + String? genCode, + }) => + FloorSketch( + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + dateCreated: dateCreated ?? this.dateCreated, + floorSketch: floorSketch ?? this.floorSketch, + genCode: genCode ?? this.genCode, + ); + + factory FloorSketch.fromJson(Map json) => FloorSketch( + bldgapprDetailsId: json["bldgappr_details_id"], + dateCreated: json["date_created"], + floorSketch: json["floor_sketch"], + genCode: json["gen_code"], + ); + + Map toJson() => { + "bldgappr_details_id": bldgapprDetailsId, + "date_created": dateCreated, + "floor_sketch": floorSketch, + "gen_code": genCode, + }; +} diff --git a/lib/model/passo/general_description.dart b/lib/model/passo/general_description.dart index 68002a5..19f5d62 100644 --- a/lib/model/passo/general_description.dart +++ b/lib/model/passo/general_description.dart @@ -14,19 +14,19 @@ class GeneralDesc { final int? bldgapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? bldgKind; final String? strucType; final String? bldgPermit; - final DateTime? dateIssued; + final String? dateIssued; final String? cct; - final DateTime? certCompletionIssued; - final DateTime? certOccupancyIssued; - final DateTime? dateCompleted; - final DateTime? dateOccupied; - final int? bldgAge; - final int? noStoreys; + final String? certCompletionIssued; + final String? certOccupancyIssued; + final String? dateCompleted; + final String? dateOccupied; + final String? bldgAge; + final String? noStoreys; final String? area1Stfloor; final String? area2Ndfloor; final String? area3Rdfloor; @@ -34,6 +34,8 @@ class GeneralDesc { final String? totalFloorArea; final dynamic floorSketch; final String? actualUse; + final String? unitValue; + final String? genCode; GeneralDesc({ this.id, @@ -60,70 +62,140 @@ class GeneralDesc { this.totalFloorArea, this.floorSketch, this.actualUse, + this.unitValue, + this.genCode, }); + GeneralDesc copy({ + int? id, + int? bldgapprDetailsId, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? bldgKind, + String? strucType, + String? bldgPermit, + String? dateIssued, + String? cct, + String? certCompletionIssued, + String? certOccupancyIssued, + String? dateCompleted, + String? dateOccupied, + String? bldgAge, + String? noStoreys, + String? area1Stfloor, + String? area2Ndfloor, + String? area3Rdfloor, + String? area4Thfloor, + String? totalFloorArea, + dynamic floorSketch, + String? actualUse, + String? unitValue, + String? genCode, + }) { + return GeneralDesc( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + bldgKind: bldgKind ?? this.bldgKind, + strucType: strucType ?? this.strucType, + bldgPermit: bldgPermit ?? this.bldgPermit, + dateIssued: dateIssued ?? this.dateIssued, + cct: cct ?? this.cct, + certCompletionIssued: certCompletionIssued ?? this.certCompletionIssued, + certOccupancyIssued: certOccupancyIssued ?? this.certOccupancyIssued, + dateCompleted: dateCompleted ?? this.dateCompleted, + dateOccupied: dateOccupied ?? this.dateOccupied, + bldgAge: bldgAge ?? this.bldgAge, + noStoreys: noStoreys ?? this.noStoreys, + area1Stfloor: area1Stfloor ?? this.area1Stfloor, + area2Ndfloor: area2Ndfloor ?? this.area2Ndfloor, + area3Rdfloor: area3Rdfloor ?? this.area3Rdfloor, + area4Thfloor: area4Thfloor ?? this.area4Thfloor, + totalFloorArea: totalFloorArea ?? this.totalFloorArea, + floorSketch: floorSketch ?? this.floorSketch, + actualUse: actualUse ?? this.actualUse, + unitValue: unitValue ?? this.unitValue, + genCode: genCode ?? this.genCode, + ); + } + 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"], - ); + id: json["id"], + bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"], + dateModified: json["date_modified"], + bldgKind: json["bldg_kind"], + strucType: json["struc_type"], + bldgPermit: json["bldg_permit"], + dateIssued: json["date_issued"], + cct: json["cct"], + certCompletionIssued: json["cert_completion_issued"], + certOccupancyIssued: json["cert_occupancy_issued"], + dateCompleted: json["date_completed"], + dateOccupied: 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"], + unitValue: json["unit_value"], + genCode: json["gen_code"]); + + factory GeneralDesc.fromJson2(Map json) => GeneralDesc( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + bldgKind: json["bldgKind"], + strucType: json["strucType"], + bldgPermit: json["bldgPermit"], + dateIssued: json["dateIssued"], + cct: json["cct"], + certCompletionIssued: json["certCompletionIssued"], + certOccupancyIssued: json["certOccupancyIssued"], + dateCompleted: json["dateCompleted"], + dateOccupied: json["dateOccupied"], + bldgAge: json["bldgAge"], + noStoreys: json["noStoreys"], + area1Stfloor: json["area1Stfloor"], + area2Ndfloor: json["area2Ndfloor"], + area3Rdfloor: json["area3Rdfloor"], + area4Thfloor: json["area4Thfloor"], + totalFloorArea: json["totalFloorArea"], + floorSketch: json["floorSketch"], + actualUse: json["actualUse"], + unitValue: json["unitValue"], + genCode: json["gen_code"]); Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "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')}", + "date_issued": dateIssued, "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')}", + "cert_completion_issued": certCompletionIssued, + "cert_occupancy_issued": certOccupancyIssued, + "date_completed": dateCompleted, + "date_occupied": dateOccupied, "bldg_age": bldgAge, "no_storeys": noStoreys, "area_1stfloor": area1Stfloor, @@ -133,5 +205,7 @@ class GeneralDesc { "total_floor_area": totalFloorArea, "floor_sketch": floorSketch, "actual_use": actualUse, + "unit_value": unitValue, + "gen_code": genCode, }; } diff --git a/lib/model/passo/land_appr.dart b/lib/model/passo/land_appr.dart index 91e9b1b..4c88c3c 100644 --- a/lib/model/passo/land_appr.dart +++ b/lib/model/passo/land_appr.dart @@ -27,6 +27,26 @@ class LandAppr { this.baseMarketval, }); + LandAppr copy({ + int? id, + int? landapprDetailsId, + String? classification, + String? subClass, + String? area, + String? unitValue, + String? baseMarketval, + }) { + return LandAppr( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + classification: classification ?? this.classification, + subClass: subClass ?? this.subClass, + area: area ?? this.area, + unitValue: unitValue ?? this.unitValue, + baseMarketval: baseMarketval ?? this.baseMarketval, + ); + } + factory LandAppr.fromJson(Map json) => LandAppr( id: json["id"], landapprDetailsId: json["landappr_details_id"], @@ -37,6 +57,16 @@ class LandAppr { baseMarketval: json["base_marketval"], ); + factory LandAppr.fromJson2(Map json) => LandAppr( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + classification: json["classification"], + subClass: json["subClass"], + area: json["area"], + unitValue: json["unitValue"], + baseMarketval: json["baseMarketval"], + ); + Map toJson() => { "id": id, "landappr_details_id": landapprDetailsId, diff --git a/lib/model/passo/land_classification.dart b/lib/model/passo/land_classification.dart index 0315271..cccd29c 100644 --- a/lib/model/passo/land_classification.dart +++ b/lib/model/passo/land_classification.dart @@ -21,6 +21,17 @@ class LandClassification { this.description, }); + LandClassification copy({ + final int? id, + final String? classificationCode, + final String? description, + }) { + return LandClassification( + id: id ?? this.id, + classificationCode: classificationCode ?? this.classificationCode, + description: description ?? this.description); + } + factory LandClassification.fromJson(Map json) => LandClassification( id: json["id"], @@ -28,6 +39,13 @@ class LandClassification { description: json["description"], ); + factory LandClassification.fromJson2(Map json) => + LandClassification( + id: json["id"], + classificationCode: json["classificationCode"], + description: json["description"], + ); + Map toJson() => { "id": id, "classification_code": classificationCode, diff --git a/lib/model/passo/land_ext.dart b/lib/model/passo/land_ext.dart index 5c935f8..63ad8a3 100644 --- a/lib/model/passo/land_ext.dart +++ b/lib/model/passo/land_ext.dart @@ -13,23 +13,26 @@ class LandExt { 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? dateCreated; + final String? dateModified; + final String? taxable; + final String? exempt; + final String? qtr; + final String? yr; final String? appraisedbyName; - final DateTime? appraisedbyDate; + final String? appraisedbyDate; final String? recommendapprName; - final DateTime? recommendapprDate; + final String? recommendapprDate; final String? approvedbyName; - final DateTime? approvedbyDate; + final String? approvedbyDate; final String? memoranda; final String? swornstatementNo; - final DateTime? dateReceived; - final DateTime? entryDateAssessment; + final String? dateReceived; + final String? entryDateAssessment; final String? entryDateBy; + final String? appraisedbyDesignation; + final String? recommendapprDesignation; + final String? approvedbyDesignation; LandExt({ this.id, @@ -53,44 +56,120 @@ class LandExt { this.dateReceived, this.entryDateAssessment, this.entryDateBy, + this.appraisedbyDesignation, + this.recommendapprDesignation, + this.approvedbyDesignation, }); + LandExt copy({ + final int? id, + final int? landapprDetailsId, + final String? assessedById, + final String? assessedByName, + final String? dateCreated, + final String? dateModified, + final String? taxable, + final String? exempt, + final String? qtr, + final String? yr, + final String? appraisedbyName, + final String? appraisedbyDate, + final String? recommendapprName, + final String? recommendapprDate, + final String? approvedbyName, + final String? approvedbyDate, + final String? memoranda, + final String? swornstatementNo, + final String? dateReceived, + final String? entryDateAssessment, + final String? entryDateBy, + final String? appraisedbyDesignation, + final String? recommendapprDesignation, + final String? approvedbyDesignation, + }) { + return LandExt( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + taxable: taxable ?? this.taxable, + exempt: exempt ?? this.exempt, + qtr: qtr ?? this.qtr, + yr: yr ?? this.yr, + appraisedbyName: appraisedbyName ?? this.appraisedbyName, + appraisedbyDate: appraisedbyDate ?? this.appraisedbyDate, + recommendapprName: recommendapprName ?? this.recommendapprName, + recommendapprDate: recommendapprDate ?? this.recommendapprDate, + approvedbyName: approvedbyName ?? this.approvedbyName, + approvedbyDate: approvedbyDate ?? this.approvedbyDate, + memoranda: memoranda ?? this.memoranda, + swornstatementNo: swornstatementNo ?? this.swornstatementNo, + dateReceived: dateReceived ?? this.dateReceived, + entryDateAssessment: entryDateAssessment ?? this.entryDateAssessment, + entryDateBy: entryDateBy ?? this.entryDateBy, + appraisedbyDesignation: + appraisedbyDesignation ?? this.appraisedbyDesignation, + recommendapprDesignation: + recommendapprDesignation ?? this.recommendapprDesignation, + approvedbyDesignation: + approvedbyDesignation ?? this.approvedbyDesignation, + ); + } + 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"]), + dateCreated: json["date_created"], + dateModified: 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"]), + appraisedbyDate: json["appraisedby_date"], recommendapprName: json["recommendappr_name"], - recommendapprDate: json["recommendappr_date"] == null - ? null - : DateTime.parse(json["recommendappr_date"]), + recommendapprDate: json["recommendappr_date"], approvedbyName: json["approvedby_name"], - approvedbyDate: json["approvedby_date"] == null - ? null - : DateTime.parse(json["approvedby_date"]), + approvedbyDate: 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"]), + dateReceived: json["date_received"], + entryDateAssessment: json["entry_date_assessment"], entryDateBy: json["entry_date_by"], + appraisedbyDesignation: json["appraisedby_designation"], + recommendapprDesignation: json["recommendappr_designation"], + approvedbyDesignation: json["approvedby_designation"], + ); + + factory LandExt.fromJson2(Map json) => LandExt( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + taxable: json["taxable"], + exempt: json["exempt"], + qtr: json["qtr"], + yr: json["yr"], + appraisedbyName: json["appraisedbyName"], + appraisedbyDate: json["appraisedbyDate"], + recommendapprName: json["recommendapprName"], + recommendapprDate: json["recommendapprDate"], + approvedbyName: json["approvedbyName"], + approvedbyDate: json["approvedbyDate"], + memoranda: json["memoranda"], + swornstatementNo: json["swornstatementNo"], + dateReceived: json["dateReceived"], + entryDateAssessment: json["entryDateAssessment"], + entryDateBy: json["entryDateBy"], + appraisedbyDesignation: json["appraisedby_designation"], + recommendapprDesignation: json["recommendappr_designation"], + approvedbyDesignation: json["approvedby_designation"], ); Map toJson() => { @@ -98,27 +177,25 @@ class LandExt { "landappr_details_id": landapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "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')}", + "appraisedby_date": appraisedbyDate, "recommendappr_name": recommendapprName, - "recommendappr_date": - "${recommendapprDate!.year.toString().padLeft(4, '0')}-${recommendapprDate!.month.toString().padLeft(2, '0')}-${recommendapprDate!.day.toString().padLeft(2, '0')}", + "recommendappr_date": recommendapprDate, "approvedby_name": approvedbyName, - "approvedby_date": - "${approvedbyDate!.year.toString().padLeft(4, '0')}-${approvedbyDate!.month.toString().padLeft(2, '0')}-${approvedbyDate!.day.toString().padLeft(2, '0')}", + "approvedby_date": approvedbyDate, "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')}", + "date_received": dateReceived, + "entry_date_assessment": entryDateAssessment, "entry_date_by": entryDateBy, + "appraisedby_designation": appraisedbyDesignation, + "recommendappr_designation": recommendapprDesignation, + "approvedby_designation": approvedbyDesignation, }; } diff --git a/lib/model/passo/land_property_assessment.dart b/lib/model/passo/land_property_assessment.dart index cbab632..35f007f 100644 --- a/lib/model/passo/land_property_assessment.dart +++ b/lib/model/passo/land_property_assessment.dart @@ -31,6 +31,28 @@ class LandPropertyAssessment { this.totalAssessedval, }); + LandPropertyAssessment copy({ + final int? id, + final int? landapprDetailsId, + final String? actualUse, + final String? marketval, + final String? assessmentLevel, + final String? assessedValue, + final String? totalMarketval, + final String? totalAssessedval, + }) { + return LandPropertyAssessment( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + actualUse: actualUse ?? this.actualUse, + marketval: marketval ?? this.marketval, + assessmentLevel: assessmentLevel ?? this.assessmentLevel, + assessedValue: assessedValue ?? this.assessedValue, + totalMarketval: totalMarketval ?? this.totalMarketval, + totalAssessedval: totalAssessedval ?? this.totalAssessedval, + ); + } + factory LandPropertyAssessment.fromJson(Map json) => LandPropertyAssessment( id: json["id"], @@ -43,6 +65,18 @@ class LandPropertyAssessment { totalAssessedval: json["total_assessedval"], ); + factory LandPropertyAssessment.fromJson2(Map json) => + LandPropertyAssessment( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + actualUse: json["actualUse"], + marketval: json["marketval"], + assessmentLevel: json["assessmentLevel"], + assessedValue: json["assessedValue"], + totalMarketval: json["totalMarketval"], + totalAssessedval: json["totalAssessedval"], + ); + Map toJson() => { "id": id, "landappr_details_id": landapprDetailsId, diff --git a/lib/model/passo/land_property_boundaries.dart b/lib/model/passo/land_property_boundaries.dart index 49a3ada..efbbf62 100644 --- a/lib/model/passo/land_property_boundaries.dart +++ b/lib/model/passo/land_property_boundaries.dart @@ -15,13 +15,13 @@ class LandPropertyBoundaries { final int? landapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? north; final String? east; final String? south; final String? west; - final dynamic sketch; + final String? sketch; LandPropertyBoundaries({ this.id, @@ -37,18 +37,57 @@ class LandPropertyBoundaries { this.sketch, }); + LandPropertyBoundaries copy({ + final int? id, + final int? landapprDetailsId, + final String? assessedById, + final String? assessedByName, + final String? dateCreated, + final String? dateModified, + final String? north, + final String? east, + final String? south, + final String? west, + final String? sketch, + }) { + return LandPropertyBoundaries( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + north: north ?? this.north, + east: east ?? this.east, + south: south ?? this.south, + west: west ?? this.west, + sketch: sketch ?? 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"]), + dateCreated: json["date_created"], + dateModified: json["date_modified"], + north: json["north"], + east: json["east"], + south: json["south"], + west: json["west"], + sketch: json["sketch"], + ); + + factory LandPropertyBoundaries.fromJson2(Map json) => + LandPropertyBoundaries( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], north: json["north"], east: json["east"], south: json["south"], @@ -61,8 +100,8 @@ class LandPropertyBoundaries { "landappr_details_id": landapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "north": north, "east": east, "south": south, diff --git a/lib/model/passo/land_property_loc.dart b/lib/model/passo/land_property_loc.dart index 25a7466..b91d095 100644 --- a/lib/model/passo/land_property_loc.dart +++ b/lib/model/passo/land_property_loc.dart @@ -15,8 +15,8 @@ class LandPropertyLoc { final int? landapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? street; final String? municipality; final String? barangay; @@ -35,18 +35,53 @@ class LandPropertyLoc { this.province, }); + LandPropertyLoc copy({ + int? id, + int? landapprDetailsId, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? street, + String? municipality, + String? barangay, + String? province, + }) => + LandPropertyLoc( + id: id, + landapprDetailsId: landapprDetailsId, + assessedById: assessedById, + assessedByName: assessedByName, + dateCreated: dateCreated, + dateModified: dateModified, + street: street, + municipality: municipality, + barangay: barangay, + province: 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"]), + dateCreated: json["date_created"], + dateModified: json["date_modified"], + street: json["street"], + municipality: json["municipality"], + barangay: json["barangay"], + province: json["province"], + ); + + factory LandPropertyLoc.fromJson2(Map json) => + LandPropertyLoc( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], street: json["street"], municipality: json["municipality"], barangay: json["barangay"], @@ -58,8 +93,8 @@ class LandPropertyLoc { "landappr_details_id": landapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "street": street, "municipality": municipality, "barangay": barangay, diff --git a/lib/model/passo/land_property_owner.dart b/lib/model/passo/land_property_owner.dart index 9c644af..fce1d0b 100644 --- a/lib/model/passo/land_property_owner.dart +++ b/lib/model/passo/land_property_owner.dart @@ -14,13 +14,13 @@ class LandPropertyOwner { final int? id; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? transCode; final String? tdn; final String? pin; final String? cloaNo; - final DateTime? dated; + final String? dated; final String? surveyNo; final String? lotNo; final String? blkNo; @@ -59,22 +59,68 @@ class LandPropertyOwner { this.faasType, }); + LandPropertyOwner copy({ + int? id, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? transCode, + String? tdn, + String? pin, + String? cloaNo, + String? dated, + String? surveyNo, + String? lotNo, + String? blkNo, + String? owner, + String? address, + String? telno, + String? tin, + String? adminUser, + String? adminAddress, + String? adminTelno, + String? adminTin, + String? faasType, + }) { + return LandPropertyOwner( + id: id, + assessedById: assessedById, + assessedByName: assessedByName, + dateCreated: dateCreated, + dateModified: dateModified, + transCode: transCode, + tdn: tdn, + pin: pin, + cloaNo: cloaNo, + dated: dated, + surveyNo: surveyNo, + lotNo: lotNo, + blkNo: blkNo, + owner: owner, + address: address, + telno: telno, + tin: tin, + adminUser: adminUser, + adminAddress: adminAddress, + adminTelno: adminTelno, + adminTin: adminTin, + faasType: 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"]), + dateCreated: json["date_created"], + dateModified: 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"]), + dated: json["dated"], surveyNo: json["survey_no"], lotNo: json["lot_no"], blkNo: json["blk_no"], @@ -89,18 +135,43 @@ class LandPropertyOwner { faasType: json["faas_type"], ); + factory LandPropertyOwner.fromJson2(Map json) => + LandPropertyOwner( + id: json["id"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + transCode: json["transCode"], + tdn: json["tdn"], + pin: json["pin"], + cloaNo: json["cloaNo"], + dated: json["dated"], + surveyNo: json["surveyNo"], + lotNo: json["lotNo"], + blkNo: json["blkNo"], + owner: json["owner"], + address: json["address"], + telno: json["telno"], + tin: json["tin"], + adminUser: json["adminUser"], + adminAddress: json["adminAddress"], + adminTelno: json["adminTelno"], + adminTin: json["adminTin"], + faasType: json["faasType"], + ); + Map toJson() => { "id": id, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "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')}", + "dated": dated, "survey_no": surveyNo, "lot_no": lotNo, "blk_no": blkNo, diff --git a/lib/model/passo/land_ref.dart b/lib/model/passo/land_ref.dart index 8f4649d..72ff44e 100644 --- a/lib/model/passo/land_ref.dart +++ b/lib/model/passo/land_ref.dart @@ -13,8 +13,8 @@ class LandRef { final int? bldgapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final dynamic owner; final dynamic cloaNo; final dynamic lotNo; @@ -22,6 +22,7 @@ class LandRef { final dynamic area; final dynamic surveyNo; final dynamic blkNo; + final String? genCode; LandRef({ this.id, @@ -37,26 +38,73 @@ class LandRef { this.area, this.surveyNo, this.blkNo, + this.genCode, }); + LandRef copy({ + int? id, + int? bldgapprDetailsId, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? owner, + String? cloaNo, + String? lotNo, + String? tdn, + String? area, + String? surveyNo, + String? blkNo, + String? genCode, + }) { + return LandRef( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + owner: owner ?? this.owner, + cloaNo: cloaNo ?? this.cloaNo, + lotNo: lotNo ?? this.lotNo, + tdn: tdn ?? this.tdn, + area: area ?? this.area, + surveyNo: surveyNo ?? this.surveyNo, + blkNo: blkNo ?? this.blkNo, + genCode: genCode ?? this.genCode, + ); + } + 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"], + owner: json["owner"], + cloaNo: json["cloa_no"], + lotNo: json["lot_no"], + tdn: json["tdn"], + area: json["area"], + surveyNo: json["survey_no"], + blkNo: json["blk_no"], + genCode: json["gen_code"]); + + factory LandRef.fromJson2(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"]), + bldgapprDetailsId: json["bldgapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], owner: json["owner"], - cloaNo: json["cloa_no"], - lotNo: json["lot_no"], + cloaNo: json["cloaNo"], + lotNo: json["lotNo"], tdn: json["tdn"], area: json["area"], - surveyNo: json["survey_no"], - blkNo: json["blk_no"], + surveyNo: json["surveyNo"], + blkNo: json["blkNo"], + genCode: json["gen_code"], ); Map toJson() => { @@ -64,8 +112,8 @@ class LandRef { "bldgappr_details_id": bldgapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "owner": owner, "cloa_no": cloaNo, "lot_no": lotNo, @@ -73,5 +121,6 @@ class LandRef { "area": area, "survey_no": surveyNo, "blk_no": blkNo, + "gen_code": genCode, }; } diff --git a/lib/model/passo/land_subclassification.dart b/lib/model/passo/land_subclassification.dart index 8bb042a..a9acfd4 100644 --- a/lib/model/passo/land_subclassification.dart +++ b/lib/model/passo/land_subclassification.dart @@ -27,6 +27,24 @@ class LandSubClassification { this.baseUnitMarketval, }); + LandSubClassification copy({ + final int? id, + final int? classificationId, + final String? cityCode, + final String? subclassCode, + final String? subclassDescription, + final String? baseUnitMarketval, + }) { + return LandSubClassification( + id: id ?? this.id, + classificationId: classificationId ?? this.classificationId, + cityCode: cityCode ?? this.cityCode, + subclassCode: subclassCode ?? this.subclassCode, + subclassDescription: subclassDescription ?? this.subclassDescription, + baseUnitMarketval: baseUnitMarketval ?? this.baseUnitMarketval, + ); + } + factory LandSubClassification.fromJson(Map json) => LandSubClassification( id: json["id"], @@ -37,6 +55,16 @@ class LandSubClassification { baseUnitMarketval: json["base_unit_marketval"], ); + factory LandSubClassification.fromJson2(Map json) => + LandSubClassification( + id: json["id"], + classificationId: json["classificationId"], + cityCode: json["cityCode"], + subclassCode: json["subclassCode"], + subclassDescription: json["subclassDescription"], + baseUnitMarketval: json["baseUnitMarketval"], + ); + Map toJson() => { "id": id, "classification_id": classificationId, diff --git a/lib/model/passo/land_value_adjustment.dart b/lib/model/passo/land_value_adjustment.dart index 33bdc59..f4e25ff 100644 --- a/lib/model/passo/land_value_adjustment.dart +++ b/lib/model/passo/land_value_adjustment.dart @@ -29,6 +29,26 @@ class ValueAdjustments { this.marketValue, }); + ValueAdjustments copy({ + final int? id, + final int? landapprDetailsId, + final String? baseMarketval, + final String? adjustmentFactors, + final String? adjustment, + final String? valueAdjustment, + final String? marketValue, + }) { + return ValueAdjustments( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + baseMarketval: baseMarketval ?? this.baseMarketval, + adjustmentFactors: adjustmentFactors ?? this.adjustmentFactors, + adjustment: adjustment ?? this.adjustment, + valueAdjustment: valueAdjustment ?? this.valueAdjustment, + marketValue: marketValue ?? this.marketValue, + ); + } + factory ValueAdjustments.fromJson(Map json) => ValueAdjustments( id: json["id"], @@ -40,6 +60,17 @@ class ValueAdjustments { marketValue: json["market_value"], ); + factory ValueAdjustments.fromJson2(Map json) => + ValueAdjustments( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + baseMarketval: json["baseMarketval"], + adjustmentFactors: json["adjustmentFactors"], + adjustment: json["adjustment"], + valueAdjustment: json["valueAdjustment"], + marketValue: json["marketValue"], + ); + Map toJson() => { "id": id, "landappr_details_id": landapprDetailsId, diff --git a/lib/model/passo/memoranda.dart b/lib/model/passo/memoranda.dart index 8c629fd..bd6a676 100644 --- a/lib/model/passo/memoranda.dart +++ b/lib/model/passo/memoranda.dart @@ -12,22 +12,44 @@ class Memoranda { final int? id; final String? code; final String? memoranda; + final String? genCode; Memoranda({ this.id, this.code, this.memoranda, + this.genCode, }); + Memoranda copy({ + int? id, + String? code, + String? memoranda, + String? genCode, + }) { + return Memoranda( + id: id ?? this.id, + code: code ?? this.code, + memoranda: memoranda ?? this.memoranda, + genCode: genCode ?? this.genCode); + } + factory Memoranda.fromJson(Map json) => Memoranda( - id: json["id"], - code: json["code"], - memoranda: json["memoranda"], - ); + id: json["id"], + code: json["code"], + memoranda: json["memoranda"], + genCode: json["gen_code"]); + + factory Memoranda.fromJson2(Map json) => Memoranda( + id: json["id"], + code: json["code"], + memoranda: json["memoranda"], + genCode: json["genCode"]); Map toJson() => { "id": id, "code": code, "memoranda": memoranda, + "gen_code": genCode, }; } diff --git a/lib/model/passo/other_improvements.dart b/lib/model/passo/other_improvements.dart index bb36523..1735433 100644 --- a/lib/model/passo/other_improvements.dart +++ b/lib/model/passo/other_improvements.dart @@ -20,7 +20,7 @@ class OtherImprovements { final String? baseMarketval; final int? noOfProductive; final int? noOfNonproductive; - final bool? fruitBearing; + final String? fruitBearing; OtherImprovements({ this.id, @@ -35,6 +35,32 @@ class OtherImprovements { this.fruitBearing, }); + OtherImprovements copy({ + 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 String? fruitBearing, + }) { + return OtherImprovements( + id: id ?? this.id, + landapprDetailsId: landapprDetailsId ?? this.landapprDetailsId, + kindsOfTrees: kindsOfTrees ?? this.kindsOfTrees, + subclassAge: subclassAge ?? this.subclassAge, + quantity: quantity ?? this.quantity, + unitValue: unitValue ?? this.unitValue, + baseMarketval: baseMarketval ?? this.baseMarketval, + noOfProductive: noOfProductive ?? this.noOfProductive, + noOfNonproductive: noOfNonproductive ?? this.noOfNonproductive, + fruitBearing: fruitBearing ?? this.fruitBearing, + ); + } + factory OtherImprovements.fromJson(Map json) => OtherImprovements( id: json["id"], @@ -49,6 +75,20 @@ class OtherImprovements { fruitBearing: json["fruit_bearing"], ); + factory OtherImprovements.fromJson2(Map json) => + OtherImprovements( + id: json["id"], + landapprDetailsId: json["landapprDetailsId"], + kindsOfTrees: json["kindsOfTrees"], + subclassAge: json["subclassAge"], + quantity: json["quantity"], + unitValue: json["unitValue"], + baseMarketval: json["baseMarketval"], + noOfProductive: json["noOfProductive"], + noOfNonproductive: json["noOfNonproductive"], + fruitBearing: json["fruitBearing"], + ); + Map toJson() => { "id": id, "landappr_details_id": landapprDetailsId, diff --git a/lib/model/passo/property_appraisal.dart b/lib/model/passo/property_appraisal.dart index 24271b0..1cd661b 100644 --- a/lib/model/passo/property_appraisal.dart +++ b/lib/model/passo/property_appraisal.dart @@ -15,8 +15,8 @@ class PropertyAppraisal { final int? bldgapprDetailsId; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? unitconstructCost; final String? buildingCore; final String? unitconstructSubtotal; @@ -48,18 +48,53 @@ class PropertyAppraisal { this.totalArea, this.actualUse}); + PropertyAppraisal copy({ + int? id, + int? bldgapprDetailsId, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? unitconstructCost, + String? buildingCore, + String? unitconstructSubtotal, + String? depreciationRate, + String? depreciationCost, + String? costAddItems, + String? addItemsSubtotal, + String? totalpercentDepreciation, + String? marketValue, + String? totalArea, + String? actualUse, + }) => + PropertyAppraisal( + id: this.id, + bldgapprDetailsId: bldgapprDetailsId, + assessedById: assessedById, + assessedByName: assessedByName, + dateCreated: dateCreated, + dateModified: dateModified, + unitconstructCost: unitconstructCost, + buildingCore: buildingCore, + unitconstructSubtotal: unitconstructSubtotal, + depreciationRate: depreciationRate, + depreciationCost: depreciationCost, + costAddItems: costAddItems, + addItemsSubtotal: addItemsSubtotal, + totalpercentDepreciation: totalpercentDepreciation, + marketValue: marketValue, + totalArea: totalArea, + actualUse: actualUse, + ); + 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"]), + dateCreated: json["date_created"], + dateModified: json["date_modified"], unitconstructCost: json["unitconstruct_cost"], buildingCore: json["building_core"], unitconstructSubtotal: json["unitconstruct_subtotal"], @@ -72,13 +107,33 @@ class PropertyAppraisal { totalArea: json["total_area"], actualUse: json["actual_use"]); + factory PropertyAppraisal.fromJson2(Map json) => + PropertyAppraisal( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + unitconstructCost: json["unitconstructCost"], + buildingCore: json["buildingCore"], + unitconstructSubtotal: json["unitconstructSubtotal"], + depreciationRate: json["depreciationRate"], + depreciationCost: json["depreciationCost"], + costAddItems: json["costAddItems"], + addItemsSubtotal: json["addItemsSubtotal"], + totalpercentDepreciation: json["totalpercentDepreciation"], + marketValue: json["marketValue"], + totalArea: json["totalArea"], + actualUse: json["actualUse"]); + Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "unitconstruct_cost": unitconstructCost, "building_core": buildingCore, "unitconstruct_subtotal": unitconstructSubtotal, diff --git a/lib/model/passo/property_assessment.dart b/lib/model/passo/property_assessment.dart index fb91bff..b62c1ab 100644 --- a/lib/model/passo/property_assessment.dart +++ b/lib/model/passo/property_assessment.dart @@ -14,28 +14,42 @@ String propertyAssessmentToJson(PropertyAssessment data) => class PropertyAssessment { final int id; final int bldgapprDetailsId; + final String? assessedById; + final String? assessedByName; + final String? dateCreated; + final String? dateModified; 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 taxable; + final String exempt; + final String qtr; + final String yr; final String appraisedbyName; - final DateTime appraisedbyDate; + final String appraisedbyDate; final String recommendapprName; - final DateTime recommendapprDate; + final String recommendapprDate; final String approvedbyName; + final String approvedbyDate; final String memoranda; final String swornstatementNo; - final DateTime dateReceived; - final DateTime entryDateAssessment; + final String dateReceived; + final String entryDateAssessment; final String entryDateBy; + final String genCode; + final String note; + final String? appraisedbyDesignation; + final String? recommendapprDesignation; + final String? approvedbyDesignation; PropertyAssessment({ required this.id, required this.bldgapprDetailsId, + required this.assessedById, + required this.assessedByName, + required this.dateCreated, + required this.dateModified, required this.actualUse, required this.marketValue, required this.assessmentLevel, @@ -49,17 +63,96 @@ class PropertyAssessment { required this.recommendapprName, required this.recommendapprDate, required this.approvedbyName, + required this.approvedbyDate, required this.memoranda, required this.swornstatementNo, required this.dateReceived, required this.entryDateAssessment, required this.entryDateBy, + required this.genCode, + required this.note, + required this.appraisedbyDesignation, + required this.recommendapprDesignation, + required this.approvedbyDesignation, }); + PropertyAssessment copy({ + int? id, + int? bldgapprDetailsId, + String? ass, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? actualUse, + String? marketValue, + String? assessmentLevel, + String? assessedValue, + String? taxable, + String? exempt, + String? qtr, + String? yr, + String? appraisedbyName, + String? appraisedbyDate, + String? recommendapprName, + String? recommendapprDate, + String? approvedbyName, + String? approvedbyDate, + String? memoranda, + String? swornstatementNo, + String? dateReceived, + String? entryDateAssessment, + String? entryDateBy, + String? genCode, + String? note, + String? appraisedbyDesignation, + String? recommendapprDesignation, + String? approvedbyDesignation, + }) => + PropertyAssessment( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + actualUse: actualUse ?? this.actualUse, + marketValue: marketValue ?? this.marketValue, + assessmentLevel: assessmentLevel ?? this.assessmentLevel, + assessedValue: assessedValue ?? this.assessedValue, + taxable: taxable ?? this.taxable, + exempt: exempt ?? this.exempt, + qtr: qtr ?? this.qtr, + yr: yr ?? this.yr, + appraisedbyName: appraisedbyName ?? this.appraisedbyName, + appraisedbyDate: appraisedbyDate ?? this.appraisedbyDate, + recommendapprName: recommendapprName ?? this.recommendapprName, + recommendapprDate: recommendapprDate ?? this.recommendapprDate, + approvedbyName: approvedbyName ?? this.approvedbyName, + approvedbyDate: approvedbyDate ?? this.approvedbyDate, + memoranda: memoranda ?? this.memoranda, + swornstatementNo: swornstatementNo ?? this.swornstatementNo, + dateReceived: dateReceived ?? this.dateReceived, + entryDateAssessment: entryDateAssessment ?? this.entryDateAssessment, + entryDateBy: entryDateBy ?? this.entryDateBy, + genCode: genCode ?? this.genCode, + note: note ?? this.note, + appraisedbyDesignation: + appraisedbyDesignation ?? this.appraisedbyDesignation, + recommendapprDesignation: + recommendapprDesignation ?? this.recommendapprDesignation, + approvedbyDesignation: + approvedbyDesignation ?? this.approvedbyDesignation, + ); + factory PropertyAssessment.fromJson(Map json) => PropertyAssessment( id: json["id"], bldgapprDetailsId: json["bldgappr_details_id"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"], + dateModified: json["date_modified"], actualUse: json["actual_use"], marketValue: json["market_value"], assessmentLevel: json["assessment_level"], @@ -69,20 +162,64 @@ class PropertyAssessment { qtr: json["qtr"], yr: json["yr"], appraisedbyName: json["appraisedby_name"], - appraisedbyDate: DateTime.parse(json["appraisedby_date"]), + appraisedbyDate: json["appraisedby_date"], recommendapprName: json["recommendappr_name"], - recommendapprDate: DateTime.parse(json["recommendappr_date"]), + recommendapprDate: json["recommendappr_date"], approvedbyName: json["approvedby_name"], + approvedbyDate: json["approvedby_date"], memoranda: json["memoranda"], swornstatementNo: json["swornstatement_no"], - dateReceived: DateTime.parse(json["date_received"]), - entryDateAssessment: DateTime.parse(json["entry_date_assessment"]), + dateReceived: json["date_received"], + entryDateAssessment: json["entry_date_assessment"], entryDateBy: json["entry_date_by"], + genCode: json["gen_code"], + note: json["note"], + appraisedbyDesignation: json["appraisedby_designation"], + recommendapprDesignation: json["recommendappr_designation"], + approvedbyDesignation: json["approvedby_designation"], + ); + + factory PropertyAssessment.fromJson2(Map json) => + PropertyAssessment( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + actualUse: json["actualUse"], + marketValue: json["marketValue"], + assessmentLevel: json["assessmentLevel"], + assessedValue: json["assessedValue"], + taxable: json["taxable"], + exempt: json["exempt"], + qtr: json["qtr"], + yr: json["yr"], + appraisedbyName: json["appraisedbyName"], + appraisedbyDate: json["appraisedbyDate"], + recommendapprName: json["recommendapprName"], + recommendapprDate: json["recommendapprDate"], + approvedbyName: json["approvedbyName"], + approvedbyDate: json["approvedbyDate"], + memoranda: json["memoranda"], + swornstatementNo: json["swornstatementNo"], + dateReceived: json["dateReceived"], + entryDateAssessment: json["entryDateAssessment"], + entryDateBy: json["entryDateBy"], + genCode: json["gen_code"], + note: json["note"], + appraisedbyDesignation: json["appraisedby_designation"], + recommendapprDesignation: json["recommendappr_designation"], + approvedbyDesignation: json["approvedby_designation"], ); Map toJson() => { "id": id, "bldgappr_details_id": bldgapprDetailsId, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated, + "date_modified": dateModified, "actual_use": actualUse, "market_value": marketValue, "assessment_level": assessmentLevel, @@ -92,18 +229,19 @@ class PropertyAssessment { "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')}", + "appraisedby_date": appraisedbyDate, "recommendappr_name": recommendapprName, - "recommendappr_date": - "${recommendapprDate.year.toString().padLeft(4, '0')}-${recommendapprDate.month.toString().padLeft(2, '0')}-${recommendapprDate.day.toString().padLeft(2, '0')}", + "recommendappr_date": recommendapprDate, "approvedby_name": approvedbyName, + "approvedby_date": approvedbyDate, "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')}", + "date_received": dateReceived, "entry_date_by": entryDateBy, + "gen_code": genCode, + "note": note, + "appraisedby_designation": appraisedbyDesignation, + "recommendappr_designation": recommendapprDesignation, + "approvedby_designation": approvedbyDesignation, }; } diff --git a/lib/model/passo/property_info.dart b/lib/model/passo/property_info.dart index 68406e2..4815c54 100644 --- a/lib/model/passo/property_info.dart +++ b/lib/model/passo/property_info.dart @@ -13,12 +13,15 @@ class PropertyInfo { final int? id; final String? assessedById; final String? assessedByName; - final DateTime? dateCreated; - final DateTime? dateModified; + final String? dateCreated; + final String? dateModified; final String? transCode; final String? tdn; final String? pin; - final String? owner; + final String? fname; + final String? mname; + final String? lname; + final String? bday; final String? address; final String? telno; final String? tin; @@ -27,61 +30,170 @@ class PropertyInfo { final String? adminTelno; final String? adminTin; final String? faasType; + final String? genCode; + final String? dateSynced; - PropertyInfo({ - this.id, - this.assessedById, - this.assessedByName, - this.dateCreated, - this.dateModified, - this.transCode, - this.tdn, - this.pin, - this.owner, - this.address, - this.telno, - this.tin, - this.adminUser, - this.adminAddress, - this.adminTelno, - this.adminTin, - this.faasType, - }); + PropertyInfo( + {this.id, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified, + this.transCode, + this.tdn, + this.pin, + this.fname, + this.mname, + this.lname, + this.bday, + this.address, + this.telno, + this.tin, + this.adminUser, + this.adminAddress, + this.adminTelno, + this.adminTin, + this.faasType, + this.genCode, + this.dateSynced}); + + PropertyInfo copy( + {int? id, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + String? transCode, + String? tdn, + String? pin, + String? owner, + String? address, + String? telno, + String? tin, + String? adminUser, + String? adminAddress, + String? adminTelno, + String? adminTin, + String? faasType, + String? genCode, + String? dateSynced}) => + PropertyInfo( + id: id ?? this.id, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, + transCode: transCode ?? this.transCode, + tdn: tdn ?? this.tdn, + pin: pin ?? this.pin, + fname: fname ?? this.fname, + mname: mname ?? this.mname, + lname: lname ?? this.lname, + bday: bday ?? this.bday, + address: address ?? this.address, + telno: telno ?? this.telno, + tin: tin ?? this.tin, + adminUser: adminUser ?? this.adminUser, + adminAddress: adminAddress ?? this.adminAddress, + adminTelno: adminTelno ?? this.adminTelno, + adminTin: adminTin ?? this.adminTin, + faasType: faasType ?? this.faasType, + genCode: genCode ?? this.genCode, + dateSynced: dateSynced ?? this.dateSynced); factory PropertyInfo.fromJson(Map json) => PropertyInfo( - 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"], - 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"], - ); + 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"], + fname: json["fname"], + mname: json["mname"], + lname: json["lname"], + bday: json["bday"], + 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"], + genCode: json["gen_code"], + dateSynced: json["dateSynced"]); + + factory PropertyInfo.fromJson2(Map json) => PropertyInfo( + id: json["id"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + // dateCreated: json["date_created"] == null + // ? null + // : DateTime.parse(json["date_created"]), + // dateModified: json["date_modified"] == null + // ? null + // : DateTime.parse(json["date_modified"]), + transCode: json["transCode"], + tdn: json["tdn"], + pin: json["pin"], + fname: json["fname"], + mname: json["mname"], + lname: json["lname"], + bday: json["bday"], + address: json["address"], + telno: json["telno"], + tin: json["tin"], + adminUser: json["adminUser"], + adminAddress: json["adminAddress"], + adminTelno: json["adminTelno"], + adminTin: json["adminTin"], + faasType: json["faasType"], + genCode: json["genCode"], + dateSynced: json["dateSynced"]); + + factory PropertyInfo.fromMap(Map map) => PropertyInfo( + id: map["id"], + assessedById: map["assessedById"], + assessedByName: map["assessedByName"], + dateCreated: map["dateCreated"], + dateModified: map["dateModified"], + transCode: map["transCode"], + tdn: map["tdn"], + pin: map["pin"], + fname: map["fname"], + mname: map["mname"], + lname: map["lname"], + bday: map["bday"], + address: map["address"], + telno: map["telno"], + tin: map["tin"], + adminUser: map["adminUser"], + adminAddress: map["adminUser"], + adminTelno: map["adminTelno"], + adminTin: map["adminTin"], + faasType: map["faasType"], + genCode: map["genCode"], + dateSynced: map["dateSynced"]); Map toJson() => { "id": id, "assessed_by_id": assessedById, "assessed_by_name": assessedByName, - "date_created": dateCreated?.toIso8601String(), - "date_modified": dateModified?.toIso8601String(), + "date_created": dateCreated, + "date_modified": dateModified, "trans_code": transCode, "tdn": tdn, "pin": pin, - "owner": owner, + "fname": fname, + "mname": mname, + "lname": lname, + "bday": bday, "address": address, "telno": telno, "tin": tin, @@ -90,5 +202,7 @@ class PropertyInfo { "admin_telno": adminTelno, "admin_tin": adminTin, "faas_type": faasType, + "gen_code": genCode, + "dateSynced": dateSynced }; } diff --git a/lib/model/passo/signatories.dart b/lib/model/passo/signatories.dart index 641f491..cc7c79a 100644 --- a/lib/model/passo/signatories.dart +++ b/lib/model/passo/signatories.dart @@ -15,6 +15,9 @@ class Signatories { final String firstname; final String middlename; final String lastname; + final String designation; + // final String status; + // final String genCode; Signatories({ this.id, @@ -22,14 +25,53 @@ class Signatories { required this.firstname, required this.middlename, required this.lastname, + required this.designation, + // required this.status + // required this.genCode, }); + Signatories copy({ + int? id, + int? signatoryId, + String? firstname, + String? middlename, + String? lastname, + String? designation, + // String? status + // String? genCode + }) { + return Signatories( + id: id ?? this.id, + signatoryId: signatoryId ?? this.signatoryId, + firstname: firstname ?? this.firstname, + middlename: middlename ?? this.middlename, + lastname: lastname ?? this.lastname, + designation: designation ?? this.designation, + // status: status ?? this.status + // genCode: genCode ?? this.genCode + ); + } + factory Signatories.fromJson(Map json) => Signatories( id: json["id"], signatoryId: json["signatory_id"], firstname: json["firstname"], middlename: json["middlename"], lastname: json["lastname"], + designation: json["designation"], + // status: json["status"] + // genCode: json["gen_code"], + ); + + factory Signatories.fromJson2(Map json) => Signatories( + id: json["id"], + signatoryId: json["signatoryId"], + firstname: json["firstname"], + middlename: json["middlename"], + lastname: json["lastname"], + designation: json["designation"], + // status: json["status"] + // genCode: json["gen_code"], ); Map toJson() => { @@ -38,5 +80,8 @@ class Signatories { "firstname": firstname, "middlename": middlename, "lastname": lastname, + "designation": designation, + // "status": status + // "gen_code": genCode }; } diff --git a/lib/model/passo/structural_materials_ii.dart b/lib/model/passo/structural_materials_ii.dart index cfa3ec2..df3f27e 100644 --- a/lib/model/passo/structural_materials_ii.dart +++ b/lib/model/passo/structural_materials_ii.dart @@ -13,6 +13,7 @@ String structureMaterialsIiToJson(StructureMaterialsII data) => class StructureMaterialsII { final int? id; + final int? bldgapprDetailsId; final List? foundation; final List? columns; final List? beams; @@ -21,9 +22,15 @@ class StructureMaterialsII { final List? flooring; final List? walls; final List? others; + final String? genCode; + final String? assessedById; + final String? assessedByName; + final String? dateCreated; + final String? dateModified; StructureMaterialsII( {this.id, + this.bldgapprDetailsId, this.foundation, this.columns, this.beams, @@ -31,11 +38,17 @@ class StructureMaterialsII { this.roof, this.flooring, this.walls, - this.others}); + this.others, + this.genCode, + this.assessedById, + this.assessedByName, + this.dateCreated, + this.dateModified}); factory StructureMaterialsII.fromJson(Map json) => StructureMaterialsII( id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], foundation: List.from(json["foundation"].map((x) => x)), columns: List.from(json["columns"].map((x) => x)), beams: List.from(json["beams"].map((x) => x)), @@ -44,10 +57,70 @@ class StructureMaterialsII { flooring: List.from(json["flooring"].map((x) => x)), walls: List.from(json["walls"].map((x) => x)), others: List.from(json["others"].map((x) => x)), + genCode: json["gen_code"], + assessedById: json["assessed_by_id"], + assessedByName: json["assessed_by_name"], + dateCreated: json["date_created"], + dateModified: json["date_modified"], + ); + + factory StructureMaterialsII.fromJson2(Map json) => + StructureMaterialsII( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + 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["trussFraming"].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)), + genCode: json["genCode"], + assessedById: json["assessedById"], + assessedByName: json["assessedByName"], + dateCreated: json["dateCreated"], + dateModified: json["dateModified"], + ); + + StructureMaterialsII copy({ + int? id, + int? bldgapprDetailsId, + List? foundation, + List? columns, + List? beams, + List? trussFraming, + List? roof, + List? flooring, + List? walls, + List? others, + String? genCode, + String? assessedById, + String? assessedByName, + String? dateCreated, + String? dateModified, + }) => + StructureMaterialsII( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + foundation: foundation ?? this.foundation, + columns: columns ?? this.columns, + beams: beams ?? this.beams, + trussFraming: trussFraming ?? this.trussFraming, + roof: roof ?? this.roof, + flooring: flooring ?? this.flooring, + walls: walls ?? this.walls, + others: others ?? this.others, + genCode: genCode ?? this.genCode, + assessedById: assessedById ?? this.assessedById, + assessedByName: assessedByName ?? this.assessedByName, + dateCreated: dateCreated ?? this.dateCreated, + dateModified: dateModified ?? this.dateModified, ); Map toJson() => { "id": id, + "bldgapprDetailsId": bldgapprDetailsId, "foundation": List.from(foundation!.map((x) => x)), "columns": List.from(columns!.map((x) => x)), "beams": List.from(beams!.map((x) => x)), @@ -56,5 +129,10 @@ class StructureMaterialsII { "flooring": List.from(flooring!.map((x) => x)), "walls": List.from(walls!.map((x) => x)), "others": List.from(others!.map((x) => x)), + "gen_code": genCode, + "assessed_by_id": assessedById, + "assessed_by_name": assessedByName, + "date_created": dateCreated, + "date_modified": dateModified, }; } diff --git a/lib/model/passo/structureMaterial.dart b/lib/model/passo/structureMaterial.dart index 4c07c23..b8d7e74 100644 --- a/lib/model/passo/structureMaterial.dart +++ b/lib/model/passo/structureMaterial.dart @@ -13,6 +13,7 @@ String structureMaterialsToJson(StructureMaterials data) => class StructureMaterials { final int? id; + final int? bldgapprDetailsId; final String? foundation; final String? columns; final String? beams; @@ -20,32 +21,78 @@ class StructureMaterials { final String? roof; final String? flooring; final String? walls; + final String? others; + final String? genCode; - StructureMaterials({ - this.id, - this.foundation, - this.columns, - this.beams, - this.trussFraming, - this.roof, - this.flooring, - this.walls, - }); + StructureMaterials( + {this.id, + this.bldgapprDetailsId, + this.foundation, + this.columns, + this.beams, + this.trussFraming, + this.roof, + this.flooring, + this.walls, + this.others, + this.genCode}); + + StructureMaterials copy( + {int? id, + int? bldgapprDetailsId, + String? foundation, + String? columns, + String? beams, + String? trussFraming, + String? roof, + String? flooring, + String? walls, + String? others, + String? genCode}) => + StructureMaterials( + id: id ?? this.id, + bldgapprDetailsId: bldgapprDetailsId ?? this.bldgapprDetailsId, + foundation: foundation ?? this.foundation, + columns: columns ?? this.columns, + beams: beams ?? this.beams, + trussFraming: trussFraming ?? this.trussFraming, + roof: roof ?? this.roof, + flooring: flooring ?? this.flooring, + walls: walls ?? this.walls, + others: others ?? this.others, + genCode: genCode ?? this.genCode); 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"], - ); + id: json["id"], + bldgapprDetailsId: json["bldgappr_details_id"], + foundation: json["foundation"], + columns: json["columns"], + beams: json["beams"], + trussFraming: json["truss_framing"], + roof: json["roof"], + flooring: json["flooring"], + walls: json["walls"], + others: json["others"], + genCode: json["gen_code"]); + + factory StructureMaterials.fromJson2(Map json) => + StructureMaterials( + id: json["id"], + bldgapprDetailsId: json["bldgapprDetailsId"], + foundation: json["foundation"], + columns: json["columns"], + beams: json["beams"], + trussFraming: json["trussFraming"], + roof: json["roof"], + flooring: json["flooring"], + walls: json["walls"], + others: json["others"], + genCode: json["gen_code"]); Map toJson() => { "id": id, + "bldgappr_details_id": bldgapprDetailsId, "foundation": foundation, "columns": columns, "beams": beams, @@ -53,5 +100,7 @@ class StructureMaterials { "roof": roof, "flooring": flooring, "walls": walls, + "others": others, + "gen_code": genCode, }; } diff --git a/lib/model/passo/todo.dart b/lib/model/passo/todo.dart new file mode 100644 index 0000000..a4110d4 --- /dev/null +++ b/lib/model/passo/todo.dart @@ -0,0 +1,68 @@ +const String todoTable = 'todos'; + +class TodoFields { + static final List values = [ + /// Add all fields + id, isImportant, number, title, description, time + ]; + + static const String id = '_id'; + static const String isImportant = 'isImportant'; + static const String number = 'number'; + static const String title = 'title'; + static const String description = 'description'; + static const String time = 'time'; +} + +class Todo { + final int? id; + final bool isImportant; + final int number; + final String title; + final String description; + final DateTime createdTime; + + const Todo({ + this.id, + required this.isImportant, + required this.number, + required this.title, + required this.description, + required this.createdTime, + }); + + Todo copy({ + int? id, + bool? isImportant, + int? number, + String? title, + String? description, + DateTime? createdTime, + }) => + Todo( + id: id ?? this.id, + isImportant: isImportant ?? this.isImportant, + number: number ?? this.number, + title: title ?? this.title, + description: description ?? this.description, + createdTime: createdTime ?? this.createdTime, + ); + + static Todo fromJson(Map json) => Todo( + id: json[TodoFields.id] as int?, + isImportant: json[TodoFields.isImportant] == 1, + number: json[TodoFields.number] as int, + title: json[TodoFields.title] as String, + description: json[TodoFields.description] as String, + createdTime: DateTime.parse(json[TodoFields.time] as String), + ); + + Map toJson() => { + TodoFields.id: id, + TodoFields.title: title, + TodoFields.isImportant: isImportant ? 1 : 0, + TodoFields.number: number, + TodoFields.description: description, + TodoFields.time: createdTime.toIso8601String(), + }; +} diff --git a/lib/model/passo/trees_improvements.dart b/lib/model/passo/trees_improvements.dart index cc72f4a..68e3f28 100644 --- a/lib/model/passo/trees_improvements.dart +++ b/lib/model/passo/trees_improvements.dart @@ -23,6 +23,20 @@ class TreesImprovements { this.subclassCode, }); + TreesImprovements copy({ + final int? id, + final String? improvement, + final String? pricePerTree, + final dynamic subclassCode, + }) { + return TreesImprovements( + id: id ?? this.id, + improvement: improvement ?? this.improvement, + pricePerTree: pricePerTree ?? this.pricePerTree, + subclassCode: subclassCode ?? this.subclassCode, + ); + } + factory TreesImprovements.fromJson(Map json) => TreesImprovements( id: json["id"], @@ -31,6 +45,14 @@ class TreesImprovements { subclassCode: json["subclass_code"], ); + factory TreesImprovements.fromJson2(Map json) => + TreesImprovements( + id: json["id"], + improvement: json["improvement"], + pricePerTree: json["pricePerTree"], + subclassCode: json["subclassCode"], + ); + Map toJson() => { "id": id, "improvement": improvement, diff --git a/lib/model/passo/type_of_location.dart b/lib/model/passo/type_of_location.dart index 9990236..9e2bd34 100644 --- a/lib/model/passo/type_of_location.dart +++ b/lib/model/passo/type_of_location.dart @@ -22,6 +22,15 @@ class TypeOfLocation { this.localTradingCenter, }); + TypeOfLocation copy({ + final int? id, + final String? distanceKm, + final String? allRoadTypes, + final String? localTradingCenter, + }) { + return TypeOfLocation(); + } + factory TypeOfLocation.fromJson(Map json) => TypeOfLocation( id: json["id"], distanceKm: json["distance_km"], @@ -29,6 +38,13 @@ class TypeOfLocation { localTradingCenter: json["local_trading_center"], ); + factory TypeOfLocation.fromJson2(Map json) => TypeOfLocation( + id: json["id"], + distanceKm: json["distanceKm"], + allRoadTypes: json["allRoadTypes"], + localTradingCenter: json["localTradingCenter"], + ); + Map toJson() => { "id": id, "distance_km": distanceKm, diff --git a/lib/model/passo/type_of_road.dart b/lib/model/passo/type_of_road.dart index e545e29..a3d86cc 100644 --- a/lib/model/passo/type_of_road.dart +++ b/lib/model/passo/type_of_road.dart @@ -20,12 +20,30 @@ class TypeOfRoad { this.deduction, }); + TypeOfRoad copy({ + final int? id, + final String? roadType, + final String? deduction, + }) { + return TypeOfRoad( + id: id ?? this.id, + roadType: roadType ?? this.roadType, + deduction: deduction ?? this.deduction, + ); + } + factory TypeOfRoad.fromJson(Map json) => TypeOfRoad( id: json["id"], roadType: json["road_type"], deduction: json["deduction"], ); + factory TypeOfRoad.fromJson2(Map json) => TypeOfRoad( + id: json["id"], + roadType: json["roadType"], + deduction: json["deduction"], + ); + Map toJson() => { "id": id, "road_type": roadType, diff --git a/lib/model/passo/unit_construct.dart b/lib/model/passo/unit_construct.dart index bc97fa3..cca5e0a 100644 --- a/lib/model/passo/unit_construct.dart +++ b/lib/model/passo/unit_construct.dart @@ -14,19 +14,53 @@ class UnitConstruct { final String bldgType; final String building; final String unitValue; + final String genCode; UnitConstruct({ required this.id, required this.bldgType, required this.building, required this.unitValue, + required this.genCode, }); + UnitConstruct copy({ + int? id, + String? bldgType, + String? building, + String? unitValue, + String? genCode, + }) { + return UnitConstruct( + id: id ?? this.id, + bldgType: bldgType ?? this.bldgType, + building: building ?? this.building, + unitValue: unitValue ?? this.unitValue, + genCode: genCode ?? this.genCode, + ); + } + + UnitConstruct.defaultConstruct() + : id = 0, + bldgType = 'defaultType', + building = 'defaultBuilding', + unitValue = '0', + genCode = 'defaultGenCode'; + + factory UnitConstruct.fromJson2(Map json) => UnitConstruct( + id: json["id"], + bldgType: json["bldgType"], + building: json["building"], + unitValue: json["unitValue"], + genCode: json["gen_code"], + ); + factory UnitConstruct.fromJson(Map json) => UnitConstruct( id: json["id"], bldgType: json["bldg_type"], building: json["building"], unitValue: json["unit_value"], + genCode: json["gen_code"], ); Map toJson() => { @@ -34,5 +68,6 @@ class UnitConstruct { "bldg_type": bldgType, "building": building, "unit_value": unitValue, + "gen_code": genCode, }; } diff --git a/lib/model/profile/family_backround.dart b/lib/model/profile/family_backround.dart index fb8a397..1d393ed 100644 --- a/lib/model/profile/family_backround.dart +++ b/lib/model/profile/family_backround.dart @@ -3,7 +3,6 @@ // final familyBackground = familyBackgroundFromJson(jsonString); import 'dart:convert'; -import 'dart:ffi'; import '../utils/category.dart'; import '../utils/position.dart'; diff --git a/lib/model/rbac/assigned_role.dart b/lib/model/rbac/assigned_role.dart index ca688e1..0b197bf 100644 --- a/lib/model/rbac/assigned_role.dart +++ b/lib/model/rbac/assigned_role.dart @@ -51,38 +51,4 @@ class AssignedRole { }; } -class CreatedBy { - final int id; - final String username; - final String firstName; - final String lastName; - final String email; - final bool isActive; - CreatedBy({ - required this.id, - required this.username, - required this.firstName, - required this.lastName, - required this.email, - required this.isActive, - }); - - factory CreatedBy.fromJson(Map json) => CreatedBy( - id: json["id"], - username: json["username"], - firstName: json["first_name"], - lastName: json["last_name"], - email: json["email"], - isActive: json["is_active"], - ); - - Map toJson() => { - "id": id, - "username": username, - "first_name": firstName, - "last_name": lastName, - "email": email, - "is_active": isActive, - }; -} diff --git a/lib/model/rbac/permission_assignment.dart b/lib/model/rbac/permission_assignment.dart new file mode 100644 index 0000000..1c2e06b --- /dev/null +++ b/lib/model/rbac/permission_assignment.dart @@ -0,0 +1,174 @@ +// To parse this JSON data, do +// +// final permissionAssignment = permissionAssignmentFromJson(jsonString); + +import 'package:meta/meta.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'dart:convert'; + +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/model/rbac/user.dart'; + +PermissionAssignment permissionAssignmentFromJson(String str) => PermissionAssignment.fromJson(json.decode(str)); + +String permissionAssignmentToJson(PermissionAssignment data) => json.encode(data.toJson()); + +class PermissionAssignment { + final int? id; + final RBAC? role; + final RBACPermission? permission; + final DateTime? createdAt; + final DateTime? updatedAt; + final User? createdBy; + final User? updatedBy; + + PermissionAssignment({ + required this.id, + required this.role, + required this.permission, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory PermissionAssignment.fromJson(Map json) => PermissionAssignment( + id: json["id"], + role: json["role"] == null? null: RBAC.fromJson(json["role"]), + permission:json["permission"] == null?null: RBACPermission.fromJson(json["permission"]), + createdAt: json['created_at'] == null?null: DateTime.parse(json["created_at"]), + updatedAt:json['updated_at'] == null?null: DateTime.parse(json["updated_at"]), + createdBy:json["created_by"] == null?null: User.fromJson(json["created_by"]), + updatedBy: json["updated_by"] == null? null:User.fromJson(json["created_by"]), + ); + + Map toJson() => { + "id": id, + "role": role?.toJson(), + "permission": permission?.toJson(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy?.toJson(), + "updated_by": updatedBy, + }; +} + +class CreatedBy { + final int id; + final String username; + final String firstName; + final String lastName; + final String email; + final bool isActive; + + CreatedBy({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory CreatedBy.fromJson(Map json) => CreatedBy( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} + +class Permission { + final int id; + final Role object; + final Role operation; + final DateTime createdAt; + final dynamic updatedAt; + final CreatedBy createdBy; + final dynamic updatedBy; + + Permission({ + required this.id, + required this.object, + required this.operation, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Permission.fromJson(Map json) => Permission( + id: json["id"], + object: Role.fromJson(json["object"]), + operation: Role.fromJson(json["operation"]), + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "object": object.toJson(), + "operation": operation.toJson(), + "created_at": createdAt.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy.toJson(), + "updated_by": updatedBy, + }; +} + +class Role { + final int id; + final String name; + final String slug; + final String shorthand; + final DateTime createdAt; + final dynamic updatedAt; + final CreatedBy createdBy; + final dynamic updatedBy; + + Role({ + required this.id, + required this.name, + required this.slug, + required this.shorthand, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.updatedBy, + }); + + factory Role.fromJson(Map json) => Role( + id: json["id"], + name: json["name"], + slug: json["slug"], + shorthand: json["shorthand"], + createdAt: DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"], + createdBy: CreatedBy.fromJson(json["created_by"]), + updatedBy: json["updated_by"], + ); + + Map toJson() => { + "id": id, + "name": name, + "slug": slug, + "shorthand": shorthand, + "created_at": createdAt.toIso8601String(), + "updated_at": updatedAt, + "created_by": createdBy.toJson(), + "updated_by": updatedBy, + }; +} diff --git a/lib/model/rbac/user.dart b/lib/model/rbac/user.dart new file mode 100644 index 0000000..46b1ff1 --- /dev/null +++ b/lib/model/rbac/user.dart @@ -0,0 +1,35 @@ +class User { + final int id; + final String? username; + final String? firstName; + final String? lastName; + final String? email; + final bool? isActive; + + User({ + required this.id, + required this.username, + required this.firstName, + required this.lastName, + required this.email, + required this.isActive, + }); + + factory User.fromJson(Map json) => User( + id: json["id"], + username: json["username"], + firstName: json["first_name"], + lastName: json["last_name"], + email: json["email"], + isActive: json["is_active"], + ); + + Map toJson() => { + "id": id, + "username": username, + "first_name": firstName, + "last_name": lastName, + "email": email, + "is_active": isActive, + }; +} \ No newline at end of file diff --git a/lib/screens/docsms/components/request_receipt.dart b/lib/screens/docsms/components/request_receipt.dart index d2e2491..5f57cd6 100644 --- a/lib/screens/docsms/components/request_receipt.dart +++ b/lib/screens/docsms/components/request_receipt.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:fluttericon/entypo_icons.dart'; @@ -38,11 +37,13 @@ class _RequetAutoReceiptState extends State { Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ const DocInfo(title: "4427", subTitle: documentId), const CostumDivider(), - const DocInfo(title: "Purchase of Diesel", subTitle: documentTitle), + const DocInfo( + title: "Purchase of Diesel", subTitle: documentTitle), const CostumDivider(), const DocInfo(title: "N/A", subTitle: documentSubject), const CostumDivider(), - const DocInfo(title: "Request for Quotation", subTitle: documentType), + const DocInfo( + title: "Request for Quotation", subTitle: documentType), const CostumDivider(), Form( child: Column(children: [ @@ -60,20 +61,20 @@ class _RequetAutoReceiptState extends State { ), Text( sourceRemarks, - style: Theme.of(context).textTheme.caption, + style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox( height: 12, ), FormBuilderTextField( name: "remarks", - validator: FormBuilderValidators.required( - errorText: remarksRequired), + validator: FormBuilderValidators.required( + errorText: remarksRequired), autovalidateMode: AutovalidateMode.onUserInteraction, maxLines: 5, - decoration: normalTextFieldStyle( - enterRemarks, "..."), + decoration: + normalTextFieldStyle(enterRemarks, "..."), ), const SizedBox( height: 8, @@ -123,8 +124,8 @@ class _RequetAutoReceiptState extends State { width: double.infinity, height: screenHeight * .06, child: ElevatedButton( - style: secondaryBtnStyle( - primary, Colors.transparent, Colors.white54), + style: secondaryBtnStyle(primary, + Colors.transparent, Colors.white54), child: const Text( requestAutoReceipt, style: TextStyle(color: Colors.white), diff --git a/lib/screens/offline/homepage/drawer.dart b/lib/screens/offline/homepage/drawer.dart new file mode 100644 index 0000000..a68c99a --- /dev/null +++ b/lib/screens/offline/homepage/drawer.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_zoom_drawer/flutter_zoom_drawer.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/screens/offline/homepage/menu_screen.dart'; +import 'package:unit2/screens/offline/homepage/module_screen.dart'; +import 'package:unit2/utils/global.dart'; +import '../../../../bloc/user/user_bloc.dart'; +import '../../../../widgets/splash_screen.dart'; + +class OfflineDrawerScreen extends StatefulWidget { + const OfflineDrawerScreen({ + Key? key, + }) : super( + key: key, + ); + @override + State createState() => _OfflineDrawerScreenState(); +} + +class _OfflineDrawerScreenState extends State { + final zoomDrawerController = ZoomDrawerController(); + @override + @override + Widget build(BuildContext context) { + return ZoomDrawer( + controller: zoomDrawerController, + menuScreen: const OfflineMenuScreen(), + mainScreen: SizedBox( + height: MediaQuery.of(context).size.height, + child: const OfflineModuleScreen()), + style: DrawerStyle.defaultStyle, + borderRadius: 24.0, + showShadow: false, + angle: -0.0, + slideWidth: MediaQuery.of(context).size.width * .90, + openCurve: Curves.fastOutSlowIn, + closeCurve: Curves.easeOut, + menuBackgroundColor: Colors.grey, + ); + } +} diff --git a/lib/screens/offline/homepage/menu_screen.dart b/lib/screens/offline/homepage/menu_screen.dart new file mode 100644 index 0000000..9cd4b5a --- /dev/null +++ b/lib/screens/offline/homepage/menu_screen.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import '../../../../utils/global.dart'; + +class OfflineMenuScreen extends StatefulWidget { + const OfflineMenuScreen({super.key}); + + @override + State createState() => _OfflineMenuScreenState(); +} + +class _OfflineMenuScreenState extends State { + @override + Widget build(BuildContext context) { + return Drawer( + child: SizedBox( + height: screenHeight, + child: Column( + mainAxisSize: MainAxisSize.max, + children: [ + Column( + children: [ + UserAccountsDrawerHeader( + currentAccountPictureSize: const Size.square(90), + decoration: const BoxDecoration( + color: primary, + image: DecorationImage( + image: AssetImage('assets/pngs/bg.png'), + fit: BoxFit.cover)), + accountName: null, + accountEmail: null, + currentAccountPicture: CircleAvatar( + radius: 100, + backgroundColor: fifth, + child: CircleAvatar( + radius: 100, + backgroundColor: third, + child: Image.asset( + 'assets/pngs/capitol.png', + )), + ), + ), + ListTile( + dense: true, + leading: const Icon( + Icons.exit_to_app, + color: primary, + ), + title: const Text( + "Exit Offline Mode", + style: TextStyle(color: Colors.black), + ), + onTap: () async { + Navigator.pushReplacementNamed(context, '/'); + }, + ) + ], + ), + const Expanded(child: SizedBox()), + const Divider(), + const SizedBox( + height: 10, + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/offline/homepage/module_screen.dart b/lib/screens/offline/homepage/module_screen.dart new file mode 100644 index 0000000..f68d40b --- /dev/null +++ b/lib/screens/offline/homepage/module_screen.dart @@ -0,0 +1,73 @@ +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:flutter_zoom_drawer/flutter_zoom_drawer.dart'; +import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:unit2/bloc/offline/offline_bloc/offline_bloc.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/screens/offline/passo/passo_offline_dashboard.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/dashboard/shared_card_label.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../passo/passo_main_dashboard.dart'; + +class OfflineModuleScreen extends StatelessWidget { + const OfflineModuleScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Offline Mode"), + centerTitle: true, + leading: IconButton( + onPressed: () { + ZoomDrawer.of(context)!.toggle(); + }, + icon: const Icon( + Icons.menu, + color: Colors.white, + ), + ), + ), + body: ProgressHUD( + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is OfflineLoadingState) {} + }, + builder: (context, state) { + if (state is OfflineModeState) { + return Padding( + padding: const EdgeInsets.all(24), + child: GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric( + vertical: 5, horizontal: 5), + children: state.offlineModules + .map((e) => CardLabel( + icon: FontAwesome5.eye, + title: "Rpass Offline", + ontap: () { + Navigator.push(context, + MaterialPageRoute(builder: ((context) { + return PassoOfflineMainScreen( + state.offlineProfile); + }))); + })) + .toList()), + ); + } + return Container(); + }, + ), + )); + } +} diff --git a/lib/screens/offline/passo/admin/admin_main_screen.dart b/lib/screens/offline/passo/admin/admin_main_screen.dart new file mode 100644 index 0000000..7b19068 --- /dev/null +++ b/lib/screens/offline/passo/admin/admin_main_screen.dart @@ -0,0 +1,235 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:fluttericon/elusive_icons.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_bloc.dart'; +import 'package:unit2/screens/offline/passo/admin/barangay.dart'; +import 'package:unit2/screens/offline/passo/admin/class_components.dart'; +import 'package:unit2/screens/offline/passo/admin/globalSyncService.dart'; +import 'package:unit2/screens/offline/passo/admin/land_classification.dart'; +import 'package:unit2/screens/offline/passo/admin/land_sub_classification.dart'; +import 'package:unit2/screens/offline/passo/admin/memoranda.dart'; +import 'package:unit2/screens/offline/passo/admin/municipalities.dart'; +import 'package:unit2/screens/offline/passo/admin/signatories.dart'; +import 'package:unit2/screens/offline/passo/admin/trees_improvements.dart'; +import 'package:unit2/screens/offline/passo/admin/type_of_location.dart'; +import 'package:unit2/screens/offline/passo/admin/type_of_road.dart'; +import 'package:unit2/screens/offline/passo/admin/unit_construction.dart'; +import 'package:unit2/screens/offline/passo/admin/value_adjustment.dart'; +import 'package:unit2/screens/profile/components/main_menu.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/type_of_location.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; + +class AdminMainScreen extends StatefulWidget { + const AdminMainScreen({super.key}); + + @override + _AdminMainScreen createState() => _AdminMainScreen(); +} + +class _AdminMainScreen extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("PASSO Admin"), + centerTitle: true, + // actions: [ + // TextButton( + // style: TextButton.styleFrom( + // textStyle: const TextStyle(fontSize: 15), + // ), + // onPressed: () async { + // try { + // GlobalSyncService().syncAllData(); + // } catch (e) { + // // Handle any errors that might occur during the API call or database insertion. + // print("Error: $e"); + // } + // }, + // child: const Text('SYNC'), + // ), + // ], + ), + body: ListView( + children: [ + MainMenu( + icon: Elusive.wrench, + title: "Municipalities", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + MunicipalitiesAdminBloc()..add(LoadMunicipalities()), + child: const MunicipalitiesAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Barangay", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => BarangayAdminBloc()..add(LoadBarangay()), + child: const BarangayAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Class Components", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + ClassComponentsAdminBloc()..add(LoadClassComponents()), + child: const ClassComponentsAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Structural Types", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + UnitConstructionAdminBloc()..add(LoadUnitConstruct()), + child: const UnitConstructionAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Signatories", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + SignatoriesAdminBloc()..add(LoadSignatories()), + child: const SignatoriesAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Memoranda", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(LoadMemoranda()), + child: const MemorandaAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Land SubClassification", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => LandSubclassificationBloc() + ..add(const LoadLandSubClassification()), + child: const LandSubClassificationAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Land Classification", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => LandClassificationBloc() + ..add(const LoadLandClassification()), + child: const LandClassificationAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Trees", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + TreesImprovementsBloc()..add(LoadTreesImprovements()), + child: const TreesImprovementsAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Type of Road", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(const LoadTypeOfRoad()), + child: const TypesOfRoadAdminPage(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.wrench, + title: "Type of Location", + onTap: () { + Navigator.push(context, + MaterialPageRoute(builder: (BuildContext context) { + return BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(const LoadTypeOfLocation()), + child: const TypesOfLocationAdminPage(), + ); + })); + }, + ), + ], + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/barangay.dart b/lib/screens/offline/passo/admin/barangay.dart new file mode 100644 index 0000000..e220fa1 --- /dev/null +++ b/lib/screens/offline/passo/admin/barangay.dart @@ -0,0 +1,112 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart'; + +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; + +class BarangayAdminPage extends StatefulWidget { + const BarangayAdminPage(); + + @override + _BarangayAdminPage createState() => _BarangayAdminPage(); +} + +class _BarangayAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Barangay"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = await BrgyAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final brgys = + result.map((json) => Brgy.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (Brgy brgy in brgys) { + await SQLServices.instance.createBarangay(brgy); + } + + context.read().add(LoadBarangay()); + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is BarangayLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Code'), + ), + const DataColumn( + label: Text('City Code'), + ), + const DataColumn( + label: Text('Description'), + ), + ], + rows: state.brgy.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.barangayId.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.barangayCode ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.cityCode ?? 'N/A')), + DataCell(Text( + dataRow.barangayDescription ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/class_components.dart b/lib/screens/offline/passo/admin/class_components.dart new file mode 100644 index 0000000..4169055 --- /dev/null +++ b/lib/screens/offline/passo/admin/class_components.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/model/passo/class_components%20_offline.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:http/http.dart'; +import '../../../../model/passo/city.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../utils/urls.dart'; + +class ClassComponentsAdminPage extends StatefulWidget { + const ClassComponentsAdminPage(); + + @override + _ClassComponentsAdminPage createState() => _ClassComponentsAdminPage(); +} + +class _ClassComponentsAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Class Components"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + Response response = await get(Uri.parse( + 'http://${Url.instance.host()}/api/rptass_app/class_components/')); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + result.map(((e) => ClassComponents.fromJson(e))).toList(); + + final classes = result + .map((json) => ClassComponents.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (ClassComponents classs in classes) { + await SQLServices.instance.createClassComponents( + ClassComponentsOffline( + componentName: classs.componentName, + minBaseUnitvalPercent: classs.minBaseUnitvalPercent, + maxBaseUnitvalPercent: classs.maxBaseUnitvalPercent, + minUnitvalSqrmtr: classs.minUnitvalSqrmtr, + maxUnitvalSqrmtr: classs.maxUnitvalSqrmtr, + minAddBaseunitval: classs.minAddBaseunitval, + maxAddBaseunitval: classs.maxAddBaseunitval, + minDeductBaserate: classs.minAddBaseunitval, + maxDeductBaserate: classs.maxDeductBaserate, + minLinearMeter: classs.minLinearMeter, + maxLinearMeter: classs.maxLinearMeter, + minSpacing: classs.minSpacing, + maxSpacing: classs.maxSpacing, + roughFinish: classs.roughFinish, + highFinish: classs.highFinish, + withoutBucc: classs.withoutBucc == true ? 1 : 0)); + } + } + + context + .read() + .add(LoadClassComponents()); + + // Assuming result is a List of JSON objects, convert them to City objects. + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is ClassComponentsAdminLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Components Name'), + ), + const DataColumn( + label: Text('with BUCC?'), + ), + ], + rows: state.classes.map((dataRow) { + return DataRow( + cells: [ + DataCell( + Text(dataRow.componentName ?? 'N/A')), + // Use a default value if cityCode is null + DataCell(Text(dataRow.withoutBucc + .toString() ?? + 'N/A')), // Use a default value if cityDescription is null + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/globalSyncService.dart b/lib/screens/offline/passo/admin/globalSyncService.dart new file mode 100644 index 0000000..368495a --- /dev/null +++ b/lib/screens/offline/passo/admin/globalSyncService.dart @@ -0,0 +1,246 @@ +import '../../../../model/passo/barangay.dart'; +import '../../../../model/passo/city.dart'; +import '../../../../model/passo/class_components _offline.dart'; +import '../../../../model/passo/class_components.dart'; +import '../../../../model/passo/land_classification.dart'; +import '../../../../model/passo/land_subclassification.dart'; +import '../../../../model/passo/land_value_adjustment.dart'; +import '../../../../model/passo/memoranda.dart'; +import '../../../../model/passo/signatories.dart'; +import '../../../../model/passo/trees_improvements.dart'; +import '../../../../model/passo/type_of_location.dart'; +import '../../../../model/passo/type_of_road.dart'; +import '../../../../model/passo/unit_construct.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/land_classification_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/land_sub_classification_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/signatories.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/trees_improvements_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/type_of_location.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/type_of_road_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/unit_construction_api_services.dart'; +import '../../../../sevices/offline/offline_passo/admin/api_services/value_adjustments.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class GlobalSyncService { + static final GlobalSyncService _instance = GlobalSyncService._internal(); + + factory GlobalSyncService() { + return _instance; + } + + GlobalSyncService._internal(); + + Future syncAllData() async { + const maxRetries = 100; + int retryCount = 0; + + // Helper function for retrying individual sync methods + Future syncWithRetry(Future Function() syncMethod) async { + if (retryCount < maxRetries) { + retryCount++; + print('Retrying synchronization for ${retryCount}...'); + // Implement a backoff strategy, for example, using a delay. + await Future.delayed(Duration(seconds: retryCount * 2)); + await syncMethod(); + } else { + print('Max retries reached for ${syncMethod.toString()}. Sync failed.'); + // Handle the failure as needed (e.g., show an error message). + } + } + + Future retrySync() async { + try { + await syncWithRetry(syncBrgyData); + await syncWithRetry(syncClassComponentsData); + await syncWithRetry(syncLandClassification); + await syncWithRetry(syncLandSubClassification); + await syncWithRetry(syncMemoranda); + await syncWithRetry(syncMunicipalities); + await syncWithRetry(syncSignatories); + await syncWithRetry(syncTreesImprovements); + await syncWithRetry(syncTypeOfLocation); + await syncWithRetry(syncTypeOfRoad); + await syncWithRetry(syncUnitConstruct); + await syncWithRetry(syncValueAdjustment); + } catch (e) { + print(e); + print('Max retries reached. Sync failed.'); + // Handle the failure as needed (e.g., show an error message). + } + } + + await retrySync(); + // Add more sync methods as needed + } + + Future syncBrgyData() async { + final result = await BrgyAdminApiServices.instance.fetch(); + final brgys = result.map((json) => Brgy.fromJson(json)).toList(); + + for (Brgy brgy in brgys) { + await SQLServices.instance.createBarangay(brgy); + } + } + + Future syncClassComponentsData() async { + final result = await ClassComponentAdminApiServices.instance.fetch(); + final classes = + result.map((json) => ClassComponents.fromJson(json)).toList(); + + for (ClassComponents classs in classes) { + await SQLServices.instance.createClassComponents( + ClassComponentsOffline( + componentName: classs.componentName, + minBaseUnitvalPercent: classs.minBaseUnitvalPercent, + maxBaseUnitvalPercent: classs.maxBaseUnitvalPercent, + minUnitvalSqrmtr: classs.minUnitvalSqrmtr, + maxUnitvalSqrmtr: classs.maxUnitvalSqrmtr, + minAddBaseunitval: classs.minAddBaseunitval, + maxAddBaseunitval: classs.maxAddBaseunitval, + minDeductBaserate: classs.minAddBaseunitval, + maxDeductBaserate: classs.maxDeductBaserate, + minLinearMeter: classs.minLinearMeter, + maxLinearMeter: classs.maxLinearMeter, + minSpacing: classs.minSpacing, + maxSpacing: classs.maxSpacing, + roughFinish: classs.roughFinish, + highFinish: classs.highFinish, + withoutBucc: classs.withoutBucc == true ? 1 : 0), + ); + } + } + + Future syncLandClassification() async { + final result = await LandClassificationAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final landClass = + result.map((json) => LandClassification.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (LandClassification landClassification in landClass) { + await SQLServices.instance.createLandClassification(landClassification); + } + } + + Future syncLandSubClassification() async { + final result = await LandSubClassificationAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final landSubClass = + result.map((json) => LandSubClassification.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (LandSubClassification landSubClassification in landSubClass) { + await SQLServices.instance + .createLandSubClassification(landSubClassification); + } + } + + Future syncMemoranda() async { + final result = await MemorandaAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final memos = result.map((json) => Memoranda.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (Memoranda memo in memos) { + await SQLServices.instance.createMemoranda(memo); + } + } + + Future syncMunicipalities() async { + final result = await MunicipalityAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final cities = result.map((json) => City.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (City city in cities) { + print(city.cityDescription); + print(city.cityCode); + await SQLServices.instance.createMunicipalities(city); + } + } + + Future syncSignatories() async { + final result = await SignatoriesAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final signatories = + result.map((json) => Signatories.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (Signatories signatory in signatories) { + await SQLServices.instance.createSignatories(signatory); + } + } + + Future syncTreesImprovements() async { + final result = await TreesImprovementsAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final treesImpr = + result.map((json) => TreesImprovements.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TreesImprovements treesImprovements in treesImpr) { + await SQLServices.instance.createTreesImprovements(treesImprovements); + } + } + + Future syncTypeOfLocation() async { + final result = await TypeOfLocationAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final typesOfLoc = + result.map((json) => TypeOfLocation.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TypeOfLocation typesOfLocation in typesOfLoc) { + await SQLServices.instance.createTypeOfLocation(typesOfLocation); + } + } + + Future syncTypeOfRoad() async { + final result = await TypeOfRoadAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final typesOfRoad = + result.map((json) => TypeOfRoad.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TypeOfRoad typesOfRoad in typesOfRoad) { + await SQLServices.instance.createTypeOfRoad(typesOfRoad); + } + } + + Future syncUnitConstruct() async { + final result = await UnitConstructionAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final units = result.map((json) => UnitConstruct.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (UnitConstruct unit in units) { + await SQLServices.instance.createUnitConstruction(unit); + } + } + + Future syncValueAdjustment() async { + final result = await ValueAdjustmentsAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final valueAdj = + result.map((json) => ValueAdjustments.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (ValueAdjustments valueAdjustments in valueAdj) { + await SQLServices.instance.createValueAdjustments(valueAdjustments); + } + } +} diff --git a/lib/screens/offline/passo/admin/land_classification.dart b/lib/screens/offline/passo/admin/land_classification.dart new file mode 100644 index 0000000..3389bd4 --- /dev/null +++ b/lib/screens/offline/passo/admin/land_classification.dart @@ -0,0 +1,109 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; + +import 'package:unit2/model/passo/land_classification.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/land_classification_api_services.dart'; + +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; + +class LandClassificationAdminPage extends StatefulWidget { + const LandClassificationAdminPage(); + + @override + _LandClassificationAdminPage createState() => _LandClassificationAdminPage(); +} + +class _LandClassificationAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Land Classification"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await LandClassificationAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final landClass = result + .map((json) => LandClassification.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (LandClassification landClassification in landClass) { + await SQLServices.instance + .createLandClassification(landClassification); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandClassificationLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Code'), + ), + const DataColumn( + label: Text('Memoranda'), + ), + ], + rows: state.landClassification.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.classificationCode ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.description ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/land_sub_classification.dart b/lib/screens/offline/passo/admin/land_sub_classification.dart new file mode 100644 index 0000000..f091df9 --- /dev/null +++ b/lib/screens/offline/passo/admin/land_sub_classification.dart @@ -0,0 +1,118 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/land_sub_classification_api_services.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../model/passo/land_subclassification.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class LandSubClassificationAdminPage extends StatefulWidget { + const LandSubClassificationAdminPage(); + + @override + _LandSubClassificationAdminPage createState() => + _LandSubClassificationAdminPage(); +} + +class _LandSubClassificationAdminPage + extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Land Sub-Classification"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = await LandSubClassificationAdminApiServices + .instance + .fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final landSubClass = result + .map((json) => LandSubClassification.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (LandSubClassification landSubClassification + in landSubClass) { + await SQLServices.instance + .createLandSubClassification(landSubClassification); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandSubClassificationLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Municipality'), + ), + const DataColumn( + label: Text('Sub-Class Description'), + ), + const DataColumn( + label: Text('Base Unit Market Value'), + ), + ], + rows: state.landSubClassification.map((dataRow) { + return DataRow( + cells: [ + DataCell( + Text(dataRow.id.toString() ?? 'N/A')), + DataCell(Text(dataRow.cityCode.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.subclassDescription ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell( + Text(dataRow.baseUnitMarketval ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/memoranda.dart b/lib/screens/offline/passo/admin/memoranda.dart new file mode 100644 index 0000000..034c805 --- /dev/null +++ b/lib/screens/offline/passo/admin/memoranda.dart @@ -0,0 +1,126 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/memoranda.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart'; + +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; +import '../../../../utils/urls.dart'; +import 'package:http/http.dart'; + +class MemorandaAdminPage extends StatefulWidget { + const MemorandaAdminPage(); + + @override + _MemorandaAdminPage createState() => _MemorandaAdminPage(); +} + +class _MemorandaAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Memoranda"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + // final result = await MemorandaAdminApiServices.instance.fetch(); + + // // Assuming result is a List of JSON objects, convert them to City objects. + // final memos = + // result.map((json) => Memoranda.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + Response response = await get(Uri.parse( + 'http://${Url.instance.host()}${Url.instance.getMemoranda()}')); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + result.map(((e) => Memoranda.fromJson(e))).toList(); + + final memos = + result.map((json) => Memoranda.fromJson(json)).toList(); + for (Memoranda memo in memos) { + await SQLServices.instance.createMemoranda(memo); + } + } + + context.read().add(LoadMemoranda()); + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Code'), + ), + const DataColumn( + label: Text('Memoranda'), + ), + ], + rows: state.memo.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.code ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.memoranda ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/municipalities.dart b/lib/screens/offline/passo/admin/municipalities.dart new file mode 100644 index 0000000..253e7a9 --- /dev/null +++ b/lib/screens/offline/passo/admin/municipalities.dart @@ -0,0 +1,109 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../model/passo/city.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class MunicipalitiesAdminPage extends StatefulWidget { + const MunicipalitiesAdminPage(); + + @override + _MunicipalitiesAdminPage createState() => _MunicipalitiesAdminPage(); +} + +class _MunicipalitiesAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Municipaities"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await MunicipalityAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final cities = + result.map((json) => City.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (City city in cities) { + print(city.cityDescription); + print(city.cityCode); + await SQLServices.instance.createMunicipalities(city); + } + + context + .read() + .add(LoadMunicipalities()); + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MunicipalitiesLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('City Code'), + ), + const DataColumn( + label: Text('Description'), + ), + ], + rows: state.city.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.cityCode ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.cityDescription ?? + 'N/A')), // Use a default value if cityDescription is null + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/signatories.dart b/lib/screens/offline/passo/admin/signatories.dart new file mode 100644 index 0000000..931e016 --- /dev/null +++ b/lib/screens/offline/passo/admin/signatories.dart @@ -0,0 +1,132 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/signatories.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/signatories.dart'; + +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; +import 'package:http/http.dart'; + +import '../../../../utils/urls.dart'; + +class SignatoriesAdminPage extends StatefulWidget { + const SignatoriesAdminPage(); + + @override + _SignatoriesAdminPage createState() => _SignatoriesAdminPage(); +} + +class _SignatoriesAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Signatories"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + Response response = await get(Uri.parse( + 'http://${Url.instance.host()}/api/rptass_app/signatories/')); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + result.map(((e) => Signatories.fromJson(e))).toList(); + + final signatories = + result.map((json) => Signatories.fromJson(json)).toList(); + // Loop through the list of City objects and insert them into the local database. + for (Signatories signatory in signatories) { + await SQLServices.instance.createSignatories(signatory); + } + } + context.read().add(LoadSignatories()); + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is SignatoriesLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('First Name'), + ), + const DataColumn( + label: Text('Middle Name'), + ), + const DataColumn( + label: Text('Last Name'), + ), + const DataColumn( + label: Text('Designation'), + ), + // const DataColumn( + // label: Text('Status'), + // ), + ], + rows: state.signatories.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.signatoryId + .toString())), // Use a default value if cityCode is null + DataCell(Text(dataRow.firstname ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.middlename ?? 'N/A')), + DataCell(Text(dataRow.lastname ?? 'N/A')), + DataCell(Text(dataRow.designation ?? 'N/A')), + // DataCell(Text(dataRow.status ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/trees_improvements.dart b/lib/screens/offline/passo/admin/trees_improvements.dart new file mode 100644 index 0000000..9fa8a6d --- /dev/null +++ b/lib/screens/offline/passo/admin/trees_improvements.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/trees_improvements_api_services.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../model/passo/trees_improvements.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class TreesImprovementsAdminPage extends StatefulWidget { + const TreesImprovementsAdminPage(); + + @override + _TreesImprovementsAdminPage createState() => _TreesImprovementsAdminPage(); +} + +class _TreesImprovementsAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Trees Improvement"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await TreesImprovementsAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final treesImpr = result + .map((json) => TreesImprovements.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TreesImprovements treesImprovements in treesImpr) { + await SQLServices.instance + .createTreesImprovements(treesImprovements); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TreesImprovementsLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Code'), + ), + const DataColumn( + label: Text('Memoranda'), + ), + ], + rows: state.treesImprovements.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.improvement ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell( + Text(dataRow.pricePerTree ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/admin/type_of_location.dart b/lib/screens/offline/passo/admin/type_of_location.dart new file mode 100644 index 0000000..83ca701 --- /dev/null +++ b/lib/screens/offline/passo/admin/type_of_location.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/type_of_location.dart'; + +import '../../../../model/passo/type_of_location.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; + +class TypesOfLocationAdminPage extends StatefulWidget { + const TypesOfLocationAdminPage(); + + @override + _TypesOfLocationAdminPage createState() => _TypesOfLocationAdminPage(); +} + +class _TypesOfLocationAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Type of Location"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await TypeOfLocationAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final typesOfLoc = result + .map((json) => TypeOfLocation.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TypeOfLocation typesOfLocation in typesOfLoc) { + await SQLServices.instance + .createTypeOfLocation(typesOfLocation); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfLocationLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Distance in KM'), + ), + const DataColumn( + label: Text('Road Types'), + ), + const DataColumn( + label: Text( + 'Distance from Local Trading Center'), + ), + ], + rows: state.typeOfLocation.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.distanceKm ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell( + Text(dataRow.allRoadTypes ?? 'N/A')), + DataCell(Text( + dataRow.localTradingCenter ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/admin/type_of_road.dart b/lib/screens/offline/passo/admin/type_of_road.dart new file mode 100644 index 0000000..a72006f --- /dev/null +++ b/lib/screens/offline/passo/admin/type_of_road.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/type_of_road_api_services.dart'; + +import '../../../../model/passo/type_of_road.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; + +class TypesOfRoadAdminPage extends StatefulWidget { + const TypesOfRoadAdminPage(); + + @override + _TypesOfRoadAdminPage createState() => _TypesOfRoadAdminPage(); +} + +class _TypesOfRoadAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Type of Road"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await TypeOfRoadAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final typesOfRoad = + result.map((json) => TypeOfRoad.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + for (TypeOfRoad typesOfRoad in typesOfRoad) { + await SQLServices.instance.createTypeOfRoad(typesOfRoad); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfRoadLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Road Type'), + ), + const DataColumn( + label: Text('Deduction'), + ), + ], + rows: state.typeOfRoad.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.roadType ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.deduction ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/admin/unit_construction.dart b/lib/screens/offline/passo/admin/unit_construction.dart new file mode 100644 index 0000000..c7c79d1 --- /dev/null +++ b/lib/screens/offline/passo/admin/unit_construction.dart @@ -0,0 +1,132 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/model/passo/barangay.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/unit_construction_api_services.dart'; + +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; +import 'package:http/http.dart'; + +import '../../../../utils/urls.dart'; + +class UnitConstructionAdminPage extends StatefulWidget { + const UnitConstructionAdminPage(); + + @override + _UnitConstructionAdminPage createState() => _UnitConstructionAdminPage(); +} + +class _UnitConstructionAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Structural Types"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + // final result = + // await UnitConstructionAdminApiServices.instance.fetch(); + + // // Assuming result is a List of JSON objects, convert them to City objects. + // final units = + // result.map((json) => UnitConstruct.fromJson(json)).toList(); + + // Loop through the list of City objects and insert them into the local database. + Response response = await get(Uri.parse( + 'http://${Url.instance.host()}/api/rptass_app/unitconstruct_values/')); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + + result.map(((e) => UnitConstruct.fromJson(e))).toList(); + + final units = result + .map((json) => UnitConstruct.fromJson(json)) + .toList(); + + for (UnitConstruct unit in units) { + await SQLServices.instance.createUnitConstruction(unit); + } + + context + .read() + .add(LoadUnitConstruct()); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('Bldg Type'), + ), + const DataColumn( + label: Text('Building'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + ], + rows: state.unit.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.bldgType ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.building ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text(dataRow.unitValue ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/admin/value_adjustment.dart b/lib/screens/offline/passo/admin/value_adjustment.dart new file mode 100644 index 0000000..3c6f9c1 --- /dev/null +++ b/lib/screens/offline/passo/admin/value_adjustment.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/value_adjustments/value_adjustments_bloc.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/api_services/value_adjustments.dart'; + +import '../../../../model/passo/land_value_adjustment.dart'; +import '../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../../theme-data.dart/colors.dart'; + +class ValueAdjustmentsAdminPage extends StatefulWidget { + const ValueAdjustmentsAdminPage(); + + @override + _ValueAdjustmentsAdminPage createState() => _ValueAdjustmentsAdminPage(); +} + +class _ValueAdjustmentsAdminPage extends State { + final items = []; + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Value Adjustment"), + centerTitle: true, + actions: [ + TextButton( + style: TextButton.styleFrom( + textStyle: const TextStyle(fontSize: 15), + ), + onPressed: () async { + try { + final result = + await ValueAdjustmentsAdminApiServices.instance.fetch(); + + // Assuming result is a List of JSON objects, convert them to City objects. + final valueAdj = result + .map((json) => ValueAdjustments.fromJson(json)) + .toList(); + + // Loop through the list of City objects and insert them into the local database. + for (ValueAdjustments valueAdjustments in valueAdj) { + await SQLServices.instance + .createValueAdjustments(valueAdjustments); + } + } catch (e) { + // Handle any errors that might occur during the API call or database insertion. + print("Error: $e"); + } + }, + child: const Text('SYNC'), + ), + ], + ), + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is ValueAdjustmentsLoaded) { + return Column(children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(15.0), + child: Column( + children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + // ignore: prefer_const_literals_to_create_immutables + columns: [ + const DataColumn( + label: Text('ID'), + ), + const DataColumn( + label: Text('Base Market Value'), + ), + const DataColumn( + label: Text('Adjustment Factor'), + ), + const DataColumn( + label: Text('Adjustment'), + ), + const DataColumn( + label: Text('Value Adjustment'), + ), + const DataColumn( + label: Text('Market Value'), + ), + ], + rows: state.valueAdjustments.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.id.toString() ?? + 'N/A')), // Use a default value if cityCode is null + DataCell(Text(dataRow.baseMarketval ?? + 'N/A')), // Use a default value if cityDescription is null + DataCell(Text( + dataRow.adjustmentFactors ?? 'N/A')), + DataCell(Text(dataRow.adjustment ?? 'N/A')), + DataCell( + Text(dataRow.valueAdjustment ?? 'N/A')), + DataCell( + Text(dataRow.marketValue ?? 'N/A')), + ], + ); + }).toList(), + ), + ) + ], + ), + ), + ), + ) + ]); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/building/add/AddBuildingAndStructure..dart b/lib/screens/offline/passo/building/add/AddBuildingAndStructure..dart new file mode 100644 index 0000000..142d952 --- /dev/null +++ b/lib/screens/offline/passo/building/add/AddBuildingAndStructure..dart @@ -0,0 +1,406 @@ +import 'dart:convert'; + +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/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/model/passo/building_and_structure.dart'; + +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +// Function to get stored building type +Future getStoredBldgType() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String? jsonString = prefs.getString('selected_bldg_type'); + if (jsonString != null) { + Map json = jsonDecode(jsonString); + return UnitConstruct.fromJson(json); + } + // Return a default UnitConstruct if no data is found + return UnitConstruct.defaultConstruct(); +} + +class AddBuildingAndStructureOffline extends StatefulWidget { + final OfflineProfile offlineProfile; + AddBuildingAndStructureOffline(this.offlineProfile); + + @override + _AddBuildingAndStructureOffline createState() => + _AddBuildingAndStructureOffline(); +} + +class _AddBuildingAndStructureOffline + extends State { + GlobalKey formKey = GlobalKey(); + final focus = FocusNode(); + + final DateTime now; + final String formatter; + + _AddBuildingAndStructureOffline() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()), + _unitConstruct = UnitConstruct.defaultConstruct(); + + final actual_use = [ + "Residential", + "Agricultural", + "Commercial", + "Industrial", + "Mineral", + "Timberland", + ]; + double _unitBase = 0; + String _structureType = ""; + double _areaValue = 0; + double _depRate = 0; + UnitConstruct _unitConstruct; + bool _isLoading = true; + + @override + void initState() { + super.initState(); + _loadData(); + } + + Future _loadData() async { + UnitConstruct unitConstruct = await getStoredBldgType(); + setState(() { + _unitConstruct = unitConstruct; + _isLoading = false; + }); + } + + double _totalMarketValue(unitBase, bldgArea) { + return unitBase * bldgArea; + } + + double _amountofDepreciation(unitBase, area, depreciation) { + return (unitBase * area) * depreciation; + } + + double _adjustedMarketValue(unitBase, area, depreciation) { + double marketVal = unitBase * area; + double depAmount = (unitBase * area) * depreciation; + return marketVal - depAmount; + } + + void assignSelectedBldgValues() async { + UnitConstruct? storedBldgType = await getStoredBldgType(); + _unitBase = double.parse(storedBldgType!.unitValue); + _structureType = '${storedBldgType.bldgType} - ${storedBldgType.building}'; + + formKey.currentState!.patchValue({'unit_value': storedBldgType.unitValue}); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + print(state); + if (state is ShowBldgAndStructuresScreen) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + return FormBuilder( + key: formKey, + onChanged: () { + formKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: SingleChildScrollView( + padding: const EdgeInsets.all(2.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: 'actual_use', + autofocus: false, + decoration: normalTextFieldStyle("Actual Use", ""), + items: actual_use + .map((item) => DropdownMenuItem( + value: item, + child: Text(item), + )) + .toList(), + onChanged: (value) { + assignSelectedBldgValues(); + }, + ), + ), + const SizedBox( + height: 10, + ), + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: SizedBox( + height: 45, + child: SearchField( + enabled: false, + itemHeight: 70, + suggestions: state.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( + _unitConstruct!.bldgType + + ' - ' + + _unitConstruct!.building, + "") + .copyWith( + suffixIcon: + const Icon(Icons.arrow_drop_down)), + ////agency suggestion tap + focusNode: focus, + suggestionState: Suggestion.expand, + onSuggestionTap: (unit) { + setState(() {}); + focus.unfocus(); + }, + ), + ), + ), + const SizedBox( + height: 10, + ), + Container( + child: FormBuilderTextField( + name: 'unit_value', + decoration: normalTextFieldStyle("Unit Value", ""), + validator: FormBuilderValidators.compose([]), + keyboardType: TextInputType.phone, + onChanged: (value) { + // setState(() { + // _areaValue = int.parse(value!); + // }); + }, + ), + ), + SizedBox( + height: 10, + ), + Row( + children: [ + Expanded( + child: FormBuilderTextField( + name: 'dep_rate', + decoration: normalTextFieldStyle( + "Depreciation Rate", ""), + keyboardType: TextInputType.phone, + validator: FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + _depRate = double.parse(value!); + }); + }, + ), + ), + const SizedBox( + width: 5, + ), + Expanded( + child: FormBuilderTextField( + name: 'bldg_area', + decoration: normalTextFieldStyle("Area", ""), + validator: FormBuilderValidators.compose([]), + keyboardType: TextInputType.phone, + onChanged: (value) { + setState(() { + _areaValue = double.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), + const 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( + _unitBase, _areaValue, _depRate)))), + ), + const SizedBox(height: 10), + const Text('Adjusted 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(_adjustedMarketValue( + _unitBase, _areaValue, _depRate)))), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + try { + final tempID = + await SharedPreferences.getInstance(); + var bldgStructure = BldgAndStructure( + id: 1, + bldgapprDetailsId: tempID.getInt( + 'tempid')!, + // assessedById: widget + // .offlineProfile.id + // .toString(), + // assessedByName: widget + // .offlineProfile.firstName, + // dateCreated: formatter, + // dateModified: 'none', + bldgType: _structureType, + structType: _structureType, + description: 'None', + buccPercentage: '1', + actualUse: formKey.currentState?.value[ + 'actual_use'] ?? + "", + floorCount: '1', + bldgArea: _areaValue.toString(), + unitValue: _unitBase.toString(), + depRate: _depRate.toString(), + marketValue: _totalMarketValue( + _unitBase, _areaValue) + .toString(), + depAmount: _amountofDepreciation( + _unitBase, _areaValue, _depRate) + .toString(), + adjustedMarketValue: + _adjustedMarketValue(_unitBase, + _areaValue, _depRate) + .toString(), + genCode: "5TH"); + context + .read() + .add(AddBuildingAndStructure( + bldgAndStructure: bldgStructure)); + } catch (e) { + print(e); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: 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 LoadBuildingAndStructure()); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ); // Use your actual widget + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/offline/passo/building/add/AddExtraItemsOffline.dart b/lib/screens/offline/passo/building/add/AddExtraItemsOffline.dart new file mode 100644 index 0000000..4a6009b --- /dev/null +++ b/lib/screens/offline/passo/building/add/AddExtraItemsOffline.dart @@ -0,0 +1,781 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:fluttertoast/fluttertoast.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/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/class_components%20_offline.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'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; + +// Function to get stored building type +Future getStoredBldgType() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String? jsonString = prefs.getString('selected_bldg_type'); + if (jsonString != null) { + Map json = jsonDecode(jsonString); + return UnitConstruct.fromJson(json); + } + // Return a default UnitConstruct if no data is found + return UnitConstruct.defaultConstruct(); +} + +class AddExtraItemsOffline extends StatefulWidget { + final OfflineProfile offlineProfile; + AddExtraItemsOffline(this.offlineProfile); + + @override + _AddExtraItemsOffline createState() => _AddExtraItemsOffline(); +} + +class _AddExtraItemsOffline extends State { + GlobalKey formKey = GlobalKey(); + final focus = FocusNode(); + final focusAddItems = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + double _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _className = ""; + int _classId = 0; + String _structureType = ""; + bool _withoutBUCC = false; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + + final DateTime now; + final String formatter; + + _AddExtraItemsOffline() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()), + _unitConstruct = UnitConstruct.defaultConstruct(); + + UnitConstruct _unitConstruct; + + bool _isLoading = true; + + @override + void initState() { + super.initState(); + _loadData(); + } + + Future _loadData() async { + UnitConstruct unitConstruct = await getStoredBldgType(); + setState(() { + _unitConstruct = unitConstruct; + _isLoading = false; + }); + } + + 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(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); + } + } + + double _calculateMarketValue(unitVal, unitBase, area, withBUCC) { + if (withBUCC == false) { + return ((unitVal * unitBase) * area); + } else { + return (unitVal * area); + } + } + + void assignSelectedBldgValues() async { + UnitConstruct? storedBldgType = await getStoredBldgType(); + if (_withoutBUCC) { + _unitBase = _unitValue; + _structureType = + storedBldgType!.bldgType + ' - ' + storedBldgType.building; + formKey.currentState!.patchValue({'buccValue': '100'}); + } else { + _unitBase = double.parse(storedBldgType!.unitValue); + _structureType = + storedBldgType!.bldgType + ' - ' + storedBldgType.building; + ; + formKey.currentState!.patchValue({'unitValue': storedBldgType.unitValue}); + } + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowAddItemsScreen) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is ClassComponentsAdminLoaded) { + final classes = state.classes; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + return FormBuilder( + key: formKey, + onChanged: () { + formKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: SingleChildScrollView( + padding: const EdgeInsets.all(2.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: SizedBox( + height: 45, + child: SearchField( + itemHeight: 70, + suggestions: classes + .map((ClassComponentsOffline clss) => + SearchFieldListItem( + '${clss.componentName}', + item: clss, + child: ListTile( + title: Text( + '${clss.componentName}', + overflow: + TextOverflow.ellipsis, + ), + ))) + .toList(), + + validator: FormBuilderValidators.required( + errorText: "This field is required"), + + searchInputDecoration: normalTextFieldStyle( + "Additional Improvements", "") + .copyWith( + suffixIcon: const Icon( + Icons.arrow_drop_down)), + ////agency suggestion tap + focusNode: focusAddItems, + suggestionState: Suggestion.expand, + onSuggestionTap: (value) { + setState(() { + if (value.item!.minBaseUnitvalPercent != + '0.00') { + setState(() { + _unitValue = double.parse(value + .item!.minBaseUnitvalPercent!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': value + .item!.minBaseUnitvalPercent + }); + formKey.currentState!.patchValue({ + 'buccValue': (double.parse(value + .item! + .minBaseUnitvalPercent!) * + 100) + .toString() + }); + } + if (value.item!.maxBaseUnitvalPercent != + '0.00') { + setState(() { + _unitValue = double.parse(value + .item!.maxBaseUnitvalPercent!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': value + .item!.maxBaseUnitvalPercent + }); + formKey.currentState!.patchValue({ + 'buccValue': (double.parse(value + .item! + .maxBaseUnitvalPercent!) * + 100) + .toString() + }); + } + if (value.item!.minUnitvalSqrmtr != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.minUnitvalSqrmtr!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.minUnitvalSqrmtr + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.item!.maxUnitvalSqrmtr != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.maxUnitvalSqrmtr!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.maxUnitvalSqrmtr + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.item!.minAddBaseunitval != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.minAddBaseunitval!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.minAddBaseunitval + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.item!.maxAddBaseunitval != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.maxAddBaseunitval!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.maxAddBaseunitval + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.item!.minDeductBaserate != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.minDeductBaserate!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.minDeductBaserate + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.item!.maxDeductBaserate != + '0.00') { + setState(() { + _unitValue = double.parse( + value.item!.maxDeductBaserate!); + _className = + value.item!.componentName!; + _classId = value.item!.id!; + _withoutBUCC = + value.item!.withoutBucc == 1 + ? true + : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': + value.item!.maxDeductBaserate + }); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + assignSelectedBldgValues(); + focusAddItems.unfocus(); + }); + }, + ), + ), + ), + const SizedBox(height: 10), + Container( + margin: const EdgeInsets.only( + left: 0, top: 10, right: 0, bottom: 0), + child: SizedBox( + height: 45, + child: SearchField( + enabled: false, + itemHeight: 70, + suggestions: state.unit + .map((UnitConstruct unit) => + SearchFieldListItem( + _unitConstruct.bldgType + + ' - ' + + _unitConstruct.building, + item: unit, + child: ListTile( + title: Text( + _unitConstruct.bldgType + + ' - ' + + _unitConstruct.building, + overflow: + TextOverflow.ellipsis, + ), + ))) + .toList(), + + validator: FormBuilderValidators.required( + errorText: "This field is required"), + + searchInputDecoration: normalTextFieldStyle( + _unitConstruct.bldgType + + ' - ' + + _unitConstruct.building, + "") + .copyWith( + suffixIcon: const Icon( + Icons.arrow_drop_down)), + ////agency suggestion tap + focusNode: focus, + suggestionState: Suggestion.expand, + onSuggestionTap: (unit) { + setState(() {}); + focus.unfocus(); + }, + ), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'unitValue', + decoration: normalTextFieldStyle( + "Unit Value", ""), + keyboardType: TextInputType.phone, + validator: + FormBuilderValidators.compose([]), + ), + ), + const SizedBox(width: 10), + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'buccValue', + decoration: + normalTextFieldStyle("BUCC", ""), + keyboardType: TextInputType.phone, + validator: + FormBuilderValidators.compose([]), + onChanged: (value) { + // setState(() { + // _areaValue = double.parse(value!); + // }); + }, + ), + ), + const SizedBox( + height: 40, + width: 40, + child: Center( + child: Text( + '%', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold), + ), + ), + ) + ], + ), + SizedBox( + height: 10, + ), + Row( + children: [ + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'areaValue', + decoration: + normalTextFieldStyle("Area", ""), + keyboardType: TextInputType.phone, + validator: + FormBuilderValidators.compose([]), + onChanged: (value) { + setState(() { + _areaValue = double.parse(value!); + }); + }, + ), + ), + ], + ), + Visibility( + visible: !_withoutBUCC, + child: Column( + children: [ + const SizedBox(height: 10), + const 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), + const 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', + keyboardType: + TextInputType.phone, + 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), + ), + ), + ) + ], + ), + ], + ), + ), + ], + ), + ), + 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( + _unitValue, + _unitBase, + _areaValue, + _depValue, + _withoutBUCC, + _className, + isPainted, + isSecondHand, + _notPaintedUnitVal, + _secondHandUnitVal)))), + ), + const SizedBox(height: 40), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Container( + width: 120, + height: 60, + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: () async { + try { + final tempID = await SharedPreferences + .getInstance(); + + context.read().add( + AddAdditionalItems( + id: 1, + bldgapprDetailsId: + tempID.getInt('tempid')!, + classId: _classId, + assessedById: widget + .offlineProfile.id + .toString(), + assessedByName: widget + .offlineProfile + .firstName!, + dateCreated: formatter, + dateModified: 'None', + className: _className, + structType: _structureType, + unitValue: _withoutBUCC == true + ? 100 + : _unitValue * 100, + baseUnitValue: _unitBase, + area: _areaValue, + marketValue: + _calculateMarketValue( + _unitValue, + _unitBase, + _areaValue, + _withoutBUCC), + 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', + genCode: "5th")); + } catch (e) { + Fluttertoast.showToast( + msg: + "Slow internet connection, please try again!", + ); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: 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 LoadAdditionalItems()); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + )); // Use your actual widget + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + // if (state is Add) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add(LoadAdditionalItems()); + // }, + // ); + // } + return Container(); + }); + } +} diff --git a/lib/screens/offline/passo/building/add/add_building.dart b/lib/screens/offline/passo/building/add/add_building.dart new file mode 100644 index 0000000..d01fb99 --- /dev/null +++ b/lib/screens/offline/passo/building/add/add_building.dart @@ -0,0 +1,318 @@ +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:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/building_and_structure.dart'; +import 'package:unit2/screens/offline/passo/building/add/drawing_pad.dart'; +import 'package:unit2/screens/offline/passo/building/add/flutter_painter.dart'; +import 'package:unit2/screens/offline/passo/building/add/imagePicker.dart'; +import 'package:unit2/screens/offline/passo/building/add/property_appraisal.dart'; +import 'package:unit2/screens/offline/passo/building/add/property_assessment.dart'; +import 'package:unit2/screens/offline/passo/building/add/property_owner_info.dart'; +import 'package:unit2/screens/offline/passo/building/add/additional_items.dart'; +import 'package:unit2/screens/offline/passo/building/add/general_description.dart'; +import 'package:unit2/screens/offline/passo/building/add/landref_location.dart'; +import 'package:unit2/screens/offline/passo/building/add/structural_material.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../../bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; +import '../../../../../model/passo/property_info.dart'; +import '../../../../../utils/alerts.dart'; + +GlobalKey offlineBldgKey = GlobalKey(); + +class AddBuilding extends StatefulWidget { + Function triggerBlocEvent; + final OfflineProfile offlineProfile; + AddBuilding(this.triggerBlocEvent, this.offlineProfile); + @override + _AddBuilding createState() => _AddBuilding(); +} + +class _AddBuilding extends State { + int activeStep = 0; // Initial step set to 5. + int upperBound = 7; + + List foundation = []; + List column = []; + List beam = []; + List trussFraming = []; + 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; + + String bldgType = ""; + String bldgKind = "Structure type"; + String unitValue = ""; + + void PrevBtn() { + setState(() { + activeStep--; + }); + } + + void NextBtn() { + setState(() { + activeStep++; + }); + } + + void updateFoundation(List updatedList) { + setState(() { + foundation = updatedList; + }); + } + + void updateColumn(List updatedList) { + setState(() { + column = updatedList; + }); + } + + void updateBeam(List updatedList) { + setState(() { + beam = updatedList; + }); + } + + void updateTrussFraming(List updatedList) { + setState(() { + trussFraming = updatedList; + }); + } + + void updateRoof(List updatedList) { + setState(() { + roof = updatedList; + }); + } + + void updateFlooring(List updatedList) { + setState(() { + flooring = updatedList; + }); + } + + void updateWalls(List updatedList) { + setState(() { + walls = updatedList; + }); + } + + void updateFoundationOthers(bool updatedOthers) { + setState(() { + foundationOthers = updatedOthers; + }); + } + + void updateColumOthers(bool updatedOthers) { + setState(() { + columOthers = updatedOthers; + }); + } + + void updateBeamsOthers(bool updatedOthers) { + setState(() { + beamsOthers = updatedOthers; + }); + } + + void updateTfOthers(bool updatedOthers) { + setState(() { + tfOthers = updatedOthers; + }); + } + + void updateRoofOthers(bool updatedOthers) { + setState(() { + roofOthers = updatedOthers; + }); + } + + void updateFlooringOthers(bool updatedOthers) { + setState(() { + flooringOthers = updatedOthers; + }); + } + + void updateWpOthers(bool updatedOthers) { + setState(() { + wpOthers = updatedOthers; + }); + } + + void updatedBldgType(dynamic updatedBldgType) { + setState(() { + bldgType = updatedBldgType; + }); + } + + void updatedBldgKind(dynamic updatedBldgKind) { + setState(() { + bldgKind = updatedBldgKind; + }); + } + + void updatedUnitValue(dynamic updatedUnitValue) { + setState(() { + unitValue = updatedUnitValue; + }); + } + + @override + Widget build(BuildContext context) { + print(widget.offlineProfile.toJson()); + return WillPopScope( + onWillPop: () async { + confirmAlertWithCancel( + context, + onCloseTransaction, + () => null, + 'Cancel transaction?', + "Are you sure you want to cancel this transaction?"); // Action to perform on back pressed + return false; + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: primary, + centerTitle: true, + title: const Text("Offline Building FAAS"), + ), + body: Column(children: [ + NumberStepper( + numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9], + stepPadding: 5, + 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: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return FormBuilder( + key: offlineBldgKey, + onChanged: () { + offlineBldgKey.currentState?.save(); + }, + autovalidateMode: AutovalidateMode.disabled, + child: Container( + child: content(PrevBtn, NextBtn), + ), + ); + }), + ), + ]), + ), + ); + } + + Widget content(PrevBtn, NextBtn) { + switch (activeStep) { + case 0: + return PropertyInfoOfflinePage(NextBtn, widget.offlineProfile); + + case 1: + return LandRefLocationOfflinePage( + PrevBtn, NextBtn, widget.offlineProfile); + + case 2: + return GeneralDescriptionOfflinePage( + NextBtn, + PrevBtn, + widget.offlineProfile, + bldgKind, + bldgType, + unitValue, + updatedUnitValue, + updatedBldgKind, + updatedBldgType); + case 3: + return FlutterDraw(); + + case 4: + return BuildingAndStructureOfflinePage( + PrevBtn, NextBtn, widget.offlineProfile); + + case 5: + return StatefulBuilder( + builder: (context, StateSetter setInnerState) => + StructuralMaterialsOfflinePage( + PrevBtn, + NextBtn, + foundationOthers: foundationOthers, + columOthers: columOthers, + beamsOthers: beamsOthers, + tfOthers: tfOthers, + roofOthers: roofOthers, + flooringOthers: flooringOthers, + wpOthers: wpOthers, + foundation: foundation, + column: column, + beam: beam, + trussFraming: trussFraming, + roof: roof, + flooring: flooring, + walls: walls, + updateFoundation: updateFoundation, + updateColumn: updateColumn, + updateBeam: updateBeam, + updateFlooring: updateFlooring, + updateRoof: updateRoof, + updateTrussFraming: updateTrussFraming, + updateWalls: updateWalls, + updateFoundationOthers: updateFoundationOthers, + updateColumOthers: updateColumOthers, + updateBeamsOthers: updateBeamsOthers, + updateTfOthers: updateTfOthers, + updateRoofOthers: updateRoofOthers, + updateFlooringOthers: updateFlooringOthers, + updateWpOthers: updateWpOthers, + )); + + case 6: + return AdditionalItemOfflinePage( + PrevBtn, NextBtn, widget.offlineProfile); + + case 7: + return PropertyAppraisalOfflinePage( + NextBtn, PrevBtn, widget.offlineProfile); + + case 8: + return PropertyAssessmentOfflinePage( + onCloseTransaction, widget.offlineProfile); + + default: + return Text("Property Info"); + } + } + + void onCloseTransaction() async { + final tempID = await SharedPreferences.getInstance(); + Navigator.of(context).pop(); + WidgetsBinding.instance.addPostFrameCallback((_) { + widget.triggerBlocEvent(); + }); + await tempID.setBool('floorSketchSaved', false); + } +} diff --git a/lib/screens/offline/passo/building/add/additional_items.dart b/lib/screens/offline/passo/building/add/additional_items.dart new file mode 100644 index 0000000..3b3bf1d --- /dev/null +++ b/lib/screens/offline/passo/building/add/additional_items.dart @@ -0,0 +1,310 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/AddExtraItemsOffline.dart'; + +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class AdditionalItemOfflinePage extends StatefulWidget { + final VoidCallback additionalItemsPrevBtn; + final VoidCallback additionalItemsNextBtn; + final OfflineProfile offlineProfile; + + const AdditionalItemOfflinePage(this.additionalItemsPrevBtn, + this.additionalItemsNextBtn, this.offlineProfile); + + @override + _AdditionalItemOfflinePage createState() => _AdditionalItemOfflinePage(); +} + +class _AdditionalItemOfflinePage extends State { + // void deleteItem(int itemId) { + // context.read().add(DeleteAdditionalItems(id: itemId)); + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteAdditionalItems(id: itemId)); + } + + final items = []; + + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += row.adjustedMarketVal; + }); + return total; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is AdditionalItemsOfflineInitial) { + 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), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowAdditionalItems()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ) + ])))) + ]); + } + if (state is AdditionalItemsLoaded) { + 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), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + context + .read() + .add(ShowAdditionalItems()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + 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('Area'), + ), + const DataColumn( + label: Text('% of BUCC'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.addItem.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.className)), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(dataRow.baseUnitValue).toString())), + DataCell(Text(dataRow.area.toString())), + DataCell(Text(dataRow.unitValue.toString())), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ) + .format(((double.parse( + dataRow.adjustedMarketVal.toString())))) + .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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).toList(), + ), + ) + ], + ), + ), + )), + Padding( + padding: const EdgeInsets.only(left: 20.0, right: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total Market Value', + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ), + Text( + NumberFormat.currency(locale: 'en-PH', symbol: "₱") + .format(_totalMarketValue(state.addItem)), + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ) + ], + ), + ), + 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) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(LoadAdditionalItems()); + }); + }); + } + } + if (state is ShowAddItemsScreen) { + return showDialog(context); + } + return Container(); + }, + )); + } + + Widget showDialog(BuildContext context) { + return AlertDialog( + insetPadding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 20.0, + ), + title: const Text( + 'ADD ADDITIONAL ITEMS', + textAlign: TextAlign.center, + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AddExtraItemsOffline(widget.offlineProfile), + ], + ), + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/add/building_and_structure.dart b/lib/screens/offline/passo/building/add/building_and_structure.dart new file mode 100644 index 0000000..f08b1bf --- /dev/null +++ b/lib/screens/offline/passo/building/add/building_and_structure.dart @@ -0,0 +1,337 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/AddBuildingAndStructure..dart'; + +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class BuildingAndStructureOfflinePage extends StatefulWidget { + final VoidCallback additionalItemsPrevBtn; + final VoidCallback additionalItemsNextBtn; + final OfflineProfile offlineProfile; + + const BuildingAndStructureOfflinePage(this.additionalItemsPrevBtn, + this.additionalItemsNextBtn, this.offlineProfile); + + @override + _BuildingAndStructureOfflinePage createState() => + _BuildingAndStructureOfflinePage(); +} + +class _BuildingAndStructureOfflinePage + extends State { + // void deleteItem(int itemId) { + // context.read().add(DeleteAdditionalItems(id: itemId)); + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteBuildingAndStructure(id: itemId)); + } + + final items = []; + + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketValue); + }); + return total; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is BuildingAndStructureOfflineInitial) { + 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('BUILDING AND STRUCTURE', + 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(ShowBuildingAndStructure()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD NEW'), // <-- Text + SizedBox( + width: 5, + ), + Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ) + ])))) + ]); + } + if (state is BuildingAndStructureLoaded) { + 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('BUILDING AND STRUCTURES', + 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(ShowBuildingAndStructure()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + 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('Building Core'), + ), + const DataColumn( + label: Text('Type'), + ), + const DataColumn( + label: Text('Area'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('% of BUCC'), + ), + const DataColumn( + label: Text('Base Market Value'), + ), + const DataColumn( + label: Text('% of Depreciation'), + ), + const DataColumn( + label: Text('Depreciation Cost'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.bldgAndStructure.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.actualUse!)), + DataCell(Text(dataRow.bldgType!)), + DataCell(Text(dataRow.bldgArea!)), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse(dataRow.unitValue!)), + )), + const DataCell(Text("100%")), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format( + double.parse(dataRow.marketValue!)), + )), + DataCell(Text(dataRow.depRate!)), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse(dataRow.depAmount!)), + )), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse( + dataRow.adjustedMarketValue!)), + )), + 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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).toList(), + ), + ) + ], + ), + ), + )), + Padding( + padding: const EdgeInsets.only(left: 20.0, right: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total Market Value', + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ), + Text( + NumberFormat.currency(locale: 'en-PH', symbol: "₱") + .format(_totalMarketValue(state.bldgAndStructure)), + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ) + ], + ), + ), + 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 BuildingAndStructureDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(LoadBuildingAndStructure()); + }); + }); + } + } + if (state is ShowBldgAndStructuresScreen) { + return showDialog( + context); // Placeholder return; replace with your desired widget + } + return Container(); + }, + )); + } + + Widget showDialog(BuildContext context) { + return AlertDialog( + insetPadding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 20.0, + ), + title: const Text( + 'ADD NEW BLDG & STRUCTURE', + textAlign: TextAlign.center, + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AddBuildingAndStructureOffline(widget.offlineProfile), + ], + ), + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/add/drawing_pad.dart b/lib/screens/offline/passo/building/add/drawing_pad.dart new file mode 100644 index 0000000..8f7d2c2 --- /dev/null +++ b/lib/screens/offline/passo/building/add/drawing_pad.dart @@ -0,0 +1,463 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_drawing_board/flutter_drawing_board.dart'; +import 'package:flutter_drawing_board/paint_contents.dart'; +import 'package:flutter_drawing_board/paint_extension.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:unit2/utils/request_permission.dart'; +import 'package:http/http.dart'; +import 'package:unit2/utils/urls.dart'; // Removed 'as http' + +// import 'test_data.dart'; + +Future _getImage(String path) async { + final Completer completer = Completer(); + final NetworkImage img = NetworkImage(path); + img.resolve(ImageConfiguration.empty).addListener( + ImageStreamListener((ImageInfo info, _) { + completer.complete(info); + }), + ); + + final ImageInfo imageInfo = await completer.future; + + return imageInfo.image; +} + +const Map _testLine1 = { + 'type': 'StraightLine', + 'startPoint': { + 'dx': 68.94337550070736, + 'dy': 62.05980083656557 + }, + 'endPoint': { + 'dx': 277.1373386828114, + 'dy': 277.32029957032194 + }, + 'paint': { + 'blendMode': 3, + 'color': 4294198070, + 'filterQuality': 3, + 'invertColors': false, + 'isAntiAlias': false, + 'strokeCap': 1, + 'strokeJoin': 1, + 'strokeWidth': 4.0, + 'style': 1 + } +}; + +const Map _testLine2 = { + 'type': 'StraightLine', + 'startPoint': { + 'dx': 106.35164817830423, + 'dy': 255.9575653134524 + }, + 'endPoint': { + 'dx': 292.76034659254094, + 'dy': 92.125586665872 + }, + 'paint': { + 'blendMode': 3, + 'color': 4294198070, + 'filterQuality': 3, + 'invertColors': false, + 'isAntiAlias': false, + 'strokeCap': 1, + 'strokeJoin': 1, + 'strokeWidth': 4.0, + 'style': 1 + } +}; + +/// Custom drawn triangles +class Triangle extends PaintContent { + Triangle(); + + Triangle.data({ + required this.startPoint, + required this.A, + required this.B, + required this.C, + required Paint paint, + }) : super.paint(paint); + + factory Triangle.fromJson(Map data) { + return Triangle.data( + startPoint: jsonToOffset(data['startPoint'] as Map), + A: jsonToOffset(data['A'] as Map), + B: jsonToOffset(data['B'] as Map), + C: jsonToOffset(data['C'] as Map), + paint: jsonToPaint(data['paint'] as Map), + ); + } + + Offset startPoint = Offset.zero; + + Offset A = Offset.zero; + Offset B = Offset.zero; + Offset C = Offset.zero; + + @override + void startDraw(Offset startPoint) => this.startPoint = startPoint; + + @override + void drawing(Offset nowPoint) { + A = Offset( + startPoint.dx + (nowPoint.dx - startPoint.dx) / 2, startPoint.dy); + B = Offset(startPoint.dx, nowPoint.dy); + C = nowPoint; + } + + @override + void draw(Canvas canvas, Size size, bool deeper) { + final Path path = Path() + ..moveTo(A.dx, A.dy) + ..lineTo(B.dx, B.dy) + ..lineTo(C.dx, C.dy) + ..close(); + + canvas.drawPath(path, paint); + } + + @override + Triangle copy() => Triangle(); + + @override + Map toContentJson() { + return { + 'startPoint': startPoint.toJson(), + 'A': A.toJson(), + 'B': B.toJson(), + 'C': C.toJson(), + 'paint': paint.toJson(), + }; + } +} + +/// Custom drawn image +/// url: https://web-strapi.mrmilu.com/uploads/flutter_logo_470e9f7491.png +const String _imageUrl = + 'https://web-strapi.mrmilu.com/uploads/flutter_logo_470e9f7491.png'; + +class ImageContent extends PaintContent { + ImageContent(this.image, {this.imageUrl = ''}); + + ImageContent.data({ + required this.startPoint, + required this.size, + required this.image, + required this.imageUrl, + required Paint paint, + }) : super.paint(paint); + + factory ImageContent.fromJson(Map data) { + return ImageContent.data( + startPoint: jsonToOffset(data['startPoint'] as Map), + size: jsonToOffset(data['size'] as Map), + imageUrl: data['imageUrl'] as String, + image: data['image'] as ui.Image, + paint: jsonToPaint(data['paint'] as Map), + ); + } + + Offset startPoint = Offset.zero; + Offset size = Offset.zero; + final String imageUrl; + final ui.Image image; + + @override + void startDraw(Offset startPoint) => this.startPoint = startPoint; + + @override + void drawing(Offset nowPoint) => size = nowPoint - startPoint; + + @override + void draw(Canvas canvas, Size size, bool deeper) { + final Rect rect = Rect.fromPoints(startPoint, startPoint + this.size); + paintImage(canvas: canvas, rect: rect, image: image, fit: BoxFit.fill); + } + + @override + ImageContent copy() => ImageContent(image); + + @override + Map toContentJson() { + return { + 'startPoint': startPoint.toJson(), + 'size': size.toJson(), + 'imageUrl': imageUrl, + 'paint': paint.toJson(), + }; + } +} + +class DrawingScreen extends StatelessWidget { + const DrawingScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Drawing Test', + theme: ThemeData(primarySwatch: Colors.blue), + home: const MyHomePage(), + ); + } +} + +class MyHomePage extends StatefulWidget { + const MyHomePage({Key? key}) : super(key: key); + + @override + State createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + /// 绘制控制器 + final DrawingController _drawingController = DrawingController(); + + final TransformationController _transformationController = + TransformationController(); + + final GlobalKey _repaintBoundaryKey = GlobalKey(); + + File? _image; + + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + @override + void dispose() { + _drawingController.dispose(); + super.dispose(); + } + + /// 获取画板数据 `getImageData()` + Future _getImageData() async { + final Uint8List? data = + (await _drawingController.getImageData())?.buffer.asUint8List(); + if (data == null) { + debugPrint('获取图片数据失败'); + return; + } + + if (mounted) { + showDialog( + context: context, + builder: (BuildContext c) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () => Navigator.pop(c), child: Image.memory(data)), + ); + }, + ); + } + } + + Future _saveImageToDevice(Uint8List data) async { + // Get the temporary directory + final directory = await getTemporaryDirectory(); + final tempDirectory = directory.path; + + // Create a file path in the temporary directory + final filePath = '$tempDirectory/181.png'; + final file = File(filePath); + + // Write the image bytes to the file + await file.writeAsBytes(data); + + // Return the file path + print(filePath); + return filePath; + } + + Future _saveAndShowImage() async { + final Uint8List? data = + (await _drawingController.getImageData())?.buffer.asUint8List(); + if (data == null) { + debugPrint('Failed to get image data'); + return; + } + + final path = await _saveImageToDevice(data); + + if (mounted) { + showDialog( + context: context, + builder: (BuildContext c) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () => Navigator.pop(c), child: Image.memory(data)), + ); + }, + ); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image saved to $path')), + ); + } + } + + Future _showImage() async { + showDialog( + context: context, + builder: (BuildContext c) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () => Navigator.pop(c), + child: + Image.file(File('/data/user/0/com.app.rpass/cache/img.png'))), + ); + }, + ); + } + + void _restBoard() { + _transformationController.value = Matrix4.identity(); + } + + Future _postBuildingDetails(Map details) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + // Construct the headers for the request + Map headers = { + 'Content-Type': 'multipart/form-data', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret, + }; + + // Create a MultipartRequest + var request = MultipartRequest( + 'POST', + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/bldgappr_sketch/'), + ); + + // Add the headers to the request + request.headers.addAll(headers); + + // Add JSON data as a field + // Add individual fields to the request + details.forEach((key, value) { + request.fields[key] = value.toString(); + }); + + var file = File(imagePath); + // Add the floor sketch image file, if it exists + + request.files.add( + await MultipartFile.fromPath( + 'floor_sketch', // Field name in the API + file.path, + filename: file.path, + ), + ); + + // Send the request and get the response + var streamedResponse = await request.send(); + return await Response.fromStream(streamedResponse); + } + + Future _uploadImage() async { + // Create a map with the required fields + var file = File(imagePath); + Map detailsMap = { + "bldgappr_details_id": 182, // int8 NOT NULL + "date_created": DateTime.now().toIso8601String(), // timestamptz NULL + "floor_sketch": file.path, // text NULL + "gen_code": "5TH", // varchar(20) NOT NULL + }; + + try { + Response response = await _postBuildingDetails(detailsMap); + print(response.body); + + if (response.statusCode == 201) { + print('Upload successful'); + } else { + print('Upload failed with status: ${response.statusCode}'); + } + } catch (e) { + print('Error: $e'); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + resizeToAvoidBottomInset: false, + backgroundColor: Colors.white, + body: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + icon: const Icon(Icons.delete_rounded), + color: Colors.red, + iconSize: 38, + tooltip: 'Open shopping cart', + onPressed: () { + _showImage(); + }, + ), + IconButton( + icon: const Icon(Icons.check_circle), + color: Colors.red, + iconSize: 35, + tooltip: 'Open shopping cart', + onPressed: () { + _saveAndShowImage(); + }, + ), + ], + ), + Expanded( + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return RepaintBoundary( + key: _repaintBoundaryKey, + child: DrawingBoard( + // boardPanEnabled: false, + // boardScaleEnabled: false, + transformationController: _transformationController, + controller: _drawingController, + background: Container( + width: constraints.maxWidth, + height: constraints.maxHeight, + color: Colors.grey, + ), + showDefaultActions: true, + showDefaultTools: true, + + defaultToolsBuilder: (Type t, _) { + return DrawingBoard.defaultTools(t, _drawingController) + ..insert( + 1, + DefToolItem( + icon: Icons.change_history_rounded, + isActive: t == Triangle, + onTap: () => + _drawingController.setPaintContent(Triangle()), + ), + ); + }, + ), + ); + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/add/flutter_painter.dart b/lib/screens/offline/passo/building/add/flutter_painter.dart new file mode 100644 index 0000000..20ccb54 --- /dev/null +++ b/lib/screens/offline/passo/building/add/flutter_painter.dart @@ -0,0 +1,818 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:ui'; + +import 'package:http/http.dart'; // Removed 'as http' +import 'package:path/path.dart'; // For basename function +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_painter_v2/flutter_painter.dart'; +import 'package:flutter_painter_v2/flutter_painter_extensions.dart'; +import 'package:flutter_painter_v2/flutter_painter_pure.dart'; + +import 'package:path_provider/path_provider.dart'; + +import 'dart:ui' as ui; + +import 'package:phosphor_flutter/phosphor_flutter.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/floor_sketch.dart'; + +import 'package:unit2/utils/urls.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class FlutterDraw extends StatefulWidget { + const FlutterDraw({Key? key}) : super(key: key); + + @override + _FlutterPainterExampleState createState() => _FlutterPainterExampleState(); +} + +class _FlutterPainterExampleState extends State { + static const Color red = Color.fromARGB(255, 0, 0, 0); + FocusNode textFocusNode = FocusNode(); + late PainterController controller; + ui.Image? backgroundImage; + Paint shapePaint = Paint() + ..strokeWidth = 5 + ..color = Colors.black + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + File? _image; + + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + static const List imageLinks = [ + "https://i.imgur.com/btoI5OX.png", + "https://i.imgur.com/EXTQFt7.png", + "https://i.imgur.com/EDNjJYL.png", + "https://i.imgur.com/uQKD6NL.png", + "https://i.imgur.com/cMqVRbl.png", + "https://i.imgur.com/1cJBAfI.png", + "https://i.imgur.com/eNYfHKL.png", + "https://i.imgur.com/c4Ag5yt.png", + "https://i.imgur.com/GhpCJuf.png", + "https://i.imgur.com/XVMeluF.png", + "https://i.imgur.com/mt2yO6Z.png", + "https://i.imgur.com/rw9XP1X.png", + "https://i.imgur.com/pD7foZ8.png", + "https://i.imgur.com/13Y3vp2.png", + "https://i.imgur.com/ojv3yw1.png", + "https://i.imgur.com/f8ZNJJ7.png", + "https://i.imgur.com/BiYkHzw.png", + "https://i.imgur.com/snJOcEz.png", + "https://i.imgur.com/b61cnhi.png", + "https://i.imgur.com/FkDFzYe.png", + "https://i.imgur.com/P310x7d.png", + "https://i.imgur.com/5AHZpua.png", + "https://i.imgur.com/tmvJY4r.png", + "https://i.imgur.com/PdVfGkV.png", + "https://i.imgur.com/1PRzwBf.png", + "https://i.imgur.com/VeeMfBS.png", + ]; + + @override + void initState() { + super.initState(); + controller = PainterController( + settings: PainterSettings( + text: TextSettings( + focusNode: textFocusNode, + textStyle: const TextStyle( + fontWeight: FontWeight.bold, color: red, fontSize: 18), + ), + freeStyle: const FreeStyleSettings( + color: red, + strokeWidth: 5, + ), + shape: ShapeSettings( + paint: shapePaint, + ), + scale: const ScaleSettings( + enabled: true, + minScale: 1, + maxScale: 5, + ))); + // Listen to focus events of the text field + textFocusNode.addListener(onFocus); + // Initialize background + initBackground(); + } + + /// Fetches image from an [ImageProvider] (in this example, [NetworkImage]) + /// to use it as a background + void initBackground() async { + final prefs = await SharedPreferences.getInstance(); + final floorSketchSaved = prefs.getBool('floorSketchSaved') ?? false; + final tempID = prefs.getInt('tempid'); + + print(floorSketchSaved); + + ui.Image image; + + if (floorSketchSaved && tempID != null) { + final String imagePath = '/data/user/0/com.app.rpass/cache/$tempID.png'; + image = await _loadImageFromPath(imagePath); + } else { + image = await const AssetImage('assets/pngs/white_bg.png').image; + } + + setState(() { + backgroundImage = image; + controller.background = image.backgroundDrawable; + }); + } + + /// Updates UI when the focus changes + void onFocus() { + setState(() {}); + } + + Future _loadImageFromPath(String imagePath) async { + final file = File(imagePath); + final bytes = await file.readAsBytes(); + final Completer completer = Completer(); + ui.decodeImageFromList(bytes, (ui.Image img) { + completer.complete(img); + }); + return completer.future; + } + + Future deleteImage(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + final tempID = prefs.getInt('tempid'); + if (tempID != null) { + final String imagePath = '/data/user/0/com.app.rpass/cache/$tempID.png'; + final file = File(imagePath); + + if (await file.exists()) { + await file.delete(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image deleted successfully')), + ); + + final image = await const AssetImage('assets/pngs/white_bg.png').image; + setState(() { + backgroundImage = image; + controller.background = image.backgroundDrawable; + }); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image does not exist')), + ); + } + } + } + + Widget buildDefault(BuildContext context) { + return Scaffold( + appBar: PreferredSize( + preferredSize: const Size(double.infinity, kToolbarHeight), + // Listen to the controller and update the UI when it updates. + child: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, child) { + return AppBar( + title: child, + automaticallyImplyLeading: false, // Disable the back button + + actions: [ + // Delete the selected drawable + IconButton( + icon: const Icon( + PhosphorIcons.trash, + ), + onPressed: controller.selectedObjectDrawable == null + ? null + : removeSelectedDrawable, + ), + // Delete the selected drawable + IconButton( + icon: const Icon( + Icons.flip, + ), + onPressed: controller.selectedObjectDrawable != null && + controller.selectedObjectDrawable is ImageDrawable + ? flipSelectedImageDrawable + : null, + ), + // Redo action + IconButton( + icon: const Icon( + PhosphorIcons.arrowClockwise, + ), + onPressed: controller.canRedo ? redo : null, + ), + // Undo action + IconButton( + icon: const Icon( + PhosphorIcons.arrowCounterClockwise, + ), + onPressed: controller.canUndo ? undo : null, + ), + ], + ); + }), + ), + // Generate image + floatingActionButton: Stack( + children: [ + Align( + alignment: Alignment.bottomRight, + child: FloatingActionButton( + heroTag: 'btn1', + child: const Icon( + PhosphorIcons.imageFill, + ), + onPressed: () => renderAndDisplayImage(context), + ), + ), + Align( + alignment: Alignment.bottomRight, + child: Padding( + padding: const EdgeInsets.only(bottom: 60.0), + child: FloatingActionButton( + heroTag: 'btn2', + child: const Icon( + Icons.delete, + ), + onPressed: () => deleteImage(context), + ), + ), + ), + // Add more FloatingActionButton widgets here if needed + ], + ), + body: Stack( + children: [ + if (backgroundImage != null) + // Enforces constraints + Positioned.fill( + child: Center( + child: AspectRatio( + aspectRatio: + backgroundImage!.width / backgroundImage!.height, + child: FlutterPainter( + controller: controller, + ), + ), + ), + ), + Positioned( + bottom: 0, + right: 0, + left: 0, + child: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, __) => Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Flexible( + child: Container( + constraints: const BoxConstraints( + maxWidth: 400, + ), + padding: const EdgeInsets.symmetric(horizontal: 15), + decoration: const BoxDecoration( + borderRadius: + BorderRadius.vertical(top: Radius.circular(20)), + color: Colors.white54, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (controller.freeStyleMode != + FreeStyleMode.none) ...[ + const Divider(), + const Text("Free Style Settings"), + // Control free style stroke width + Row( + children: [ + const Expanded( + flex: 1, child: Text("Stroke Width")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 2, + max: 25, + value: controller.freeStyleStrokeWidth, + onChanged: setFreeStyleStrokeWidth), + ), + ], + ), + if (controller.freeStyleMode == + FreeStyleMode.draw) + Row( + children: [ + const Expanded( + flex: 1, child: Text("Color")), + // Control free style color hue + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + controller.freeStyleColor) + .hue, + activeColor: + controller.freeStyleColor, + onChanged: setFreeStyleColor), + ), + ], + ), + ], + if (textFocusNode.hasFocus) ...[ + const Divider(), + const Text("Text settings"), + // Control text font size + Row( + children: [ + const Expanded( + flex: 1, child: Text("Font Size")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 8, + max: 96, + value: + controller.textStyle.fontSize ?? 14, + onChanged: setTextFontSize), + ), + ], + ), + + // Control text color hue + Row( + children: [ + const Expanded(flex: 1, child: Text("Color")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + controller.textStyle.color ?? + red) + .hue, + activeColor: controller.textStyle.color, + onChanged: setTextColor), + ), + ], + ), + ], + if (controller.shapeFactory != null) ...[ + const Divider(), + const Text("Shape Settings"), + + // Control text color hue + Row( + children: [ + const Expanded( + flex: 1, child: Text("Stroke Width")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 2, + max: 25, + value: controller + .shapePaint?.strokeWidth ?? + shapePaint.strokeWidth, + onChanged: (value) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + strokeWidth: value, + ))), + ), + ], + ), + + // Control shape color hue + Row( + children: [ + const Expanded(flex: 1, child: Text("Color")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + (controller.shapePaint ?? + shapePaint) + .color) + .hue, + activeColor: (controller.shapePaint ?? + shapePaint) + .color, + onChanged: (hue) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + color: HSVColor.fromAHSV( + 1, hue, 1, 1) + .toColor(), + ))), + ), + ], + ), + + Row( + children: [ + const Expanded( + flex: 1, child: Text("Fill shape")), + Expanded( + flex: 3, + child: Center( + child: Switch( + value: (controller.shapePaint ?? + shapePaint) + .style == + PaintingStyle.fill, + onChanged: (value) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + style: value + ? PaintingStyle.fill + : PaintingStyle.stroke, + ))), + ), + ), + ], + ), + ] + ], + ), + ), + ), + ], + ), + ), + ), + ], + ), + bottomNavigationBar: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, __) => Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + // Free-style eraser + IconButton( + icon: Icon( + PhosphorIcons.eraser, + color: controller.freeStyleMode == FreeStyleMode.erase + ? Theme.of(context).primaryColor + : null, + ), + onPressed: toggleFreeStyleErase, + ), + // Free-style drawing + IconButton( + icon: Icon( + PhosphorIcons.scribbleLoop, + color: controller.freeStyleMode == FreeStyleMode.draw + ? Theme.of(context).primaryColor + : null, + ), + onPressed: toggleFreeStyleDraw, + ), + // Add text + IconButton( + icon: Icon( + PhosphorIcons.textT, + color: textFocusNode.hasFocus + ? Theme.of(context).primaryColor + : null, + ), + onPressed: addText, + ), + // Add sticker image + IconButton( + icon: const Icon( + PhosphorIcons.sticker, + ), + onPressed: () => addSticker(context), + ), + // Add shapes + if (controller.shapeFactory == null) + PopupMenuButton( + tooltip: "Add shape", + itemBuilder: (context) => { + LineFactory(): "Line", + ArrowFactory(): "Arrow", + DoubleArrowFactory(): "Double Arrow", + RectangleFactory(): "Rectangle", + OvalFactory(): "Oval", + } + .entries + .map((e) => PopupMenuItem( + value: e.key, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Icon( + getShapeIcon(e.key), + color: Colors.black, + ), + Text(" ${e.value}") + ], + ))) + .toList(), + onSelected: selectShape, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Icon( + getShapeIcon(controller.shapeFactory), + color: controller.shapeFactory != null + ? Theme.of(context).primaryColor + : null, + ), + ), + ) + else + IconButton( + icon: Icon( + getShapeIcon(controller.shapeFactory), + color: Theme.of(context).primaryColor, + ), + onPressed: () => selectShape(null), + ), + ], + ), + )); + } + + @override + Widget build(BuildContext context) { + return buildDefault(context); + } + + static IconData getShapeIcon(ShapeFactory? shapeFactory) { + if (shapeFactory is LineFactory) return PhosphorIcons.lineSegment; + if (shapeFactory is ArrowFactory) return PhosphorIcons.arrowUpRight; + if (shapeFactory is DoubleArrowFactory) { + return PhosphorIcons.arrowsHorizontal; + } + if (shapeFactory is RectangleFactory) return PhosphorIcons.rectangle; + if (shapeFactory is OvalFactory) return PhosphorIcons.circle; + return PhosphorIcons.polygon; + } + + void undo() { + controller.undo(); + } + + void redo() { + controller.redo(); + } + + void toggleFreeStyleDraw() { + controller.freeStyleMode = controller.freeStyleMode != FreeStyleMode.draw + ? FreeStyleMode.draw + : FreeStyleMode.none; + } + + void toggleFreeStyleErase() { + controller.freeStyleMode = controller.freeStyleMode != FreeStyleMode.erase + ? FreeStyleMode.erase + : FreeStyleMode.none; + } + + void addText() { + if (controller.freeStyleMode != FreeStyleMode.none) { + controller.freeStyleMode = FreeStyleMode.none; + } + controller.addText(); + } + + void addSticker(BuildContext context) async { + final imageLink = await showDialog( + context: context, + builder: (context) => const SelectStickerImageDialog( + imagesLinks: imageLinks, + )); + if (imageLink == null) return; + controller.addImage( + await NetworkImage(imageLink).image, const Size(100, 100)); + } + + void setFreeStyleStrokeWidth(double value) { + controller.freeStyleStrokeWidth = value; + } + + void setFreeStyleColor(double hue) { + controller.freeStyleColor = HSVColor.fromAHSV(1, hue, 1, 1).toColor(); + } + + void setTextFontSize(double size) { + // Set state is just to update the current UI, the [FlutterPainter] UI updates without it + setState(() { + controller.textSettings = controller.textSettings.copyWith( + textStyle: + controller.textSettings.textStyle.copyWith(fontSize: size)); + }); + } + + void setShapeFactoryPaint(Paint paint) { + // Set state is just to update the current UI, the [FlutterPainter] UI updates without it + setState(() { + controller.shapePaint = paint; + }); + } + + void setTextColor(double hue) { + controller.textStyle = controller.textStyle + .copyWith(color: HSVColor.fromAHSV(1, hue, 1, 1).toColor()); + } + + void selectShape(ShapeFactory? factory) { + controller.shapeFactory = factory; + } + + Future _uploadImage() async { + // Create a map with the required fields + final tempID = await SharedPreferences.getInstance(); + final tempIDS = tempID.getInt('tempid'); + + final String imagePath = '/data/user/0/com.app.rpass/cache/$tempIDS.png'; + + await tempID.setBool('floorSketchSaved', true); + var file = File(imagePath); + // Map detailsMap = { + // "bldgappr_details_id": 182, // int8 NOT NULL + // "date_created": DateTime.now().toIso8601String(), // timestamptz NULL + // "floor_sketch": file.path, // text NULL + // "gen_code": "5TH", // varchar(20) NOT NULL + // }; + + var floorSketchs = FloorSketch( + bldgapprDetailsId: tempIDS, + dateCreated: DateTime.now().toIso8601String(), + floorSketch: file.path, + genCode: "5TH"); + + try { + // Response response = await _postBuildingDetails(detailsMap); + // print(response.body); + await SQLServices.instance.createFloorSketch(floorSketchs); + // if (response.statusCode == 201) { + // print('Upload successful'); + // } else { + // print('Upload failed with status: ${response.statusCode}'); + // } + } catch (e) { + if (kDebugMode) { + print('Error: $e'); + } + } + } + + void renderAndDisplayImage(BuildContext context) async { + if (backgroundImage == null) return; + + final backgroundImageSize = Size( + backgroundImage!.width.toDouble(), + backgroundImage!.height.toDouble(), + ); + + try { + // Render the image + final image = await controller.renderImage(backgroundImageSize); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + final imageBytes = byteData!.buffer.asUint8List(); + final tempID = await SharedPreferences.getInstance(); + final tempIDS = tempID.getInt('tempid'); + + // Write the PNG image data to a file + final file = File('${(await getTemporaryDirectory()).path}/$tempIDS.png'); + await file.writeAsBytes(imageBytes); + + // Show a dialog with the image + // ignore: use_build_context_synchronously + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Rendered Image'), + content: Image.memory(imageBytes), + actions: [ + TextButton( + child: const Text('SAVE'), + onPressed: () { + _uploadImage(); + }, + ), + TextButton( + child: const Text('Close'), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + ], + ), + ); + + // Show a snackbar with the file path + // ignore: use_build_context_synchronously + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image saved to ${file.path}')), + ); + } catch (e) { + // Handle potential errors + // ignore: use_build_context_synchronously + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e')), + ); + } + } + + void removeSelectedDrawable() { + final selectedDrawable = controller.selectedObjectDrawable; + if (selectedDrawable != null) controller.removeDrawable(selectedDrawable); + } + + void flipSelectedImageDrawable() { + final imageDrawable = controller.selectedObjectDrawable; + if (imageDrawable is! ImageDrawable) return; + + controller.replaceDrawable( + imageDrawable, imageDrawable.copyWith(flipped: !imageDrawable.flipped)); + } +} + +class RenderedImageDialog extends StatelessWidget { + final Future imageFuture; + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + const RenderedImageDialog({Key? key, required this.imageFuture}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text("Rendered Image"), + content: FutureBuilder( + future: imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const SizedBox( + height: 50, + child: Center(child: CircularProgressIndicator.adaptive()), + ); + } + if (!snapshot.hasData || snapshot.data == null) { + return const SizedBox(); + } + return InteractiveViewer( + maxScale: 10, child: Image.memory(snapshot.data!)); + }, + ), + ); + } +} + +class SelectStickerImageDialog extends StatelessWidget { + final List imagesLinks; + + const SelectStickerImageDialog({Key? key, this.imagesLinks = const []}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text("Select sticker"), + content: imagesLinks.isEmpty + ? const Text("No images") + : FractionallySizedBox( + heightFactor: 0.5, + child: SingleChildScrollView( + child: Wrap( + children: [ + for (final imageLink in imagesLinks) + InkWell( + onTap: () => Navigator.pop(context, imageLink), + child: FractionallySizedBox( + widthFactor: 1 / 4, + child: Image.network(imageLink), + ), + ), + ], + ), + ), + ), + actions: [ + TextButton( + child: const Text("Cancel"), + onPressed: () => Navigator.pop(context), + ) + ], + ); + } +} diff --git a/lib/screens/offline/passo/building/add/general_description.dart b/lib/screens/offline/passo/building/add/general_description.dart new file mode 100644 index 0000000..b9f0f2d --- /dev/null +++ b/lib/screens/offline/passo/building/add/general_description.dart @@ -0,0 +1,332 @@ +import 'dart:convert'; +import 'dart:ui'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:fluttertoast/fluttertoast.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/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; + +import '../../../../../model/passo/general_description.dart'; +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; +import 'package:intl/intl.dart'; + +class GeneralDescriptionOfflinePage extends StatefulWidget { + final VoidCallback onPutGeneralDescription; + final VoidCallback gendescPrevBtn; + final OfflineProfile offlineProfile; + + final String bldgKind; + final String bldgType; + final String unitValue; + + final Function(String) updatedUnitValue; + final Function(String) updatedBldgKind; + final Function(String) updatedBldgType; + + GeneralDescriptionOfflinePage( + this.onPutGeneralDescription, + this.gendescPrevBtn, + this.offlineProfile, + this.bldgKind, + this.bldgType, + this.unitValue, + this.updatedUnitValue, + this.updatedBldgKind, + this.updatedBldgType); + + @override + _GeneralDescriptionOfflinePage createState() => + _GeneralDescriptionOfflinePage(); +} + +class _GeneralDescriptionOfflinePage + extends State { + final focus = FocusNode(); + + final actual_use = [ + "Residential", + "Agricultural", + "Commercial", + "Industrial", + "Mineral", + "Timberland", + ]; + + final DateTime now; + final String formatter; + + _GeneralDescriptionOfflinePage() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()); + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + 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('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: SizedBox( + height: 45, + child: SearchField( + itemHeight: 70, + suggestions: state.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(widget.bldgKind, "").copyWith( + suffixIcon: const Icon(Icons.arrow_drop_down)), + ////agency suggestion tap + focusNode: focus, + suggestionState: Suggestion.expand, + onSuggestionTap: (unit) async { + setState(() { + widget.updatedBldgKind( + '${unit.item!.bldgType} - ${unit.item!.building}'); + widget.updatedBldgType( + '${unit.item!.bldgType} - ${unit.item!.building}'); + widget.updatedUnitValue(unit.item!.unitValue); + + offlineBldgKey.currentState! + .patchValue({'bldg_type': unit.item}); + }); + + // Save the selected UnitConstruct to SharedPreferences + SharedPreferences prefs = + await SharedPreferences.getInstance(); + String jsonString = jsonEncode(unit.item!.toJson()); + await prefs.setString( + 'selected_bldg_type', jsonString); + + // Unfocus the current focus node + focus.unfocus(); + }, + ), + ), + ), + customDropDownField( + "Actual Use", "", 'actual_use', actual_use), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Bldg. Permit No.", "", + 'bldg_permit', TextInputType.number), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDatTimePicker( + "Date Issued", "", 'date_issued')) + ]), + Container( + margin: const EdgeInsets.only( + left: 0, top: 20, right: 0, bottom: 10), + child: const Text('Condominium Certificate of Title (CCT)', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 15), + textAlign: TextAlign.start), + ), + 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', + TextInputType.number), + ), + 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', TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Area of 1st Floor", "", + 'area_of_1stFl', TextInputType.number), + ), + 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', TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Area of 3rd Floor", "", + 'area_of_3rdFl', TextInputType.number)), + 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', TextInputType.number)) + ]), + customTextField( + "Total Area", "", 'total_area', TextInputType.number), + SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + 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: () async { + { + final tempID = + await SharedPreferences.getInstance(); + + context.read().add(AddGendesc( + id: 1, + bldgapprDetailsId: tempID.getInt('tempid')!, + assessedById: + widget.offlineProfile.id.toString(), + assessedByName: + widget.offlineProfile.firstName!, + dateCreated: formatter, + dateModified: 'None', + bldgKind: widget.bldgKind ?? "", + strucType: widget.bldgType ?? "", + bldgPermit: + offlineBldgKey.currentState?.value['bldg_permit'] ?? + " ", + dateIssued: offlineBldgKey + .currentState!.value['date_issued'] + .toString() ?? + " ", + cct: 'None', + certCompletionIssued: offlineBldgKey + .currentState!.value['coc_issued'] + .toString() ?? + " ", + certOccupancyIssued: offlineBldgKey + .currentState!.value['coo_issued'] + .toString() ?? + " ", + dateCompleted: offlineBldgKey.currentState!.value['date_cnstructed'].toString() ?? "", + dateOccupied: offlineBldgKey.currentState!.value['date_occupied'].toString() ?? "", + bldgAge: offlineBldgKey.currentState!.value['bldg_age'] ?? "0", + noStoreys: offlineBldgKey.currentState!.value['no_of_storeys'] ?? "0", + area1Stfloor: offlineBldgKey.currentState!.value['area_of_1stFl'] ?? "0", + area2Ndfloor: offlineBldgKey.currentState!.value['area_of_2ndFl'] ?? "0", + area3Rdfloor: offlineBldgKey.currentState!.value['area_of_3rdFl'] ?? "0", + area4Thfloor: offlineBldgKey.currentState!.value['area_of_4thFl'] ?? "0", + totalFloorArea: offlineBldgKey.currentState?.value['total_area'] ?? "0", + floorSketch: null, + actualUse: offlineBldgKey.currentState?.value['actual_use'] ?? "", + unitValue: widget.unitValue ?? "", + genCode: '5th')); + widget.onPutGeneralDescription(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/offline/passo/building/add/imagePicker.dart b/lib/screens/offline/passo/building/add/imagePicker.dart new file mode 100644 index 0000000..814833e --- /dev/null +++ b/lib/screens/offline/passo/building/add/imagePicker.dart @@ -0,0 +1,129 @@ +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:http/http.dart'; // Removed 'as http' +import 'package:path/path.dart'; // For basename function +import 'dart:convert'; +import 'dart:io'; + +import 'package:unit2/model/location/purok.dart'; +import 'package:unit2/utils/urls.dart'; + +class ImagePickerScreen extends StatefulWidget { + @override + _ImagePickerScreenState createState() => _ImagePickerScreenState(); +} + +class _ImagePickerScreenState extends State { + File? _image; + + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + Future _pickImage() async { + final pickedFile = + await ImagePicker().pickImage(source: ImageSource.gallery); + + setState(() { + if (pickedFile != null) { + _image = File(pickedFile.path); + } else { + print('No image selected.'); + } + }); + } + + Future _postBuildingDetails(Map details) async { + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + // Construct the headers for the request + Map headers = { + 'Content-Type': 'multipart/form-data', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientKeySecret, + }; + + // Create a MultipartRequest + var request = MultipartRequest( + 'POST', + Uri.parse( + 'https://${Url.instance.host()}/api/rptass_app/bldgappr_sketch/'), + ); + + // Add the headers to the request + request.headers.addAll(headers); + + // Add JSON data as a field + // Add individual fields to the request + details.forEach((key, value) { + request.fields[key] = value.toString(); + }); + + var file = File(imagePath); + // Add the floor sketch image file, if it exists + + var fileName = basename(file.path); + request.files.add( + await MultipartFile.fromPath( + 'floor_sketch', // Field name in the API + file.path, + filename: fileName, + ), + ); + + // Send the request and get the response + var streamedResponse = await request.send(); + return await Response.fromStream(streamedResponse); + } + + Future _uploadImage() async { + // Create a map with the required fields + var file = File(imagePath); + Map detailsMap = { + "bldgappr_details_id": 182, // int8 NOT NULL + "date_created": DateTime.now().toIso8601String(), // timestamptz NULL + "floor_sketch": file.path, // text NULL + "gen_code": "5TH", // varchar(20) NOT NULL + }; + + try { + Response response = await _postBuildingDetails(detailsMap); + print(response.body); + + if (response.statusCode == 201) { + print('Upload successful'); + } else { + print('Upload failed with status: ${response.statusCode}'); + } + } catch (e) { + print('Error: $e'); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('Pick and Upload Image'), + ), + body: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _image == null ? Text('No image selected.') : Image.file(_image!), + SizedBox(height: 20), + ElevatedButton( + onPressed: _pickImage, + child: Text('Pick Image'), + // return "192.168.10.221:3004"; + ), + SizedBox(height: 20), + ElevatedButton( + onPressed: _uploadImage, + child: Text('Upload Image'), + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/add/landref_location.dart b/lib/screens/offline/passo/building/add/landref_location.dart new file mode 100644 index 0000000..6c379df --- /dev/null +++ b/lib/screens/offline/passo/building/add/landref_location.dart @@ -0,0 +1,395 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/location/location_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; + +import '../../../../../model/passo/barangay.dart'; +import '../../../../../model/passo/city.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; +import 'package:intl/intl.dart'; + +class LandRefLocationOfflinePage extends StatefulWidget { + final VoidCallback PrevBtn; + final VoidCallback NextBtn; + final OfflineProfile offlineProfile; + + LandRefLocationOfflinePage(this.PrevBtn, this.NextBtn, this.offlineProfile); + + @override + _LandRefLocationOfflinePage createState() => _LandRefLocationOfflinePage(); +} + +class _LandRefLocationOfflinePage extends State { + final DateTime now; + final String formatter; + bool sameOwner = false; + + _LandRefLocationOfflinePage() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()); + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MunicipalitiesLoaded) { + final city = state.city; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + 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( + child: 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: const Align( + alignment: Alignment.center, + child: Text( + "AGUSAN DEL NORTE", + style: TextStyle(fontSize: 15), + ), + ), + ), + ), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'municipality', + autofocus: false, + decoration: normalTextFieldStyle( + "Municipality", ""), + items: city + .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(LoadBarangayInMunicipality( + cityCode: + selectedCityCode!)); // Use selectedCityCode directly + } + }, + )), + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("No. / Street", "", + 'street', TextInputType.text), + ), + 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), + ), + Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Row( + children: [ + SizedBox( + width: 50, // Adjust the width as needed + height: 50, // Adjust the height as needed + child: Checkbox( + checkColor: Colors.white, + value: sameOwner, + onChanged: (bool? value) { + setState(() { + sameOwner = value!; + offlineBldgKey.currentState! + .patchValue({ + 'l_owner': offlineBldgKey.currentState + ?.value['fname'] + + ' ' + + offlineBldgKey.currentState + ?.value['mname'] + + ' ' + + offlineBldgKey + .currentState?.value['lname'] + }); + offlineBldgKey.currentState! + .patchValue({ + 'l_td_arp': offlineBldgKey + .currentState?.value['arp_td'] + }); + }); + }, + ), + ), + Text('Same building owner') + ], + ), + // Other widgets in the column + ], + ), + customTextField( + "Land Owner", "", 'l_owner', TextInputType.text), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("OCT/TCT/CLOA No.", "", + 'oct_tct_cloa', TextInputType.phone), + ), + 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', TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Lot No.", "", 'lot_no', + TextInputType.streetAddress), + ), + 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', TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("TD / ARP No.", "", + 'l_td_arp', TextInputType.phone), + ), + 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', TextInputType.phone)) + ]), + const SizedBox( + height: 50, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_left_rounded, + color: Colors.white), + onPressed: () { + { + widget.PrevBtn(); + } + ; + }, + ), + // Builder(builder: (context) { + // return CustomButton( + // icon: const Icon( + // Icons.chevron_right_rounded, + // color: Colors.white), + // onPressed: () async { + // { + // try { + // final progress = + // ProgressHUD.of(context); + // Future.delayed(Duration(seconds: 3), + // () { + // progress?.dismiss(); + // }); + // 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: "Agusan Del Norte"); + // 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)); + // } catch (e) { + // Fluttertoast.showToast( + // msg: + // "Slow internet connection, please try again!"); + // } + // } + // ; + // }, + // ); + // }) + Builder(builder: (context) { + return CustomButton( + icon: const Icon( + Icons.chevron_right_rounded, + color: Colors.white, + ), + onPressed: () async { + // Rest of your code... + final tempID = + await SharedPreferences.getInstance(); + + print('id check'); + print(tempID.getInt('tempid')!); + + context.read().add(AddLocation( + id: 1, + bldgapprDetailsId: + tempID.getInt('tempid')!, + assessedById: + widget.offlineProfile.id.toString(), + assessedByName: + widget.offlineProfile.firstName!, + dateCreated: 'None', + dateModified: 'NOne', + street: offlineBldgKey + .currentState?.value['street'] ?? + "", + barangay: offlineBldgKey + .currentState?.value['brgy'] ?? + "", + municipality: offlineBldgKey + .currentState + ?.value['municipality'] + .cityDescription ?? + "", + province: "AGUSAN DEL NORTE", + genCode: "5th")); + + context.read().add(AddLandRef( + id: 1, + bldgapprDetailsId: + tempID.getInt('tempid')!, + assessedById: + widget.offlineProfile.id.toString(), + assessedByName: + widget.offlineProfile.firstName!, + dateCreated: 'None', + dateModified: 'None', + owner: offlineBldgKey + .currentState?.value['l_owner'] ?? + "", + cloaNo: offlineBldgKey.currentState + ?.value['oct_tct_cloa'] ?? + "", + lotNo: offlineBldgKey + .currentState?.value['lot_no'] ?? + "", + tdn: offlineBldgKey.currentState + ?.value['l_td_arp'] ?? + "", + area: + offlineBldgKey.currentState?.value['area'] ?? "0", + surveyNo: offlineBldgKey.currentState?.value['survey_no'] ?? "", + blkNo: offlineBldgKey.currentState?.value['blk_no'] ?? "", + genCode: '5th')); + + widget.NextBtn(); + }, + ); + }) + ], + ) + ], + ), + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/offline/passo/building/add/property_appraisal.dart b/lib/screens/offline/passo/building/add/property_appraisal.dart new file mode 100644 index 0000000..49f5a41 --- /dev/null +++ b/lib/screens/offline/passo/building/add/property_appraisal.dart @@ -0,0 +1,890 @@ +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/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:unit2/screens/offline/passo/building/add/additional_items.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class PropertyAppraisalOfflinePage extends StatefulWidget { + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + final OfflineProfile offlineProfile; + + PropertyAppraisalOfflinePage(this.NextBtn, this.PrevBtn, this.offlineProfile); + + @override + _PropertyAppraisalOfflinePage createState() => + _PropertyAppraisalOfflinePage(); +} + +class _PropertyAppraisalOfflinePage + 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 = 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 = 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; + } + + _calculateMarketValue( + List items, List bldg) { + double add_sum = 0; + double product = 1; + double bldg_sum = 0; + + for (AdditionalItems value in items) { + add_sum += double.parse(value.adjustedMarketVal.toString()); + } + + for (BldgAndStructure value in bldg) { + bldg_sum += double.parse(value.adjustedMarketValue.toString()); + } + + return add_sum + bldg_sum; + } + + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += row.adjustedMarketVal; + }); + return total; + } + + double _totalMarketValueBLDG(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketValue); + }); + return total; + } + + // 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; + // } + + @override + Widget build(BuildContext context) { + final width = MediaQuery.of(context).size.width; + return Scaffold( + body: BlocConsumer( + listener: (context, state) {}, + builder: (context, state) { + if (state is AdditionalItemsLoaded) { + final addItem = state.addItem; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is BuildingAndStructureLoaded) { + return SingleChildScrollView( + padding: const EdgeInsets.all(20), + 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: 20), + textAlign: TextAlign.left), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text('BUILDING & STRUCTURE', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context).size.width / 4, + columns: [ + const DataColumn( + label: Text('Building Core'), + ), + const DataColumn( + label: Text(''), + ), + const DataColumn( + label: Text('Market Value'), + ), + ], + rows: [ + ...state.bldgAndStructure + .map((dataRow) { + return DataRow(cells: [ + DataCell(Text(dataRow.structType!)), + DataCell(Text("")), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse(dataRow + .adjustedMarketValue + .toString()!)), + )) + ]); + }), + DataRow(cells: [ + DataCell(Text('Total', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 15, + color: Colors.red))), + DataCell(Text('')), + DataCell( + Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(_totalMarketValueBLDG( + state.bldgAndStructure)), + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 15, + color: Colors.red)), + ) + ]), + ], + ) + ], + )), + ), + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text('ADDITIONAL ITEMS', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context).size.width / + 3, + columns: const [ + DataColumn( + label: Text('Additional Item'), + ), + DataColumn( + label: Text(''), + ), + DataColumn( + label: Text('Market Value'), + ), + ], + rows: [ + ...addItem.map((dataRow) { + return DataRow(cells: [ + DataCell( + Text(dataRow.className!)), + DataCell(Text('')), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱") + .format(double.parse(dataRow + .marketValue + .toString()!)) + .toString(), + )) + ]); + }).toList(), + DataRow( + // color: MaterialStateColor.resolveWith( + // (states) { + // // Use a color for the DataRow, for example, Colors.blue + // return Colors.redAccent; + // }), + cells: [ + DataCell(Text('Total', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15, + color: Colors.red))), + DataCell(Text('')), + DataCell( + Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format( + _totalMarketValue( + addItem)), + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15, + color: Colors.red)), + ) + ]), + ]), + ], + )), + ), + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + 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: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context).size.width / + 6, + columns: const [ + DataColumn( + label: Text('Actual Use'), + ), + DataColumn( + label: Text('Market Value'), + ), + DataColumn( + label: Text('Ass. Level'), + ), + DataColumn( + label: Text('Ass. Value'), + ), + ], + rows: [ + DataRow( + cells: [ + DataCell(Text(offlineBldgKey + .currentState + ?.value['actual_use'] ?? + "")), + DataCell(Text(NumberFormat + .currency( + locale: 'en-PH', + symbol: "₱") + .format(_calculateMarketValue( + addItem, + state + .bldgAndStructure)))), + DataCell( + Text( + assessmentLevel( + _calculateMarketValue( + addItem, + state + .bldgAndStructure), + offlineBldgKey + .currentState + ?.value[ + 'actual_use']), + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱") + .format(double.parse( + assessmentValue( + _calculateMarketValue( + addItem, + state + .bldgAndStructure), + offlineBldgKey + .currentState + ?.value[ + 'actual_use']) + .toString(), + )) + .toString(), + )), + ], + ), + ]) + ], + )), + ), + ], + ), + const 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')); + // context.read().add(AddBldgAppraisal( + // id: 1, + // bldgapprDetailsId: tempID.getInt('tempid')!, + // assessedById: '1', + // assessedByName: 'ad', + // dateCreated: '00', + // dateModified: '00', + // unitconstructCost: offlineBldgKey + // .currentState + // ?.value['bldg_type'] + // .unitValue, + // buildingCore: 'test', + // unitconstructSubtotal: + // (double.parse(offlineBldgKey.currentState!.value['total_area']) * + // double.parse(offlineBldgKey + // .currentState! + // .value['bldg_type'] + // .unitValue)) + // .toString(), + // depreciationRate: depRate.toString(), + // depreciationCost: calculateDepCost( + // (double.parse(offlineBldgKey.currentState!.value['total_area']) * + // double.parse(offlineBldgKey.currentState?.value['bldg_type'].unitValue)), + // addItem, + // depRate) + // .toString(), + // costAddItems: calculateAdditionalItems(addItem).toString(), + // addItemsSubtotal: calculateAdditionalItems(addItem).toString(), + // totalpercentDepreciation: (depRate * 100).toStringAsFixed(2), + // marketValue: calculateMarketValue((double.parse(offlineBldgKey.currentState!.value['total_area']) * double.parse(offlineBldgKey.currentState!.value['bldg_type'].unitValue)), addItem, depRate).toString(), + // totalArea: offlineBldgKey.currentState!.value['total_area'], + // actualUse: "Residential")); + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ], + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/building/add/property_assessment.dart b/lib/screens/offline/passo/building/add/property_assessment.dart new file mode 100644 index 0000000..79625ea --- /dev/null +++ b/lib/screens/offline/passo/building/add/property_assessment.dart @@ -0,0 +1,1507 @@ +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/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:accordion/accordion.dart'; +import 'package:accordion/controllers.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +import '../../../../../bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import '../../../../../bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart'; +import '../../../../../bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../model/passo/memoranda.dart'; +import '../../../../../model/passo/signatories.dart'; +import '../../../../../theme-data.dart/colors.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import 'package:intl/intl.dart'; // Import the intl package + +class PropertyAssessmentOfflinePage extends StatefulWidget { + Function function; + final OfflineProfile offlineProfile; + + PropertyAssessmentOfflinePage(this.function, this.offlineProfile); + + @override + _PropertyAssessmentOfflinePage createState() => + _PropertyAssessmentOfflinePage(); +} + +class _PropertyAssessmentOfflinePage + extends State { + double assessment_level = 0; + bool isTaxable = false; + bool isExempt = false; + String _memoranda = ""; + String _notes = ""; + String appraised_by = ""; + String rec_by = ""; + String approved_by = ""; + String appraised_by_designation = ""; + String rec_by_designation = ""; + String approved_by_designation = ""; + final focus = FocusNode(); + final focuss = FocusNode(); + final appraisedByFocus = FocusNode(); + final recByFocus = FocusNode(); + final apprvdByFocus = FocusNode(); + + final quarter = ['1st', '2nd', '3rd', '4th']; + + TextEditingController memorandaController = TextEditingController(); + TextEditingController noteController = TextEditingController(); + + String assessmentLevel(marketValues, property_class) { + final marketValue = 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 = 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; + } + + _calculateMarketValue( + List items, List bldg) { + double add_sum = 0; + double product = 1; + double bldg_sum = 0; + + for (AdditionalItems value in items) { + add_sum += double.parse(value.adjustedMarketVal.toString()); + } + + for (BldgAndStructure value in bldg) { + bldg_sum += double.parse(value.adjustedMarketValue.toString()); + } + + return add_sum + bldg_sum; + } + + @override + Widget build(BuildContext context) { + var width = MediaQuery.of(context).size.width; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + final memoranda = state.memo; + final note = state.memo; + 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 AdditionalItemsLoaded) { + final addItem = state.addItem; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is BuildingAndStructureLoaded) { + return Column( + 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, + ), + textAlign: TextAlign.left, + ), + ), + ), + Expanded( + child: Container( + margin: const EdgeInsets.symmetric( + horizontal: 20), // Adjust margins here + child: SingleChildScrollView( + 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 / SWORN STATEMENT:', + style: TextStyle( + fontWeight: + FontWeight.bold), + ), + const SizedBox( + height: 20, + ), + Row( + mainAxisAlignment: + MainAxisAlignment + .spaceAround, + children: [ + SizedBox( + width: width / 3 - 20, + height: 50, + child: + customDropDownField( + 'Qtr', + '', + 'qtr', + quarter)), + SizedBox( + width: width / 3 - 20, + height: 50, + child: customTextField( + 'Sworn Statement No.', + '', + 'sworn_statement', + TextInputType + .number)), + SizedBox( + width: width / 3 - 20, + height: 50, + child: customTextField( + 'Year', + '', + 'yr', + TextInputType + .number)), + ], + ), + ], + ), + const SizedBox( + height: 10, + ), + const Divider( + thickness: 2, + ), + Row( + children: [ + SizedBox( + width: 10, + ), + Expanded( + child: SizedBox( + width: width / 2 - 100, + height: 50, + child: customDatTimePicker( + 'Date Received', + '', + 'date_received', + ), + ), + ), + SizedBox( + width: 20, + ), + Expanded( + child: SizedBox( + width: width / 2 - 100, + height: 50, + child: customDatTimePicker( + 'Date of Entry', + '', + 'date_of_entry', + ), + ), + ), + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPRAISED/ASSESSED BY:', + style: TextStyle( + fontWeight: FontWeight.bold), + textAlign: TextAlign.start, + ), + ), + const SizedBox( + height: 15, + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: + appraisedByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + appraised_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + appraised_by_designation = + appraised.item! + .designation; + }); + appraisedByFocus + .unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + appraised_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'app_date')), + ], + ), + ]), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'RECOMMENDING APPROVAL:', + style: TextStyle( + fontWeight: + FontWeight.bold), + )), + const SizedBox( + height: 15, + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: recByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + rec_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + rec_by_designation = + appraised.item! + .designation; + }); + recByFocus.unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + rec_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'rec_date')), + ], + ), + ]), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPROVED BY:', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + const SizedBox( + height: 15, + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: apprvdByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + approved_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + approved_by_designation = + appraised.item! + .designation; + }); + apprvdByFocus.unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + approved_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'approve_date')), + ], + ), + ]), + ), + const SizedBox( + height: 50, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'MEMORANDA: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + const SizedBox( + height: 30, + ), + SizedBox( + width: 500, + height: 50, + child: SearchField( + itemHeight: 200, + controller: memorandaController, + suggestions: memoranda + .map( + (Memoranda memoranda) => + SearchFieldListItem( + '${memoranda.memoranda}', + item: + memoranda, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${memoranda.memoranda}', + overflow: + TextOverflow + .visible, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + // searchInputDecoration: + // normalTextFieldStyle("Memoranda", "") + // .copyWith( + // suffixIcon: + // const Icon(Icons.arrow_drop_down), + // contentPadding: EdgeInsets.symmetric( + // vertical: 15.0, horizontal: 16.0), + // border: OutlineInputBorder( + // borderRadius: BorderRadius.circular(10.0), + // borderSide: BorderSide( + // color: + // Colors.grey, // Adjust border color + // ), + // ), + // focusedBorder: OutlineInputBorder( + // borderRadius: BorderRadius.circular(10.0), + // borderSide: BorderSide( + // color: Colors + // .blue, // Adjust focused border color + // ), + // ), + // ), + focusNode: focuss, + suggestionState: + Suggestion.expand, + suggestionDirection: + SuggestionDirection.up, + onSuggestionTap: (memoranda) { + setState(() { + _memoranda = + memorandaController + .text; + }); + focuss.unfocus(); + }, + )), + Container( + alignment: Alignment.center, + padding: EdgeInsets.all(10), + child: Column( + children: [ + TextField( + controller: + memorandaController, + keyboardType: + TextInputType.multiline, + maxLines: 7, + decoration: InputDecoration( + focusedBorder: + OutlineInputBorder( + borderSide: BorderSide( + width: 1, + color: Colors + .redAccent)), + disabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + width: 1, + color: Colors.grey, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + enabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + color: Colors.grey, + width: 1, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + ), + ), + ], + ), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'NOTE: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + const SizedBox( + height: 30, + ), + SizedBox( + width: 400, + height: 50, + child: SearchField( + itemHeight: 200, + controller: noteController, + suggestions: note + .map((Memoranda note) => + SearchFieldListItem( + '${note.memoranda}', + item: + note, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${note.memoranda}', + overflow: + TextOverflow + .visible, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: + InputDecoration().copyWith( + suffixIcon: const Icon( + Icons.arrow_drop_down), + ), + focusNode: focus, + suggestionState: + Suggestion.expand, + suggestionDirection: + SuggestionDirection.up, + onSuggestionTap: (memoranda) { + setState(() { + _notes = + noteController.text; + }); + focus.unfocus(); + }, + )), + Container( + alignment: Alignment.center, + padding: EdgeInsets.all(10), + child: Column( + children: [ + TextField( + controller: noteController, + keyboardType: + TextInputType.multiline, + maxLines: 7, + decoration: InputDecoration( + focusedBorder: + OutlineInputBorder( + borderSide: BorderSide( + width: 1, + color: Colors + .redAccent)), + disabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + width: 1, + color: Colors.grey, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + enabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + color: Colors.grey, + width: 1, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + ), + ), + ], + ), + ), + const SizedBox( + height: 30, + ), + ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences + .getInstance(); + print( + tempID.getInt('tempid')! - 1); + // final List + // propertyAssessments = []; + DateTime? appDate = offlineBldgKey + .currentState! + .value['app_date']; + DateTime? recDate = offlineBldgKey + .currentState! + .value['rec_date']; + DateTime? approveDate = + offlineBldgKey.currentState! + .value['approve_date']; + DateTime? dateReceived = + offlineBldgKey.currentState! + .value['date_received']; + DateTime? entryDate = + offlineBldgKey.currentState! + .value['date_of_entry']; + String appDateString = + appDate != null + ? appDate.toString() + : ''; + String recDateString = + recDate != null + ? recDate.toString() + : ''; + String approveDateString = + approveDate != null + ? approveDate.toString() + : ''; + String receivedDateString = + recDate != null + ? recDate.toString() + : ''; + String entryDateString = + recDate != null + ? recDate.toString() + : ''; + context.read().add( + AddBldgAssessment( + id: 1, + bldgapprDetailsId: tempID + .getInt('tempid')!, + assessedById: widget + .offlineProfile.id + .toString(), + assessedByName: widget + .offlineProfile + .firstName!, + dateCreated: '', + dateModified: '', + actualUse: offlineBldgKey.currentState!.value['actual_use'] ?? + '', // Replace null with an empty string + marketValue: + _calculateMarketValue(addItem, state.bldgAndStructure) + .toString(), + assessmentLevel: assessmentLevel( + _calculateMarketValue( + addItem, + state + .bldgAndStructure), + offlineBldgKey + .currentState + ?.value['actual_use']), + assessedValue: assessmentValue(_calculateMarketValue(addItem, state.bldgAndStructure), offlineBldgKey.currentState?.value['actual_use']).toString(), + taxable: isTaxable == true ? '1' : '0', + exempt: isExempt == true ? '1' : '0', + qtr: offlineBldgKey.currentState!.value['qtr'] ?? '0', // Replace null with '0' + yr: int.parse(offlineBldgKey.currentState!.value['yr'] ?? '0'), // Replace null with '0' + appraisedbyName: appraised_by, + appraisedbyDate: appDateString, // Replace null with current date + recommendapprName: rec_by, + recommendapprDate: recDateString, // Replace null with current date + approvedbyName: approved_by, + approvedbyDate: approveDateString, + memoranda: _memoranda, + note: _notes, + swornstatementNo: offlineBldgKey.currentState!.value['sworn_statement'] ?? " ", // Replace null with an empty string + dateReceived: receivedDateString, + // Replace null with current date + entryDateAssessment: entryDateString, + // Replace null with current date + entryDateBy: widget.offlineProfile.firstName!, + genCode: '5th', + appraisedbyDesignation: appraised_by_designation, + approvedbyDesignation: approved_by_designation, + recommendapprDesignation: rec_by_designation + // Replace null with an empty string + )); + // print('assess'); + // print((asses)); + + widget.function(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: primary, + foregroundColor: Colors.red), + child: const Padding( + padding: EdgeInsets.all(15.0), + child: Align( + alignment: Alignment.center, + child: Text( + 'Save', + style: TextStyle( + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ], + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} + +class MyInputForm extends StatelessWidget //__ +{ + const MyInputForm({super.key}); + + @override + Widget build(context) //__ + { + return Column( + children: [ + TextFormField( + maxLines: 5, + decoration: InputDecoration( + label: const Text('Some text goes here ...'), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + ), + ], + ); + } +} diff --git a/lib/screens/offline/passo/building/add/property_owner_info.dart b/lib/screens/offline/passo/building/add/property_owner_info.dart new file mode 100644 index 0000000..69b49ad --- /dev/null +++ b/lib/screens/offline/passo/building/add/property_owner_info.dart @@ -0,0 +1,230 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; +import 'package:intl/intl.dart'; +import '../../../../../bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; + +class PropertyInfoOfflinePage extends StatefulWidget { + final VoidCallback handleButtonPress; + final OfflineProfile offlineProfile; + const PropertyInfoOfflinePage(this.handleButtonPress, this.offlineProfile, + {super.key}); + + @override + _PropertyInfoPage createState() => _PropertyInfoPage(); +} + +class _PropertyInfoPage extends State { + int tempId = 0; + final transaction_codes = ['New', 'Revision']; + final DateTime now; + final String formatter; + bool isOptional = false; + + _PropertyInfoPage() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(20.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), + 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', + TextInputType.phone)), + 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', TextInputType.phone)), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "First Name", "", 'fname', TextInputType.text), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Middle Name", "", 'mname', TextInputType.text), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Last Name", "", 'lname', TextInputType.text), + ) + ]), + customDatTimePicker("Birthday", "", "bday"), + customTextField("Address", "", 'address', TextInputType.text), + Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Row( + children: [ + SizedBox( + width: 50, // Adjust the width as needed + height: 50, // Adjust the height as needed + child: Checkbox( + checkColor: Colors.white, + value: isOptional, + onChanged: (bool? value) { + setState(() { + isOptional = value!; + }); + }, + ), + ), + Text('Show optional information') + ], + ), + // Other widgets in the column + ], + ), + Visibility( + visible: isOptional, + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Tel No.", "", 'tel_no', TextInputType.phone), + ), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: customTextField( + "TIN", "", 'tin', TextInputType.phone), + ), + ], + ), + const SizedBox(height: 10.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Administrator / Beneficial User", + "", + 'benificiary', + TextInputType.text, + ), + ), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: customTextField("TIN", "", 'benificiary_tin', + TextInputType.phone), + ), + ], + ), + const SizedBox(height: 10.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Address", "", + 'benificiary_address', TextInputType.text), + ), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: customTextField("Tel No.", "", + 'benificiary_telno', TextInputType.phone), + ), + ], + ), + ], + ), + ), + const SizedBox(height: 25), + CustomButton( + icon: const Icon(Icons.chevron_right, color: Colors.white), + onPressed: () async { + final tempID = await SharedPreferences.getInstance(); + // Dispatch the event to add the property_info + context.read().add( + AddTodo( + id: '1', + transCode: offlineBldgKey + .currentState!.value['transaction_code'] + ?.toString() ?? + ' ', + tdn: offlineBldgKey.currentState!.value['arp_td'] ?? + ' ', + pin: offlineBldgKey.currentState!.value['pin'] ?? + ' ', + fname: + offlineBldgKey.currentState!.value['fname'] ?? + ' ', + mname: + offlineBldgKey.currentState!.value['mname'] ?? + ' ', + lname: + offlineBldgKey.currentState!.value['lname'] ?? + ' ', + bday: offlineBldgKey.currentState!.value['bday'] + .toString() ?? + ' ', + address: + offlineBldgKey.currentState!.value['address'] ?? + ' ', + telno: + offlineBldgKey.currentState!.value['tel_no'] ?? + ' ', + tin: offlineBldgKey.currentState!.value['tin'] ?? ' ', + adminUser: offlineBldgKey.currentState!.value['benificiary'] ?? ' ', + adminAddress: offlineBldgKey.currentState!.value['benificiary_address'] ?? ' ', + adminTin: offlineBldgKey.currentState!.value['benificiary_tin'] ?? ' ', + adminTelno: offlineBldgKey.currentState!.value['benificiary_telno'] ?? ' ', + faasType: "BUILDING", + assessedById: widget.offlineProfile.id.toString(), + assessedByName: widget.offlineProfile.firstName!, + dateCreated: formatter, + dateModified: ' ', + genCode: '5th'), + ); + widget.handleButtonPress(); + }, + ) + ]), + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/add/signature_draw.dart b/lib/screens/offline/passo/building/add/signature_draw.dart new file mode 100644 index 0000000..5d6a51d --- /dev/null +++ b/lib/screens/offline/passo/building/add/signature_draw.dart @@ -0,0 +1,213 @@ +import 'dart:developer'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_svg/svg.dart'; +import 'package:signature/signature.dart'; +import 'package:unit2/screens/offline/passo/building/add/utils.dart'; + +class SignatureDraw extends StatefulWidget { + const SignatureDraw({super.key}); + + @override + State createState() => _HomeState(); +} + +class _HomeState extends State { + // initialize the signature controller + final SignatureController _controller = SignatureController( + penStrokeWidth: 1, + penColor: Colors.red, + exportBackgroundColor: Colors.transparent, + exportPenColor: Colors.black, + onDrawStart: () => log('onDrawStart called!'), + onDrawEnd: () => log('onDrawEnd called!'), + ); + + @override + void initState() { + super.initState(); + _controller + ..addListener(() => log('Value changed')) + ..onDrawEnd = () => setState( + () { + // setState for build to update value of "empty label" in gui + }, + ); + } + + @override + void dispose() { + // IMPORTANT to dispose of the controller + _controller.dispose(); + super.dispose(); + } + + Future exportImage(BuildContext context) async { + if (_controller.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + key: Key('snackbarPNG'), + content: Text('No content'), + ), + ); + return; + } + + final Uint8List? data = + await _controller.toPngBytes(height: 1000, width: 1000); + if (data == null) { + return; + } + + if (!mounted) return; + + await push( + context, + Scaffold( + appBar: AppBar( + title: const Text('PNG Image'), + ), + body: Center( + child: Container( + color: Colors.grey[300], + child: Image.memory(data), + ), + ), + ), + ); + } + + Future exportSVG(BuildContext context) async { + if (_controller.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + key: Key('snackbarSVG'), + content: Text('No content'), + ), + ); + return; + } + + final SvgPicture data = _controller.toSVG()!; + + if (!mounted) return; + + await push( + context, + Scaffold( + appBar: AppBar( + title: const Text('SVG Image'), + ), + body: Center( + child: Container( + color: Colors.grey[300], + child: data, + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Signature Demo'), + ), + body: ListView( + children: [ + const SizedBox( + height: 300, + child: Center( + child: Text('Big container to test scrolling issues'), + ), + ), + //SIGNATURE CANVAS + Padding( + padding: const EdgeInsets.all(16.0), + child: Signature( + key: const Key('signature'), + controller: _controller, + height: 300, + backgroundColor: Colors.grey[300]!, + ), + ), + Text(_controller.isEmpty + ? "Signature pad is empty" + : "Signature pad is not empty"), + const SizedBox( + height: 300, + child: Center( + child: Text('Big container to test scrolling issues'), + ), + ), + ], + ), + bottomNavigationBar: BottomAppBar( + child: Container( + decoration: const BoxDecoration(color: Colors.black), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + mainAxisSize: MainAxisSize.max, + children: [ + //SHOW EXPORTED IMAGE IN NEW ROUTE + IconButton( + key: const Key('exportPNG'), + icon: const Icon(Icons.image), + color: Colors.blue, + onPressed: () => exportImage(context), + tooltip: 'Export Image', + ), + IconButton( + key: const Key('exportSVG'), + icon: const Icon(Icons.share), + color: Colors.blue, + onPressed: () => exportSVG(context), + tooltip: 'Export SVG', + ), + IconButton( + icon: const Icon(Icons.undo), + color: Colors.blue, + onPressed: () { + setState(() => _controller.undo()); + }, + tooltip: 'Undo', + ), + IconButton( + icon: const Icon(Icons.redo), + color: Colors.blue, + onPressed: () { + setState(() => _controller.redo()); + }, + tooltip: 'Redo', + ), + //CLEAR CANVAS + IconButton( + key: const Key('clear'), + icon: const Icon(Icons.clear), + color: Colors.blue, + onPressed: () { + setState(() => _controller.clear()); + }, + tooltip: 'Clear', + ), + // STOP Edit + IconButton( + key: const Key('stop'), + icon: Icon( + _controller.disabled ? Icons.pause : Icons.play_arrow, + ), + color: Colors.blue, + onPressed: () { + setState(() => _controller.disabled = !_controller.disabled); + }, + tooltip: _controller.disabled ? 'Pause' : 'Play', + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/passo/Building/add_building_components/structural_materials.dart b/lib/screens/offline/passo/building/add/structural_material.dart similarity index 55% rename from lib/screens/passo/Building/add_building_components/structural_materials.dart rename to lib/screens/offline/passo/building/add/structural_material.dart index 95c7db4..981f5fa 100644 --- a/lib/screens/passo/Building/add_building_components/structural_materials.dart +++ b/lib/screens/offline/passo/building/add/structural_material.dart @@ -3,9 +3,10 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:multiselect/multiselect.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.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/screens/offline/passo/building/add/add_building.dart'; import 'package:unit2/widgets/passo/custom_button.dart'; import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; @@ -16,31 +17,91 @@ class MaterialOption { MaterialOption(this.id, this.label); } -class StructuralMaterialsPage extends StatefulWidget { - final VoidCallback NextBtn; +class StructuralMaterialsOfflinePage extends StatefulWidget { final VoidCallback PrevBtn; + final VoidCallback NextBtn; - StructuralMaterialsPage(this.NextBtn, this.PrevBtn); + final List foundation; + final List column; + final List beam; + final List trussFraming; + final List roof; + final List flooring; + final List walls; + + final bool foundationOthers; + final bool columOthers; + final bool beamsOthers; + final bool tfOthers; + final bool roofOthers; + final bool flooringOthers; + final bool wpOthers; + + final Function(bool) updateFoundationOthers; + final Function(bool) updateColumOthers; + final Function(bool) updateBeamsOthers; + final Function(bool) updateTfOthers; + final Function(bool) updateRoofOthers; + final Function(bool) updateFlooringOthers; + final Function(bool) updateWpOthers; + + final Function(List) updateFoundation; + final Function(List) updateColumn; + final Function(List) updateBeam; + final Function(List) updateTrussFraming; + final Function(List) updateRoof; + final Function(List) updateFlooring; + final Function(List) updateWalls; + + StructuralMaterialsOfflinePage( + this.PrevBtn, + this.NextBtn, { + Key? key, + required this.foundation, + required this.column, + required this.beam, + required this.trussFraming, + required this.roof, + required this.flooring, + required this.walls, + required this.updateFoundation, + required this.updateColumn, + required this.updateBeam, + required this.updateTrussFraming, + required this.updateRoof, + required this.updateFlooring, + required this.updateWalls, + required this.updateFoundationOthers, + required this.updateColumOthers, + required this.updateBeamsOthers, + required this.updateTfOthers, + required this.updateRoofOthers, + required this.updateFlooringOthers, + required this.updateWpOthers, + required this.foundationOthers, + required this.columOthers, + required this.beamsOthers, + required this.tfOthers, + required this.roofOthers, + required this.flooringOthers, + required this.wpOthers, + // Repeat for other update methods... + }); @override - _StructuralMaterialsPage createState() => _StructuralMaterialsPage(); + _StructuralMaterialsOfflinePage createState() => + _StructuralMaterialsOfflinePage(); } -class _StructuralMaterialsPage extends State { - List foundation = []; - List column = []; - List beam = []; - List truss_framing = []; - 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; +class _StructuralMaterialsOfflinePage + extends State { + // List foundation = []; + // List column = []; + // List beam = []; + // List trussFraming = []; + // List roof = []; + // List flooring = []; + // List walls = []; List columnOptions = [ MaterialOption('steel', 'Steel'), @@ -50,6 +111,8 @@ class _StructuralMaterialsPage extends State { List selectedColumnValues = []; + FocusNode _focusNode = FocusNode(); + @override Widget build(BuildContext context) { return StatefulBuilder(builder: (context, structuralState) { @@ -74,10 +137,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: foundationOthers, + value: widget.foundationOthers, onChanged: (bool? value) { structuralState(() { - foundationOthers = value!; + widget.updateFoundationOthers(value!); }); }, ) @@ -87,18 +150,16 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: foundationOthers, - child: customTextField( - "Enter other foundation", "", "other_foundation"), + visible: widget.foundationOthers, + child: customTextField("Enter other foundation", "", + "other_foundation", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - foundation = x; - }); + widget.updateFoundation(x); }, options: const ['Reinforced Concrete', 'Plain Concrete'], - selectedValues: foundation, + selectedValues: widget.foundation, whenEmpty: 'Select Foundations', ), ), @@ -113,10 +174,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: columOthers, + value: widget.columOthers, onChanged: (bool? value) { structuralState(() { - columOthers = value!; + widget.updateColumOthers(value!); }); }, ) @@ -126,18 +187,16 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: columOthers, - child: - customTextField("Enter other columns", "", "other_column"), + visible: widget.columOthers, + child: customTextField("Enter other columns", "", + "other_column", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - column = x; - }); + widget.updateColumn(x); }, options: const ['Steel', 'Reinforced Concrete', 'Wood'], - selectedValues: column, + selectedValues: widget.column, whenEmpty: 'Select Column/s', ), ), @@ -152,10 +211,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: beamsOthers, + value: widget.beamsOthers, onChanged: (bool? value) { structuralState(() { - beamsOthers = value!; + widget.updateBeamsOthers(value!); }); }, ) @@ -165,17 +224,16 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: beamsOthers, - child: customTextField("Enter other beam/s", "", "other_beam"), + visible: widget.beamsOthers, + child: customTextField( + "Enter other beam/s", "", "other_beam", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - beam = x; - }); + widget.updateBeam(x); }, options: const ['Steel', 'Reinforced Concrete', 'Wood'], - selectedValues: beam, + selectedValues: widget.beam, whenEmpty: 'Select Beam/s', ), ), @@ -190,10 +248,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: tfOthers, + value: widget.tfOthers, onChanged: (bool? value) { structuralState(() { - tfOthers = value!; + widget.updateTfOthers(value!); }); }, ) @@ -203,24 +261,22 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: tfOthers, - child: customTextField( - "Enter other truss framing/s", "", "other_tf"), + visible: widget.tfOthers, + child: customTextField("Enter other truss framing/s", "", + "other_tf", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - truss_framing = x; - }); + widget.updateTrussFraming(x); }, options: const ['Steel', 'Wood'], - selectedValues: truss_framing, + selectedValues: widget.trussFraming, whenEmpty: 'Select Truss Framing/s', ), ), ), Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text( + const Text( 'ROOF', textAlign: TextAlign.start, ), @@ -229,10 +285,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: roofOthers, + value: widget.roofOthers, onChanged: (bool? value) { structuralState(() { - roofOthers = value!; + widget.updateRoofOthers(value!); }); }, ) @@ -242,14 +298,13 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: roofOthers, - child: customTextField("Enter other roof/s", "", "other_roof"), + visible: widget.roofOthers, + child: customTextField( + "Enter other roof/s", "", "other_roof", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - roof = x; - }); + widget.updateRoof(x); }, options: const [ 'Reinforced Concrete', @@ -261,7 +316,7 @@ class _StructuralMaterialsPage extends State { 'Concrete Desk', 'Nipa/Anahaw/Cogon' ], - selectedValues: roof, + selectedValues: widget.roof, whenEmpty: 'Select Roof/s', ), ), @@ -276,10 +331,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: flooringOthers, + value: widget.flooringOthers, onChanged: (bool? value) { structuralState(() { - flooringOthers = value!; + widget.updateFlooringOthers(value!); }); }, ) @@ -289,15 +344,13 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: flooringOthers, - child: customTextField( - "Enter other flooring/s", "", "other_flooring"), + visible: widget.flooringOthers, + child: customTextField("Enter other flooring/s", "", + "other_flooring", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - structuralState(() { - flooring = x; - }); + widget.updateFlooring(x); }, options: const [ 'Reinforced Concrete', @@ -306,7 +359,7 @@ class _StructuralMaterialsPage extends State { 'Wood', 'Tiles' ], - selectedValues: flooring, + selectedValues: widget.flooring, whenEmpty: 'Select Flooring/s', ), ), @@ -321,10 +374,10 @@ class _StructuralMaterialsPage extends State { const Text('Others'), Checkbox( checkColor: Colors.white, - value: wpOthers, + value: widget.wpOthers, onChanged: (bool? value) { structuralState(() { - wpOthers = value!; + widget.updateWpOthers(value!); }); }, ) @@ -334,15 +387,13 @@ class _StructuralMaterialsPage extends State { Padding( padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( - visible: wpOthers, - child: customTextField( - "Enter other walls & partition/s", "", "other_wp"), + visible: widget.wpOthers, + child: customTextField("Enter other walls & partition/s", "", + "other_wp", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { - setState(() { - walls = x; - }); + widget.updateWalls(x); }, options: const [ 'Reinforced Concrete', @@ -354,7 +405,7 @@ class _StructuralMaterialsPage extends State { 'Sawali', 'Bamboo' ], - selectedValues: walls, + selectedValues: widget.walls, whenEmpty: 'Select Walls & Partition/s', ), ), @@ -377,46 +428,66 @@ class _StructuralMaterialsPage extends State { color: Colors.white), onPressed: () async { { - try { - 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)); - } catch (e) { - Fluttertoast.showToast( - msg: "Slow internet connection, please try again!"); - } + final tempID = await SharedPreferences.getInstance(); + + context.read().add( + AddStructuralMaterial( + id: 1, + bldgapprDetailsId: tempID.getInt('tempid')!, + assessedById: '', + assessedByName: '', + dateCreated: '', + dateModified: '', + foundation: widget.foundationOthers + ? [ + offlineBldgKey.currentState! + .value['other_foundation'] + ] + : widget.foundation, + columns: widget + .columOthers + ? [ + offlineBldgKey + .currentState!.value['other_column'] + ] + : widget.column, + beams: + widget + .beamsOthers + ? [ + offlineBldgKey + .currentState!.value['other_beam'] + ] + : widget.beam, + trussFraming: widget.tfOthers + ? [ + offlineBldgKey + .currentState!.value['other_tf'] + ] + : widget.trussFraming, + roof: + widget.roofOthers + ? [ + offlineBldgKey + .currentState!.value['other_roof'] + ] + : widget.roof, + flooring: + widget.flooringOthers + ? [ + offlineBldgKey.currentState! + .value['other_flooring'] + ] + : widget.flooring, + walls: widget.wpOthers + ? [ + offlineBldgKey + .currentState!.value['other_wp'] + ] + : widget.walls, + others: const ["Others"], + genCode: '5th')); + widget.NextBtn(); } ; }, diff --git a/lib/screens/offline/passo/building/add/utils.dart b/lib/screens/offline/passo/building/add/utils.dart new file mode 100644 index 0000000..49f7645 --- /dev/null +++ b/lib/screens/offline/passo/building/add/utils.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; + +/// Pushes a widget to a new route. +Future push(context, widget) { + return Navigator.of(context).push( + MaterialPageRoute( + builder: (BuildContext context) { + return widget; + }, + ), + ); +} diff --git a/lib/screens/passo/Building/edit_building/AddExtraItems.dart b/lib/screens/offline/passo/building/edit/AddExtraItemsEdit.dart similarity index 51% rename from lib/screens/passo/Building/edit_building/AddExtraItems.dart rename to lib/screens/offline/passo/building/edit/AddExtraItemsEdit.dart index 374968d..02515b0 100644 --- a/lib/screens/passo/Building/edit_building/AddExtraItems.dart +++ b/lib/screens/offline/passo/building/edit/AddExtraItemsEdit.dart @@ -4,25 +4,26 @@ 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'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/model/passo/class_components%20_offline.dart'; -class AddExtraItemsEdit extends StatefulWidget { +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/class_components.dart'; +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../theme-data.dart/form-style.dart'; + +class AddExtraItemsEditOffline extends StatefulWidget { final List unit; - final List options; + final List options; final int tempId; - AddExtraItemsEdit(this.unit, this.options, this.tempId); + AddExtraItemsEditOffline(this.unit, this.options, this.tempId); @override - _AddExtraItemsEdit createState() => _AddExtraItemsEdit(); + _AddExtraItemsEditOffline createState() => _AddExtraItemsEditOffline(); } -class _AddExtraItemsEdit extends State { +class _AddExtraItemsEditOffline extends State { GlobalKey formKey = GlobalKey(); final focus = FocusNode(); double _computedValue = 0; @@ -30,7 +31,7 @@ class _AddExtraItemsEdit extends State { bool isSecondHand = false; TextEditingController textEditingController = TextEditingController(); double _unitBase = 0; - int _areaValue = 0; + double _areaValue = 0; double _depValue = 0; double _unitValue = 0; double _marketValue = 0; @@ -80,11 +81,11 @@ class _AddExtraItemsEdit extends State { @override Widget build(BuildContext context) { - return BlocBuilder( + return BlocBuilder( buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddItemsScreenEdit) { + if (state is ShowAddItemsScreen) { return FormBuilder( key: formKey, onChanged: () { @@ -105,107 +106,145 @@ class _AddExtraItemsEdit extends State { 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}); - } - }, + child: SizedBox( + height: 45, + width: 300, + 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 == 1 ? true : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': value.minBaseUnitvalPercent + }); + formKey.currentState!.patchValue({ + 'buccValue': (double.parse( + value.minBaseUnitvalPercent!) * + 100) + .toString() + }); + } + if (value.maxBaseUnitvalPercent != '0.00') { + setState(() { + _unitValue = double.parse( + value.maxBaseUnitvalPercent!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue({ + 'unitValue': value.maxBaseUnitvalPercent + }); + formKey.currentState!.patchValue({ + 'buccValue': (double.parse( + value.maxBaseUnitvalPercent!) * + 100) + .toString() + }); + } + if (value.minUnitvalSqrmtr != '0.00') { + setState(() { + _unitValue = + double.parse(value.minUnitvalSqrmtr!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minUnitvalSqrmtr}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.maxUnitvalSqrmtr != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxUnitvalSqrmtr!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxUnitvalSqrmtr}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.minAddBaseunitval != '0.00') { + setState(() { + _unitValue = + double.parse(value.minAddBaseunitval!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minAddBaseunitval}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.maxAddBaseunitval != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxAddBaseunitval!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxAddBaseunitval}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.minDeductBaserate != '0.00') { + setState(() { + _unitValue = + double.parse(value.minDeductBaserate!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.minDeductBaserate}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + if (value.maxDeductBaserate != '0.00') { + setState(() { + _unitValue = + double.parse(value.maxDeductBaserate!); + _className = value.componentName!; + _classId = value.id!; + _withoutBUCC = + value.withoutBucc == 1 ? true : false; + }); + formKey.currentState!.patchValue( + {'unitValue': value.maxDeductBaserate}); + formKey.currentState! + .patchValue({'buccValue': '100'}); + } + }, + ), ), ), const SizedBox(height: 10), @@ -219,15 +258,11 @@ class _AddExtraItemsEdit 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, ), ))) @@ -246,41 +281,26 @@ class _AddExtraItemsEdit extends State { suggestionState: Suggestion.expand, onSuggestionTap: (unit) { setState(() { - _unitBase = - double.parse(unit.item!.unitValue); - _structureType = unit.item!.bldgType + - ' - ' + - unit.item!.building; + if (_withoutBUCC) { + _unitBase = _unitValue; + _structureType = + '${unit.item!.bldgType} - ${unit.item!.building}'; + formKey.currentState! + .patchValue({'buccValue': '100'}); + } else { + _unitBase = + double.parse(unit.item!.unitValue); + _structureType = + '${unit.item!.bldgType} - ${unit.item!.building}'; + formKey.currentState!.patchValue( + {'unitValue': unit.item!.unitValue}); + } }); 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: [ @@ -290,75 +310,60 @@ class _AddExtraItemsEdit extends State { name: 'unitValue', decoration: normalTextFieldStyle("Unit Value", ""), + keyboardType: TextInputType.phone, validator: FormBuilderValidators.compose([]), ), ), const SizedBox(width: 10), + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'buccValue', + decoration: normalTextFieldStyle("BUCC", ""), + keyboardType: TextInputType.phone, + validator: FormBuilderValidators.compose([]), + onChanged: (value) { + // setState(() { + // _areaValue = double.parse(value!); + // }); + }, + ), + ), + const SizedBox( + height: 40, + width: 40, + child: Center( + child: Text( + '%', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold), + ), + ), + ) + ], + ), + SizedBox( + height: 10, + ), + Row( + children: [ Expanded( flex: 1, child: FormBuilderTextField( name: 'areaValue', decoration: normalTextFieldStyle("Area", ""), + keyboardType: TextInputType.phone, validator: FormBuilderValidators.compose([]), onChanged: (value) { setState(() { - _areaValue = int.parse(value!); + _areaValue = double.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( @@ -442,6 +447,7 @@ class _AddExtraItemsEdit extends State { validator: FormBuilderValidators.compose( []), + keyboardType: TextInputType.phone, onChanged: (value) { // Check if the value is not null before parsing to double if (value != null && @@ -477,7 +483,6 @@ class _AddExtraItemsEdit extends State { ], ), ), - const SizedBox(height: 10), Text('Market Value'), const SizedBox(height: 5), @@ -517,47 +522,55 @@ class _AddExtraItemsEdit extends State { 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)); + context + .read() + .add(AddAdditionalItems( + id: 1, + bldgapprDetailsId: widget.tempId, + classId: _classId, + assessedById: '', + assessedByName: '', + dateCreated: '', + dateModified: '', + className: _className, + structType: _structureType, + unitValue: _withoutBUCC == true + ? 100 + : _unitValue * 100, + baseUnitValue: _unitBase.toString(), + area: _areaValue, + marketValue: + (_unitValue * _unitBase) * + _areaValue, + depreciationRate: _depValue, + adjustedMarketVal: _totalMarketValue( + _unitValue, + _unitBase, + _areaValue, + _depValue, + _withoutBUCC, + _className, + isPainted, + isSecondHand, + _notPaintedUnitVal, + _secondHandUnitVal) + .toString(), + actualUse: 'Test', + amtDepreciation: + _amountofDepreciation( + _unitValue, + _unitBase, + _areaValue, + _depValue, + ), + painted: true, + secondhand: true, + paintedUnitval: '1', + secondhandUnitval: '1', + genCode: "5th")); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Submit"), ), @@ -572,11 +585,11 @@ class _AddExtraItemsEdit extends State { child: ElevatedButton( onPressed: () { context - .read() + .read() .add(LoadAdditionalItems()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Cancel"), ), diff --git a/lib/screens/offline/passo/building/edit/AddExtraItemsOffline.dart b/lib/screens/offline/passo/building/edit/AddExtraItemsOffline.dart new file mode 100644 index 0000000..ab2e5e7 --- /dev/null +++ b/lib/screens/offline/passo/building/edit/AddExtraItemsOffline.dart @@ -0,0 +1,747 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:fluttertoast/fluttertoast.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/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.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'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; + +class AddExtraItemsOffline extends StatefulWidget { + final OfflineProfile offlineProfile; + AddExtraItemsOffline(this.offlineProfile); + + @override + _AddExtraItemsOffline createState() => _AddExtraItemsOffline(); +} + +class _AddExtraItemsOffline extends State { + GlobalKey formKey = GlobalKey(); + final focus = FocusNode(); + bool isPainted = false; + bool isSecondHand = false; + TextEditingController textEditingController = TextEditingController(); + double _unitBase = 0; + double _areaValue = 0; + final double _depValue = 0; + double _unitValue = 0; + String _className = ""; + int _classId = 0; + String _structureType = ""; + bool _withoutBUCC = false; + int _notPaintedUnitVal = 0; + int _secondHandUnitVal = 0; + + final DateTime now; + final String formatter; + + _AddExtraItemsOffline() + : now = DateTime.now(), + formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()); + + 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(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 ShowAddItemsScreen) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is ClassComponentsAdminLoaded) { + final classes = state.classes; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + 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: classes + .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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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 == 1 + ? true + : false; + }); + 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: state.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(() { + if (_withoutBUCC) { + _unitBase = double.parse( + unit.item!.unitValue); + _structureType = + '${unit.item!.bldgType} - ${unit.item!.building}'; + } else { + _unitBase = double.parse( + unit.item!.unitValue); + _structureType = + '${unit.item!.bldgType} - ${unit.item!.building}'; + formKey.currentState! + .patchValue({ + 'unitValue': + unit.item!.unitValue + }); + } + }); + 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( + []), + keyboardType: TextInputType.phone, + ), + ), + const SizedBox(width: 10), + Expanded( + flex: 1, + child: FormBuilderTextField( + name: 'areaValue', + decoration: normalTextFieldStyle( + "Area", ""), + keyboardType: TextInputType.phone, + validator: + FormBuilderValidators.compose( + []), + onChanged: (value) { + setState(() { + _areaValue = + double.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), + const 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), + const 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", + ""), + keyboardType: + TextInputType.phone, + 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), + ), + ), + ) + ], + ), + ], + ), + ), + ], + ), + ), + + 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( + _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: () async { + try { + final tempID = + await SharedPreferences + .getInstance(); + + context.read().add( + AddAdditionalItems( + id: 1, + bldgapprDetailsId: tempID + .getInt('tempid')!, + classId: _classId, + assessedById: widget + .offlineProfile.id + .toString(), + assessedByName: widget + .offlineProfile + .firstName!, + dateCreated: formatter, + dateModified: 'None', + 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', + genCode: "5th")); + } catch (e) { + Fluttertoast.showToast( + msg: + "Slow internet connection, please try again!", + ); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: 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< + AdditionalItemsOfflineBloc>() + .add( + const LoadAdditionalItems()); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ))); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + // if (state is Add) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add(LoadAdditionalItems()); + // }, + // ); + // } + return Container(); + }); + } +} diff --git a/lib/screens/passo/Building/add_building_components/additional_items.dart b/lib/screens/offline/passo/building/edit/additional_items_edit.dart similarity index 65% rename from lib/screens/passo/Building/add_building_components/additional_items.dart rename to lib/screens/offline/passo/building/edit/additional_items_edit.dart index dd0f133..68aaace 100644 --- a/lib/screens/passo/Building/add_building_components/additional_items.dart +++ b/lib/screens/offline/passo/building/edit/additional_items_edit.dart @@ -3,34 +3,47 @@ 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: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/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; -import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/model/passo/class_components%20_offline.dart'; +import 'package:unit2/screens/offline/passo/building/edit/AddExtraItemsEdit.dart'; -class AdditionalItemPage extends StatefulWidget { +import '../../../../../bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/class_components.dart'; +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class AdditionalItemEditPageOffline extends StatefulWidget { final List unit; - final List options; + final List options; + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; - final VoidCallback additionalItemsPrevBtn; - final VoidCallback additionalItemsNextBtn; - - const AdditionalItemPage(this.unit, this.options, this.additionalItemsPrevBtn, - this.additionalItemsNextBtn); + AdditionalItemEditPageOffline( + this.unit, this.options, this.tempId, this.NextBtn, this.PrevBtn); @override - _AdditionalItemPage createState() => _AdditionalItemPage(); + _AdditionalItemEditPageOffline createState() => + _AdditionalItemEditPageOffline(); } -class _AdditionalItemPage extends State { +class _AdditionalItemEditPageOffline + extends State { void deleteItem(int itemId) { - context.read().add(DeleteAdditionalItems(id: itemId)); + context + .read() + .add(DeleteAdditionalItems(id: itemId)); } + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row.adjustedMarketVal); + // }); + // return total; + // } + double _totalMarketValue(items) { double total = 0; items.forEach((row) { @@ -46,23 +59,11 @@ class _AdditionalItemPage extends State { padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is AdditionalItemsLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AdditionalItemsLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is AdditionalItemsErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, + child: BlocConsumer( + listener: (context, state) {}, builder: (context, state) { - final state = context.watch().state; + final state = context.watch().state; if (state is AdditionalItemsLoaded) { return Column( children: [ @@ -89,12 +90,12 @@ class _AdditionalItemPage extends State { ), onPressed: () { context - .read() + .read() .add(ShowAdditionalItems()); }, - child: Row( + child: const Row( mainAxisSize: MainAxisSize.min, - children: const [ + children: [ Text('ADD ITEM'), // <-- Text SizedBox( width: 5, @@ -129,15 +130,22 @@ class _AdditionalItemPage extends State { label: Text('Action'), ) ], - rows: state.items.map((dataRow) { + rows: state.addItem.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(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow.baseUnitValue)))), + DataCell( + Text(dataRow.unitValue.toString())), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow.adjustedMarketVal)))), DataCell(Row( children: [ InkWell( @@ -155,7 +163,12 @@ class _AdditionalItemPage extends State { ), ), onTap: () { - deleteItem(dataRow.id); + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); }, ), const SizedBox( @@ -195,15 +208,15 @@ class _AdditionalItemPage extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( - 'Total', + 'Total Market Value', style: TextStyle( - fontWeight: FontWeight.bold, fontSize: 15), + fontWeight: FontWeight.bold, fontSize: 17), ), Text( NumberFormat.currency(locale: 'en-PH', symbol: "₱") - .format(_totalMarketValue(state.items)), + .format(_totalMarketValue(state.addItem)), style: TextStyle( - fontWeight: FontWeight.bold, fontSize: 15), + fontWeight: FontWeight.bold, fontSize: 17), ) ], ), @@ -218,9 +231,8 @@ class _AdditionalItemPage extends State { color: Colors.white), onPressed: () { { - widget.additionalItemsPrevBtn(); + widget.PrevBtn(); } - ; }, ), CustomButton( @@ -228,9 +240,8 @@ class _AdditionalItemPage extends State { color: Colors.white), onPressed: () { { - widget.additionalItemsNextBtn(); + widget.NextBtn(); } - ; }, ) ], @@ -245,16 +256,17 @@ class _AdditionalItemPage extends State { successAlert(context, "Deletion Successful", "Extra item has been deleted successfully", () { Navigator.of(context).pop(); - context - .read() - .add(const LoadAdditionalItems()); + context.read().add( + LoadAdditionalItemsEdit( + items: const [], + id: widget.tempId)); }); }); } } if (state is ShowAddItemsScreen) { return ConstrainedBox( - constraints: BoxConstraints(maxHeight: 1000.0), + constraints: const BoxConstraints(maxHeight: 1000.0), child: AlertDialog( insetPadding: const EdgeInsets.symmetric( horizontal: 20.0, @@ -269,21 +281,51 @@ class _AdditionalItemPage extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( - child: AddExtraItems(widget.unit, widget.options)) + child: AddExtraItemsEditOffline( + widget.unit, widget.options, widget.tempId)) ], ), ), ); } - if (state is AdditionalItemsErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add(LoadAdditionalItems()); - }, - ); - } - return Container(); + 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: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ), + ], + ), + ); }, ), ), diff --git a/lib/screens/offline/passo/building/edit/building_and_structure.dart b/lib/screens/offline/passo/building/edit/building_and_structure.dart new file mode 100644 index 0000000..1a20ffc --- /dev/null +++ b/lib/screens/offline/passo/building/edit/building_and_structure.dart @@ -0,0 +1,336 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/add/AddBuildingAndStructure..dart'; + +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class BuildingAndStructureOfflinePage extends StatefulWidget { + final VoidCallback additionalItemsPrevBtn; + final VoidCallback additionalItemsNextBtn; + final OfflineProfile offlineProfile; + + const BuildingAndStructureOfflinePage(this.additionalItemsPrevBtn, + this.additionalItemsNextBtn, this.offlineProfile); + + @override + _BuildingAndStructureOfflinePage createState() => + _BuildingAndStructureOfflinePage(); +} + +class _BuildingAndStructureOfflinePage + extends State { + // void deleteItem(int itemId) { + // context.read().add(DeleteAdditionalItems(id: itemId)); + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteBuildingAndStructure(id: itemId)); + } + + final items = []; + + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketValue); + }); + return total; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is BuildingAndStructureOfflineInitial) { + 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('BUILDING AND STRUCTURE', + 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(ShowBuildingAndStructure()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD NEW'), // <-- Text + SizedBox( + width: 5, + ), + Icon( + // <-- Icon + Icons.add, + size: 24.0, + ), + ], + ), + ), + ) + ])))) + ]); + } + if (state is BuildingAndStructureLoaded) { + 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('BUILDING AND STRUCTURES', + 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(ShowBuildingAndStructure()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + 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('Building Core'), + ), + const DataColumn( + label: Text('Type'), + ), + const DataColumn( + label: Text('Area'), + ), + const DataColumn( + label: Text('Unit Value'), + ), + const DataColumn( + label: Text('% of BUCC'), + ), + const DataColumn( + label: Text('Base Market Value'), + ), + const DataColumn( + label: Text('% of Depreciation'), + ), + const DataColumn( + label: Text('Depreciation Cost'), + ), + const DataColumn( + label: Text('Market Value'), + ), + const DataColumn( + label: Text('Action'), + ) + ], + rows: state.bldgAndStructure.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.actualUse!)), + DataCell(Text(dataRow.bldgType!)), + DataCell(Text(dataRow.bldgArea!)), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse(dataRow.unitValue!)), + )), + const DataCell(Text("100%")), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format( + double.parse(dataRow.marketValue!)), + )), + DataCell(Text(dataRow.depRate!)), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse(dataRow.depAmount!)), + )), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', symbol: "₱") + .format(double.parse( + dataRow.adjustedMarketValue!)), + )), + 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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).toList(), + ), + ) + ], + ), + ), + )), + Padding( + padding: const EdgeInsets.only(left: 20.0, right: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total Market Value', + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ), + Text( + NumberFormat.currency(locale: 'en-PH', symbol: "₱") + .format(_totalMarketValue(state.bldgAndStructure)), + style: + TextStyle(fontWeight: FontWeight.bold, fontSize: 17), + ) + ], + ), + ), + 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 BuildingAndStructureDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(LoadBuildingAndStructure()); + }); + }); + } + } + if (state is ShowBldgAndStructuresScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 10.0, + ), + title: const Text( + 'ADD NEW BLDG & STRUCTURE', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: + AddBuildingAndStructureOffline(widget.offlineProfile)) + ], + ), + ), + ); + } + return Container(); + }, + )); + } +} diff --git a/lib/screens/offline/passo/building/edit/edit_building.dart b/lib/screens/offline/passo/building/edit/edit_building.dart new file mode 100644 index 0000000..372f7fb --- /dev/null +++ b/lib/screens/offline/passo/building/edit/edit_building.dart @@ -0,0 +1,265 @@ +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:im_stepper/stepper.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/building/edit/additional_items_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/building_and_structure.dart'; +import 'package:unit2/screens/offline/passo/building/edit/flutter_painter_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/general_description_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/landref_location_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_appraisal_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_assessment_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart'; +import 'package:unit2/screens/offline/passo/building/edit/structural_materials_edit.dart'; +import 'package:unit2/utils/alerts.dart'; + +import '../../../../../bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart'; +import '../../../../../model/passo/property_info.dart'; +import '../../../../../theme-data.dart/colors.dart'; + +GlobalKey offlineBldgEditKey = GlobalKey(); + +class EditBuildingOffline extends StatefulWidget { + final int index; + final PropertyInfo faas; + final String title; + final OfflineProfile offlineProfile; + final Function loadBldg; + + const EditBuildingOffline( + {super.key, + required this.title, + required this.index, + required this.faas, + required this.offlineProfile, + required this.loadBldg}); + @override + _EditBuildingOffline createState() => _EditBuildingOffline(); +} + +class _EditBuildingOffline extends State { + // THE FOLLOWING TWO VARIABLES ARE REQUIRED TO CONTROL THE STEPPER. + int activeStep = 0; // Initial step set to 5. + + int upperBound = 8; // upperBound MUST BE total number of icons minus 1. + + void PrevBtn() { + setState(() { + activeStep--; + }); + } + + void NextBtn() { + setState(() { + activeStep++; + }); + } + + void onSAveAll() { + Navigator.of(context).pop(); + widget.loadBldg(); + } + + List foundation = []; + List column = []; + List beam = []; + List trussFraming = []; + List roof = []; + List flooring = []; + List walls = []; + + void updateFoundation(List updatedList) { + setState(() { + foundation = updatedList; + }); + } + + void updateColumn(List updatedList) { + setState(() { + column = updatedList; + }); + } + + void updateBeam(List updatedList) { + setState(() { + beam = updatedList; + }); + } + + void updateTrussFraming(List updatedList) { + setState(() { + trussFraming = updatedList; + }); + } + + void updateRoof(List updatedList) { + setState(() { + roof = updatedList; + }); + } + + void updateFlooring(List updatedList) { + setState(() { + flooring = updatedList; + }); + } + + void updateWalls(List updatedList) { + setState(() { + walls = updatedList; + }); + } + + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async { + confirmAlertWithCancel( + context, + onSAveAll, + () => null, + 'Cancel Editing?', + "Unsaved edited data will not be saved, are you sure you want to exit?"); // Action to perform on back pressed + return false; + }, + child: Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const 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) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is SpecificStructuralMaterialLoaded) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + final unit = state.unit; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is ClassComponentsAdminLoaded) { + return Column( + children: [ + NumberStepper( + numbers: const [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + activeStepColor: primary, + numberStyle: + const 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: StatefulBuilder(builder: + (BuildContext context, + StateSetter setState) { + return Container( + child: content(PrevBtn, NextBtn, unit, + state.classes), + ); + }), + ), + ], + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ))), + ); + } + + // Returns the header text based on the activeStep. + Widget content(PrevBtn, NextBtn, unit, classes) { + switch (activeStep) { + case 0: + return PropertyOwnerInfoEditOffline( + widget.index, + widget.faas, + 'Edit', + PrevBtn, + NextBtn, + ); + + case 1: + return BldgLocLandRefEditOffline(widget.faas.id!, NextBtn, PrevBtn); + + case 2: + return GeneralDescriptionEditOffline(widget.faas.id!, NextBtn, PrevBtn); + + case 4: + return BuildingAndStructureOfflinePage( + PrevBtn, NextBtn, widget.offlineProfile); + + case 3: + return FlutterDrawEdit(widget.faas.id!); + + case 5: + return StructuralMaterialsPageEditOffline( + widget.faas.id!, NextBtn, PrevBtn); + + case 6: + return AdditionalItemEditPageOffline( + unit, classes, widget.faas.id!, NextBtn, PrevBtn); + + case 7: + return PropertyAppraisalEditPageOffline( + widget.faas.id!, NextBtn, PrevBtn); + + case 8: + return PropertyAssessmentEditOfflinePage( + widget.faas.id!, onSAveAll, widget.offlineProfile); + + default: + return Container(); + // return PropertyOwnerInfoEdit( + // widget.index, widget.faas, widget.title, NextBtn, PrevBtn); + } + } +} diff --git a/lib/screens/offline/passo/building/edit/flutter_painter_edit.dart b/lib/screens/offline/passo/building/edit/flutter_painter_edit.dart new file mode 100644 index 0000000..d089a67 --- /dev/null +++ b/lib/screens/offline/passo/building/edit/flutter_painter_edit.dart @@ -0,0 +1,814 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:ui'; + +import 'package:http/http.dart'; // Removed 'as http' +import 'package:path/path.dart'; // For basename function +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_painter_v2/flutter_painter.dart'; +import 'package:flutter_painter_v2/flutter_painter_extensions.dart'; +import 'package:flutter_painter_v2/flutter_painter_pure.dart'; + +import 'package:path_provider/path_provider.dart'; + +import 'dart:ui' as ui; + +import 'package:phosphor_flutter/phosphor_flutter.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/model/passo/floor_sketch.dart'; + +import 'package:unit2/utils/urls.dart'; + +import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; + +class FlutterDrawEdit extends StatefulWidget { + final int tempId; + FlutterDrawEdit(this.tempId); + + @override + _FlutterPainterExampleState createState() => _FlutterPainterExampleState(); +} + +class _FlutterPainterExampleState extends State { + static const Color red = Color.fromARGB(255, 0, 0, 0); + FocusNode textFocusNode = FocusNode(); + late PainterController controller; + ui.Image? backgroundImage; + Paint shapePaint = Paint() + ..strokeWidth = 5 + ..color = Colors.black + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + File? _image; + + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + static const List imageLinks = [ + "https://i.imgur.com/btoI5OX.png", + "https://i.imgur.com/EXTQFt7.png", + "https://i.imgur.com/EDNjJYL.png", + "https://i.imgur.com/uQKD6NL.png", + "https://i.imgur.com/cMqVRbl.png", + "https://i.imgur.com/1cJBAfI.png", + "https://i.imgur.com/eNYfHKL.png", + "https://i.imgur.com/c4Ag5yt.png", + "https://i.imgur.com/GhpCJuf.png", + "https://i.imgur.com/XVMeluF.png", + "https://i.imgur.com/mt2yO6Z.png", + "https://i.imgur.com/rw9XP1X.png", + "https://i.imgur.com/pD7foZ8.png", + "https://i.imgur.com/13Y3vp2.png", + "https://i.imgur.com/ojv3yw1.png", + "https://i.imgur.com/f8ZNJJ7.png", + "https://i.imgur.com/BiYkHzw.png", + "https://i.imgur.com/snJOcEz.png", + "https://i.imgur.com/b61cnhi.png", + "https://i.imgur.com/FkDFzYe.png", + "https://i.imgur.com/P310x7d.png", + "https://i.imgur.com/5AHZpua.png", + "https://i.imgur.com/tmvJY4r.png", + "https://i.imgur.com/PdVfGkV.png", + "https://i.imgur.com/1PRzwBf.png", + "https://i.imgur.com/VeeMfBS.png", + ]; + + @override + void initState() { + super.initState(); + controller = PainterController( + settings: PainterSettings( + text: TextSettings( + focusNode: textFocusNode, + textStyle: const TextStyle( + fontWeight: FontWeight.bold, color: red, fontSize: 18), + ), + freeStyle: const FreeStyleSettings( + color: red, + strokeWidth: 5, + ), + shape: ShapeSettings( + paint: shapePaint, + ), + scale: const ScaleSettings( + enabled: true, + minScale: 1, + maxScale: 5, + ))); + // Listen to focus events of the text field + textFocusNode.addListener(onFocus); + // Initialize background + initBackground(); + } + + /// Fetches image from an [ImageProvider] (in this example, [NetworkImage]) + /// to use it as a background + void initBackground() async { + final prefs = await SharedPreferences.getInstance(); + final floorSketchSaved = prefs.getBool('floorSketchSaved') ?? false; + + print(floorSketchSaved); + + ui.Image image; + + final String imagePath = + '/data/user/0/com.app.rpass/cache/${widget.tempId}.png'; + image = await _loadImageFromPath(imagePath); + + setState(() { + backgroundImage = image; + controller.background = image.backgroundDrawable; + }); + } + + /// Updates UI when the focus changes + void onFocus() { + setState(() {}); + } + + Future _loadImageFromPath(String imagePath) async { + final file = File(imagePath); + final bytes = await file.readAsBytes(); + final Completer completer = Completer(); + ui.decodeImageFromList(bytes, (ui.Image img) { + completer.complete(img); + }); + return completer.future; + } + + Future deleteImage(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + + final String imagePath = + '/data/user/0/com.app.rpass/cache/${widget.tempId}.png'; + final file = File(imagePath); + + if (await file.exists()) { + await file.delete(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image deleted successfully')), + ); + + final image = await const AssetImage('assets/pngs/white_bg.png').image; + setState(() { + backgroundImage = image; + controller.background = image.backgroundDrawable; + }); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image does not exist')), + ); + } + } + + Widget buildDefault(BuildContext context) { + return Scaffold( + appBar: PreferredSize( + preferredSize: const Size(double.infinity, kToolbarHeight), + // Listen to the controller and update the UI when it updates. + child: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, child) { + return AppBar( + title: child, + automaticallyImplyLeading: false, // Disable the back button + + actions: [ + // Delete the selected drawable + IconButton( + icon: const Icon( + PhosphorIcons.trash, + ), + onPressed: controller.selectedObjectDrawable == null + ? null + : removeSelectedDrawable, + ), + // Delete the selected drawable + IconButton( + icon: const Icon( + Icons.flip, + ), + onPressed: controller.selectedObjectDrawable != null && + controller.selectedObjectDrawable is ImageDrawable + ? flipSelectedImageDrawable + : null, + ), + // Redo action + IconButton( + icon: const Icon( + PhosphorIcons.arrowClockwise, + ), + onPressed: controller.canRedo ? redo : null, + ), + // Undo action + IconButton( + icon: const Icon( + PhosphorIcons.arrowCounterClockwise, + ), + onPressed: controller.canUndo ? undo : null, + ), + ], + ); + }), + ), + // Generate image + floatingActionButton: Stack( + children: [ + Align( + alignment: Alignment.bottomRight, + child: FloatingActionButton( + heroTag: 'btn1', + child: const Icon( + PhosphorIcons.imageFill, + ), + onPressed: () => renderAndDisplayImage(context), + ), + ), + Align( + alignment: Alignment.bottomRight, + child: Padding( + padding: const EdgeInsets.only(bottom: 60.0), + child: FloatingActionButton( + heroTag: 'btn2', + child: const Icon( + Icons.delete, + ), + onPressed: () => deleteImage(context), + ), + ), + ), + // Add more FloatingActionButton widgets here if needed + ], + ), + body: Stack( + children: [ + if (backgroundImage != null) + // Enforces constraints + Positioned.fill( + child: Center( + child: AspectRatio( + aspectRatio: + backgroundImage!.width / backgroundImage!.height, + child: FlutterPainter( + controller: controller, + ), + ), + ), + ), + Positioned( + bottom: 0, + right: 0, + left: 0, + child: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, __) => Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Flexible( + child: Container( + constraints: const BoxConstraints( + maxWidth: 400, + ), + padding: const EdgeInsets.symmetric(horizontal: 15), + decoration: const BoxDecoration( + borderRadius: + BorderRadius.vertical(top: Radius.circular(20)), + color: Colors.white54, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (controller.freeStyleMode != + FreeStyleMode.none) ...[ + const Divider(), + const Text("Free Style Settings"), + // Control free style stroke width + Row( + children: [ + const Expanded( + flex: 1, child: Text("Stroke Width")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 2, + max: 25, + value: controller.freeStyleStrokeWidth, + onChanged: setFreeStyleStrokeWidth), + ), + ], + ), + if (controller.freeStyleMode == + FreeStyleMode.draw) + Row( + children: [ + const Expanded( + flex: 1, child: Text("Color")), + // Control free style color hue + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + controller.freeStyleColor) + .hue, + activeColor: + controller.freeStyleColor, + onChanged: setFreeStyleColor), + ), + ], + ), + ], + if (textFocusNode.hasFocus) ...[ + const Divider(), + const Text("Text settings"), + // Control text font size + Row( + children: [ + const Expanded( + flex: 1, child: Text("Font Size")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 8, + max: 96, + value: + controller.textStyle.fontSize ?? 14, + onChanged: setTextFontSize), + ), + ], + ), + + // Control text color hue + Row( + children: [ + const Expanded(flex: 1, child: Text("Color")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + controller.textStyle.color ?? + red) + .hue, + activeColor: controller.textStyle.color, + onChanged: setTextColor), + ), + ], + ), + ], + if (controller.shapeFactory != null) ...[ + const Divider(), + const Text("Shape Settings"), + + // Control text color hue + Row( + children: [ + const Expanded( + flex: 1, child: Text("Stroke Width")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 2, + max: 25, + value: controller + .shapePaint?.strokeWidth ?? + shapePaint.strokeWidth, + onChanged: (value) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + strokeWidth: value, + ))), + ), + ], + ), + + // Control shape color hue + Row( + children: [ + const Expanded(flex: 1, child: Text("Color")), + Expanded( + flex: 3, + child: Slider.adaptive( + min: 0, + max: 359.99, + value: HSVColor.fromColor( + (controller.shapePaint ?? + shapePaint) + .color) + .hue, + activeColor: (controller.shapePaint ?? + shapePaint) + .color, + onChanged: (hue) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + color: HSVColor.fromAHSV( + 1, hue, 1, 1) + .toColor(), + ))), + ), + ], + ), + + Row( + children: [ + const Expanded( + flex: 1, child: Text("Fill shape")), + Expanded( + flex: 3, + child: Center( + child: Switch( + value: (controller.shapePaint ?? + shapePaint) + .style == + PaintingStyle.fill, + onChanged: (value) => + setShapeFactoryPaint( + (controller.shapePaint ?? + shapePaint) + .copyWith( + style: value + ? PaintingStyle.fill + : PaintingStyle.stroke, + ))), + ), + ), + ], + ), + ] + ], + ), + ), + ), + ], + ), + ), + ), + ], + ), + bottomNavigationBar: ValueListenableBuilder( + valueListenable: controller, + builder: (context, _, __) => Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + // Free-style eraser + IconButton( + icon: Icon( + PhosphorIcons.eraser, + color: controller.freeStyleMode == FreeStyleMode.erase + ? Theme.of(context).primaryColor + : null, + ), + onPressed: toggleFreeStyleErase, + ), + // Free-style drawing + IconButton( + icon: Icon( + PhosphorIcons.scribbleLoop, + color: controller.freeStyleMode == FreeStyleMode.draw + ? Theme.of(context).primaryColor + : null, + ), + onPressed: toggleFreeStyleDraw, + ), + // Add text + IconButton( + icon: Icon( + PhosphorIcons.textT, + color: textFocusNode.hasFocus + ? Theme.of(context).primaryColor + : null, + ), + onPressed: addText, + ), + // Add sticker image + IconButton( + icon: const Icon( + PhosphorIcons.sticker, + ), + onPressed: () => addSticker(context), + ), + // Add shapes + if (controller.shapeFactory == null) + PopupMenuButton( + tooltip: "Add shape", + itemBuilder: (context) => { + LineFactory(): "Line", + ArrowFactory(): "Arrow", + DoubleArrowFactory(): "Double Arrow", + RectangleFactory(): "Rectangle", + OvalFactory(): "Oval", + } + .entries + .map((e) => PopupMenuItem( + value: e.key, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Icon( + getShapeIcon(e.key), + color: Colors.black, + ), + Text(" ${e.value}") + ], + ))) + .toList(), + onSelected: selectShape, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Icon( + getShapeIcon(controller.shapeFactory), + color: controller.shapeFactory != null + ? Theme.of(context).primaryColor + : null, + ), + ), + ) + else + IconButton( + icon: Icon( + getShapeIcon(controller.shapeFactory), + color: Theme.of(context).primaryColor, + ), + onPressed: () => selectShape(null), + ), + ], + ), + )); + } + + @override + Widget build(BuildContext context) { + return buildDefault(context); + } + + static IconData getShapeIcon(ShapeFactory? shapeFactory) { + if (shapeFactory is LineFactory) return PhosphorIcons.lineSegment; + if (shapeFactory is ArrowFactory) return PhosphorIcons.arrowUpRight; + if (shapeFactory is DoubleArrowFactory) { + return PhosphorIcons.arrowsHorizontal; + } + if (shapeFactory is RectangleFactory) return PhosphorIcons.rectangle; + if (shapeFactory is OvalFactory) return PhosphorIcons.circle; + return PhosphorIcons.polygon; + } + + void undo() { + controller.undo(); + } + + void redo() { + controller.redo(); + } + + void toggleFreeStyleDraw() { + controller.freeStyleMode = controller.freeStyleMode != FreeStyleMode.draw + ? FreeStyleMode.draw + : FreeStyleMode.none; + } + + void toggleFreeStyleErase() { + controller.freeStyleMode = controller.freeStyleMode != FreeStyleMode.erase + ? FreeStyleMode.erase + : FreeStyleMode.none; + } + + void addText() { + if (controller.freeStyleMode != FreeStyleMode.none) { + controller.freeStyleMode = FreeStyleMode.none; + } + controller.addText(); + } + + void addSticker(BuildContext context) async { + final imageLink = await showDialog( + context: context, + builder: (context) => const SelectStickerImageDialog( + imagesLinks: imageLinks, + )); + if (imageLink == null) return; + controller.addImage( + await NetworkImage(imageLink).image, const Size(100, 100)); + } + + void setFreeStyleStrokeWidth(double value) { + controller.freeStyleStrokeWidth = value; + } + + void setFreeStyleColor(double hue) { + controller.freeStyleColor = HSVColor.fromAHSV(1, hue, 1, 1).toColor(); + } + + void setTextFontSize(double size) { + // Set state is just to update the current UI, the [FlutterPainter] UI updates without it + setState(() { + controller.textSettings = controller.textSettings.copyWith( + textStyle: + controller.textSettings.textStyle.copyWith(fontSize: size)); + }); + } + + void setShapeFactoryPaint(Paint paint) { + // Set state is just to update the current UI, the [FlutterPainter] UI updates without it + setState(() { + controller.shapePaint = paint; + }); + } + + void setTextColor(double hue) { + controller.textStyle = controller.textStyle + .copyWith(color: HSVColor.fromAHSV(1, hue, 1, 1).toColor()); + } + + void selectShape(ShapeFactory? factory) { + controller.shapeFactory = factory; + } + + Future _uploadImage() async { + // Create a map with the required fields + final tempID = await SharedPreferences.getInstance(); + + final String imagePath = + '/data/user/0/com.app.rpass/cache/${widget.tempId}.png'; + + await tempID.setBool('floorSketchSaved', true); + var file = File(imagePath); + // Map detailsMap = { + // "bldgappr_details_id": 182, // int8 NOT NULL + // "date_created": DateTime.now().toIso8601String(), // timestamptz NULL + // "floor_sketch": file.path, // text NULL + // "gen_code": "5TH", // varchar(20) NOT NULL + // }; + + var floorSketchs = FloorSketch( + bldgapprDetailsId: widget.tempId, + dateCreated: DateTime.now().toIso8601String(), + floorSketch: file.path, + genCode: "5TH"); + + try { + // Response response = await _postBuildingDetails(detailsMap); + // print(response.body); + await SQLServices.instance.createFloorSketch(floorSketchs); + // if (response.statusCode == 201) { + // print('Upload successful'); + // } else { + // print('Upload failed with status: ${response.statusCode}'); + // } + } catch (e) { + if (kDebugMode) { + print('Error: $e'); + } + } + } + + void renderAndDisplayImage(BuildContext context) async { + if (backgroundImage == null) return; + + final backgroundImageSize = Size( + backgroundImage!.width.toDouble(), + backgroundImage!.height.toDouble(), + ); + + try { + // Render the image + final image = await controller.renderImage(backgroundImageSize); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + final imageBytes = byteData!.buffer.asUint8List(); + final tempID = await SharedPreferences.getInstance(); + + // Write the PNG image data to a file + final file = + File('${(await getTemporaryDirectory()).path}/${widget.tempId}.png'); + await file.writeAsBytes(imageBytes); + + // Show a dialog with the image + // ignore: use_build_context_synchronously + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Rendered Image'), + content: Image.memory(imageBytes), + actions: [ + TextButton( + child: const Text('SAVE'), + onPressed: () { + _uploadImage(); + }, + ), + TextButton( + child: const Text('Close'), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + ], + ), + ); + + // Show a snackbar with the file path + // ignore: use_build_context_synchronously + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image saved to ${file.path}')), + ); + } catch (e) { + // Handle potential errors + // ignore: use_build_context_synchronously + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e')), + ); + } + } + + void removeSelectedDrawable() { + final selectedDrawable = controller.selectedObjectDrawable; + if (selectedDrawable != null) controller.removeDrawable(selectedDrawable); + } + + void flipSelectedImageDrawable() { + final imageDrawable = controller.selectedObjectDrawable; + if (imageDrawable is! ImageDrawable) return; + + controller.replaceDrawable( + imageDrawable, imageDrawable.copyWith(flipped: !imageDrawable.flipped)); + } +} + +class RenderedImageDialog extends StatelessWidget { + final Future imageFuture; + final String imagePath = '/data/user/0/com.app.rpass/cache/182.png'; + + const RenderedImageDialog({Key? key, required this.imageFuture}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text("Rendered Image"), + content: FutureBuilder( + future: imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const SizedBox( + height: 50, + child: Center(child: CircularProgressIndicator.adaptive()), + ); + } + if (!snapshot.hasData || snapshot.data == null) { + return const SizedBox(); + } + return InteractiveViewer( + maxScale: 10, child: Image.memory(snapshot.data!)); + }, + ), + ); + } +} + +class SelectStickerImageDialog extends StatelessWidget { + final List imagesLinks; + + const SelectStickerImageDialog({Key? key, this.imagesLinks = const []}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text("Select sticker"), + content: imagesLinks.isEmpty + ? const Text("No images") + : FractionallySizedBox( + heightFactor: 0.5, + child: SingleChildScrollView( + child: Wrap( + children: [ + for (final imageLink in imagesLinks) + InkWell( + onTap: () => Navigator.pop(context, imageLink), + child: FractionallySizedBox( + widthFactor: 1 / 4, + child: Image.network(imageLink), + ), + ), + ], + ), + ), + ), + actions: [ + TextButton( + child: const Text("Cancel"), + onPressed: () => Navigator.pop(context), + ) + ], + ); + } +} diff --git a/lib/screens/offline/passo/building/edit/general_description_edit.dart b/lib/screens/offline/passo/building/edit/general_description_edit.dart new file mode 100644 index 0000000..fc170e3 --- /dev/null +++ b/lib/screens/offline/passo/building/edit/general_description_edit.dart @@ -0,0 +1,349 @@ +import 'dart:convert'; + +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:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart'; + +import '../../../../../model/passo/general_description.dart'; +import '../../../../../model/passo/unit_construct.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class GeneralDescriptionEditOffline extends StatefulWidget { + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + GeneralDescriptionEditOffline(this.tempId, this.NextBtn, this.PrevBtn); + @override + _GeneralDescriptionEditOffline createState() => + _GeneralDescriptionEditOffline(); +} + +class _GeneralDescriptionEditOffline + extends State { + final actual_use = [ + "Residential", + "Agricultural", + "Commercial", + "Industrial", + "Mineral", + "Timberland", + ]; + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) async { + // if (state is GenDescLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is GenDescLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + + // final tempID = await SharedPreferences.getInstance(); + // await tempID.setInt( + // 'totalValue', int.parse(state.gendesc.totalFloorArea!)); + // await tempID.setString( + // 'actualUse', state.gendesc.actualUse!); + + // } + // if (state is GenDescErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SpecificGeneralDescriptionLoaded) { + final gendesc = state.gendesc; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is UnitConstructLoaded) { + return FormBuilder( + key: offlineBldgEditKey, + initialValue: { + 'bldg_permit': gendesc.bldgPermit, + 'date_issued': gendesc.dateIssued.toString(), + 'cct': gendesc.cct.toString(), + 'coc_issued': gendesc.certCompletionIssued.toString(), + 'coo_issued': gendesc.certOccupancyIssued.toString(), + 'date_cnstructed': gendesc.dateIssued.toString(), + 'date_occupied': gendesc.dateOccupied.toString(), + 'bldg_age': gendesc.bldgAge.toString(), + 'no_of_storeys': gendesc.noStoreys.toString(), + 'area_of_1stFl': gendesc.area1Stfloor, + 'area_of_2ndFl': gendesc.area2Ndfloor, + 'area_of_3rdFl': gendesc.area3Rdfloor, + 'area_of_4thFl': gendesc.area4Thfloor, + 'total_area': gendesc.totalFloorArea.toString(), + 'actual_use': gendesc.actualUse + }, + enabled: true, + onChanged: () { + offlineBldgEditKey.currentState!.save(); + debugPrint( + offlineBldgEditKey.currentState!.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: 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('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( + gendesc.bldgKind ?? "Kind of Building", + "Kind of Building"), + items: state.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', TextInputType.phone), + ), + 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', + TextInputType.number), + 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', TextInputType.phone), + ), + 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', TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Area of 1st Floor", + "", 'area_of_1stFl', TextInputType.phone), + ), + 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', + TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Area of 3rd Floor", + "", + 'area_of_3rdFl', + TextInputType.phone)), + 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', + TextInputType.phone)) + ]), + customTextField("Total Area", "", 'total_area', + TextInputType.phone), + 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: () { + { + offlineBldgEditKey.currentState!.save(); + + var gendescData = GeneralDesc( + id: 1, + bldgapprDetailsId: widget.tempId, + assessedById: "1", + assessedByName: 'hhs', + bldgKind: offlineBldgEditKey + .currentState + ?.value['bldg_type'] + ?.building ?? + gendesc.bldgKind, + strucType: offlineBldgEditKey + .currentState + ?.value['bldg_type'] + ?.bldgType ?? + gendesc.strucType, + bldgPermit: offlineBldgEditKey + .currentState + ?.value['bldg_permit'] ?? + gendesc.bldgPermit, + dateIssued: offlineBldgEditKey + .currentState + ?.value['date_issued'] != + null + ? offlineBldgEditKey.currentState!.value['date_issued'] + .toString() + : gendesc.dateIssued, + cct: offlineBldgEditKey.currentState!.value['cct'] ?? gendesc.cct, + certCompletionIssued: offlineBldgEditKey.currentState!.value['coc_issued'].toString(), + certOccupancyIssued: offlineBldgEditKey.currentState!.value['coo_issued'].toString(), + dateCompleted: offlineBldgEditKey.currentState!.value['date_cnstructed'].toString(), + dateOccupied: offlineBldgEditKey.currentState!.value['date_occupied'].toString(), + bldgAge: offlineBldgEditKey.currentState?.value['bldg_age']!, + noStoreys: offlineBldgEditKey.currentState?.value['no_of_storeys']!, + area1Stfloor: offlineBldgEditKey.currentState?.value['area_of_1stFl'], + area2Ndfloor: offlineBldgEditKey.currentState?.value['area_of_2ndFl'], + area3Rdfloor: offlineBldgEditKey.currentState?.value['area_of_3rdFl'], + area4Thfloor: offlineBldgEditKey.currentState?.value['area_of_4thFl'], + totalFloorArea: offlineBldgEditKey.currentState?.value['total_area'], + floorSketch: 'null', + actualUse: offlineBldgEditKey.currentState?.value['actual_use'], + unitValue: offlineBldgEditKey.currentState?.value['bldg_type']?.unitValue ?? gendesc.unitValue); + + context.read().add( + UpdateGeneralDescription( + id: widget.tempId, + gendesc: gendescData)); + + widget.NextBtn(); + } + ; + }, + ) + ], + ) + ], + ), + ), + ), + ); + } + return Container(); + }, + ); + } + // 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/offline/passo/building/edit/landref_location_edit.dart b/lib/screens/offline/passo/building/edit/landref_location_edit.dart new file mode 100644 index 0000000..1158c04 --- /dev/null +++ b/lib/screens/offline/passo/building/edit/landref_location_edit.dart @@ -0,0 +1,494 @@ +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/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/location/location_bloc.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; + +import '../../../../../model/passo/barangay.dart'; +import '../../../../../model/passo/bldg_loc.dart'; +import '../../../../../model/passo/city.dart'; +import '../../../../../model/passo/land_ref.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class BldgLocLandRefEditOffline extends StatefulWidget { + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + BldgLocLandRefEditOffline(this.tempId, this.NextBtn, this.PrevBtn); + @override + _BldgLocLandRefEditOffline createState() => _BldgLocLandRefEditOffline(); +} + +class _BldgLocLandRefEditOffline extends State { + Set seenCityCodes = Set(); + @override + Widget build(BuildContext context) { + 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 LocationLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + + // if (state is LocationErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SpecificLocationLoaded) { + final bldgloc = state.location; + return BlocConsumer( + listener: (context, state) { + // if (state is LandrefLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandrefErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SpecificLandrefLoaded) { + 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 MunicipalityErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, builder: (context, state) { + if (state is MunicipalitiesLoaded) { + final cityList = state.city; + 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 BarangayLoaded) { + 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(); + // } + }, builder: (context, state) { + if (state is BarangayLoaded) { + List brgyList = state.brgy; + List brgyNAmes = brgyList + .map((brgy) => brgy.barangayDescription) + .toList() + .cast(); + return FormBuilder( + key: offlineBldgEditKey, + initialValue: { + 'street': bldgloc.street ?? "", + 'province': bldgloc.province ?? "", + 'l_owner': landRef.owner, + 'oct_tct_cloa': landRef.cloaNo ?? "no", + 'survey_no': landRef.surveyNo ?? "", + 'lot_no': landRef.lotNo ?? "", + 'blk_no': landRef.blkNo ?? "", + 'l_td_arp': landRef.tdn ?? "", + 'area': landRef.area ?? "" + }, + enabled: true, + onChanged: () { + offlineBldgEditKey.currentState!.save(); + debugPrint(offlineBldgEditKey + .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: 20), + child: const Text('BUILDING LOCATION', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.center), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + child: 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: const Align( + alignment: Alignment.center, + child: Text( + "AGUSAN DEL NORTE", + style: + TextStyle(fontSize: 15), + ), + ), + ), + ), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: FormBuilderDropdown( + name: 'municipality', + autofocus: false, + decoration: + normalTextFieldStyle( + bldgloc.municipality ?? + "Municipality", + "", + ), + items: uniqueItems + .map( + (city) => + DropdownMenuItem< + City>( + 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!)); + // }, + ), + ), + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customDropDownField( + bldgloc.barangay, + "", + 'brgy', + brgyNAmes)), + const SizedBox(width: 10.0), + Expanded( + flex: 1, + child: customTextField( + "No. / Street", + "", + 'street', + TextInputType.text), + ), + + // Expanded( + // // optional flex property if flex is 1 because the default flex is 1 + // flex: 1, + // child: customDropDownField( + // bldgloc.barangay ?? "", + // "Barangay", + // 'brgy', + // brgyNAmes)) + ]), + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text('LAND REFERENCE', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + textAlign: TextAlign.center), + ), + customTextField("Land Owner", "", + 'l_owner', TextInputType.text), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "OCT/TCT/CLOA No.", + "", + 'oct_tct_cloa', + TextInputType.phone), + ), + 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', + TextInputType.phone)) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Lot No.", + "", + 'lot_no', + TextInputType.phone), + ), + 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', + TextInputType.phone)) + ]), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "TD / ARP No.", + "", + 'l_td_arp', + TextInputType.phone), + ), + 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', + TextInputType.phone)) + ]), + 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, + bldgapprDetailsId: + widget.tempId, + assessedById: '1', + assessedByName: 'cyril', + street: offlineBldgEditKey + .currentState + ?.value['street'] ?? + bldgloc.street, + barangay: offlineBldgEditKey + .currentState + ?.value['brgy'] ?? + bldgloc.barangay, + municipality: offlineBldgEditKey + .currentState + ?.value[ + 'municipality'] + ?.cityDescription ?? + bldgloc.municipality, + province: offlineBldgEditKey + .currentState + ?.value['province'] ?? + bldgloc.province, + ); + var landRefData = LandRef( + id: widget.tempId, + bldgapprDetailsId: + widget.tempId, + assessedById: '1', + assessedByName: 'cyril', + owner: offlineBldgEditKey + .currentState + ?.value['l_owner'] ?? + landRef.owner, + cloaNo: offlineBldgEditKey + .currentState + ?.value[ + 'oct_tct_cloa'] ?? + landRef.cloaNo, + lotNo: offlineBldgEditKey + .currentState + ?.value['lot_no'] ?? + landRef.lotNo, + tdn: offlineBldgEditKey + .currentState + ?.value['l_td_arp'] ?? + landRef.tdn, + area: offlineBldgEditKey + .currentState + ?.value['area'] ?? + landRef.area, + surveyNo: offlineBldgEditKey + .currentState + ?.value[ + 'survey_no'] ?? + landRef.surveyNo, + blkNo: offlineBldgEditKey + .currentState + ?.value['blk_no'] ?? + landRef.blkNo, + ); + context + .read() + .add(UpdateBldgLoc( + id: widget.tempId, + bldgLoc: bldgLocData)); + context + .read() + .add(UpdateBldgLandRef( + id: widget.tempId, + landRef: 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/offline/passo/building/edit/property_appraisal_edit.dart b/lib/screens/offline/passo/building/edit/property_appraisal_edit.dart new file mode 100644 index 0000000..4a6cacf --- /dev/null +++ b/lib/screens/offline/passo/building/edit/property_appraisal_edit.dart @@ -0,0 +1,955 @@ +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:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart'; + +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class PropertyAppraisalEditPageOffline extends StatefulWidget { + final int tempId; + final VoidCallback NextBtn; + final VoidCallback PrevBtn; + + PropertyAppraisalEditPageOffline(this.tempId, this.NextBtn, this.PrevBtn); + + @override + _PropertyAppraisalEditPage createState() => _PropertyAppraisalEditPage(); +} + +class _PropertyAppraisalEditPage + extends State { + double depRate = 0; + // int totalAreas = 0; + // String actualUse = ""; + + // @override + // void initState() { + // super.initState(); + // _loadDataFromSharedPreferences(); // Call the method to load data + // } + + // Method to load data from SharedPreferences + // _loadDataFromSharedPreferences() async { + // SharedPreferences prefs = await SharedPreferences.getInstance(); + // setState(() { + // actualUse = prefs.getString('actualUse') ?? ''; + // totalAreas = prefs.getInt('totalArea') ?? + // 0; // Provide a default value if the key doesn't exist + // }); + // } + + 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; + } + + _calculateMarketValue( + List items, List bldg) { + double add_sum = 0; + double product = 1; + double bldg_sum = 0; + + for (AdditionalItems value in items) { + add_sum += double.parse(value.adjustedMarketVal.toString()); + } + + for (BldgAndStructure value in bldg) { + bldg_sum += double.parse(value.adjustedMarketValue.toString()); + } + + return add_sum + bldg_sum; + } + + double _totalMarketValue(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketVal); + }); + return total; + } + + double _totalMarketValueBLDG(items) { + double total = 0; + items.forEach((row) { + total += double.parse(row.adjustedMarketValue); + }); + return total; + } + + @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) {}, + builder: (context, state) { + if (state is AdditionalItemsLoaded) { + final addItem = state.addItem; + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is SpecificGeneralDescriptionLoaded) { + final genDesc = state.gendesc; + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is BuildingAndStructureLoaded) { + return SingleChildScrollView( + padding: EdgeInsets.all(20), + 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: 20), + textAlign: TextAlign.left), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text( + 'BUILDING & STRUCTURE', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context) + .size + .width / + 3, + columns: [ + const DataColumn( + label: Text('Building Core'), + ), + const DataColumn( + label: Text(''), + ), + const DataColumn( + label: Text('Market Value'), + ), + ], + rows: [ + ...state.bldgAndStructure + .map((dataRow) { + return DataRow(cells: [ + DataCell(Text( + dataRow.actualUse!)), + DataCell(Text("")), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow + .adjustedMarketValue + .toString()!)), + )) + ]); + }), + DataRow(cells: [ + DataCell(Text('Total', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15, + color: Colors.red))), + DataCell(Text('')), + DataCell( + Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format( + _totalMarketValueBLDG( + state + .bldgAndStructure)), + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15, + color: Colors.red)), + ) + ]), + ], + ) + ], + )), + ), + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + children: [ + Container( + margin: const EdgeInsets.only( + left: 0, + top: 20, + right: 0, + bottom: 20), + child: const Text( + 'ADDITIONAL ITEMS', + style: TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context) + .size + .width / + 3, + columns: [ + const DataColumn( + label: + Text('Additional Item'), + ), + const DataColumn( + label: Text(''), + ), + const DataColumn( + label: Text('Market Value'), + ), + ], + rows: [ + ...addItem.map((dataRow) { + return DataRow(cells: [ + DataCell(Text( + dataRow.className!)), + DataCell(Text('')), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱") + .format(double + .parse(dataRow + .marketValue + .toString()!)) + .toString(), + )) + ]); + }).toList(), + DataRow( + // color: MaterialStateColor.resolveWith( + // (states) { + // // Use a color for the DataRow, for example, Colors.blue + // return Colors.redAccent; + // }), + cells: [ + DataCell(Text('Total', + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 15, + color: Colors + .red))), + DataCell(Text('')), + DataCell( + Text( + NumberFormat + .currency( + locale: 'en-PH', + symbol: "₱", + ).format( + _totalMarketValue( + addItem)), + style: TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: 15, + color: Colors + .red)), + ) + ]), + ]), + ], + )), + ), + ], + ), + Row( + children: [ + Expanded( + flex: 1, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Column( + 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: 15), + textAlign: TextAlign.left), + ), + DataTable( + columnSpacing: + MediaQuery.of(context) + .size + .width / + 6, + columns: const [ + DataColumn( + label: Text('Actual Use'), + ), + DataColumn( + label: Text('Market Value'), + ), + DataColumn( + label: Text('Ass. Level'), + ), + DataColumn( + label: Text('Ass. Value'), + ), + ], + rows: [ + DataRow( + cells: [ + DataCell(Text( + genDesc.actualUse ?? + "")), + DataCell(Text(NumberFormat + .currency( + locale: + 'en-PH', + symbol: "₱") + .format(_calculateMarketValue( + addItem, + state + .bldgAndStructure)))), + DataCell( + Text( + assessmentLevel( + _calculateMarketValue( + addItem, + state + .bldgAndStructure) + .toString(), + genDesc + .actualUse) + .toString(), + style: + const TextStyle( + fontWeight: + FontWeight.bold, + fontSize: 13, + ), + textAlign: + TextAlign.center, + ), + ), + DataCell(Text( + NumberFormat.currency( + locale: 'en-PH', + symbol: "₱") + .format(double.parse(assessmentValue( + _calculateMarketValue( + addItem, + state + .bldgAndStructure) + .toString(), + genDesc + .actualUse) + .toString())) + .toString(), + )), + ], + ), + ]) + ], + )), + ), + ], + ), + const 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')); + // context.read().add(AddBldgAppraisal( + // id: 1, + // bldgapprDetailsId: tempID.getInt('tempid')!, + // assessedById: '1', + // assessedByName: 'ad', + // dateCreated: '00', + // dateModified: '00', + // unitconstructCost: offlineBldgKey + // .currentState + // ?.value['bldg_type'] + // .unitValue, + // buildingCore: 'test', + // unitconstructSubtotal: + // (double.parse(offlineBldgKey.currentState!.value['total_area']) * + // double.parse(offlineBldgKey + // .currentState! + // .value['bldg_type'] + // .unitValue)) + // .toString(), + // depreciationRate: depRate.toString(), + // depreciationCost: calculateDepCost( + // (double.parse(offlineBldgKey.currentState!.value['total_area']) * + // double.parse(offlineBldgKey.currentState?.value['bldg_type'].unitValue)), + // addItem, + // depRate) + // .toString(), + // costAddItems: calculateAdditionalItems(addItem).toString(), + // addItemsSubtotal: calculateAdditionalItems(addItem).toString(), + // totalpercentDepreciation: (depRate * 100).toStringAsFixed(2), + // marketValue: calculateMarketValue((double.parse(offlineBldgKey.currentState!.value['total_area']) * double.parse(offlineBldgKey.currentState!.value['bldg_type'].unitValue)), addItem, depRate).toString(), + // totalArea: offlineBldgKey.currentState!.value['total_area'], + // actualUse: "Residential")); + widget.NextBtn(); + } + ; + }, + ) + ], + ), + ], + ), + ); + } + return Container(); + }); + } + return Container(); + }); + } + return Container(); + })); + } +} diff --git a/lib/screens/offline/passo/building/edit/property_assessment_edit.dart b/lib/screens/offline/passo/building/edit/property_assessment_edit.dart new file mode 100644 index 0000000..73b0ed2 --- /dev/null +++ b/lib/screens/offline/passo/building/edit/property_assessment_edit.dart @@ -0,0 +1,1531 @@ +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:intl/intl.dart'; +import 'package:searchfield/searchfield.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; + +import '../../../../../model/offline/offline_profile.dart'; +import '../../../../../model/passo/memoranda.dart'; +import '../../../../../model/passo/property_assessment.dart'; +import '../../../../../model/passo/property_assessment_edit.dart'; +import '../../../../../model/passo/signatories.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class PropertyAssessmentEditOfflinePage extends StatefulWidget { + int tempId; + Function onSAve; + final OfflineProfile offlineProfile; + PropertyAssessmentEditOfflinePage( + this.tempId, this.onSAve, this.offlineProfile); + @override + _PropertyAssessmentEditOfflinePage createState() => + _PropertyAssessmentEditOfflinePage(); +} + +class _PropertyAssessmentEditOfflinePage + extends State { + double assessment_level = 0; + bool isTaxable = false; + bool isExempt = false; + String _memoranda = ''; + String _notes = ""; + String appraised_by = ""; + String rec_by = ""; + String approved_by = ""; + String appraised_by_designation = ""; + String rec_by_designation = ""; + String approved_by_designation = ""; + final focus = FocusNode(); + final focuss = FocusNode(); + final appraisedByFocus = FocusNode(); + final recByFocus = FocusNode(); + final apprvdByFocus = FocusNode(); + final quarter = ['1st', '2nd', '3rd', '4th']; + + TextEditingController memorandaController = TextEditingController(); + TextEditingController noteController = TextEditingController(); + + 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) { + var width = MediaQuery.of(context).size.width; + return ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: + BlocConsumer( + listener: (context, state) { + // if (state is PropertyAssessmentEditLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + if (state is SpecificBldgAssessmentLoaded) { + setState(() { + isTaxable = state.assessment.taxable == '1' ? true : false; + isExempt = state.assessment.exempt == '1' ? true : false; + memorandaController.text = state.assessment.memoranda; + _memoranda = state.assessment.memoranda; + noteController.text = state.assessment.note; + _notes = state.assessment.note; + appraised_by_designation = + state.assessment.appraisedbyDesignation!; + rec_by_designation = state.assessment.recommendapprDesignation!; + approved_by_designation = state.assessment.approvedbyDesignation!; + }); + } + // if (state is PropertyAssessmentEditErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SpecificBldgAssessmentLoaded) { + final assessment = state.assessment; + return BlocConsumer( + listener: (context, state) { + // if (state is SignatoriesLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + + // if (state is SignatoriesErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SignatoriesLoaded) { + 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(); + // } + }, + builder: (context, state) { + if (state is MemorandaLoaded) { + final memoranda = state.memo; + final note = state.memo; + return Padding( + padding: const EdgeInsets.all(20.0), + child: FormBuilder( + key: offlineBldgEditKey, + initialValue: { + 'qtr': assessment.qtr?.toString() ?? '', + 'yr': assessment.yr?.toString() ?? '', + 'app_date': + assessment.appraisedbyDate?.toString() ?? '', + 'rec_date': + assessment.recommendapprDate?.toString() ?? + '', + 'sworn_statement': + assessment.swornstatementNo ?? '', + 'date_received': + assessment.dateReceived?.toString() ?? '', + 'date_of_entry': + assessment.entryDateAssessment?.toString() ?? + '', + 'approve_date': + assessment.approvedbyDate?.toString() ?? '', + }, + enabled: true, + onChanged: () { + offlineBldgEditKey.currentState!.save(); + debugPrint(offlineBldgEditKey.currentState!.value + .toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + 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( + child: Container( + margin: const EdgeInsets.symmetric( + horizontal: 20), + 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 / SWORN STATEMENT:', + style: TextStyle( + fontWeight: + FontWeight.bold), + ), + const SizedBox( + height: 20, + ), + SingleChildScrollView( + scrollDirection: + Axis.horizontal, + child: Row( + mainAxisAlignment: + MainAxisAlignment + .spaceAround, + children: [ + SizedBox( + width: 90, + height: 50, + child: + customDropDownField( + 'Qtr', + '', + 'qtr', + quarter)), + SizedBox( + width: 10, + ), + SizedBox( + width: 100, + height: 50, + child: customTextField( + 'Sworn Statement No.', + '', + 'sworn_statement', + TextInputType + .number)), + SizedBox( + width: 10, + ), + SizedBox( + width: 90, + height: 50, + child: customTextField( + 'Year', + '', + 'yr', + TextInputType + .number)), + ], + ), + ), + ], + ), + const SizedBox( + height: 10, + ), + Divider( + thickness: 2, + ), + Row( + children: [ + const SizedBox( + width: 10, + ), + Expanded( + child: SizedBox( + width: width / 2 - 100, + height: 50, + child: customDatTimePicker( + 'Date Received', + '', + 'date_received')), + ), + const SizedBox( + width: 20, + ), + Expanded( + child: SizedBox( + width: width / 2 - 100, + height: 50, + child: customDatTimePicker( + 'Date of Entry', + '', + 'date_of_entry')), + ) + ], + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPRAISED/ASSESSED BY:', + style: TextStyle( + fontWeight: FontWeight.bold), + textAlign: TextAlign.start, + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + hint: assessment + .appraisedbyName, + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: + appraisedByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + appraised_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + appraised_by_designation = + appraised.item! + .designation; + }); + appraisedByFocus + .unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + appraised_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'app_date')), + ], + ), + ]), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'RECOMMENDING APPROVAL:', + style: TextStyle( + fontWeight: + FontWeight.bold), + )), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + hint: assessment + .recommendapprName, + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: recByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + rec_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + rec_by_designation = + appraised.item! + .designation; + }); + recByFocus.unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + rec_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'rec_date')), + ], + ), + ]), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'APPROVED BY:', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + const Text('Name'), + Container( + padding: + EdgeInsets.fromLTRB( + 20, 0, 0, 0), + margin: const EdgeInsets + .fromLTRB(0, 10, 0, 0), + width: 250, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: SearchField( + itemHeight: 65, + hint: assessment + .approvedbyName, + suggestions: signatories + .map((Signatories + signatories) => + SearchFieldListItem( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}', + item: + signatories, + child: + ListTile( + title: Text( + '${signatories.firstname} ${signatories.middlename} ${signatories.lastname!}', + overflow: + TextOverflow + .ellipsis, + textAlign: + TextAlign + .center, + ), + ))) + .toList(), + + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + searchStyle: TextStyle(), + + ////agency suggestion tap + focusNode: apprvdByFocus, + suggestionState: + Suggestion.expand, + onSuggestionTap: + (appraised) { + setState(() { + approved_by = + "${appraised.item?.firstname} ${appraised.item?.middlename} ${appraised.item?.lastname}"; + approved_by_designation = + appraised.item! + .designation; + }); + apprvdByFocus.unfocus(); + }, + ), + ), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Designation'), + Container( + padding: + EdgeInsets.fromLTRB( + 10, 15, 10, 10), + margin: const EdgeInsets + .fromLTRB( + 0, 10, 0, 0), + width: 250, + height: 50, + decoration: BoxDecoration( + border: Border.all( + color: Colors + .grey, // You can set the color here + width: + 0.9, // You can set the width here + ), + borderRadius: + BorderRadius.circular( + 5), // Set the border radius here + ), + child: Text( + approved_by_designation + .toUpperCase(), + style: TextStyle( + fontSize: 15), + textAlign: + TextAlign.center, + )), + ], + ), + const SizedBox( + width: 10, + ), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text('Date'), + Container( + width: 100, + child: + customDatTimePicker( + '', + '', + 'approve_date')), + ], + ), + ]), + ), + const SizedBox( + height: 50, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'MEMORANDA: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + const SizedBox( + height: 30, + ), + SizedBox( + width: 500, + height: 50, + child: SearchField( + itemHeight: 200, + controller: memorandaController, + suggestions: memoranda + .map( + (Memoranda memoranda) => + SearchFieldListItem( + '${memoranda.memoranda}', + item: + memoranda, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${memoranda.memoranda}', + overflow: + TextOverflow + .visible, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + // searchInputDecoration: + // normalTextFieldStyle("Memoranda", "") + // .copyWith( + // suffixIcon: + // const Icon(Icons.arrow_drop_down), + // contentPadding: EdgeInsets.symmetric( + // vertical: 15.0, horizontal: 16.0), + // border: OutlineInputBorder( + // borderRadius: BorderRadius.circular(10.0), + // borderSide: BorderSide( + // color: + // Colors.grey, // Adjust border color + // ), + // ), + // focusedBorder: OutlineInputBorder( + // borderRadius: BorderRadius.circular(10.0), + // borderSide: BorderSide( + // color: Colors + // .blue, // Adjust focused border color + // ), + // ), + // ), + focusNode: focuss, + suggestionState: + Suggestion.expand, + suggestionDirection: + SuggestionDirection.up, + onSuggestionTap: (memoranda) { + setState(() { + _memoranda = + memorandaController + .text; + }); + focus.unfocus(); + }, + )), + Container( + alignment: Alignment.center, + padding: EdgeInsets.all(10), + child: Column( + children: [ + TextField( + controller: + memorandaController, + keyboardType: + TextInputType.multiline, + maxLines: 7, + decoration: InputDecoration( + focusedBorder: + OutlineInputBorder( + borderSide: BorderSide( + width: 1, + color: Colors + .redAccent)), + disabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + width: 1, + color: Colors.grey, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + enabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + color: Colors.grey, + width: 1, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + ), + ), + ], + ), + ), + const SizedBox( + height: 30, + ), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'NOTE: ', + style: TextStyle( + fontWeight: FontWeight.bold, + ), + )), + const SizedBox( + height: 30, + ), + SizedBox( + width: 400, + height: 50, + child: SearchField( + itemHeight: 200, + controller: noteController, + suggestions: note + .map((Memoranda note) => + SearchFieldListItem( + '${note.memoranda}', + item: + note, // Change: Use individual Memoranda object + child: ListTile( + title: Text( + '${note.memoranda}', + overflow: + TextOverflow + .visible, + ), + ), + )) + .toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + searchInputDecoration: + InputDecoration().copyWith( + suffixIcon: const Icon( + Icons.arrow_drop_down), + ), + focusNode: focus, + suggestionState: + Suggestion.expand, + suggestionDirection: + SuggestionDirection.up, + onSuggestionTap: (memoranda) { + setState(() { + _notes = + noteController.text; + }); + focus.unfocus(); + }, + )), + Container( + alignment: Alignment.center, + padding: EdgeInsets.all(10), + child: Column( + children: [ + TextField( + controller: noteController, + keyboardType: + TextInputType.multiline, + maxLines: 7, + decoration: InputDecoration( + focusedBorder: + OutlineInputBorder( + borderSide: BorderSide( + width: 1, + color: Colors + .redAccent)), + disabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + width: 1, + color: Colors.grey, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + enabledBorder: + OutlineInputBorder( + borderSide: + const BorderSide( + color: Colors.grey, + width: 1, + ), + borderRadius: + BorderRadius.circular( + 5), + ), + ), + ), + ], + ), + ), + const SizedBox( + height: 30, + ), + SizedBox( + width: MediaQuery.of(context) + .size + .width, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: primary, + foregroundColor: Colors.red), + child: const SizedBox( + width: 200, + height: 50, + child: Align( + alignment: Alignment.center, + child: Text( + 'Save', + style: TextStyle( + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + ), + ), + onPressed: () { + offlineBldgEditKey.currentState! + .save(); + var ass = PropertyAssessment( + id: 1, + bldgapprDetailsId: + widget.tempId, + assessedById: widget + .offlineProfile.id + .toString(), + assessedByName: widget + .offlineProfile + .firstName!, + dateCreated: "None", + dateModified: "None", + actualUse: + assessment.actualUse, + marketValue: '0.0', + assessmentLevel: '0.0', + assessedValue: "1.0", + taxable: isTaxable == true + ? '1' + : '0', + exempt: isExempt == true + ? '1' + : '0', + qtr: offlineBldgEditKey + .currentState! + .value['qtr'], + yr: offlineBldgEditKey + .currentState! + .value['yr'], + appraisedbyName: appraised_by == "" + ? assessment + .appraisedbyName + : appraised_by, + appraisedbyDate: + offlineBldgEditKey.currentState!.value['app_date'].toString(), + recommendapprName: rec_by == "" ? assessment.recommendapprName : rec_by, + recommendapprDate: offlineBldgEditKey.currentState!.value['rec_date'].toString(), + approvedbyName: approved_by == "" ? assessment.approvedbyName : approved_by, + approvedbyDate: offlineBldgEditKey.currentState!.value['approve_date'].toString(), + memoranda: _memoranda, + note: _notes, + swornstatementNo: offlineBldgEditKey.currentState!.value['sworn_statement'], + dateReceived: offlineBldgEditKey.currentState!.value['date_received'].toString(), + entryDateAssessment: offlineBldgEditKey.currentState!.value['date_of_entry'].toString(), + entryDateBy: "none", + genCode: '5th', + appraisedbyDesignation: appraised_by_designation == "" ? assessment.appraisedbyDesignation : appraised_by_designation, + approvedbyDesignation: approved_by_designation == "" ? assessment.approvedbyDesignation : approved_by_designation, + recommendapprDesignation: rec_by_designation == "" ? assessment.recommendapprDesignation : rec_by_designation); + + context + .read< + BldgAssessmentOfflineBloc>() + .add(UpdateBldgAssessment( + id: widget.tempId, + assessment: ass)); + + widget.onSAve(); + }, + ), + ), + ], + ), + ), + ), + ) + ], + ), + ), + ); + } + // if (state is MemorandaErrorState) { + // return SomethingWentWrong( + // message: state.error, + // onpressed: () { + // context + // .read() + // .add(const LoadMemoranda()); + // }, + // ); + // } + return Container(); + }, + ); + } + // if (state is SignatoriesErrorState) { + // return SomethingWentWrong( + // message: state.error, + // onpressed: () { + // context + // .read() + // .add(const LoadSignatories()); + // }, + // ); + // } + return Container(); + }, + ); + } + // if (state is PropertyAssessmentEditErrorState) { + // return SomethingWentWrong( + // message: state.error, + // onpressed: () { + // context.read().add( + // LoadPropertyAssessmentEdit( + // assessmentsEdit: PropertyAssessmentEdit(), + // id: widget.tempId)); + // }, + // ); + // } + return Container(); + }, + ), + ); + } +} diff --git a/lib/screens/offline/passo/building/edit/property_owner_info_edit.dart b/lib/screens/offline/passo/building/edit/property_owner_info_edit.dart new file mode 100644 index 0000000..581331c --- /dev/null +++ b/lib/screens/offline/passo/building/edit/property_owner_info_edit.dart @@ -0,0 +1,267 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; +import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; + +class PropertyOwnerInfoEditOffline extends StatefulWidget { + final int index; + final PropertyInfo faas; + final String title; + final VoidCallback PrevBtn; + final VoidCallback NextBtn; + + const PropertyOwnerInfoEditOffline( + this.index, this.faas, this.title, this.PrevBtn, this.NextBtn); + + @override + State createState() => + _PropertyOwnerInfoEditOffline(); +} + +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 _PropertyOwnerInfoEditOffline + extends State { + Map myMap = {'zero': 0, 'one': 1, 'two': 2}; + + final transaction_codes = ['New', 'Revision']; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Column( + children: [ + FormBuilder( + key: offlineBldgEditKey, + initialValue: { + 'transaction_code': widget.faas.transCode, + 'arp_td': widget.faas.tdn, + 'pin': widget.faas.pin, + 'fname': widget.faas.fname, + 'mname': widget.faas.mname, + 'lname': widget.faas.lname, + 'bday': widget.faas.bday, + '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, + 'benificiary_tin': widget.faas.adminTin, + }, + enabled: true, + onChanged: () { + offlineBldgEditKey.currentState!.save(); + debugPrint(offlineBldgEditKey.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: Row( + children: [ + Expanded( + child: const Text( + 'PROPERTY OWNER INFO', + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.center, + ), + ), + ], + ), + ), + Align( + alignment: Alignment.topRight, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () {}, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('SAVE'), // <-- Text + SizedBox( + width: 5, + ), + Icon( + // <-- Icon + Icons.save, + size: 24.0, + ), + ], + ), + ), + ), + const SizedBox(height: 15), + customDropDownField( + widget.faas.transCode ?? "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', TextInputType.phone)), + 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', TextInputType.phone)), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("First Name", "", 'fname', + TextInputType.text), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField("Middle Name", "", 'mname', + TextInputType.text), + ), + const SizedBox(width: 10.0), + Expanded( + // optional flex property if flex is 1 because the default flex is 1 + flex: 1, + child: customTextField( + "Last Name", "", 'lname', TextInputType.text), + ) + ]), + customDatTimePicker("Birthday", "", "bday"), + customTextField( + "Address", "", 'address', TextInputType.text), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Tel No.", "", 'tel_no', TextInputType.phone), + ), + 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', TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Administrator / Benificial User", + "", + 'benificiary', + TextInputType.text), + ), + 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', TextInputType.phone)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Address", "", + 'benificiary_address', TextInputType.text), + ), + 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', TextInputType.phone)) + ]), + 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: offlineBldgEditKey + .currentState?.value['transaction_code'] + .toString() ?? + widget.faas.transCode, + assessedById: '1', + assessedByName: 'cyril', + tdn: offlineBldgEditKey.currentState!.value['arp_td'] ?? + widget.faas.tdn, + pin: offlineBldgEditKey.currentState!.value['pin'] ?? + widget.faas.pin, + fname: offlineBldgEditKey.currentState!.value['fname'] ?? + widget.faas.fname, + mname: offlineBldgEditKey.currentState!.value['mname'] ?? + widget.faas.mname, + bday: offlineBldgEditKey.currentState!.value['bday'] + .toString(), + lname: offlineBldgEditKey.currentState!.value['lname'] ?? + widget.faas.lname, + address: offlineBldgEditKey.currentState!.value['address'] ?? widget.faas.address, + telno: offlineBldgEditKey.currentState!.value['tel_no'] ?? widget.faas.telno, + tin: offlineBldgEditKey.currentState!.value['tin'] ?? widget.faas.tin, + adminUser: offlineBldgEditKey.currentState!.value['benificiary'] ?? widget.faas.adminUser, + adminAddress: offlineBldgEditKey.currentState!.value['benificiary_address'] ?? widget.faas.adminAddress, + adminTin: offlineBldgEditKey.currentState!.value['benificiary_tin'] ?? widget.faas.adminTin, + adminTelno: offlineBldgEditKey.currentState!.value['benificiary_telno'] ?? widget.faas.adminTelno, + faasType: "Building"); + + context.read().add( + UpdatePropertyOwnerInfo( + id: widget.faas.id!, + propertyInfo: property_info)); + + widget.NextBtn(); + }, + ), + ), + ])), + ], + ), + ), + ); + } +} diff --git a/lib/screens/passo/Building/edit_building/structural_materials_edit.dart b/lib/screens/offline/passo/building/edit/structural_materials_edit.dart similarity index 64% rename from lib/screens/passo/Building/edit_building/structural_materials_edit.dart rename to lib/screens/offline/passo/building/edit/structural_materials_edit.dart index 57f9d3c..4e31dcd 100644 --- a/lib/screens/passo/Building/edit_building/structural_materials_edit.dart +++ b/lib/screens/offline/passo/building/edit/structural_materials_edit.dart @@ -1,42 +1,29 @@ 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: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/bloc/passo/bulding/structural_material/structural_material_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_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'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; -class MaterialOption { - final String id; - final String label; +import '../../../../../model/passo/structureMaterial.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; - MaterialOption(this.id, this.label); -} - -class StructuralMaterialsEditPage extends StatefulWidget { +class StructuralMaterialsPageEditOffline extends StatefulWidget { + // final VoidCallback onPutStructuralMaterials; final int tempId; final VoidCallback NextBtn; final VoidCallback PrevBtn; - StructuralMaterialsEditPage(this.tempId, this.NextBtn, this.PrevBtn); + StructuralMaterialsPageEditOffline(this.tempId, this.NextBtn, this.PrevBtn); @override - _StructuralMaterialsEditPage createState() => _StructuralMaterialsEditPage(); + _StructuralMaterialsPageEditOffline createState() => + _StructuralMaterialsPageEditOffline(); } -class _StructuralMaterialsEditPage extends State { - List foundation = []; - List column = []; - List beam = []; - List truss_framing = []; - List roof = []; - List flooring = []; - List walls = []; +class _StructuralMaterialsPageEditOffline + extends State { bool foundationOthers = false; bool columOthers = false; bool beamsOthers = false; @@ -44,64 +31,56 @@ class _StructuralMaterialsEditPage extends State { bool roofOthers = false; bool flooringOthers = false; bool wpOthers = false; - - List columnOptions = [ - MaterialOption('steel', 'Steel'), - MaterialOption('concrete', 'Reinforced Concrete'), - MaterialOption('wood', 'Wood'), - ]; + List foundation = []; + List column = []; + List beam = []; + List truss_framing = []; + List roof = []; + List flooring = []; + List walls = []; List selectedColumnValues = []; @override Widget build(BuildContext context) { - 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 StructuralMaterialsLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - - if (state is StructuralMaterialsLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - 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 - }); - } - if (state is StructuralMaterialsErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, builder: (context, state) { - return SingleChildScrollView( - padding: const EdgeInsets.all(30.0), + return BlocConsumer(listener: (context, state) { + if (state is SpecificStructuralMaterialLoaded) { + setState(() { + foundation = state.materials.foundation?.split(', ') ?? []; + column = state.materials.columns?.split(', ') ?? []; + beam = state.materials.beams?.split(', ') ?? []; + truss_framing = state.materials.trussFraming?.split(', ') ?? []; + roof = state.materials.roof?.split(', ') ?? []; + flooring = state.materials.flooring?.split(', ') ?? []; + walls = state.materials.walls?.split(', ') ?? []; + // Update other local state variables here if needed + }); + } + // TODO: implement listener + }, builder: (context, state) { + if (state is SpecificStructuralMaterialLoaded) { + return SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Padding( + padding: const EdgeInsets.all(15.0), child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + // Added this line 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), + child: const Text( + 'STRUCTURAL MATERIALS', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + textAlign: TextAlign.center, + ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text( + const Text( 'FOUNDATION', textAlign: TextAlign.start, ), @@ -124,8 +103,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: foundationOthers, - child: customTextField( - "Enter other foundation", "", "other_foundation"), + child: customTextField("Enter other foundation", "", + "other_foundation", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -135,7 +114,8 @@ class _StructuralMaterialsEditPage extends State { }, options: const ['Reinforced Concrete', 'Plain Concrete'], selectedValues: foundation, - whenEmpty: 'Select Foundations', + whenEmpty: + state.materials.foundation ?? 'Select Foundations', ), ), ), @@ -165,8 +145,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: columOthers, - child: customTextField( - "Enter other columns", "", "other_column"), + child: customTextField("Enter other columns", "", + "other_column", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -176,7 +156,7 @@ class _StructuralMaterialsEditPage extends State { }, options: const ['Steel', 'Reinforced Concrete', 'Wood'], selectedValues: column, - whenEmpty: 'Select Column/s', + whenEmpty: state.materials.columns ?? 'Select Column/s', ), ), ), @@ -206,8 +186,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: beamsOthers, - child: - customTextField("Enter other beam/s", "", "other_beam"), + child: customTextField("Enter other beam/s", "", + "other_beam", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -217,7 +197,7 @@ class _StructuralMaterialsEditPage extends State { }, options: const ['Steel', 'Reinforced Concrete', 'Wood'], selectedValues: beam, - whenEmpty: 'Select Beam/s', + whenEmpty: state.materials.beams ?? 'Select Beam/s', ), ), ), @@ -247,8 +227,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: tfOthers, - child: customTextField( - "Enter other truss framing/s", "", "other_tf"), + child: customTextField("Enter other truss framing/s", "", + "other_tf", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -258,7 +238,8 @@ class _StructuralMaterialsEditPage extends State { }, options: const ['Steel', 'Wood'], selectedValues: truss_framing, - whenEmpty: 'Select Truss Framing/s', + whenEmpty: state.materials.trussFraming ?? + 'Select Truss Framing/s', ), ), ), @@ -288,8 +269,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: roofOthers, - child: - customTextField("Enter other roof/s", "", "other_roof"), + child: customTextField("Enter other roof/s", "", + "other_roof", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -308,7 +289,7 @@ class _StructuralMaterialsEditPage extends State { 'Nipa/Anahaw/Cogon' ], selectedValues: roof, - whenEmpty: 'Select Roof/s', + whenEmpty: state.materials.roof ?? 'Select Roof/s', ), ), ), @@ -338,8 +319,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: flooringOthers, - child: customTextField( - "Enter other flooring/s", "", "other_flooring"), + child: customTextField("Enter other flooring/s", "", + "other_flooring", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -355,7 +336,8 @@ class _StructuralMaterialsEditPage extends State { 'Tiles' ], selectedValues: flooring, - whenEmpty: 'Select Flooring/s', + whenEmpty: + state.materials.flooring ?? 'Select Flooring/s', ), ), ), @@ -385,8 +367,8 @@ class _StructuralMaterialsEditPage extends State { padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), child: Visibility( visible: wpOthers, - child: customTextField( - "Enter other walls & partition/s", "", "other_wp"), + child: customTextField("Enter other walls & partition/s", + "", "other_wp", TextInputType.text), replacement: DropDownMultiSelect( selected_values_style: TextStyle(color: Colors.black), onChanged: (List x) { @@ -405,7 +387,8 @@ class _StructuralMaterialsEditPage extends State { 'Bamboo' ], selectedValues: walls, - whenEmpty: 'Select Walls & Partition/s', + whenEmpty: + state.materials.walls ?? 'Select Walls & Partition/s', ), ), ), @@ -416,66 +399,78 @@ class _StructuralMaterialsEditPage extends State { icon: const Icon(Icons.chevron_left_rounded, color: Colors.white), onPressed: () { - { - widget.NextBtn(); - } - ; + widget.PrevBtn(); }, ), 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(); - } - ; + onPressed: () { + var strucMaterials = StructureMaterialsII( + id: 1, + bldgapprDetailsId: widget.tempId, + foundation: foundationOthers + ? offlineBldgEditKey + .currentState!.value['other_foundation'] + : foundation.isNotEmpty + ? foundation + : [state.materials.foundation!], + columns: columOthers + ? offlineBldgEditKey + .currentState!.value['other_column'] + : column.isNotEmpty + ? column + : [state.materials.columns!], + beams: beamsOthers + ? offlineBldgEditKey + .currentState!.value['other_beam'] + : beam.isNotEmpty + ? beam + : [state.materials.beams!], + trussFraming: tfOthers + ? offlineBldgEditKey + .currentState!.value['other_tf'] + : truss_framing.isNotEmpty + ? truss_framing + : [state.materials.trussFraming!], + roof: roofOthers + ? offlineBldgEditKey + .currentState!.value['other_roof'] + : roof.isNotEmpty + ? roof + : [state.materials.roof!], + flooring: flooringOthers + ? offlineBldgEditKey + .currentState!.value['other_flooring'] + : flooring.isNotEmpty + ? flooring + : [state.materials.flooring!], + walls: wpOthers + ? offlineBldgEditKey + .currentState!.value['other_wp'] + : walls.isNotEmpty + ? walls + : [state.materials.walls!], + others: ["Others"]); + print('struct mat'); + print(strucMaterials.toJson()); + context.read().add( + UpdateStructuralMaterials( + id: widget.tempId, materials: strucMaterials)); + widget.NextBtn(); }, - ) + ), ], ) ], ), - ); - }), - ), - ); + ), + ); + } + // if (state is StructuralMaterialsErrorState) { + // return Text(state.error); + // } + return Container(); + }); } } diff --git a/lib/screens/offline/passo/building_home_offline.dart b/lib/screens/offline/passo/building_home_offline.dart new file mode 100644 index 0000000..5bfa662 --- /dev/null +++ b/lib/screens/offline/passo/building_home_offline.dart @@ -0,0 +1,493 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_speed_dial/flutter_speed_dial.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/building_and_structure/building_and_structure_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/location/location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/model/passo/additional_items.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/model/passo/building_and_structure.dart'; +import 'package:unit2/model/passo/building_details.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/property_appraisal.dart'; +import 'package:unit2/model/passo/property_assessment.dart'; +import 'package:unit2/model/passo/property_info.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:unit2/screens/offline/passo/building/add/drawing_pad.dart'; +import 'package:unit2/screens/offline/passo/building/add/flutter_painter.dart'; +import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/widgets/empty_data.dart'; + +import '../../../bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; +import '../../../bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; +import '../../../model/passo/general_description.dart'; +import '../../../model/passo/structureMaterial.dart'; +import '../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import '../../../utils/alerts.dart'; +import 'package:http/http.dart'; +import 'package:date_format/date_format.dart'; + +import '../../../utils/urls.dart'; + +class BuildingHomeOffline extends StatelessWidget { + final OfflineProfile offlineProfile; + const BuildingHomeOffline(this.offlineProfile, {super.key}); + + @override + Widget build(BuildContext context) { + void deleteItem(int itemId) { + context.read().add(DeleteTodo(id: itemId)); + } + + void triggerLoadBldgFaas() { + final myBloc = BlocProvider.of(context); + myBloc.add(FetchTodos()); + } + + void triggerLoadLandFaas() { + final myBloc = BlocProvider.of(context); + myBloc.add(LoadLandPropertyOwner()); + } + + return Scaffold( + body: ProgressHUD( + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) async { + if (state is UploadBuildingFaasLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Syncing data please wait..."); + } + // if (state is GenDescLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + + // final tempID = await SharedPreferences.getInstance(); + // await tempID.setInt( + // 'totalValue', int.parse(state.gendesc.totalFloorArea!)); + // await tempID.setString( + // 'actualUse', state.gendesc.actualUse!); + + // } + if (state is PropertyInfoLoaded) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + if (state is PropertyOwnerInfoErrorState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is PropertyInfoLoaded) { + if (state.propertyInfos.isNotEmpty) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Column( + children: [ + Expanded( + child: ListView.builder( + shrinkWrap: true, + itemCount: state.propertyInfos.length, + itemBuilder: (BuildContext context, int index) { + return _listCard( + state.propertyInfos[index], + context, + index, + deleteItem, + state.propertyInfos.length, + offlineProfile, + triggerLoadBldgFaas); + }, + ), + ), + ], + ), + ); + } else { + return const EmptyData( + message: + "You don't have any building faas added. Please click + to add"); + } + } + if (state is PropertyOwnerInfoErrorState) { + WidgetsBinding.instance.addPostFrameCallback((_) { + // Perform actions after the current build frame; safe place for setState or context-dependent actions + confirmAlertWithCancelCustom( + context, + () => context.read().add( + UploadBuildingFaas(offlineProfile: offlineProfile)), + () => context.read().add(FetchTodos()), + "Sync unsuccesful!", + "Please try again!", + "Retry", + "Cancel"); + }); + } + 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) => CrudBloc(), + ), + BlocProvider( + create: (context) => AdditionalItemsOfflineBloc(), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => BarangayAdminBloc() + ..add( + const LoadBarangayInMunicipality(cityCode: '01')), + ), + BlocProvider( + create: (context) => BuildingAndStructureBloc()), + BlocProvider( + create: (context) => ClassComponentsAdminBloc() + ..add(const LoadClassComponents()), + ), + BlocProvider( + create: (context) => UnitConstructionAdminBloc() + ..add(const LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => SignatoriesAdminBloc() + ..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider(create: (context) => LandrefLocationBloc()), + BlocProvider(create: (context) => LocationBloc()), + BlocProvider( + create: (context) => GeneralDescriptionBloc()), + BlocProvider( + create: (context) => StructuralMaterialOfflineBloc()), + BlocProvider( + create: (context) => AdditionalItemsOfflineBloc() + ..add(const LoadAdditionalItems())), + BlocProvider( + create: (context) => BldgAppraisalOfflineBloc()), + BlocProvider( + create: (context) => BldgAssessmentOfflineBloc()), + ], child: AddBuilding(triggerLoadBldgFaas, offlineProfile)); + })); + }), + 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) => LandPropertyOwnerBloc(), + ), + BlocProvider( + create: (context) => LandPropertyAppraisalBloc() + ..add(const LoadLandPropertyAppraisal()), + ), + BlocProvider( + create: (context) => LandClassificationBloc() + ..add(const LoadLandClassification()), + ), + BlocProvider( + create: (context) => LandSubclassificationBloc() + ..add(const LoadLandSubClassification()), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => OtherImprovementsBloc() + ..add(const LoadOtherImprovements()), + ), + BlocProvider( + create: (context) => TreesImprovementsBloc() + ..add(const LoadTreesImprovements()), + ), + BlocProvider( + create: (context) => ValueAdjustmentBloc() + ..add(const LoadValueAdjustment()), + ), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(const LoadTypeOfRoad()), + ), + BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(const LoadTypeOfLocation()), + ), + BlocProvider( + create: (context) => LandPropertyAssessmentBloc() + ..add(const LoadLandPropertyAssessment()), + ), + BlocProvider( + create: (context) => LandPropertySignatureBloc()), + BlocProvider( + create: (context) => + SignatoriesAdminBloc()..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider( + create: (context) => LandPropertyLocationBloc(), + ), + BlocProvider( + create: (context) => LandPropertyBoundariesBloc(), + ), + BlocProvider( + create: (context) => TreesImprovementsBloc() + ..add(const LoadTreesImprovements()), + ), + ], child: AddLandOffline(triggerLoadBldgFaas)); + })); + }, + ), + SpeedDialChild( + child: const Icon( + Icons.precision_manufacturing_rounded, + color: primary, + ), + label: 'Machinery', + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const DrawingScreen()), + ); + }, + ), + SpeedDialChild( + child: const Icon( + Icons.upload, + color: primary, + ), + label: 'Upload/Sync', + onTap: () { + context + .read() + .add(UploadBuildingFaas(offlineProfile: offlineProfile)); + }, + ), + ]), + ); + } +} + +Card _listCard(PropertyInfo property_info, context, index, deleteItem, + bldgLength, offlineProfile, triggerLoadLandFaas) { + 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) => CrudBloc()..add(FetchTodos()), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => BarangayAdminBloc() + ..add(const LoadBarangayInMunicipality(cityCode: '01')), + ), + BlocProvider( + create: (context) => ClassComponentsAdminBloc() + ..add(const LoadClassComponents()), + ), + BlocProvider( + create: (context) => UnitConstructionAdminBloc() + ..add(const LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => + SignatoriesAdminBloc()..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider( + create: (context) => BldgAppraisalOfflineBloc() + ..add(FetchSingleBldgAppraisal(id: property_info.id!)), + ), + BlocProvider( + create: (context) => LandrefLocationBloc() + ..add(FetchSingleLandref(id: property_info.id!))), + BlocProvider( + create: (context) => LocationBloc() + ..add(FetchSingleLocation(id: property_info.id!))), + BlocProvider( + create: (context) => GeneralDescriptionBloc() + ..add(FetchSingleGeneralDescription( + id: property_info.id!))), + BlocProvider( + create: (context) => StructuralMaterialOfflineBloc() + ..add(FetchSingleStructuralMaterial( + id: property_info.id!))), + BlocProvider( + create: (context) => BldgAssessmentOfflineBloc() + ..add(FetchSingleBldgAssessment(id: property_info.id!))), + BlocProvider( + create: (context) => AdditionalItemsOfflineBloc() + ..add(LoadAdditionalItemsEdit( + items: const [], + id: property_info.id!))), + BlocProvider( + create: (context) => BuildingAndStructureBloc() + ..add(LoadBuildingAndStructureEdit( + bldgAndStructure: const [], + id: property_info.id!))), + ], + child: EditBuildingOffline( + index: index, + faas: property_info, + title: 'Bldg & Structure Edit', + offlineProfile: offlineProfile, + loadBldg: triggerLoadLandFaas), + ); + })); + }, + 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: 1, // Border width + ), + ), + child: const Icon( + Icons.maps_home_work_rounded, + color: primary, // Icon color + ), + ), + const SizedBox( + width: 20, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${property_info.fname} ${property_info.mname} ${property_info.lname}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.left, + ), + SizedBox(height: 5), + Text( + 'TDN: ${property_info.tdn}', + style: TextStyle( + fontSize: 13, + ), + textAlign: TextAlign.left, + ), + Text( + 'Uploaded on: ${property_info.dateSynced == null ? '--' : property_info.dateSynced}', + style: TextStyle( + fontSize: 13, + ), + textAlign: TextAlign.left, + ), + ], + ), + ), + IconButton( + onPressed: () { + confirmAlertWithCancel( + context, + () => deleteItem(property_info.id), + () => null, + 'Delete FAAS Item?', + "Are you sure you want to delete this item?"); + }, + icon: const Icon(Icons.delete_rounded), + color: primary, + ), + ], + ), + ), + ), + ); +} diff --git a/lib/screens/passo/Land/edit_land/AddLandAppraisalEdit.dart b/lib/screens/offline/passo/land/add/AddLandAppraisal.dart similarity index 77% rename from lib/screens/passo/Land/edit_land/AddLandAppraisalEdit.dart rename to lib/screens/offline/passo/land/add/AddLandAppraisal.dart index 10da057..0c42bf9 100644 --- a/lib/screens/passo/Land/edit_land/AddLandAppraisalEdit.dart +++ b/lib/screens/offline/passo/land/add/AddLandAppraisal.dart @@ -1,41 +1,40 @@ 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: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/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_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/utils/text_container.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; import 'package:unit2/widgets/error_state.dart'; -import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; -class AddLandAppraisalEditModal extends StatefulWidget { +import '../../../../../model/passo/city.dart'; +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../model/passo/land_classification.dart'; +import '../../../../../model/passo/land_subclassification.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; + +class AddLandAppraisalOfflineModal extends StatefulWidget { // final List unit; // final List options; - final int tempId; + // final int tempId; - AddLandAppraisalEditModal(this.tempId); + // AddLandAppraisalModal(this.unit, this.options, this.tempId); @override - _AddLandAppraisalEditModal createState() => _AddLandAppraisalEditModal(); + _AddLandAppraisalOfflineModal createState() => + _AddLandAppraisalOfflineModal(); } -class _AddLandAppraisalEditModal extends State { +class _AddLandAppraisalOfflineModal + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -73,45 +72,33 @@ class _AddLandAppraisalEditModal extends State { @override Widget build(BuildContext context) { - return BlocConsumer( - listener: (context, state) { - if (state is LandAppraisalLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is LandAppraisalLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is LandAppraisalErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, buildWhen: (previous, current) { + return BlocBuilder( + buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddLandAppraisalScreen) { + if (state is ShowAddItemsScreen) { return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { if (state is LandClassificationLoaded) { - final classification = state.land_classification; - return BlocConsumer( + final classification = state.landClassification; + return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { if (state is LandSubClassificationLoaded) { - final subclassification = state.land_subclassification; - return BlocConsumer( + final subclassification = state.landSubClassification; + return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is MunicipalityLoaded) { + if (state is MunicipalitiesLoaded) { return FormBuilder( key: appraisalLandKey, onChanged: () { @@ -148,7 +135,7 @@ class _AddLandAppraisalEditModal extends State { cityDesc ?? "Municipality", ""), - items: state.municipality + items: state.city .map((municipality) => DropdownMenuItem< City>( @@ -166,16 +153,23 @@ class _AddLandAppraisalEditModal extends State { selectedCityCode!; cityDesc = selectedCity .cityDescription!; + _classDesc = ""; + appraisalLandKey + .currentState + ?.patchValue({ + 'classification': + LandClassification(), + }); }); final barangayBloc = context.read< - LandSubClassificationBloc>(); + LandSubclassificationBloc>(); barangayBloc.add( - LoadLandSubClassification( - classCode: - classCode!, + LoadSpecificLandSubClassification( cityCode: - selectedCityCode!)); // Use selectedCityCode directly + cityCode, + classCode: + classCode)); // Use selectedCityCode directly } }, )), @@ -215,20 +209,21 @@ class _AddLandAppraisalEditModal extends State { selectedClass.id; setState(() { classCode = - selectedClassCode!; - _classDesc = - selectedClass - .description!; + selectedClassCode ?? + 0; + _classDesc = selectedClass + .description ?? + ''; }); final barangayBloc = context.read< - LandSubClassificationBloc>(); + LandSubclassificationBloc>(); barangayBloc.add( - LoadLandSubClassification( - classCode: - selectedClassCode!, + LoadSpecificLandSubClassification( cityCode: - cityCode)); // Use selectedCityCode directly + cityCode, + classCode: + classCode)); // Use selectedCityCode directly } }, )), @@ -276,6 +271,8 @@ class _AddLandAppraisalEditModal extends State { focusNode: focus, suggestionState: Suggestion.expand, + suggestionDirection: + SuggestionDirection.up, onSuggestionTap: (subclass) { setState(() { _unitBase = double.parse( @@ -344,32 +341,33 @@ class _AddLandAppraisalEditModal extends State { .getInstance(); print(tempID .getInt('landid')); - var land_appraisal = LandAppr( - landapprDetailsId: - widget.tempId, - classification: - _classDesc, - subClass: _subClassDesc, - area: _areaValue - .toString(), - unitValue: _unitBase - .toString(), - baseMarketval: - _totalMarketValue( - _unitBase, - _areaValue) - .toString()); context .read< - LandAppraisalBloc>() - .add(AddLandAppraisal( - land_appr: - land_appraisal)); + LandPropertyAppraisalBloc>() + .add(AddLandPropertyAppraisal( + landapprDetailsId: + tempID.getInt( + 'landid')! + + 1, + classification: + _classDesc, + subClass: + _subClassDesc, + area: _areaValue + .toString(), + unitValue: _unitBase + .toString(), + baseMarketval: + _totalMarketValue( + _unitBase, + _areaValue) + .toString())); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: + Colors.black, ), child: const Text("Submit"), ), @@ -386,17 +384,14 @@ class _AddLandAppraisalEditModal extends State { onPressed: () { context .read< - LandAppraisalBloc>() + LandPropertyAppraisalBloc>() .add( - LoadLandAppraisalEdit( - land_appr: < - LandAppr>[], - id: widget.tempId, - )); + const LoadLandPropertyAppraisal()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: + Colors.black, ), child: const Text("Cancel"), ), @@ -408,44 +403,44 @@ class _AddLandAppraisalEditModal extends State { ), ))); } - if (state is MunicipalityErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadMunicipality()); - }, - ); - } + // if (state is MunicipalityErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(LoadMunicipality()); + // }, + // ); + // } return Container(); }, ); } - if (state is LandSubClassificationErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add( - const LoadLandSubClassification( - cityCode: '1', classCode: 1)); - }, - ); - } + // if (state is LandSubClassificationErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add( + // const LoadLandSubClassification( + // cityCode: '1', classCode: 1)); + // }, + // ); + // } return Container(); }, ); } - if (state is LandClassificationErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadLandClassification()); - }, - ); - } + // if (state is LandClassificationErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(const LoadLandClassification()); + // }, + // ); + // } return Container(); }, ); @@ -454,7 +449,9 @@ class _AddLandAppraisalEditModal extends State { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadLandAppraisal()); + context + .read() + .add(const LoadLandPropertyAppraisal()); }, ); } diff --git a/lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart b/lib/screens/offline/passo/land/add/AddLandPropertyAssessmentModal.dart similarity index 83% rename from lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart rename to lib/screens/offline/passo/land/add/AddLandPropertyAssessmentModal.dart index 8752a6f..9a5d6b3 100644 --- a/lib/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart +++ b/lib/screens/offline/passo/land/add/AddLandPropertyAssessmentModal.dart @@ -3,15 +3,16 @@ 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'; -import 'package:unit2/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; -class AddPropertyAssessmentModal extends StatefulWidget { +import '../../../../../bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import '../../../../../model/passo/land_property_assessment.dart'; +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class AddPropertyAssessmentOfflineModal extends StatefulWidget { // final List unit; // final List options; // final int tempId; @@ -19,10 +20,12 @@ class AddPropertyAssessmentModal extends StatefulWidget { // AddLandAppraisalModal(this.unit, this.options, this.tempId); @override - _AddPropertyAssessmentModal createState() => _AddPropertyAssessmentModal(); + _AddPropertyAssessmentOfflineModal createState() => + _AddPropertyAssessmentOfflineModal(); } -class _AddPropertyAssessmentModal extends State { +class _AddPropertyAssessmentOfflineModal + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -68,23 +71,17 @@ class _AddPropertyAssessmentModal extends State { calculateAssessmentValue() { switch (_actualUse) { case "Residential": - return _unitValue * 0.20; - break; + return (_unitValue * 0.20).ceil(); case "Agricultural": - return _unitValue * 0.40; - break; + return (_unitValue * 0.40).ceil(); case "Commercial": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Industrial": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Mineral": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Timberland": - return _unitValue * 0.20; - break; + return (_unitValue * 0.20).ceil(); default: } } @@ -109,13 +106,13 @@ class _AddPropertyAssessmentModal extends State { buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddLandPropertyAssessmentScreen) { - return BlocConsumer(listener: (context, state) { + if (state is ShowLandPropertyAssessmentcreen) { + return BlocConsumer( + listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is LandValueAdjustmentsLoaded) { - final assessment = state.val_adj; + if (state is ValueAdjustmentLoaded) { + final assessment = state.valueAdjustment; return FormBuilder( key: assessmentKey, onChanged: () { @@ -142,7 +139,7 @@ class _AddPropertyAssessmentModal extends State { autofocus: false, decoration: normalTextFieldStyle( "Value Adjustments", ""), - items: state.val_adj + items: state.valueAdjustment .map((adj) => DropdownMenuItem( value: adj, @@ -278,25 +275,23 @@ class _AddPropertyAssessmentModal extends State { 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)); + landapprDetailsId: + tempID.getInt('landid')! + 1, + actualUse: _actualUse, + marketval: _unitValue.toString(), + assessmentLevel: _assessmentLevel, + assessedValue: + calculateAssessmentValue() + .toString(), + totalMarketval: '0', + totalAssessedval: '0')); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Submit"), ), @@ -316,7 +311,7 @@ class _AddPropertyAssessmentModal extends State { const LoadLandPropertyAssessment()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Cancel"), ), @@ -329,13 +324,13 @@ class _AddPropertyAssessmentModal extends State { ), )); } - if (state is LandValueAdjustmentsErrorState) { + if (state is ValueAdjustmentErrorState) { return SomethingWentWrong( message: onError, onpressed: () { context - .read() - .add(LoadLandValueAdjustments()); + .read() + .add(const LoadValueAdjustment()); }, ); } @@ -348,7 +343,7 @@ class _AddPropertyAssessmentModal extends State { onpressed: () { context .read() - .add(LoadLandPropertyAssessment()); + .add(const LoadLandPropertyAssessment()); }, ); } diff --git a/lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart b/lib/screens/offline/passo/land/add/AddOtherImprovementModal.dart similarity index 86% rename from lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart rename to lib/screens/offline/passo/land/add/AddOtherImprovementModal.dart index 3f6e6b4..033bd8c 100644 --- a/lib/screens/passo/Land/add_land/AddOtherImprovementModal.dart +++ b/lib/screens/offline/passo/land/add/AddOtherImprovementModal.dart @@ -4,15 +4,18 @@ 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/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.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'; import 'package:unit2/utils/text_container.dart'; import 'package:unit2/widgets/error_state.dart'; -class AddOtherImprovementModal extends StatefulWidget { +import '../../../../../bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; + +class AddOtherImprovementModalOffline extends StatefulWidget { // final List unit; // final List options; // final int tempId; @@ -20,10 +23,12 @@ class AddOtherImprovementModal extends StatefulWidget { // AddLandAppraisalModal(this.unit, this.options, this.tempId); @override - _AddOtherImprovementModal createState() => _AddOtherImprovementModal(); + _AddOtherImprovementModalOffline createState() => + _AddOtherImprovementModalOffline(); } -class _AddOtherImprovementModal extends State { +class _AddOtherImprovementModalOffline + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -85,13 +90,13 @@ class _AddOtherImprovementModal extends State { buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddOtherImprovementScreen) { - return BlocConsumer(listener: (context, state) { + if (state is ShowOtherImprovementScreen) { + return BlocConsumer( + listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is LandTreesImprovementsLoaded) { - final trees = state.trees_imp; + if (state is TreesImprovementsLoaded) { + final trees = state.treesImprovements; return FormBuilder( key: otherImpKey, onChanged: () { @@ -118,7 +123,7 @@ class _AddOtherImprovementModal extends State { autofocus: false, decoration: normalTextFieldStyle( "Kinds of Trees", ""), - items: state.trees_imp + items: state.treesImprovements .map((trees) => DropdownMenuItem( value: trees, @@ -177,7 +182,7 @@ class _AddOtherImprovementModal extends State { }, ), ), - SizedBox( + const SizedBox( width: 10, ), Expanded( @@ -280,26 +285,27 @@ class _AddOtherImprovementModal extends State { 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)); + context + .read() + .add(AddOtherImprovements( + 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 == true ? '1' : '0', + )); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Submit"), ), @@ -315,10 +321,10 @@ class _AddOtherImprovementModal extends State { onPressed: () { context .read() - .add(const LoadOtherImprovement()); + .add(const LoadOtherImprovements()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Cancel"), ), @@ -344,11 +350,11 @@ class _AddOtherImprovementModal extends State { return Container(); }); } - if (state is OtherImprovementErrorState) { + if (state is OtherImprovementsErrorState) { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadOtherImprovement()); + context.read().add(LoadOtherImprovements()); }, ); } diff --git a/lib/screens/offline/passo/land/add/AddValueAdjustmentModal.dart b/lib/screens/offline/passo/land/add/AddValueAdjustmentModal.dart new file mode 100644 index 0000000..20dc9cf --- /dev/null +++ b/lib/screens/offline/passo/land/add/AddValueAdjustmentModal.dart @@ -0,0 +1,526 @@ +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:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; + +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../model/passo/type_of_location.dart'; +import '../../../../../model/passo/type_of_road.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class AddLandValueAdjustmentOfflineModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddLandValueAdjustmentOfflineModal createState() => + _AddLandValueAdjustmentOfflineModal(); +} + +class _AddLandValueAdjustmentOfflineModal + 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 Scaffold( + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowValueAdjustmentcreen) { + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is LandPropertyAppraisalLoaded) { + final land_appr = state.landAppr; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfRoadLoaded) { + final roadType = state.typeOfRoad; + 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< + LandAppr?>( + 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.typeOfLocation + .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.typeOfLocation + .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')); + + context.read().add(AddValueAdjustments( + 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())); + }, + style: + ElevatedButton.styleFrom( + backgroundColor: + 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< + ValueAdjustmentBloc>() + .add( + const LoadValueAdjustment()); + }, + style: + ElevatedButton.styleFrom( + backgroundColor: + Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ), + )); + } + if (state is TypeOfLocationState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadTypeOfLocation()); + }, + ); + } + return Container(); + }, + ); + } + if (state is LandPropertyAppraisalErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadLandPropertyAppraisal()); + }, + ); + } + return Container(); + }, + ); + } + if (state is ValueAdjustmentErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadValueAdjustment()); + }, + ); + } + return Container(); + }); + } + if (state is ValueAdjustmentErrorState) { + return Text(state.error); + } + return Container( + child: Text("Land Value Adjustment"), + ); + }), + ), + ); + } +} diff --git a/lib/screens/offline/passo/land/add/add_land.dart b/lib/screens/offline/passo/land/add/add_land.dart new file mode 100644 index 0000000..848986e --- /dev/null +++ b/lib/screens/offline/passo/land/add/add_land.dart @@ -0,0 +1,134 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; + +import 'package:im_stepper/stepper.dart'; +import 'package:unit2/screens/offline/passo/land/add/land_appraisal.dart'; +import 'package:unit2/screens/offline/passo/land/add/land_property_assessment.dart'; +import 'package:unit2/screens/offline/passo/land/add/land_property_owner_offline.dart'; +import 'package:unit2/screens/offline/passo/land/add/land_property_signatories.dart'; +import 'package:unit2/screens/offline/passo/land/add/location_and_boundaries_offline.dart'; +import 'package:unit2/screens/offline/passo/land/add/other_improvement.dart'; +import 'package:unit2/screens/offline/passo/land/add/value_adjustment_offline.dart'; + +import '../../../../../theme-data.dart/colors.dart'; +import '../../../../../utils/alerts.dart'; + +GlobalKey landKeyOffline = GlobalKey(); + +class AddLandOffline extends StatefulWidget { + Function loadLandFass; + AddLandOffline(this.loadLandFass); + @override + _AddLandOffline createState() => _AddLandOffline(); +} + +class _AddLandOffline 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 onCloseTransaction() { + Navigator.of(context).pop(); + widget.loadLandFass(); + } + + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async { + confirmAlertWithCancel( + context, + onCloseTransaction, + () => null, + 'Cancel transaction?', + "Are you sure you want to cancel this transaction?"); // Action to perform on back pressed + return false; + }, + child: Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text('Land FAAS'), + ), + body: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + NumberStepper( + numbers: const [1, 2, 3, 4, 5, 6, 7], + activeStepColor: primary, + numberStyle: const 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: landKeyOffline, + + // enabled: false, + onChanged: () { + landKeyOffline.currentState?.save(); + + print(landKeyOffline.currentState?.value.toString()); + }, + autovalidateMode: AutovalidateMode.disabled, + skipDisabled: true, + child: Container( + child: content(PrevBtn, NextBtn, onCloseTransaction), + ), + ), + ), + ], + ), + ), + ), + ); + } + + /// Returns the next button. + + // Returns the content widget based on the activeStep. + Widget content(PrevBtn, NextBtn, onSAveAll) { + switch (activeStep) { + case 0: + return LandPropertyOwnerInfoOffline(NextBtn); + case 1: + return LandLocationAndBoundariesOffline(PrevBtn, NextBtn); + case 2: + return LandAppraisalOffline(PrevBtn, NextBtn); + case 3: + return OtherImprovementOfflinePage(PrevBtn, NextBtn); + case 4: + return ValueAdjustmentOfflinePage(PrevBtn, NextBtn); + case 5: + return LandPropertyAssessmentOfflinePage(PrevBtn, NextBtn); + case 6: + return LandSignatoriesOfflinePage(onSAveAll); + + default: + return Container(); + } + } +} diff --git a/lib/screens/offline/passo/land/add/land_appraisal.dart b/lib/screens/offline/passo/land/add/land_appraisal.dart new file mode 100644 index 0000000..cc43ad9 --- /dev/null +++ b/lib/screens/offline/passo/land/add/land_appraisal.dart @@ -0,0 +1,276 @@ +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: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/offline/passo/land/add/AddLandAppraisal.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/utils/text_container.dart'; +import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +import '../../../../../bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; + +class LandAppraisalOffline extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandAppraisalOffline(this.PrevBtn, this.NextBtn); + @override + _LandAppraisalOffline createState() => _LandAppraisalOffline(); +} + +class _LandAppraisalOffline extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteLandPropertyAppraisal(id: itemId)); + } + + @override + Widget build(BuildContext context) { + 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 LandAppraisalLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandAppraisalLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandAppraisalErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, builder: (context, state) { + final state = context.watch().state; + if (state is LandPropertyAppraisalLoaded) { + 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(ShowAdditionalItems()); + }, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + 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.landAppr.map((dataRow) { + return DataRow( + cells: [ + DataCell( + Text(dataRow.classification ?? "")), + DataCell(Text(dataRow.subClass ?? "")), + DataCell(Text(dataRow.area ?? "")), + DataCell(Text(((double.parse( + dataRow.unitValue ?? "0"))) + .toString())), + DataCell(Text(((double.parse( + dataRow.baseMarketval ?? "0"))) + .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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).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 LandPropertyAppraisalDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadLandPropertyAppraisal()); + }); + }); + } + } + if (state is ShowAddItemsScreen) { + return ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: const Text( + 'ADD LAND APPRAISAL', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: AddLandAppraisalOfflineModal()), + ], + ), + ), + ); + } + if (state is LandAppraisalErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(const LoadLandPropertyAppraisal()); + }, + ); + } + return Container(); + }), + ), + ); + } +} diff --git a/lib/screens/offline/passo/land/add/land_property_assessment.dart b/lib/screens/offline/passo/land/add/land_property_assessment.dart new file mode 100644 index 0000000..6896eae --- /dev/null +++ b/lib/screens/offline/passo/land/add/land_property_assessment.dart @@ -0,0 +1,255 @@ +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/screens/offline/passo/land/add/AddLandPropertyAssessmentModal.dart'; + +import '../../../../../bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class LandPropertyAssessmentOfflinePage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandPropertyAssessmentOfflinePage(this.PrevBtn, this.NextBtn); + @override + _LandPropertyAssessmentOfflinePage createState() => + _LandPropertyAssessmentOfflinePage(); +} + +class _LandPropertyAssessmentOfflinePage + 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 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 LandPropertyAssessmentLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandPropertyAssessmentLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandPropertyAssessmentErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, 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.landPropertyAssessment.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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).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 ShowLandPropertyAssessmentcreen) { + 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: AddPropertyAssessmentOfflineModal()) + ], + ), + ), + ); + } + return Container(); + }), + ), + ); + } +} diff --git a/lib/screens/offline/passo/land/add/land_property_owner_offline.dart b/lib/screens/offline/passo/land/add/land_property_owner_offline.dart new file mode 100644 index 0000000..9d776ee --- /dev/null +++ b/lib/screens/offline/passo/land/add/land_property_owner_offline.dart @@ -0,0 +1,198 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; + +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class LandPropertyOwnerInfoOffline extends StatefulWidget { + Function NextBtn; + LandPropertyOwnerInfoOffline(this.NextBtn); + @override + _LandPropertyOwnerInfoOffline createState() => + _LandPropertyOwnerInfoOffline(); +} + +class _LandPropertyOwnerInfoOffline + 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", TextInputType.number), + customTextField("Owner", "", "owner", TextInputType.text), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "PIN", "", "pin", TextInputType.number)), + 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", TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("OCT/TCT CLOA No.", "", "cloa_no", + TextInputType.number), + ), + 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", TextInputType.number), + ), + 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", TextInputType.number)), + 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", TextInputType.number)), + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Address", "", "address", TextInputType.text), + ), + 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", TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Administrator/Beneficial User", "", + "admin", TextInputType.text), + ), + 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", TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "Address", "", "admin_address", TextInputType.text), + ), + 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", TextInputType.number)) + ]), + SizedBox( + height: 30, + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CustomButton( + icon: const Icon(Icons.chevron_right, color: Colors.white), + onPressed: () { + context.read().add( + AddLandPropertyOwner( + id: 1, + transCode: landKeyOffline + .currentState!.value['transaction_code'] + .toString(), + tdn: landKeyOffline.currentState!.value['td_no'] ?? + '', + cloaNo: + landKeyOffline.currentState!.value['cloa_no'] ?? + '', + dated: landKeyOffline.currentState!.value['dated'] + .toString(), + assessedById: "1", + assessedByName: "cyril", + dateCreated: landKeyOffline + .currentState!.value['dated'] + .toString(), + dateModified: landKeyOffline + .currentState!.value['dated'] + .toString(), + pin: landKeyOffline.currentState!.value['pin'], + surveyNo: + landKeyOffline.currentState!.value['survey_no'], + lotNo: landKeyOffline.currentState!.value['lot_no'], + blkNo: landKeyOffline.currentState!.value['blk'], + owner: landKeyOffline.currentState!.value['owner'], + address: + landKeyOffline.currentState!.value['address'], + telno: landKeyOffline.currentState!.value['tel_no'], + tin: landKeyOffline.currentState!.value['tin'], + adminUser: + landKeyOffline.currentState!.value['admin'], + adminAddress: landKeyOffline + .currentState!.value['admin_address'], + adminTin: + landKeyOffline.currentState!.value['admin_tin'], + // faasType: "LAND", + adminTelno: landKeyOffline + .currentState!.value['admin_telno'], + faasType: 'Land')); + + widget.NextBtn(); + }, + ) + ], + ), + const SizedBox( + height: 20, + ), + ]), + )); + } +} diff --git a/lib/screens/offline/passo/land/add/land_property_signatories.dart b/lib/screens/offline/passo/land/add/land_property_signatories.dart new file mode 100644 index 0000000..913b3aa --- /dev/null +++ b/lib/screens/offline/passo/land/add/land_property_signatories.dart @@ -0,0 +1,628 @@ +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:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; + +import '../../../../../model/passo/land_ext.dart'; +import '../../../../../model/passo/memoranda.dart'; +import '../../../../../model/passo/signatories.dart'; +import '../../../../../theme-data.dart/colors.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class LandSignatoriesOfflinePage extends StatefulWidget { + Function onSAve; + LandSignatoriesOfflinePage(this.onSAve); + + @override + _LandSignatoriesOfflinePage createState() => _LandSignatoriesOfflinePage(); +} + +class _LandSignatoriesOfflinePage extends State { + bool isTaxable = false; + bool isExempt = false; + final focus = FocusNode(); + String _memoranda = ""; + @override + Widget build(BuildContext context) { + 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 LandExtLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + + // if (state is LandExtErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is LandPropertySignatureInitial) { + return BlocConsumer( + listener: (context, state) { + // if (state is SignatoriesLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + + // if (state is SignatoriesErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, + builder: (context, state) { + if (state is SignatoriesLoaded) { + 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(); + // } + }, + 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: 50, + child: SearchField( + itemHeight: 70, + suggestions: state.memo + .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, + suggestionDirection: SuggestionDirection.up, + 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([]), + ), + ), + ], + ), + const SizedBox( + height: 30, + ), + ElevatedButton( + onPressed: () async { + final tempID = + await SharedPreferences.getInstance(); + var ext = LandExt(); + + print(ext.toJson()); + context.read().add(AddLandPropertySignature( + id: 1, + landapprDetailsId: + tempID.getInt('landid')! + 1, + dateCreated: 'test', + dateModified: 'test', + assessedById: 'test', + assessedByName: 'test', + taxable: isTaxable == true ? '1' : '0', + exempt: isExempt == true ? '1' : '0', + qtr: landKeyOffline + .currentState!.value['land_qtr'], + yr: landKeyOffline + .currentState!.value['land_yr'], + appraisedbyName: landKeyOffline + .currentState! + .value['appraised_by_land'] + .firstname + + ' ' + + landKeyOffline + .currentState! + .value['appraised_by_land'] + .middlename + + ' ' + + landKeyOffline + .currentState! + .value['appraised_by_land'] + .lastname, + appraisedbyDate: landKeyOffline.currentState!.value['app_date_land'] + .toString(), + recommendapprName: landKeyOffline + .currentState! + .value['rec_approval_land'] + .firstname + + ' ' + + landKeyOffline + .currentState! + .value['rec_approval_land'] + .middlename + + ' ' + + landKeyOffline.currentState!.value['rec_approval_land'].lastname, + recommendapprDate: landKeyOffline.currentState!.value['rec_date_land'].toString(), + approvedbyName: landKeyOffline.currentState!.value['apprvd_by_land'].firstname + ' ' + landKeyOffline.currentState!.value['apprvd_by_land'].middlename + ' ' + landKeyOffline.currentState!.value['apprvd_by_land'].lastname, + approvedbyDate: landKeyOffline.currentState!.value['apprvd_by_date_land'].toString(), + memoranda: _memoranda, + swornstatementNo: landKeyOffline.currentState!.value['sworn_statement_land'], + dateReceived: landKeyOffline.currentState!.value['date_received_land'].toString(), + entryDateAssessment: landKeyOffline.currentState!.value['date_of_entry_land'].toString(), + entryDateBy: landKeyOffline.currentState!.value['by_land'])); + 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, + ), + ], + )); + } + // if (state is MemorandaErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // // context + // // .read() + // // .add(LoadMemoranda()); + // }, + // ); + // } + return Container(); + }, + ); + } + // if (state is SignatoriesAd) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add(LoadSignatories()); + // }, + // ); + // } + return Container(); + }, + ); + } + // if (state is LandExtErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add(LoadLandExt()); + // }, + // ); + // } + return Container(); + }, + ), + ), + ); + } +} diff --git a/lib/screens/offline/passo/land/add/location_and_boundaries_offline.dart b/lib/screens/offline/passo/land/add/location_and_boundaries_offline.dart new file mode 100644 index 0000000..3587cee --- /dev/null +++ b/lib/screens/offline/passo/land/add/location_and_boundaries_offline.dart @@ -0,0 +1,199 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; + +import '../../../../../model/passo/land_property_boundaries.dart'; +import '../../../../../model/passo/land_property_loc.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class LandLocationAndBoundariesOffline extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + LandLocationAndBoundariesOffline(this.PrevBtn, this.NextBtn); + @override + _LandLocationAndBoundariesOffline createState() => + _LandLocationAndBoundariesOffline(); +} + +class _LandLocationAndBoundariesOffline + extends State { + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandPropertyLocationInitial) { + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is LandPropertyBoundariesInitial) { + 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", TextInputType.text)), + 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", TextInputType.text)), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Municipality", "", + "municipality", TextInputType.text), + ), + 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", TextInputType.text)) + ]), + 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", TextInputType.text), + ), + 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", TextInputType.text)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField( + "South", "", "south", TextInputType.text), + ), + 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", TextInputType.text)) + ]), + 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: () async { + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('landid')); + + context + .read() + .add(AddLandPropertyLocation( + id: tempID.getInt('landid')! - 1, + landapprDetailsId: + tempID.getInt('landid')!, + assessedById: 'test', + assessedByName: 'test', + dateCreated: 'test', + dateModified: 'test', + street: landKeyOffline + .currentState?.value['street'], + barangay: landKeyOffline + .currentState?.value['brgy'], + municipality: landKeyOffline + .currentState + ?.value['municipality'], + province: landKeyOffline + .currentState?.value['province'], + )); + + context + .read() + .add(AddLandPropertyBoundaries( + id: tempID.getInt('landid')! - 1, + landapprDetailsId: + tempID.getInt('landid')!, + assessedById: 'test', + assessedByName: 'test', + dateCreated: 'test', + dateModified: 'test', + north: landKeyOffline + .currentState?.value['north'], + east: landKeyOffline + .currentState?.value['east'], + south: landKeyOffline + .currentState?.value['south'], + west: landKeyOffline + .currentState?.value['west'], + sketch: 'test')); + widget.NextBtn(); + }) + ], + ) + ]), + ), + ); + } + return Container(); + }, + ); + } + return Container(); + }, + ); + } +} diff --git a/lib/screens/offline/passo/land/add/other_improvement.dart b/lib/screens/offline/passo/land/add/other_improvement.dart new file mode 100644 index 0000000..79c9ab8 --- /dev/null +++ b/lib/screens/offline/passo/land/add/other_improvement.dart @@ -0,0 +1,275 @@ +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/screens/offline/passo/land/add/AddOtherImprovementModal.dart'; + +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/passo/custom_button.dart'; + +import '../../../../../bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; + +class OtherImprovementOfflinePage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + OtherImprovementOfflinePage(this.PrevBtn, this.NextBtn); + @override + _OtherImprovementOfflinePage createState() => _OtherImprovementOfflinePage(); +} + +class _OtherImprovementOfflinePage extends State { + // double _totalMarketValue(items) { + // double total = 0; + // items.forEach((row) { + // total += double.parse(row); + // }); + // return total; + // } + + void deleteItem(int itemId) { + context + .read() + .add(DeleteOtherImprovements(id: itemId)); + } + + @override + Widget build(BuildContext context) { + 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 OtherImprovementLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is OtherImprovementLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is OtherImprovementErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, builder: (context, state) { + final state = context.watch().state; + if (state is OtherImprovementsLoaded) { + 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: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('ADD ITEM'), // <-- Text + SizedBox( + width: 5, + ), + 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.otherImprovements.map((dataRow) { + return DataRow( + cells: [ + DataCell(Text(dataRow.kindsOfTrees!)), + DataCell(Text(dataRow.subclassAge!)), + DataCell(Text(dataRow.fruitBearing == true + ? "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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).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 OtherImprovementsDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadOtherImprovements()); + }); + }); + } + } + if (state is ShowOtherImprovementScreen) { + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: 1000.0), + child: AlertDialog( + insetPadding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10.0, + ), + title: const Text( + 'ADD OTHER IMPROVEMENTS', + textAlign: TextAlign.center, + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: AddOtherImprovementModalOffline()) + ], + ), + ), + ); + } + return Container(); + }), + ), + ); + } +} diff --git a/lib/screens/offline/passo/land/add/value_adjustment_offline.dart b/lib/screens/offline/passo/land/add/value_adjustment_offline.dart new file mode 100644 index 0000000..041e30c --- /dev/null +++ b/lib/screens/offline/passo/land/add/value_adjustment_offline.dart @@ -0,0 +1,246 @@ +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/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/add/AddValueAdjustmentModal.dart'; + +import '../../../../../utils/alerts.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class ValueAdjustmentOfflinePage extends StatefulWidget { + Function PrevBtn; + Function NextBtn; + ValueAdjustmentOfflinePage(this.PrevBtn, this.NextBtn); + @override + _ValueAdjustmentOfflinePage createState() => _ValueAdjustmentOfflinePage(); +} + +class _ValueAdjustmentOfflinePage extends State { + void deleteItem(int itemId) { + context.read().add(DeleteValueAdjustment(id: itemId)); + } + + @override + Widget build(BuildContext context) { + 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 LandValueAdjustmentsLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandValueAdjustmentsLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandValueAdjustmentsErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + }, builder: (context, state) { + final state = context.watch().state; + if (state is ValueAdjustmentLoaded) { + 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(ShowValueAdjustment()); + }, + 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.valueAdjustment.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: () { + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); + }, + ), + ], + )) + ], + ); + }).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 ValueAdjustmentDeletedState) { + if (state.success) { + WidgetsBinding.instance.addPostFrameCallback((_) { + successAlert(context, "Deletion Successful", + "Extra item has been deleted successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(const LoadValueAdjustment()); + }); + }); + } + } + if (state is ShowValueAdjustmentcreen) { + 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: AddLandValueAdjustmentOfflineModal()) + ], + ), + ), + ); + } + return Container(); + }), + ), + ); + } +} diff --git a/lib/screens/passo/Land/add_land/AddLandAppraisal.dart b/lib/screens/offline/passo/land/edit/AddLandAppraisal.dart similarity index 80% rename from lib/screens/passo/Land/add_land/AddLandAppraisal.dart rename to lib/screens/offline/passo/land/edit/AddLandAppraisal.dart index a271e40..3ee5066 100644 --- a/lib/screens/passo/Land/add_land/AddLandAppraisal.dart +++ b/lib/screens/offline/passo/land/edit/AddLandAppraisal.dart @@ -5,36 +5,34 @@ 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/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_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/utils/text_container.dart'; import 'package:unit2/widgets/error_state.dart'; -import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart'; -class AddLandAppraisalModal extends StatefulWidget { +import '../../../../../model/passo/city.dart'; +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../model/passo/land_classification.dart'; +import '../../../../../model/passo/land_subclassification.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; + +class AddLandAppraisalEditOfflineModal extends StatefulWidget { // final List unit; // final List options; - // final int tempId; + final int tempId; - // AddLandAppraisalModal(this.unit, this.options, this.tempId); + AddLandAppraisalEditOfflineModal(this.tempId); @override - _AddLandAppraisalModal createState() => _AddLandAppraisalModal(); + _AddLandAppraisalEditOfflineModal createState() => + _AddLandAppraisalEditOfflineModal(); } -class _AddLandAppraisalModal extends State { +class _AddLandAppraisalEditOfflineModal + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -72,32 +70,33 @@ class _AddLandAppraisalModal extends State { @override Widget build(BuildContext context) { - return BlocBuilder( + return BlocBuilder( buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddLandAppraisalScreen) { + if (state is ShowAddItemsScreen) { return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { if (state is LandClassificationLoaded) { - final classification = state.land_classification; - return BlocConsumer( + final classification = state.landClassification; + return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { if (state is LandSubClassificationLoaded) { - final subclassification = state.land_subclassification; - return BlocConsumer( + final subclassification = state.landSubClassification; + return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is MunicipalityLoaded) { + if (state is MunicipalitiesLoaded) { return FormBuilder( key: appraisalLandKey, onChanged: () { @@ -134,7 +133,7 @@ class _AddLandAppraisalModal extends State { cityDesc ?? "Municipality", ""), - items: state.municipality + items: state.city .map((municipality) => DropdownMenuItem< City>( @@ -155,13 +154,9 @@ class _AddLandAppraisalModal extends State { }); final barangayBloc = context.read< - LandSubClassificationBloc>(); + LandSubclassificationBloc>(); barangayBloc.add( - LoadLandSubClassification( - classCode: - classCode!, - cityCode: - selectedCityCode!)); // Use selectedCityCode directly + LoadLandSubClassification()); // Use selectedCityCode directly } }, )), @@ -208,13 +203,9 @@ class _AddLandAppraisalModal extends State { }); final barangayBloc = context.read< - LandSubClassificationBloc>(); + LandSubclassificationBloc>(); barangayBloc.add( - LoadLandSubClassification( - classCode: - selectedClassCode!, - cityCode: - cityCode)); // Use selectedCityCode directly + LoadLandSubClassification()); // Use selectedCityCode directly } }, )), @@ -330,34 +321,30 @@ class _AddLandAppraisalModal extends State { .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)); + context.read().add( + AddLandPropertyAppraisal( + landapprDetailsId: + tempID.getInt( + 'landid')!, + classification: + _classDesc, + subClass: + _subClassDesc, + area: _areaValue + .toString(), + unitValue: _unitBase + .toString(), + baseMarketval: + _totalMarketValue( + _unitBase, + _areaValue) + .toString())); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: + Colors.black, ), child: const Text("Submit"), ), @@ -374,13 +361,14 @@ class _AddLandAppraisalModal extends State { onPressed: () { context .read< - LandAppraisalBloc>() + LandPropertyAppraisalBloc>() .add( - const LoadLandAppraisal()); + const LoadLandPropertyAppraisal()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: + Colors.black, ), child: const Text("Cancel"), ), @@ -392,44 +380,44 @@ class _AddLandAppraisalModal extends State { ), ))); } - if (state is MunicipalityErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadMunicipality()); - }, - ); - } + // if (state is MunicipalityErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(LoadMunicipality()); + // }, + // ); + // } return Container(); }, ); } - if (state is LandSubClassificationErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add( - const LoadLandSubClassification( - cityCode: '1', classCode: 1)); - }, - ); - } + // if (state is LandSubClassificationErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context.read().add( + // const LoadLandSubClassification( + // cityCode: '1', classCode: 1)); + // }, + // ); + // } return Container(); }, ); } - if (state is LandClassificationErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadLandClassification()); - }, - ); - } + // if (state is LandClassificationErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(const LoadLandClassification()); + // }, + // ); + // } return Container(); }, ); @@ -438,7 +426,9 @@ class _AddLandAppraisalModal extends State { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadLandAppraisal()); + context + .read() + .add(const LoadLandPropertyAppraisal()); }, ); } diff --git a/lib/screens/passo/Land/edit_land/AddOtherImprovementEditModal.dart b/lib/screens/offline/passo/land/edit/AddOtherImprovementModal.dart similarity index 80% rename from lib/screens/passo/Land/edit_land/AddOtherImprovementEditModal.dart rename to lib/screens/offline/passo/land/edit/AddOtherImprovementModal.dart index 30df942..669d01e 100644 --- a/lib/screens/passo/Land/edit_land/AddOtherImprovementEditModal.dart +++ b/lib/screens/offline/passo/land/edit/AddOtherImprovementModal.dart @@ -4,28 +4,28 @@ 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'; -import 'package:unit2/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; -class AddOtherImprovementEditModal extends StatefulWidget { +import '../../../../../model/passo/trees_improvements.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class AddOtherImprovementModalEditOffline extends StatefulWidget { // final List unit; // final List options; final int tempId; - AddOtherImprovementEditModal(this.tempId); + AddOtherImprovementModalEditOffline(this.tempId); @override - _AddOtherImprovementEditModal createState() => - _AddOtherImprovementEditModal(); + _AddOtherImprovementModalEditOffline createState() => + _AddOtherImprovementModalEditOffline(); } -class _AddOtherImprovementEditModal - extends State { +class _AddOtherImprovementModalEditOffline + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -87,13 +87,13 @@ class _AddOtherImprovementEditModal buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddOtherImprovementScreen) { - return BlocConsumer(listener: (context, state) { + if (state is ShowOtherImprovementScreen) { + return BlocConsumer( + listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is LandTreesImprovementsLoaded) { - final trees = state.trees_imp; + if (state is TreesImprovementsLoaded) { + final trees = state.treesImprovements; return FormBuilder( key: otherImpKey, onChanged: () { @@ -120,7 +120,7 @@ class _AddOtherImprovementEditModal autofocus: false, decoration: normalTextFieldStyle( "Kinds of Trees", ""), - items: state.trees_imp + items: state.treesImprovements .map((trees) => DropdownMenuItem( value: trees, @@ -279,25 +279,30 @@ class _AddOtherImprovementEditModal padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () async { - var improvement = OtherImprovements( - landapprDetailsId: widget.tempId, - kindsOfTrees: _treeType, - subclassAge: _subClassDesc, - quantity: qty, - unitValue: _unitValue.toString(), - baseMarketval: - _calculateBaseMarketValue() - .toString(), - noOfProductive: pr_qty, - noOfNonproductive: nonpr_qty, - fruitBearing: _fruitBearing); + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('landid')); - context.read().add( - AddOtherImprovement( - other_imp: improvement)); + context + .read() + .add(AddOtherImprovements( + 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 == true ? '1' : '0', + )); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Submit"), ), @@ -311,13 +316,12 @@ class _AddOtherImprovementEditModal padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { - context.read().add( - LoadOtherImprovementEdit( - other_imps: [], - ids: widget.tempId)); + context + .read() + .add(const LoadOtherImprovements()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Cancel"), ), @@ -330,24 +334,24 @@ class _AddOtherImprovementEditModal ), )); } - if (state is LandTreesImprovementsErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadLandTreesImprovements()); - }, - ); - } + // if (state is LandTreesImprovementsErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(LoadLandTreesImprovements()); + // }, + // ); + // } return Container(); }); } - if (state is OtherImprovementErrorState) { + if (state is OtherImprovementsErrorState) { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadOtherImprovement()); + context.read().add(LoadOtherImprovements()); }, ); } diff --git a/lib/screens/passo/Land/edit_land/AddPropertyAssessmentEditModal.dart b/lib/screens/offline/passo/land/edit/AddPropertyAssessmentEditModal.dart similarity index 81% rename from lib/screens/passo/Land/edit_land/AddPropertyAssessmentEditModal.dart rename to lib/screens/offline/passo/land/edit/AddPropertyAssessmentEditModal.dart index b96977d..318ccb8 100644 --- a/lib/screens/passo/Land/edit_land/AddPropertyAssessmentEditModal.dart +++ b/lib/screens/offline/passo/land/edit/AddPropertyAssessmentEditModal.dart @@ -3,28 +3,28 @@ 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'; -import 'package:unit2/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; -class AddPropertyAssessmentEditModal extends StatefulWidget { +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class AddPropertyAssessmentEditOfflineModal extends StatefulWidget { // final List unit; // final List options; - final int tempId; + // final int tempId; - AddPropertyAssessmentEditModal(this.tempId); + // AddLandAppraisalModal(this.unit, this.options, this.tempId); @override - _AddPropertyAssessmentEditModal createState() => - _AddPropertyAssessmentEditModal(); + _AddPropertyAssessmentEditOfflineModal createState() => + _AddPropertyAssessmentEditOfflineModal(); } -class _AddPropertyAssessmentEditModal - extends State { +class _AddPropertyAssessmentEditOfflineModal + extends State { final focus = FocusNode(); bool isPainted = false; bool isSecondHand = false; @@ -70,23 +70,17 @@ class _AddPropertyAssessmentEditModal calculateAssessmentValue() { switch (_actualUse) { case "Residential": - return _unitValue * 0.20; - break; + return (_unitValue * 0.20).ceil(); case "Agricultural": - return _unitValue * 0.40; - break; + return (_unitValue * 0.40).ceil(); case "Commercial": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Industrial": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Mineral": - return _unitValue * 0.50; - break; + return (_unitValue * 0.50).ceil(); case "Timberland": - return _unitValue * 0.20; - break; + return (_unitValue * 0.20).ceil(); default: } } @@ -111,13 +105,13 @@ class _AddPropertyAssessmentEditModal buildWhen: (previous, current) { return false; }, builder: (context, state) { - if (state is ShowAddLandPropertyAssessmentScreen) { - return BlocConsumer(listener: (context, state) { + if (state is ShowLandPropertyAssessmentcreen) { + return BlocConsumer( + listener: (context, state) { // TODO: implement listener }, builder: (context, state) { - if (state is LandValueAdjustmentsLoaded) { - final assessment = state.val_adj; + if (state is ValueAdjustmentLoaded) { + final assessment = state.valueAdjustment; return FormBuilder( key: assessmentKey, onChanged: () { @@ -144,7 +138,7 @@ class _AddPropertyAssessmentEditModal autofocus: false, decoration: normalTextFieldStyle( "Value Adjustments", ""), - items: state.val_adj + items: state.valueAdjustment .map((adj) => DropdownMenuItem( value: adj, @@ -277,24 +271,26 @@ class _AddPropertyAssessmentEditModal padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () async { - var assessment = LandPropertyAssessment( - landapprDetailsId: widget.tempId, - actualUse: _actualUse, - marketval: _unitValue.toString(), - assessmentLevel: _assessmentLevel, - assessedValue: - calculateAssessmentValue() - .toString(), - totalMarketval: '0', - totalAssessedval: '0'); + final tempID = + await SharedPreferences.getInstance(); + print(tempID.getInt('landid')! - 1); context .read() .add(AddLandPropertyAssessment( - assessment: assessment)); + landapprDetailsId: + tempID.getInt('landid')! - 1, + actualUse: _actualUse, + marketval: _unitValue.toString(), + assessmentLevel: _assessmentLevel, + assessedValue: + calculateAssessmentValue() + .toString(), + totalMarketval: '0', + totalAssessedval: '0')); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Submit"), ), @@ -314,7 +310,7 @@ class _AddPropertyAssessmentEditModal const LoadLandPropertyAssessment()); }, style: ElevatedButton.styleFrom( - primary: Colors.black, + backgroundColor: Colors.black, ), child: const Text("Cancel"), ), @@ -327,13 +323,13 @@ class _AddPropertyAssessmentEditModal ), )); } - if (state is LandValueAdjustmentsErrorState) { + if (state is ValueAdjustmentErrorState) { return SomethingWentWrong( message: onError, onpressed: () { context - .read() - .add(LoadLandValueAdjustments()); + .read() + .add(const LoadValueAdjustment()); }, ); } @@ -346,7 +342,7 @@ class _AddPropertyAssessmentEditModal onpressed: () { context .read() - .add(LoadLandPropertyAssessment()); + .add(const LoadLandPropertyAssessment()); }, ); } diff --git a/lib/screens/offline/passo/land/edit/AddValueAdjustmentModalOffline.dart b/lib/screens/offline/passo/land/edit/AddValueAdjustmentModalOffline.dart new file mode 100644 index 0000000..2bcf996 --- /dev/null +++ b/lib/screens/offline/passo/land/edit/AddValueAdjustmentModalOffline.dart @@ -0,0 +1,525 @@ +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:intl/intl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; + +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../model/passo/type_of_location.dart'; +import '../../../../../model/passo/type_of_road.dart'; +import '../../../../../theme-data.dart/form-style.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class AddLandValueAdjustmentEditOfflineModal extends StatefulWidget { + // final List unit; + // final List options; + // final int tempId; + + // AddLandAppraisalModal(this.unit, this.options, this.tempId); + + @override + _AddLandValueAdjustmentEditOfflineModal createState() => + _AddLandValueAdjustmentEditOfflineModal(); +} + +class _AddLandValueAdjustmentEditOfflineModal + 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 Scaffold( + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder( + buildWhen: (previous, current) { + return false; + }, builder: (context, state) { + if (state is ShowValueAdjustmentcreen) { + return BlocConsumer(listener: (context, state) { + // TODO: implement listener + }, builder: (context, state) { + if (state is LandPropertyAppraisalLoaded) { + final land_appr = state.landAppr; + return BlocConsumer( + listener: (context, state) { + // TODO: implement listener + }, + builder: (context, state) { + if (state is TypeOfRoadLoaded) { + final roadType = state.typeOfRoad; + 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< + LandAppr?>( + 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.typeOfLocation + .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.typeOfLocation + .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')); + + context.read().add(AddValueAdjustments( + 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())); + }, + style: + ElevatedButton.styleFrom( + backgroundColor: + 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< + ValueAdjustmentBloc>() + .add( + const LoadValueAdjustment()); + }, + style: + ElevatedButton.styleFrom( + backgroundColor: + Colors.black, + ), + child: const Text("Cancel"), + ), + ), + ], + ) + ], + ), + ), + ), + )); + } + if (state is TypeOfLocationState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadTypeOfLocation()); + }, + ); + } + return Container(); + }, + ); + } + if (state is LandPropertyAppraisalErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadLandPropertyAppraisal()); + }, + ); + } + return Container(); + }, + ); + } + if (state is ValueAdjustmentErrorState) { + return SomethingWentWrong( + message: onError, + onpressed: () { + context + .read() + .add(LoadValueAdjustment()); + }, + ); + } + return Container(); + }); + } + if (state is ValueAdjustmentErrorState) { + return Text(state.error); + } + return Container( + child: Text("Land Value Adjustment"), + ); + }), + ), + ); + } +} diff --git a/lib/screens/passo/Land/edit_land.dart b/lib/screens/offline/passo/land/edit/edit_land.dart similarity index 58% rename from lib/screens/passo/Land/edit_land.dart rename to lib/screens/offline/passo/land/edit/edit_land.dart index 2491dce..7689469 100644 --- a/lib/screens/passo/Land/edit_land.dart +++ b/lib/screens/offline/passo/land/edit/edit_land.dart @@ -1,34 +1,34 @@ import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; - import 'package:im_stepper/stepper.dart'; -import 'package:unit2/model/passo/land_property_owner.dart'; -import 'package:unit2/screens/passo/Land/edit_land/land_appraisal.dart'; -import 'package:unit2/screens/passo/Land/edit_land/location_and_boundaries_edit.dart'; -import 'package:unit2/screens/passo/Land/edit_land/other_improvements_edit.dart'; -import 'package:unit2/screens/passo/Land/edit_land/property_assessment_cont_edit.dart'; -import 'package:unit2/screens/passo/Land/edit_land/property_assessment_edit.dart'; -import 'package:unit2/screens/passo/Land/edit_land/property_owner_info_edit.dart'; -import 'package:unit2/screens/passo/Land/edit_land/value_adjustments_edit.dart'; -import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/screens/offline/passo/land/edit/land_appraisal_edit_offline.dart'; +import 'package:unit2/screens/offline/passo/land/edit/land_property_assessement_edit.dart'; +import 'package:unit2/screens/offline/passo/land/edit/land_property_owner_offline_edit.dart'; +import 'package:unit2/screens/offline/passo/land/edit/land_signatories_edit.dart'; +import 'package:unit2/screens/offline/passo/land/edit/location_and_boundaries_edit_offline.dart'; +import 'package:unit2/screens/offline/passo/land/edit/other_improvements_edit.dart'; +import 'package:unit2/screens/offline/passo/land/edit/value_adjustment_edit.dart'; -GlobalKey landKey = GlobalKey(); +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../theme-data.dart/colors.dart'; -class EditLand extends StatefulWidget { +GlobalKey landOfflineKeyEdit = GlobalKey(); + +class EditLandOffline extends StatefulWidget { final int index; final LandPropertyOwner faas; final String title; - const EditLand( + const EditLandOffline( {super.key, required this.title, required this.index, required this.faas}); @override - _EditLand createState() => _EditLand(); + _EditLandOffline createState() => _EditLandOffline(); } -class _EditLand extends State { +class _EditLandOffline extends State { // THE FOLLOWING TWO VARIABLES ARE REQUIRED TO CONTROL THE STEPPER. int activeStep = 0; // Initial step set to 5. @@ -95,23 +95,26 @@ class _EditLand extends State { Widget content(PrevBtn, NextBtn, onSAveAll) { switch (activeStep) { case 0: - return LandPropertyOwnerInfoEdit(NextBtn, widget.faas!); + return LandPropertyOwnerInfoOfflineEdit(NextBtn, widget.faas); case 1: - return LandLocationAndBoundariesEdit(PrevBtn, NextBtn, widget.faas!); + return LandLocationAndBoundariesOfflineEdit( + PrevBtn, NextBtn, widget.faas!); case 2: - return LandAppraisalEdit(PrevBtn, NextBtn, widget.faas.id!); + return LandAppraisalEditOffline(PrevBtn, NextBtn, widget.faas.id!); case 3: - return OtherImprovementEditPage(PrevBtn, NextBtn, widget.faas.id!); + return OtherImprovementEditPageOffline( + PrevBtn, NextBtn, widget.faas.id!); case 4: - return ValueAdjustmentEditPage(PrevBtn, NextBtn, widget.faas.id!); + return ValueAdjustmentEditPageOffline( + PrevBtn, NextBtn, widget.faas.id!); case 5: - return LandPropertyAssessmentEditPage( + return LandPropertyAssessmentEditPageOffline( PrevBtn, NextBtn, widget.faas.id!); case 6: - return LandSignatoriesEdit(onSAveAll, widget.faas.id!); + return LandSignatoriesEditOffline(onSAveAll, widget.faas.id!); default: - return LandPropertyOwnerInfoEdit(NextBtn, widget.faas!); + return SizedBox.shrink(); } } } diff --git a/lib/screens/passo/Land/edit_land/land_appraisal.dart b/lib/screens/offline/passo/land/edit/land_appraisal_edit_offline.dart similarity index 67% rename from lib/screens/passo/Land/edit_land/land_appraisal.dart rename to lib/screens/offline/passo/land/edit/land_appraisal_edit_offline.dart index 7cb966e..43f0839 100644 --- a/lib/screens/passo/Land/edit_land/land_appraisal.dart +++ b/lib/screens/offline/passo/land/edit/land_appraisal_edit_offline.dart @@ -3,25 +3,25 @@ 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: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/edit_land/AddLandAppraisalEdit.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/AddLandAppraisal.dart'; -import 'package:unit2/utils/alerts.dart'; -import 'package:unit2/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; -import 'package:unit2/widgets/passo/custom_button.dart'; +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; +import '../../../../../widgets/passo/custom_button.dart'; -class LandAppraisalEdit extends StatefulWidget { +class LandAppraisalEditOffline extends StatefulWidget { Function PrevBtn; Function NextBtn; final int faasId; - LandAppraisalEdit(this.PrevBtn, this.NextBtn, this.faasId); + LandAppraisalEditOffline(this.PrevBtn, this.NextBtn, this.faasId); @override - _LandAppraisalEdit createState() => _LandAppraisalEdit(); + _LandAppraisalEditOffline createState() => _LandAppraisalEditOffline(); } -class _LandAppraisalEdit extends State { +class _LandAppraisalEditOffline extends State { // double _totalMarketValue(items) { // double total = 0; // items.forEach((row) { @@ -31,7 +31,9 @@ class _LandAppraisalEdit extends State { // } void deleteItem(int itemId) { - context.read().add(DeleteLandAppraisal(id: itemId)); + context + .read() + .add(DeleteLandPropertyAppraisal(id: itemId)); } @override @@ -40,23 +42,24 @@ class _LandAppraisalEdit extends State { padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is LandAppraisalLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is LandAppraisalLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is LandAppraisalErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + child: + BlocConsumer( + listener: (context, state) { + // if (state is LandAppraisalLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandAppraisalLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandAppraisalErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { - final state = context.watch().state; - if (state is LandAppraisalLoaded) { + final state = context.watch().state; + if (state is LandPropertyAppraisalLoaded) { return Column( children: [ Expanded( @@ -81,17 +84,17 @@ class _LandAppraisalEdit extends State { ), onPressed: () { context - .read() - .add(ShowLandAppraisal()); + .read() + .add(ShowAdditionalItems()); }, - child: Row( + child: const Row( mainAxisSize: MainAxisSize.min, children: [ - const Text('ADD ITEM'), // <-- Text - const SizedBox( + Text('ADD ITEM'), // <-- Text + SizedBox( width: 5, ), - const Icon( + Icon( // <-- Icon Icons.add, size: 24.0, @@ -124,57 +127,51 @@ class _LandAppraisalEdit extends State { label: Text('Action'), ) ], - rows: state.land_appr.map((dataRow) { + rows: state.landAppr.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(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ) + .format(((double.parse( + dataRow.unitValue!)))) + .toString())), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ) + .format(((double.parse( + dataRow.baseMarketval!)))) + .toString())), DataCell(Row( children: [ InkWell( child: Container( height: 30, width: 30, - decoration: BoxDecoration( + decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.red, ), - child: Icon( + child: const Icon( Icons.delete, color: Colors.white, size: 20.0, ), ), onTap: () { - deleteItem(dataRow.id!); + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); }, ), - 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: () {}, - ), ], )) ], @@ -232,19 +229,20 @@ class _LandAppraisalEdit extends State { ], ); } - if (state is LandAppraisalDeletedState) { + if (state is LandPropertyAppraisalDeletedState) { if (state.success) { WidgetsBinding.instance.addPostFrameCallback((_) { successAlert(context, "Deletion Successful", "Extra item has been deleted successfully", () { Navigator.of(context).pop(); - context.read().add(LoadLandAppraisalEdit( - land_appr: const [], id: widget.faasId!)); + context.read().add( + LoadLandPropertyAppraisalEdit( + landAppr: const [], id: widget.faasId!)); }); }); } } - if (state is ShowAddLandAppraisalScreen) { + if (state is ShowAddItemsScreen) { return ConstrainedBox( constraints: const BoxConstraints( maxHeight: 700.0, @@ -266,10 +264,8 @@ class _LandAppraisalEdit extends State { alignment: Alignment.topCenter, child: Container( child: ConstrainedBox( - constraints: BoxConstraints(maxHeight: 500), - child: Container( - child: AddLandAppraisalEditModal(widget.faasId), - ), + constraints: const BoxConstraints(maxHeight: 500), + child: AddLandAppraisalEditOfflineModal(widget.faasId), ), ), ), @@ -278,12 +274,13 @@ class _LandAppraisalEdit extends State { ), ); } - if (state is LandAppraisalErrorState) { + if (state is LandPropertyAppraisalErrorState) { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadLandAppraisalEdit( - land_appr: [], id: widget.faasId!)); + context.read().add( + LoadLandPropertyAppraisalEdit( + landAppr: const [], id: widget.faasId!)); }, ); } diff --git a/lib/screens/passo/Land/edit_land/property_assessment_edit.dart b/lib/screens/offline/passo/land/edit/land_property_assessement_edit.dart similarity index 74% rename from lib/screens/passo/Land/edit_land/property_assessment_edit.dart rename to lib/screens/offline/passo/land/edit/land_property_assessement_edit.dart index 097dabe..389d573 100644 --- a/lib/screens/passo/Land/edit_land/property_assessment_edit.dart +++ b/lib/screens/offline/passo/land/edit/land_property_assessement_edit.dart @@ -2,28 +2,29 @@ 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/bulding/property_assessment_edit/property_assessment_edit_bloc.dart'; -import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart'; -import 'package:unit2/model/passo/land_property_assessment.dart'; -import 'package:unit2/screens/passo/Land/add_land/AddPropertyAssessmentModal.dart'; -import 'package:unit2/screens/passo/Land/edit_land/AddPropertyAssessmentEditModal.dart'; -import 'package:unit2/utils/alerts.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:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/AddPropertyAssessmentEditModal.dart'; -class LandPropertyAssessmentEditPage extends StatefulWidget { +import '../../../../../model/passo/land_property_assessment.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class LandPropertyAssessmentEditPageOffline extends StatefulWidget { Function PrevBtn; Function NextBtn; final int faasId; - LandPropertyAssessmentEditPage(this.PrevBtn, this.NextBtn, this.faasId); + LandPropertyAssessmentEditPageOffline( + this.PrevBtn, this.NextBtn, this.faasId); @override - _LandPropertyAssessmentEditPage createState() => - _LandPropertyAssessmentEditPage(); + _LandPropertyAssessmentEditPageOffline createState() => + _LandPropertyAssessmentEditPageOffline(); } -class _LandPropertyAssessmentEditPage - extends State { +class _LandPropertyAssessmentEditPageOffline + extends State { // double _totalMarketValue(items) { // double total = 0; // items.forEach((row) { @@ -47,18 +48,18 @@ class _LandPropertyAssessmentEditPage indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer(listener: (context, state) { - if (state is LandPropertyAssessmentLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is LandPropertyAssessmentLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is LandPropertyAssessmentErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + // if (state is LandPropertyAssessmentLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandPropertyAssessmentLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandPropertyAssessmentErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { final state = context.watch().state; if (state is LandPropertyAssessmentLoaded) { @@ -126,14 +127,23 @@ class _LandPropertyAssessmentEditPage label: Text('Action'), ) ], - rows: state.assessment.map((dataRow) { + rows: + state.landPropertyAssessment.map((dataRow) { return DataRow( cells: [ - DataCell(Text(dataRow.actualUse!)), - DataCell(Text(dataRow.marketval!)), - DataCell( - Text(dataRow.assessmentLevel! + '%')), - DataCell(Text(dataRow.assessedValue!)), + DataCell(Text(dataRow.actualUse ?? "")), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format( + double.parse(dataRow.marketval!)))), + DataCell(Text(dataRow.assessmentLevel ?? + "0" + '%')), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow.assessedValue!)))), DataCell(Row( children: [ InkWell( @@ -151,28 +161,14 @@ class _LandPropertyAssessmentEditPage ), ), onTap: () { - deleteItem(dataRow.id!); + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); }, ), - 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: () {}, - ), ], )) ], @@ -238,13 +234,13 @@ class _LandPropertyAssessmentEditPage Navigator.of(context).pop(); context.read().add( LoadLandPropertyAssessmentEdit( - assessment: [], + landPropertyAssessment: [], id: widget.faasId)); }); }); } } - if (state is ShowAddLandPropertyAssessmentScreen) { + if (state is ShowLandPropertyAssessmentcreen) { return ConstrainedBox( constraints: BoxConstraints(maxHeight: 1000.0), child: AlertDialog( @@ -260,8 +256,7 @@ class _LandPropertyAssessmentEditPage mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( - child: AddPropertyAssessmentEditModal(widget.faasId)) + Container(child: AddPropertyAssessmentEditOfflineModal()) ], ), ), @@ -273,7 +268,7 @@ class _LandPropertyAssessmentEditPage onpressed: () { context.read().add( LoadLandPropertyAssessmentEdit( - assessment: const [], + landPropertyAssessment: const [], id: widget.faasId)); }, ); diff --git a/lib/screens/passo/Land/edit_land/property_owner_info_edit.dart b/lib/screens/offline/passo/land/edit/land_property_owner_offline_edit.dart similarity index 57% rename from lib/screens/passo/Land/edit_land/property_owner_info_edit.dart rename to lib/screens/offline/passo/land/edit/land_property_owner_offline_edit.dart index 73fddbf..2320f6b 100644 --- a/lib/screens/passo/Land/edit_land/property_owner_info_edit.dart +++ b/lib/screens/offline/passo/land/edit/land_property_owner_offline_edit.dart @@ -1,33 +1,34 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.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'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/edit_land.dart'; -GlobalKey landEditKey = GlobalKey(); +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; -class LandPropertyOwnerInfoEdit extends StatefulWidget { +class LandPropertyOwnerInfoOfflineEdit extends StatefulWidget { Function NextBtn; LandPropertyOwner land; - LandPropertyOwnerInfoEdit(this.NextBtn, this.land); + LandPropertyOwnerInfoOfflineEdit(this.NextBtn, this.land); @override - _LandPropertyOwnerInfoEdit createState() => _LandPropertyOwnerInfoEdit(); + _LandPropertyOwnerInfoOfflineEdit createState() => + _LandPropertyOwnerInfoOfflineEdit(); } -class _LandPropertyOwnerInfoEdit extends State { +class _LandPropertyOwnerInfoOfflineEdit + extends State { final transaction_codes = ['New', 'Revision']; @override Widget build(BuildContext context) { - return BlocConsumer( + return BlocConsumer( listener: (context, state) { // TODO: implement listener }, builder: (context, state) { return FormBuilder( - key: landEditKey, + key: landOfflineKeyEdit, initialValue: { 'transaction_code': widget.land.transCode ?? '', 'td_no': widget.land.tdn ?? '', @@ -48,8 +49,8 @@ class _LandPropertyOwnerInfoEdit extends State { }, enabled: true, onChanged: () { - landEditKey.currentState!.save(); - debugPrint(landEditKey.currentState!.value.toString()); + landOfflineKeyEdit.currentState!.save(); + debugPrint(landOfflineKeyEdit.currentState!.value.toString()); }, autovalidateMode: AutovalidateMode.disabled, skipDisabled: true, @@ -70,26 +71,30 @@ class _LandPropertyOwnerInfoEdit extends State { const SizedBox(height: 15), customDropDownField("Transaction Code", "", "transaction_code", transaction_codes), - customTextField("ARP No./ TD No.", "", "td_no"), - customTextField("Owner", "", "owner"), + customTextField( + "ARP No./ TD No.", "", "td_no", TextInputType.number), + customTextField("Owner", "", "owner", TextInputType.text), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( - flex: 1, child: customTextField("PIN", "", "pin")), + flex: 1, + child: customTextField( + "PIN", "", "pin", TextInputType.number)), 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")) + child: customTextField( + "TIN", "", "tin", TextInputType.number)) ]), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( flex: 1, - child: customTextField( - "OCT/TCT CLOA No.", "", "cloa_no"), + child: customTextField("OCT/TCT CLOA No.", "", + "cloa_no", TextInputType.number), ), const SizedBox(width: 10.0), Expanded( @@ -102,31 +107,21 @@ class _LandPropertyOwnerInfoEdit extends State { children: [ Expanded( flex: 1, - child: customTextField("Survey No.", "", "survey_no"), + child: customTextField("Survey No.", "", "survey_no", + TextInputType.number), ), 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")), + child: customTextField( + "Lot No.", "", "lot_no", TextInputType.number)), 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")) + child: customTextField( + "Blk", "", "blk", TextInputType.number)), ]), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -134,28 +129,47 @@ class _LandPropertyOwnerInfoEdit extends State { Expanded( flex: 1, child: customTextField( - "Administrator/Beneficial User", "", "admin"), + "Address", "", "address", TextInputType.text), ), 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")) + child: customTextField( + "Tel No.", "", "tel_no", TextInputType.number)) ]), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( flex: 1, - child: - customTextField("Address", "", "admin_address"), + child: customTextField( + "Administrator/Beneficial User", + "", + "admin", + TextInputType.text), ), 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")) + child: customTextField( + "TIN", "", "admin_tin", TextInputType.number)) + ]), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded( + flex: 1, + child: customTextField("Address", "", "admin_address", + TextInputType.text), + ), + 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", + TextInputType.number)) ]), SizedBox( height: 30, @@ -167,44 +181,45 @@ class _LandPropertyOwnerInfoEdit extends State { icon: const Icon(Icons.chevron_right, color: Colors.white), onPressed: () { - var land = LandPropertyOwner( - id: widget.land.id, - transCode: landEditKey + var landOwner = LandPropertyOwner( + id: widget.land.id!, + transCode: landOfflineKeyEdit .currentState!.value['transaction_code'] .toString(), - tdn: landEditKey.currentState!.value['td_no'], - cloaNo: - landEditKey.currentState!.value['cloa_no'], - dated: landEditKey.currentState!.value['dated'], + tdn: landOfflineKeyEdit + .currentState!.value['td_no'], + cloaNo: landOfflineKeyEdit + .currentState!.value['cloa_no'], + dated: landOfflineKeyEdit + .currentState!.value['dated'] + .toString(), assessedById: "1", assessedByName: "cyril", - dateCreated: - landEditKey.currentState!.value['dated'], - dateModified: - landEditKey.currentState!.value['dated'], - pin: landEditKey.currentState!.value['pin'], - surveyNo: - landEditKey.currentState!.value['survey_no'], - lotNo: landEditKey.currentState!.value['lot_no'], - blkNo: landEditKey.currentState!.value['blk'], - owner: landEditKey.currentState!.value['owner'], - address: - landEditKey.currentState!.value['address'], - telno: landEditKey.currentState!.value['tel_no'], - tin: landEditKey.currentState!.value['tin'], - adminUser: - landEditKey.currentState!.value['admin'], - adminAddress: landEditKey - .currentState!.value['admin_address'], - adminTin: - landEditKey.currentState!.value['admin_tin'], - // faasType: "LAND", - adminTelno: landEditKey - .currentState!.value['admin_telno']); - - context.read().add( - UpdateLandPropertyOwner( - land_edit: land, id: widget.land.id!)); + dateCreated: 'none', + dateModified: 'none', + pin: + landOfflineKeyEdit.currentState!.value['pin'], + surveyNo: landOfflineKeyEdit + .currentState!.value['survey_no'], + lotNo: landOfflineKeyEdit + .currentState!.value['lot_no'], + blkNo: + landOfflineKeyEdit.currentState!.value['blk'], + owner: landOfflineKeyEdit + .currentState!.value['owner'], + address: landOfflineKeyEdit + .currentState!.value['address'], + telno: landOfflineKeyEdit.currentState!.value['tel_no'], + tin: landOfflineKeyEdit.currentState!.value['tin'], + adminUser: landOfflineKeyEdit.currentState!.value['admin'], + adminAddress: landOfflineKeyEdit.currentState!.value['admin_address'], + adminTin: landOfflineKeyEdit.currentState!.value['admin_tin'], + faasType: "LAND", + adminTelno: landOfflineKeyEdit.currentState!.value['admin_telno']); + context.read().add( + UpdateLandPropertyOwnerInfo( + landPropertyOwner: landOwner, + id: widget.land.id!)); widget.NextBtn(); }, diff --git a/lib/screens/passo/Land/edit_land/property_assessment_cont_edit.dart b/lib/screens/offline/passo/land/edit/land_signatories_edit.dart similarity index 79% rename from lib/screens/passo/Land/edit_land/property_assessment_cont_edit.dart rename to lib/screens/offline/passo/land/edit/land_signatories_edit.dart index 4d43bb5..f1a1cf4 100644 --- a/lib/screens/passo/Land/edit_land/property_assessment_cont_edit.dart +++ b/lib/screens/offline/passo/land/edit/land_signatories_edit.dart @@ -6,27 +6,28 @@ import 'package:flutter_spinkit/flutter_spinkit.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_bloc/land_ext_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/land_ext.dart'; -import 'package:unit2/model/passo/memoranda.dart'; -import 'package:unit2/model/passo/signatories.dart'; -import 'package:unit2/screens/passo/Land/edit_land/property_owner_info_edit.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/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/edit_land.dart'; -class LandSignatoriesEdit extends StatefulWidget { +import '../../../../../model/passo/land_ext.dart'; +import '../../../../../model/passo/memoranda.dart'; +import '../../../../../model/passo/signatories.dart'; +import '../../../../../theme-data.dart/colors.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; + +class LandSignatoriesEditOffline extends StatefulWidget { Function onSAve; final int faasId; - LandSignatoriesEdit(this.onSAve, this.faasId); + LandSignatoriesEditOffline(this.onSAve, this.faasId); @override - _LandSignatoriesEdit createState() => _LandSignatoriesEdit(); + _LandSignatoriesEditOffline createState() => _LandSignatoriesEditOffline(); } -class _LandSignatoriesEdit extends State { +class _LandSignatoriesEditOffline extends State { bool isTaxable = false; bool isExempt = false; final focus = FocusNode(); @@ -38,46 +39,52 @@ class _LandSignatoriesEdit extends State { padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( + child: + BlocConsumer( listener: (context, state) { - if (state is LandExtEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } + // if (state is LandExtEditLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } - if (state is LandExtEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); + if (state is LoadSpecificLandPropertySignature) { + setState(() { + isTaxable = + state.landPropertySignature.taxable == '1' ? true : false; + isExempt = + state.landPropertySignature.exempt == '1' ? true : false; + }); } }, builder: (context, state) { - if (state is LandExtEditLoaded) { - final landext = state.land_ext_edit; - return BlocConsumer( + if (state is LoadSpecificLandPropertySignature) { + final landext = state.landPropertySignature; + return BlocConsumer( listener: (context, state) { - if (state is SignatoriesErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + // if (state is SignatoriesErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { if (state is SignatoriesLoaded) { final signatories = state.signatories; - return BlocConsumer( + return BlocConsumer( listener: (context, state) { - if (state is MemorandaLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is MemorandaErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + // if (state is MemorandaLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is MemorandaErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { if (state is MemorandaLoaded) { return FormBuilder( - key: landEditKey, + key: landOfflineKeyEdit, initialValue: { 'land_qtr': landext.qtr.toString(), 'land_yr': landext.yr.toString(), @@ -91,9 +98,9 @@ class _LandSignatoriesEdit extends State { }, enabled: true, onChanged: () { - landEditKey.currentState!.save(); - debugPrint( - landEditKey.currentState!.value.toString()); + landOfflineKeyEdit.currentState!.save(); + debugPrint(landOfflineKeyEdit.currentState!.value + .toString()); }, autovalidateMode: AutovalidateMode.disabled, skipDisabled: true, @@ -414,7 +421,9 @@ class _LandSignatoriesEdit extends State { width: 500, height: 100, child: SearchField( - suggestions: state.memorada + itemHeight: 70, + hint: landext.memoranda, + suggestions: state.memo .map((Memoranda memoranda) => SearchFieldListItem( '${memoranda.memoranda}', @@ -438,7 +447,9 @@ class _LandSignatoriesEdit extends State { // suffixIcon: const Icon( // Icons.arrow_drop_down), // ), - // focusNode: focus, + focusNode: focus, + suggestionDirection: + SuggestionDirection.up, suggestionState: Suggestion.expand, onSuggestionTap: (memoranda) { setState(() { @@ -548,45 +559,55 @@ class _LandSignatoriesEdit extends State { await SharedPreferences.getInstance(); var ext = LandExt( landapprDetailsId: - tempID.getInt('landid')! - 1, - taxable: isTaxable, - exempt: isExempt, - qtr: int.parse(landEditKey - .currentState!.value['land_qtr']), - yr: int.parse(landEditKey - .currentState!.value['land_yr']), - appraisedbyName: landEditKey.currentState!.value['appraised_by_land'].firstname + + landext.landapprDetailsId, + assessedById: 'test', + assessedByName: 'test', + dateCreated: 'test', + dateModified: 'test', + taxable: isTaxable == true ? '1' : '0', + exempt: isExempt == true ? '1' : '0', + qtr: landOfflineKeyEdit + .currentState!.value['land_qtr'], + yr: landOfflineKeyEdit + .currentState!.value['land_yr'], + appraisedbyName: (landOfflineKeyEdit.currentState!.value['appraised_by_land']?.firstname ?? '') + ' ' + - landEditKey - .currentState! - .value['appraised_by_land'] - .middlename + + (landOfflineKeyEdit + .currentState! + .value['appraised_by_land'] + ?.middlename ?? + '') + ' ' + - landEditKey - .currentState! - .value['appraised_by_land'] - .lastname, - appraisedbyDate: landEditKey - .currentState! - .value['app_date_land'], - recommendapprName: landEditKey.currentState!.value['rec_approval_land'].firstname + + (landOfflineKeyEdit + .currentState! + .value['appraised_by_land'] + ?.lastname ?? + ''), + appraisedbyDate: landOfflineKeyEdit.currentState!.value['app_date_land'] + .toString(), + recommendapprName: (landOfflineKeyEdit + .currentState! + .value['rec_approval_land'] + ?.firstname ?? + '') + ' ' + - landEditKey.currentState!.value['rec_approval_land'].middlename + + (landOfflineKeyEdit.currentState!.value['rec_approval_land']?.middlename ?? '') + ' ' + - landEditKey.currentState!.value['rec_approval_land'].lastname, - recommendapprDate: landEditKey.currentState!.value['rec_date_land'], - approvedbyName: landEditKey.currentState!.value['apprvd_by_land'].firstname + ' ' + landEditKey.currentState!.value['apprvd_by_land'].middlename + ' ' + landEditKey.currentState!.value['apprvd_by_land'].lastname, - approvedbyDate: landEditKey.currentState!.value['apprvd_by_date_land'], + (landOfflineKeyEdit.currentState!.value['rec_approval_land']?.lastname ?? ''), + recommendapprDate: landOfflineKeyEdit.currentState!.value['rec_date_land'].toString(), + approvedbyName: (landOfflineKeyEdit.currentState!.value['apprvd_by_land']?.firstname ?? '') + ' ' + (landOfflineKeyEdit.currentState!.value['apprvd_by_land']?.middlename ?? '') + ' ' + (landOfflineKeyEdit.currentState!.value['apprvd_by_land']?.lastname ?? ''), + approvedbyDate: landOfflineKeyEdit.currentState!.value['apprvd_by_date_land'].toString(), memoranda: _memoranda, - swornstatementNo: landEditKey.currentState!.value['sworn_statement_land'], - dateReceived: landEditKey.currentState!.value['date_received_land'], - entryDateAssessment: landEditKey.currentState!.value['date_of_entry_land'], - entryDateBy: landEditKey.currentState!.value['by_land']); + swornstatementNo: landOfflineKeyEdit.currentState!.value['sworn_statement_land'], + dateReceived: landOfflineKeyEdit.currentState!.value['date_received_land'].toString(), + entryDateAssessment: landOfflineKeyEdit.currentState!.value['date_of_entry_land'].toString(), + entryDateBy: landOfflineKeyEdit.currentState!.value['by_land']); - context.read().add( - UpdateLandExtEdit( - land_ext_edit: ext, - id: widget.faasId)); + context + .read() + .add(UpdateLandPropertySignatureInfo( + id: landext.id!, + landPropertySignature: ext)); widget.onSAve(); }, style: ElevatedButton.styleFrom( @@ -614,40 +635,40 @@ class _LandSignatoriesEdit extends State { )), ); } - if (state is MemorandaErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(const LoadMemoranda()); - }, - ); - } + // if (state is Memo) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(const LoadMemoranda()); + // }, + // ); + // } return Container(); }, ); } - if (state is SignatoriesErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(const LoadSignatories()); - }, - ); - } + // if (state is SignatoriesErrorState) { + // return SomethingWentWrong( + // message: onError, + // onpressed: () { + // context + // .read() + // .add(const LoadSignatories()); + // }, + // ); + // } return Container(); }, ); } - if (state is LandExtEditErrorState) { + if (state is LandPropertySignatureInfoErrorState) { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add(LoadLandExtEdit( - land_ext_edit: LandExt(), id: widget.faasId)); + context.read().add( + LoadSpecificLandPropertySignatureInfo(id: widget.faasId)); }, ); } diff --git a/lib/screens/passo/Land/edit_land/location_and_boundaries_edit.dart b/lib/screens/offline/passo/land/edit/location_and_boundaries_edit_offline.dart similarity index 61% rename from lib/screens/passo/Land/edit_land/location_and_boundaries_edit.dart rename to lib/screens/offline/passo/land/edit/location_and_boundaries_edit_offline.dart index 658720b..d55a9f0 100644 --- a/lib/screens/passo/Land/edit_land/location_and_boundaries_edit.dart +++ b/lib/screens/offline/passo/land/edit/location_and_boundaries_edit_offline.dart @@ -3,29 +3,28 @@ 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/land/land_boundaries_edit/land_boundaries_edit_bloc.dart'; -import 'package:unit2/bloc/passo/land/land_location_edit/land_location_edit_bloc.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/screens/passo/Land/edit_land/property_owner_info_edit.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 'package:unit2/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/edit_land.dart'; -class LandLocationAndBoundariesEdit extends StatefulWidget { +import '../../../../../model/passo/land_property_boundaries.dart'; +import '../../../../../model/passo/land_property_loc.dart'; +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../widgets/passo/custom_button.dart'; +import '../../../../../widgets/passo/custom_formBuilder_fields.dart'; + +class LandLocationAndBoundariesOfflineEdit extends StatefulWidget { Function PrevBtn; Function NextBtn; LandPropertyOwner land; - LandLocationAndBoundariesEdit(this.PrevBtn, this.NextBtn, this.land); + LandLocationAndBoundariesOfflineEdit(this.PrevBtn, this.NextBtn, this.land); @override - _LandLocationAndBoundariesEdit createState() => - _LandLocationAndBoundariesEdit(); + _LandLocationAndBoundariesOfflineEdit createState() => + _LandLocationAndBoundariesOfflineEdit(); } -class _LandLocationAndBoundariesEdit - extends State { +class _LandLocationAndBoundariesOfflineEdit + extends State { @override Widget build(BuildContext context) { return Scaffold( @@ -33,51 +32,44 @@ class _LandLocationAndBoundariesEdit padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( + child: + BlocConsumer( listener: (context, state) { - if (state is LandLocationEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } + // if (state is LandLocationEditLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } - if (state is LandLocationEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + // if (state is LandLocationEditErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { - if (state is LandLocationEditLoaded) { - final landLoc = state.land_loc_edit; - return BlocConsumer( - listener: (context, state) { - if (state is LandBoundariesEditLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is LandBoundariesEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, + if (state is SpecificLandPropertyLocationLoaded) { + final landLoc = state.landpropertylocation; + return BlocConsumer( + listener: (context, state) {}, builder: (context, state) { - if (state is LandBoundariesEditLoaded) { + if (state is SpecificLandPropertyBoundariesLoaded) { return FormBuilder( - key: landEditKey, + key: landOfflineKeyEdit, initialValue: { 'street': landLoc.street, 'brgy': landLoc.barangay, 'municipality': landLoc.municipality, 'province': landLoc.province, - 'north': state.land_boundaries_edit.north, - 'south': state.land_boundaries_edit.south, - 'east': state.land_boundaries_edit.east, - 'west': state.land_boundaries_edit.west + 'north': state.landpropertyboundaries.north, + 'south': state.landpropertyboundaries.south, + 'east': state.landpropertyboundaries.east, + 'west': state.landpropertyboundaries.west }, enabled: true, onChanged: () { - landEditKey.currentState!.save(); - debugPrint(landEditKey.currentState!.value.toString()); + landOfflineKeyEdit.currentState!.save(); + debugPrint( + landOfflineKeyEdit.currentState!.value.toString()); }, autovalidateMode: AutovalidateMode.disabled, skipDisabled: true, @@ -104,14 +96,14 @@ class _LandLocationAndBoundariesEdit Expanded( // optional flex property if flex is 1 because the default flex is 1 flex: 1, - child: customTextField( - "No. / Street", "", "street")), + child: customTextField("No. / Street", + "", "street", TextInputType.text)), 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")), + child: customTextField("Brgy./District", + "", "brgy", TextInputType.text)), ], ), Row( @@ -121,14 +113,20 @@ class _LandLocationAndBoundariesEdit Expanded( flex: 1, child: customTextField( - "Municipality", "", "municipality"), + "Municipality", + "", + "municipality", + TextInputType.text), ), 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")) + "Province/City", + "", + "province", + TextInputType.text)) ]), Container( margin: const EdgeInsets.only( @@ -145,15 +143,15 @@ class _LandLocationAndBoundariesEdit children: [ Expanded( flex: 1, - child: customTextField( - "North", "", "north"), + child: customTextField("North", "", + "north", TextInputType.text), ), 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")) + child: customTextField("East", "", + "east", TextInputType.text)) ]), Row( mainAxisAlignment: @@ -161,15 +159,15 @@ class _LandLocationAndBoundariesEdit children: [ Expanded( flex: 1, - child: customTextField( - "South", "", "south"), + child: customTextField("South", "", + "south", TextInputType.text), ), 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")) + child: customTextField("West", "", + "west", TextInputType.text)) ]), const SizedBox( height: 50, @@ -192,38 +190,52 @@ class _LandLocationAndBoundariesEdit var boundaries = LandPropertyBoundaries( id: widget.land.id, - north: landEditKey + landapprDetailsId: widget.land.id, + assessedById: '1', + assessedByName: 'Cyril', + sketch: 'None', + dateCreated: 'test', + dateModified: 'test', + north: landOfflineKeyEdit .currentState?.value['north'], - east: landEditKey + east: landOfflineKeyEdit .currentState?.value['east'], - west: landEditKey + west: landOfflineKeyEdit .currentState?.value['west'], - south: landEditKey + south: landOfflineKeyEdit .currentState?.value['south'], ); var location = LandPropertyLoc( id: widget.land.id, - street: landEditKey + landapprDetailsId: widget.land.id, + assessedById: '1', + assessedByName: 'Cyril', + dateCreated: 'test', + dateModified: 'test', + street: landOfflineKeyEdit .currentState?.value['street'], - barangay: landEditKey + barangay: landOfflineKeyEdit .currentState?.value['brgy'], - municipality: landEditKey + municipality: landOfflineKeyEdit .currentState ?.value['municipality'], - province: landEditKey.currentState + province: landOfflineKeyEdit + .currentState ?.value['province'], ); context - .read() - .add(UpdateLandLocationEdit( - land_loc_edit: location, + .read() + .add(UpdateLandPropertyLocation( + landPropertyLocation: + location, id: widget.land.id!)); context - .read() - .add(UpdateLandBoundariesEdit( - land_boundaries_edit: + .read< + LandPropertyBoundariesBloc>() + .add(UpdateLandPropertyBoundaries( + landPropertyBoundaries: boundaries, id: widget.land.id!)); @@ -236,31 +248,13 @@ class _LandLocationAndBoundariesEdit ), ); } - if (state is LandBoundariesEditErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add( - LoadLandBoundariesEdit( - land_boundaries_edit: LandPropertyBoundaries(), - id: widget.land.id!)); - }, - ); - } + return Container(); }, ); } ; - if (state is LandLocationEditErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add(LoadLandLocationEdit( - land_loc_edit: LandPropertyLoc(), id: widget.land.id!)); - }, - ); - } + return Container(); }, ), diff --git a/lib/screens/passo/Land/edit_land/other_improvements_edit.dart b/lib/screens/offline/passo/land/edit/other_improvements_edit.dart similarity index 75% rename from lib/screens/passo/Land/edit_land/other_improvements_edit.dart rename to lib/screens/offline/passo/land/edit/other_improvements_edit.dart index 13cf33c..99a70d7 100644 --- a/lib/screens/passo/Land/edit_land/other_improvements_edit.dart +++ b/lib/screens/offline/passo/land/edit/other_improvements_edit.dart @@ -2,25 +2,28 @@ 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/land/other_improvements/other_improvements_bloc.dart'; -import 'package:unit2/model/passo/other_improvements.dart'; -import 'package:unit2/screens/passo/Land/add_land/AddOtherImprovementModal.dart'; -import 'package:unit2/screens/passo/Land/edit_land/AddOtherImprovementEditModal.dart'; -import 'package:unit2/utils/alerts.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:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/AddOtherImprovementModal.dart'; -class OtherImprovementEditPage extends StatefulWidget { +import '../../../../../model/passo/other_improvements.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class OtherImprovementEditPageOffline extends StatefulWidget { Function PrevBtn; Function NextBtn; final int faasId; - OtherImprovementEditPage(this.PrevBtn, this.NextBtn, this.faasId); + OtherImprovementEditPageOffline(this.PrevBtn, this.NextBtn, this.faasId); @override - _OtherImprovementEditPage createState() => _OtherImprovementEditPage(); + _OtherImprovementEditPageOffline createState() => + _OtherImprovementEditPageOffline(); } -class _OtherImprovementEditPage extends State { +class _OtherImprovementEditPageOffline + extends State { // double _totalMarketValue(items) { // double total = 0; // items.forEach((row) { @@ -32,7 +35,7 @@ class _OtherImprovementEditPage extends State { void deleteItem(int itemId) { context .read() - .add(DeleteOtherImprovement(id: itemId)); + .add(DeleteOtherImprovements(id: itemId)); } @override @@ -44,21 +47,21 @@ class _OtherImprovementEditPage extends State { indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer( listener: (context, state) { - if (state is OtherImprovementLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is OtherImprovementLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is OtherImprovementErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + // if (state is OtherImprovementLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is OtherImprovementLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is OtherImprovementErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { final state = context.watch().state; - if (state is OtherImprovementLoaded) { + if (state is OtherImprovementsLoaded) { return Column( children: [ Expanded( @@ -135,24 +138,35 @@ class _OtherImprovementEditPage extends State { label: Text('Action'), ) ], - rows: state.other_imp.map((dataRow) { + rows: state.otherImprovements.map((dataRow) { return DataRow( cells: [ - DataCell(Text(dataRow.kindsOfTrees!)), - DataCell(Text(dataRow.subclassAge!)), - DataCell(Text(dataRow.fruitBearing! + DataCell( + Text(dataRow.kindsOfTrees ?? "")), + DataCell(Text(dataRow.subclassAge ?? "")), + DataCell(Text(dataRow.fruitBearing == '1' ? "Fruit Bearing" : "Non-Fruit Bearing")), DataCell( - Text(dataRow.quantity.toString()!)), + Text(dataRow.quantity.toString())), DataCell(Text( - dataRow.noOfProductive.toString()!)), + dataRow.noOfProductive.toString())), DataCell(Text(dataRow.noOfNonproductive .toString()!)), - DataCell( - Text(dataRow.unitValue.toString()!)), - DataCell(Text( - dataRow.baseMarketval.toString()!)), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ) + .format( + double.parse(dataRow.unitValue!)) + .toString())), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ) + .format(double.parse( + dataRow.baseMarketval!)) + .toString())), DataCell(Row( children: [ InkWell( @@ -170,28 +184,14 @@ class _OtherImprovementEditPage extends State { ), ), onTap: () { - deleteItem(dataRow.id!); + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); }, ), - 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: () {}, - ), ], )) ], @@ -249,7 +249,7 @@ class _OtherImprovementEditPage extends State { ], ); } - if (state is OtherImprovementDeletedState) { + if (state is OtherImprovementsDeletedState) { if (state.success) { WidgetsBinding.instance.addPostFrameCallback((_) { successAlert(context, "Deletion Successful", @@ -257,12 +257,12 @@ class _OtherImprovementEditPage extends State { Navigator.of(context).pop(); context .read() - .add(const LoadOtherImprovement()); + .add(const LoadOtherImprovements()); }); }); } } - if (state is ShowAddOtherImprovementScreen) { + if (state is ShowOtherImprovementScreen) { return ConstrainedBox( constraints: BoxConstraints(maxHeight: 1000.0), child: AlertDialog( @@ -284,7 +284,8 @@ class _OtherImprovementEditPage extends State { child: ConstrainedBox( constraints: BoxConstraints(maxHeight: 500), child: Container( - child: AddOtherImprovementEditModal(widget.faasId), + child: AddOtherImprovementModalEditOffline( + widget.faasId), ), ), ), @@ -294,14 +295,14 @@ class _OtherImprovementEditPage extends State { ), ); } - if (state is OtherImprovementErrorState) { + if (state is OtherImprovementsErrorState) { return SomethingWentWrong( message: onError, onpressed: () { context.read().add( - LoadOtherImprovementEdit( - other_imps: const [], - ids: widget.faasId)); + LoadOtherImprovementsEdit( + otherImprovements: const [], + id: widget.faasId)); }, ); } diff --git a/lib/screens/passo/Land/edit_land/value_adjustments_edit.dart b/lib/screens/offline/passo/land/edit/value_adjustment_edit.dart similarity index 68% rename from lib/screens/passo/Land/edit_land/value_adjustments_edit.dart rename to lib/screens/offline/passo/land/edit/value_adjustment_edit.dart index d969ca8..0507619 100644 --- a/lib/screens/passo/Land/edit_land/value_adjustments_edit.dart +++ b/lib/screens/offline/passo/land/edit/value_adjustment_edit.dart @@ -2,24 +2,28 @@ 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/land/land_value_adjustments/land_value_adjustments_bloc.dart'; -import 'package:unit2/model/passo/land_value_adjustment.dart'; -import 'package:unit2/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart'; -import 'package:unit2/utils/alerts.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:intl/intl.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; +import 'package:unit2/screens/offline/passo/land/edit/AddValueAdjustmentModalOffline.dart'; -class ValueAdjustmentEditPage extends StatefulWidget { +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../utils/alerts.dart'; +import '../../../../../utils/text_container.dart'; +import '../../../../../widgets/error_state.dart'; +import '../../../../../widgets/passo/custom_button.dart'; + +class ValueAdjustmentEditPageOffline extends StatefulWidget { Function PrevBtn; Function NextBtn; final int faasId; - ValueAdjustmentEditPage(this.PrevBtn, this.NextBtn, this.faasId); + ValueAdjustmentEditPageOffline(this.PrevBtn, this.NextBtn, this.faasId); @override - _ValueAdjustmentEditPage createState() => _ValueAdjustmentEditPage(); + _ValueAdjustmentEditPageOffline createState() => + _ValueAdjustmentEditPageOffline(); } -class _ValueAdjustmentEditPage extends State { +class _ValueAdjustmentEditPageOffline + extends State { // double _totalMarketValue(items) { // double total = 0; // items.forEach((row) { @@ -29,9 +33,7 @@ class _ValueAdjustmentEditPage extends State { // } void deleteItem(int itemId) { - context - .read() - .add(DeleteLandValueAdjustments(id: itemId)); + context.read().add(DeleteValueAdjustment(id: itemId)); } @override @@ -41,24 +43,23 @@ class _ValueAdjustmentEditPage extends State { padding: const EdgeInsets.all(24), backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: - BlocConsumer( - listener: (context, state) { - if (state is LandValueAdjustmentsLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is LandValueAdjustmentsLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is LandValueAdjustmentsErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } + child: BlocConsumer( + listener: (context, state) { + // if (state is LandValueAdjustmentsLoading) { + // final progress = ProgressHUD.of(context); + // progress!.showWithText("Please wait..."); + // } + // if (state is LandValueAdjustmentsLoaded) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } + // if (state is LandValueAdjustmentsErrorState) { + // final progress = ProgressHUD.of(context); + // progress?.dismiss(); + // } }, builder: (context, state) { - final state = context.watch().state; - if (state is LandValueAdjustmentsLoaded) { + final state = context.watch().state; + if (state is ValueAdjustmentLoaded) { return Column( children: [ Expanded( @@ -83,8 +84,8 @@ class _ValueAdjustmentEditPage extends State { ), onPressed: () { context - .read() - .add(ShowLandValueAdjustments()); + .read() + .add(ShowValueAdjustment()); }, child: Row( mainAxisSize: MainAxisSize.min, @@ -126,15 +127,27 @@ class _ValueAdjustmentEditPage extends State { label: Text('Action'), ) ], - rows: state.val_adj.map((dataRow) { + rows: state.valueAdjustment.map((dataRow) { return DataRow( cells: [ - DataCell(Text(dataRow.baseMarketval!)), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow.baseMarketval!)))), DataCell( Text(dataRow.adjustmentFactors!)), DataCell(Text(dataRow.adjustment!)), - DataCell(Text(dataRow.valueAdjustment!)), - DataCell(Text(dataRow.marketValue!)), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format(double.parse( + dataRow.valueAdjustment!)))), + DataCell(Text(NumberFormat.currency( + locale: 'en-PH', + symbol: "₱", + ).format( + double.parse(dataRow.marketValue!)))), DataCell(Row( children: [ InkWell( @@ -152,28 +165,14 @@ class _ValueAdjustmentEditPage extends State { ), ), onTap: () { - deleteItem(dataRow.id!); + confirmAlertWithCancel( + context, + () => deleteItem(dataRow.id!), + () => null, + 'Delete Item?', + "Are you sure you want to delete this item?"); }, ), - 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: () {}, - ), ], )) ], @@ -231,20 +230,21 @@ class _ValueAdjustmentEditPage extends State { ], ); } - if (state is LandValueAdjustmentsDeletedState) { + if (state is ValueAdjustmentDeletedState) { if (state.success) { WidgetsBinding.instance.addPostFrameCallback((_) { successAlert(context, "Deletion Successful", "Extra item has been deleted successfully", () { Navigator.of(context).pop(); - context.read().add( - LoadLandValueAdjustmentsEdit( - val_adj: [], id: widget.faasId)); + context.read().add( + LoadValueAdjustmentEdit( + valueAdjustment: [], + id: widget.faasId)); }); }); } } - if (state is ShowAddLandValueAdjustmentsScreen) { + if (state is ShowValueAdjustmentcreen) { return ConstrainedBox( constraints: BoxConstraints(maxHeight: 1000.0), child: AlertDialog( @@ -259,19 +259,20 @@ class _ValueAdjustmentEditPage extends State { content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, - children: [Expanded(child: AddLandValueAdjustmentModal())], + children: [ + Expanded(child: AddLandValueAdjustmentEditOfflineModal()) + ], ), ), ); } - if (state is LandValueAdjustmentsErrorState) { + if (state is ValueAdjustmentErrorState) { return SomethingWentWrong( message: onError, onpressed: () { - context.read().add( - LoadLandValueAdjustmentsEdit( - val_adj: const [], - id: widget.faasId)); + context.read().add(LoadValueAdjustmentEdit( + valueAdjustment: const [], + id: widget.faasId)); }, ); } diff --git a/lib/screens/offline/passo/land_home_offline.dart b/lib/screens/offline/passo/land_home_offline.dart new file mode 100644 index 0000000..1a3c946 --- /dev/null +++ b/lib/screens/offline/passo/land_home_offline.dart @@ -0,0 +1,439 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_speed_dial/flutter_speed_dial.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_assessment/land_property_assessment_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_boundaries/land_property_boundaries_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_location/land_property_location_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart'; +import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/model/passo/land_appr.dart'; +import 'package:unit2/model/passo/land_property_assessment.dart'; +import 'package:unit2/model/passo/land_property_owner.dart'; +import 'package:unit2/model/passo/land_value_adjustment.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/screens/offline/passo/building/add/add_building.dart'; +import 'package:unit2/screens/offline/passo/land/add/add_land.dart'; +import 'package:unit2/screens/offline/passo/land/edit/edit_land.dart'; + +import '../../../bloc/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/class_components_admin.dart/class_components_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/appraisal_offline/bldg_appraisal_offline_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/assessment_offline/bldg_assessment_offline_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/general_description/general_description_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/landref/landref_location_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/location/location_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; +import '../../../bloc/offline/offline_passo/building/structural_materials_offline.dart/structural_material_offline_bloc.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../utils/alerts.dart'; +import '../../../widgets/empty_data.dart'; + +class LandHomeOffline extends StatelessWidget { + final OfflineProfile offlineProfile; + const LandHomeOffline(this.offlineProfile, {super.key}); + + @override + Widget build(BuildContext context) { + void deleteItem(int itemId) { + context + .read() + .add(DeleteLandPropertyOwner(id: itemId)); + } + + void triggerLoadBldgFaas() { + final myBloc = BlocProvider.of(context); + myBloc.add(FetchTodos()); + } + + void triggerLoadLandFaas() { + final myBloc = BlocProvider.of(context); + myBloc.add(LoadLandPropertyOwner()); + } + + return Scaffold( + body: BlocBuilder( + builder: (context, state) { + if (state is LandPropertyOwnerLoaded) { + if (state.landPropertyOwner.isNotEmpty) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Column( + children: [ + Expanded( + child: ListView.builder( + shrinkWrap: true, + itemCount: state.landPropertyOwner.length, + itemBuilder: (BuildContext context, int index) { + return _listCard( + state.landPropertyOwner[index], + context, + index, + deleteItem, + state.landPropertyOwner.length); + }, + ), + ), + ], + ), + ); + } else { + return const EmptyData( + message: + "You don't have any building faas added. Please click + to add"); + } + } + 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) => CrudBloc(), + ), + BlocProvider( + create: (context) => AdditionalItemsOfflineBloc(), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => BarangayAdminBloc() + ..add( + const LoadBarangayInMunicipality(cityCode: '01')), + ), + BlocProvider( + create: (context) => ClassComponentsAdminBloc() + ..add(const LoadClassComponents()), + ), + BlocProvider( + create: (context) => UnitConstructionAdminBloc() + ..add(const LoadUnitConstruct()), + ), + BlocProvider( + create: (context) => SignatoriesAdminBloc() + ..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider(create: (context) => LandrefLocationBloc()), + BlocProvider(create: (context) => LocationBloc()), + BlocProvider( + create: (context) => GeneralDescriptionBloc()), + BlocProvider( + create: (context) => StructuralMaterialOfflineBloc()), + BlocProvider( + create: (context) => AdditionalItemsOfflineBloc() + ..add(const LoadAdditionalItems())), + BlocProvider( + create: (context) => BldgAppraisalOfflineBloc()), + BlocProvider( + create: (context) => BldgAssessmentOfflineBloc()), + ], child: AddBuilding(triggerLoadBldgFaas, offlineProfile)); + })); + }), + 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) => LandPropertyOwnerBloc(), + ), + BlocProvider( + create: (context) => LandPropertyAppraisalBloc() + ..add(const LoadLandPropertyAppraisal()), + ), + BlocProvider( + create: (context) => LandClassificationBloc() + ..add(const LoadLandClassification()), + ), + BlocProvider( + create: (context) => LandSubclassificationBloc() + ..add(const LoadLandSubClassification()), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => OtherImprovementsBloc() + ..add(const LoadOtherImprovements()), + ), + BlocProvider( + create: (context) => TreesImprovementsBloc() + ..add(const LoadTreesImprovements()), + ), + BlocProvider( + create: (context) => ValueAdjustmentBloc() + ..add(const LoadValueAdjustment()), + ), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(const LoadTypeOfRoad()), + ), + BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(const LoadTypeOfLocation()), + ), + BlocProvider( + create: (context) => LandPropertyAssessmentBloc() + ..add(const LoadLandPropertyAssessment()), + ), + BlocProvider( + create: (context) => LandPropertySignatureBloc()), + BlocProvider( + create: (context) => + SignatoriesAdminBloc()..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider( + create: (context) => LandPropertyLocationBloc(), + ), + BlocProvider( + create: (context) => LandPropertyBoundariesBloc(), + ), + BlocProvider( + create: (context) => TreesImprovementsBloc() + ..add(const LoadTreesImprovements()), + ), + ], child: AddLandOffline(triggerLoadLandFaas)); + })); + }, + ), + SpeedDialChild( + child: const Icon( + Icons.precision_manufacturing_rounded, + color: primary, + ), + label: 'Machinery', + onTap: () {}, + ), + // SpeedDialChild(a + // 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 landPropertyOwner, context, index, deleteItem, + bldgLength) { + 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) => + LandPropertyOwnerBloc()..add(LoadLandPropertyOwner()), + ), + BlocProvider( + create: (context) => LandPropertyLocationBloc() + ..add(FetchSingleLandPropertyLocation( + id: landPropertyOwner.id!)), + ), + BlocProvider( + create: (context) => LandPropertyBoundariesBloc() + ..add(FetchSingleLandPropertyBoundaries( + id: landPropertyOwner.id!)), + ), + BlocProvider( + create: (context) => LandPropertyAppraisalBloc() + ..add(LoadLandPropertyAppraisalEdit( + id: landPropertyOwner.id!, landAppr: [])), + ), + BlocProvider( + create: (context) => LandPropertyBoundariesBloc() + ..add(FetchSingleLandPropertyBoundaries( + id: landPropertyOwner.id!)), + ), + BlocProvider( + create: (context) => OtherImprovementsBloc() + ..add(LoadOtherImprovementsEdit( + otherImprovements: [], + id: landPropertyOwner.id)), + ), + BlocProvider( + create: (context) => ValueAdjustmentBloc() + ..add(LoadValueAdjustmentEdit( + valueAdjustment: [], + id: landPropertyOwner.id)), + ), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(const LoadTypeOfRoad()), + ), + BlocProvider( + create: (context) => LandClassificationBloc() + ..add(const LoadLandClassification()), + ), + BlocProvider( + create: (context) => MunicipalitiesAdminBloc() + ..add(const LoadMunicipalities()), + ), + BlocProvider( + create: (context) => LandSubclassificationBloc() + ..add(const LoadLandSubClassification()), + ), + BlocProvider( + create: (context) => LandPropertyAssessmentBloc() + ..add(LoadLandPropertyAssessmentEdit( + landPropertyAssessment: [], + id: landPropertyOwner.id)), + ), + BlocProvider( + create: (context) => LandPropertySignatureBloc() + ..add(LoadSpecificLandPropertySignatureInfo( + id: landPropertyOwner.id!)), + ), + BlocProvider( + create: (context) => + SignatoriesAdminBloc()..add(const LoadSignatories()), + ), + BlocProvider( + create: (context) => + MemorandaAdminBloc()..add(const LoadMemoranda()), + ), + BlocProvider( + create: (context) => TreesImprovementsBloc() + ..add(const LoadTreesImprovements()), + ), + BlocProvider( + create: (context) => + TypeOfRoadBloc()..add(const LoadTypeOfRoad()), + ), + BlocProvider( + create: (context) => + TypeOfLocationBloc()..add(const LoadTypeOfLocation()), + ), + ], + child: EditLandOffline( + index: index, + faas: landPropertyOwner, + title: "Land FAAS", + )); + })); + }, + 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: 1, // Border width + ), + ), + child: const Icon( + Icons.forest_rounded, + color: primary, // Icon color + ), + ), + const SizedBox( + width: 20, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${landPropertyOwner.owner}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.left, + ), + SizedBox(height: 5), + Text( + '${landPropertyOwner.tdn} - ${landPropertyOwner.id}', + style: TextStyle( + fontSize: 13, + ), + textAlign: TextAlign.left, + ), + ], + ), + ), + IconButton( + onPressed: () { + confirmAlertWithCancel( + context, + () => deleteItem(landPropertyOwner.id), + () => null, + 'Delete FAAS Item?', + "Are you sure you want to delete this item?"); + }, + icon: const Icon(Icons.delete_rounded), + color: primary, + ), + ], + ), + ), + ), + ); +} diff --git a/lib/screens/offline/passo/passo_main_dashboard.dart b/lib/screens/offline/passo/passo_main_dashboard.dart new file mode 100644 index 0000000..1ae54b3 --- /dev/null +++ b/lib/screens/offline/passo/passo_main_dashboard.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:flutter_zoom_drawer/flutter_zoom_drawer.dart'; +import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; +import 'package:unit2/screens/offline/passo/admin/admin_main_screen.dart'; +import 'package:unit2/screens/offline/passo/passo_offline_dashboard.dart'; + +import '../../../theme-data.dart/colors.dart'; +import '../../unit2/homepage.dart/components/dashboard/shared_card_label.dart'; + +class PassoOfflineMainScreen extends StatelessWidget { + final OfflineProfile offlineProfile; + const PassoOfflineMainScreen(this.offlineProfile, {super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: primary, + title: const Text("Rpass Offline Home"), + centerTitle: true, + ), + body: Padding( + padding: const EdgeInsets.all(24), + child: GridView.count( + shrinkWrap: true, + crossAxisCount: 4, + crossAxisSpacing: 8, + mainAxisSpacing: 10, + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 5), + children: [ + CardLabel( + icon: FontAwesome5.tools, + title: "Admin Settings", + ontap: () { + Navigator.push(context, + MaterialPageRoute(builder: ((context) { + return const AdminMainScreen(); + }))); + }), + CardLabel( + icon: FontAwesome5.eye, + title: "Field Surveyor", + ontap: () { + Navigator.push(context, + MaterialPageRoute(builder: ((context) { + return PassoOfflineDashBoard(offlineProfile); + }))); + }), + ]))); + } +} diff --git a/lib/screens/passo/passo_dashboard.dart b/lib/screens/offline/passo/passo_offline_dashboard.dart similarity index 56% rename from lib/screens/passo/passo_dashboard.dart rename to lib/screens/offline/passo/passo_offline_dashboard.dart index 2380afe..c9eb2e0 100644 --- a/lib/screens/passo/passo_dashboard.dart +++ b/lib/screens/offline/passo/passo_offline_dashboard.dart @@ -1,18 +1,25 @@ 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/bloc/offline/offline_passo/land/land_property_owner_bloc/land_property_owner_bloc.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; + +import 'package:unit2/screens/offline/passo/building_home_offline.dart'; +import 'package:unit2/screens/offline/passo/land_home_offline.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/widgets/empty_data.dart'; -class PassoDashBoard extends StatefulWidget { +import '../../../bloc/offline/offline_passo/building/owner_info_bloc/crud_bloc.dart'; + +class PassoOfflineDashBoard extends StatefulWidget { + final OfflineProfile offlineProfile; + + const PassoOfflineDashBoard(this.offlineProfile, {super.key}); + @override - _PassoDashBoard createState() => _PassoDashBoard(); + _PassoOfflineDashBoard createState() => _PassoOfflineDashBoard(); } -class _PassoDashBoard extends State { +class _PassoOfflineDashBoard extends State { @override Widget build(BuildContext context) { return DefaultTabController( @@ -21,7 +28,7 @@ class _PassoDashBoard extends State { body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return [ - new SliverAppBar( + const SliverAppBar( backgroundColor: primary, title: Text('Faas Dashboard'), centerTitle: true, @@ -41,14 +48,13 @@ class _PassoDashBoard extends State { body: TabBarView( children: [ BlocProvider( - create: (context) => - PropertyInfoBloc()..add(const LoadPropertyInfo()), - child: const BuildingHome(), + create: (context) => CrudBloc()..add(FetchTodos()), + child: BuildingHomeOffline(widget.offlineProfile), ), BlocProvider( create: (context) => - LandPropertyOwnerInfoBloc()..add(const LoadLand()), - child: const LandHome(), + LandPropertyOwnerBloc()..add(LoadLandPropertyOwner()), + child: LandHomeOffline(widget.offlineProfile), ), EmptyData( message: "Sorry, this page is under construction.", diff --git a/lib/screens/passo/Building/add_building.dart b/lib/screens/passo/Building/add_building.dart deleted file mode 100644 index e87d3e9..0000000 --- a/lib/screens/passo/Building/add_building.dart +++ /dev/null @@ -1,298 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package: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'; -import 'package:unit2/screens/passo/Building/add_building_components/property_appraisal.dart'; -import 'package:unit2/screens/passo/Building/add_building_components/property_assessment.dart'; -import 'package:unit2/screens/passo/Building/add_building_components/property_info.dart'; -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(); - -class AddBuilding extends StatefulWidget { - @override - _AddBuilding createState() => _AddBuilding(); -} - -class _AddBuilding extends State { - int activeStep = 0; // Initial step set to 5. - int upperBound = 6; - - bool saveStep1 = false; - bool saveStep2 = false; - bool saveStep3 = false; - bool saveStep4 = false; - bool saveStep5 = false; - bool saveStep6 = false; - bool saveStep7 = false; - int tempId = 0; - - Future _loadTempId() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - tempId = (prefs.getInt('tempid') ?? 0); - }); - } - - void PrevBtn() { - setState(() { - activeStep--; - }); - } - - void NextBtn() { - setState(() { - activeStep++; - }); - } - - void onPutStructuralMaterials() { - if (activeStep < upperBound) { - setState(() { - activeStep++; - }); - } - // 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 - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - centerTitle: true, - title: const Text("Building FAAS"), - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer(listener: ( - context, - state, - ) { - if (state is PropertyInfoLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is PropertyInfoLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is PropertyInfoErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is ShowGenDescErrorAlertState || - state is ShowLandRefErrorAlertState || - state is ShowStrucMatErrorAlertState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - Fluttertoast.showToast( - msg: "Slow internet connection, please try again!"); - } - if (state is ShowLandRefSuccessAlertState || - state is ShowGenDescSuccessAlertState || - state is ShowStrucMatSuccessAlertState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - NextBtn(); - } - }, builder: (context, state) { - if (state is PropertyInfoLoading || - state is PropertyInfoLoaded || - state is PropertyInfoErrorState || - state is ShowBldgLocErrorAlertState || - state is ShowGenDescErrorAlertState || - state is ShowLandRefErrorAlertState || - state is ShowStrucMatErrorAlertState || - state is ShowBldgLocSuccessAlertState || - state is ShowLandRefSuccessAlertState || - state is ShowGenDescSuccessAlertState || - state is ShowStrucMatSuccessAlertState) { - return BlocConsumer( - 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, - ) { - 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: 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: 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(unit, List classes, PrevBtn, NextBtn) { - switch (activeStep) { - case 0: - return PropertyInfoPage(NextBtn); - - case 1: - return BldgLocationLandrefPage(PrevBtn, NextBtn); - - case 2: - return GeneralDescriptionPage(unit, NextBtn, PrevBtn); - - case 3: - return StructuralMaterialsPage(PrevBtn, NextBtn); - - case 4: - return AdditionalItemPage(unit, classes, PrevBtn, NextBtn); - - case 5: - return PropertyAppraisalPage(NextBtn, PrevBtn); - - case 6: - return PropertyAssessmentPage(onSAveAll); - - default: - return Text("Property Info"); - } - } - - void onSAveAll() { - return Navigator.of(context).pop(); - } -} diff --git a/lib/screens/passo/Building/add_building_components/AddExtraItems.dart b/lib/screens/passo/Building/add_building_components/AddExtraItems.dart deleted file mode 100644 index 2140035..0000000 --- a/lib/screens/passo/Building/add_building_components/AddExtraItems.dart +++ /dev/null @@ -1,598 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:fluttertoast/fluttertoast.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/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'; -import 'package:unit2/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.dart'; - -class AddExtraItems extends StatefulWidget { - final List unit; - final List options; - - AddExtraItems(this.unit, this.options); - - @override - _AddExtraItems createState() => _AddExtraItems(); -} - -class _AddExtraItems extends State { - GlobalKey formKey = GlobalKey(); - 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 _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 _amountofDepreciation(unitVal, unitBase, area, depreciation) { - return ((unitVal * unitBase) * area) * depreciation; - } - - 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 ShowAddItemsScreen) { - 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), - const 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), - const 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. - } - }, - ), - ), - const SizedBox( - height: 40, - width: 40, - child: Center( - child: Text( - '%', - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.bold), - ), - ), - ) - ], - ), - ], - ), - ), - ], - ), - ), - - 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( - _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: () async { - try { - final tempID = - await SharedPreferences.getInstance(); - var itemss = AdditionalItems( - id: 1, - bldgapprDetailsId: - tempID.getInt('tempid')! - 1, - 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(AddAdditionalItems(items: itemss)); - } catch (e) { - Fluttertoast.showToast( - msg: - "Slow internet connection, please try again!", - ); - } - }, - 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 LoadAdditionalItems()); - }, - style: ElevatedButton.styleFrom( - primary: Colors.black, - ), - child: const Text("Cancel"), - ), - ), - ], - ) - ], - ), - ), - ))); - } - if (state is AdditionalItemsErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add(LoadAdditionalItems()); - }, - ); - } - return Container(); - }); - } -} 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 deleted file mode 100644 index 3374a9e..0000000 --- a/lib/screens/passo/Building/add_building_components/bldg_location_landref.dart +++ /dev/null @@ -1,434 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:form_builder_validators/form_builder_validators.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/colors.dart'; -import 'package:unit2/theme-data.dart/form-style.dart'; -import 'package:unit2/utils/alerts.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 { - final VoidCallback PrevBtn; - final VoidCallback NextBtn; - BldgLocationLandrefPage(this.PrevBtn, this.NextBtn); - - @override - _BldgLocationLandrefPage createState() => _BldgLocationLandrefPage(); -} - -class _BldgLocationLandrefPage extends State { - @override - Widget build(BuildContext context) { - 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 MunicipalityErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - 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(); - } - }, - builder: (context, state) { - if (state is BarangayLoaded) { - List brgyList = state.brgy; - List brgyNAmes = brgyList - .map((brgy) => brgy.barangayDescription) - .toList() - .cast(); - return StatefulBuilder(builder: (context, locationState) { - 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( - child: 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: const Align( - alignment: Alignment.center, - child: Text( - "AGUSAN DEL NORTE", - style: TextStyle(fontSize: 15), - ), - ), - ), - ), - 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')) - ]), - const SizedBox( - height: 50, - ), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceEvenly, - children: [ - CustomButton( - icon: const Icon(Icons.chevron_left_rounded, - color: Colors.white), - onPressed: () { - { - widget.PrevBtn(); - } - ; - }, - ), - // Builder(builder: (context) { - // return CustomButton( - // icon: const Icon( - // Icons.chevron_right_rounded, - // color: Colors.white), - // onPressed: () async { - // { - // try { - // final progress = - // ProgressHUD.of(context); - // Future.delayed(Duration(seconds: 3), - // () { - // progress?.dismiss(); - // }); - // 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: "Agusan Del Norte"); - // 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)); - // } catch (e) { - // Fluttertoast.showToast( - // msg: - // "Slow internet connection, please try again!"); - // } - // } - // ; - // }, - // ); - // }) - Builder(builder: (context) { - return CustomButton( - icon: const Icon( - Icons.chevron_right_rounded, - color: Colors.white, - ), - onPressed: () async { - try { - // Get the ProgressHUD instance - final progress = - ProgressHUD.of(context); - - // Show the progress indicator - progress?.show(); - - // Dismiss the progress indicator - progress?.dismiss(); - - // Rest of your code... - 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: "Agusan Del Norte"); - 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)); - } catch (e) { - Fluttertoast.showToast( - msg: - "Slow internet connection, please try again!", - ); - } - }, - ); - }) - ], - ) - ], - ), - ), - ); - }); - } - 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()); - }, - ); - } - if (state is ShowBldgLocErrorAlertState) { - WidgetsBinding.instance.addPostFrameCallback((_) { - errorAlert( - context, "Something went wrong", "Please try again...", () { - Navigator.of(context).pop(); - }); - }); - } - if (state is ShowLandRefErrorAlertState) { - WidgetsBinding.instance.addPostFrameCallback((_) { - errorAlert( - context, "Something went wrong", "Please try again...", () { - Navigator.of(context).pop(); - }); - }); - } - return Container(); - }, - ), - ), - ); - } - - Future _waitForAddPropertyInfoToComplete() async { - // Wait for the state change indicating completion - final propertyInfoState = context.read().state; - - if (propertyInfoState is ShowBldgLocErrorAlertState || - propertyInfoState is ShowLandRefErrorAlertState) { - // Check if the add operation was successful - return false; // You'll need to define this in your state class - } - - // Return false if the state didn't change as expected - return true; - } -} diff --git a/lib/screens/passo/Building/add_building_components/general_description.dart b/lib/screens/passo/Building/add_building_components/general_description.dart deleted file mode 100644 index 05077ef..0000000 --- a/lib/screens/passo/Building/add_building_components/general_description.dart +++ /dev/null @@ -1,234 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:fluttertoast/fluttertoast.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; - final VoidCallback onPutGeneralDescription; - final VoidCallback gendescPrevBtn; - - GeneralDescriptionPage( - this.unit, this.onPutGeneralDescription, this.gendescPrevBtn); - - @override - _GeneralDescriptionPage createState() => _GeneralDescriptionPage(); -} - -class _GeneralDescriptionPage extends State { - final actual_use = [ - "Residential", - "Agricultural", - "Commercial", - "Industrial", - "Mineral", - "Timberland", - ]; - @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('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("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: < - Widget>[ - 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.gendescPrevBtn(); - } - ; - }, - ), - CustomButton( - icon: const Icon(Icons.chevron_right_rounded, - color: Colors.white), - onPressed: () async { - { - try { - final tempID = await SharedPreferences.getInstance(); - - 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)); - } catch (e) { - Fluttertoast.showToast( - msg: "Slow internet connection, please try again!"); - } - } - ; - }, - ) - ], - ) - ], - ), - ), - ); - } -} diff --git a/lib/screens/passo/Building/add_building_components/property_appraisal.dart b/lib/screens/passo/Building/add_building_components/property_appraisal.dart deleted file mode 100644 index 3ad760d..0000000 --- a/lib/screens/passo/Building/add_building_components/property_appraisal.dart +++ /dev/null @@ -1,1105 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package:intl/intl.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/bloc/passo/bulding/property_info/property_info_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 { - final VoidCallback NextBtn; - final VoidCallback PrevBtn; - - PropertyAppraisalPage(this.NextBtn, this.PrevBtn); - - @override - _PropertyAppraisalPage createState() => _PropertyAppraisalPage(); -} - -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; - - for (AdditionalItems value in items) { - sum += double.parse(value.adjustedMarketVal); - } - - return sum; - } - - calculateTotalConstructionCost(buildingCost, additionalItems) { - double sum = 0; - double product = 1; - - sum = buildingCost + calculateAdditionalItems(additionalItems); - - 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; - } - - @override - Widget build(BuildContext context) { - 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 AdditionalItemsLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AdditionalItemsLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is AdditionalItemsErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is AdditionalItemsLoaded) { - return 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( - formKey.currentState!.value['bldg_type'] - .unitValue + - ' 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( - (double.parse(formKey - .currentState!.value['total_area']) * - double.parse(formKey.currentState! - .value['bldg_type'].unitValue)) - .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( - calculateAdditionalItems(state.items).toString(), - 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( - calculateTotalConstructionCost( - (double.parse(formKey.currentState! - .value['total_area']) * - double.parse(formKey.currentState! - .value['bldg_type'].unitValue)), - state.items) - .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("", ""), - 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( - (double.parse(formKey.currentState! - .value['total_area']) * - double.parse(formKey.currentState! - .value['bldg_type'].unitValue)), - state.items, - depRate) - .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( - '${(depRate * 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( - (double.parse(formKey.currentState! - .value['total_area']) * - double.parse(formKey.currentState! - .value['bldg_type'].unitValue)), - state.items, - depRate) - .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')! - 1, - 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'], - actualUse: "Residential"); - context.read() - ..add(AddPropertyAppraisal( - appraisal: appraisals)); - - widget.NextBtn(); - } - ; - }, - ) - ], - ), - ], - ), - ), - ); - } - 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 unsuccessful - 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/property_assessment.dart b/lib/screens/passo/Building/add_building_components/property_assessment.dart deleted file mode 100644 index 386df67..0000000 --- a/lib/screens/passo/Building/add_building_components/property_assessment.dart +++ /dev/null @@ -1,624 +0,0 @@ -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: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 { - Function function; - - PropertyAssessmentPage(this.function); - - @override - _PropertyAssessmentPage createState() => _PropertyAssessmentPage(); -} - -class _PropertyAssessmentPage extends State { - double assessment_level = 0; - bool isTaxable = false; - bool isExempt = false; - String _memoranda = ''; - final focus = FocusNode(); - - @override - Widget build(BuildContext context) { - 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) { - // 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) { - final memoranda = state.memorada; - 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, - ), - 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: [ - 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', - 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', - 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, - 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, - - 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'] ?? - '', // Replace null with an empty string - marketValue: '0.00', - assessmentLevel: '0.00', - assessedValue: '0.00', - taxable: isTaxable, - exempt: isExempt, - qtr: int.parse(formKey - .currentState!.value['qtr'] ?? - '0'), // Replace null with '0' - yr: int.parse( - formKey.currentState!.value['yr'] ?? - '0'), // Replace null with '0' - 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'] - as DateTime? ?? - DateTime - .now(), // Replace null with current 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'] - as DateTime? ?? - DateTime - .now(), // Replace null with current 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'] ?? - '', // Replace null with an empty string - dateReceived: formKey.currentState! - .value['date_received'] - as DateTime? ?? - DateTime - .now(), // Replace null with current date - entryDateAssessment: formKey - .currentState! - .value['date_of_entry'] - as DateTime? ?? - DateTime - .now(), // Replace null with current date - entryDateBy: formKey - .currentState!.value['by'] ?? - '', // Replace null with an empty string - ); - - 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, - ), - ]), - ), - ) - ], - ); - } - return Container(); - }, - ); - } - return Container(); - }, - ))); - } -} diff --git a/lib/screens/passo/Building/add_building_components/property_info.dart b/lib/screens/passo/Building/add_building_components/property_info.dart deleted file mode 100644 index 80fafaa..0000000 --- a/lib/screens/passo/Building/add_building_components/property_info.dart +++ /dev/null @@ -1,167 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:fluttertoast/fluttertoast.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; - const PropertyInfoPage(this.handleButtonPress, {super.key}); - - @override - _PropertyInfoPage createState() => _PropertyInfoPage(); -} - -class _PropertyInfoPage extends State { - int tempId = 0; - final transaction_codes = ['New', 'Revision']; - - @override - Widget build(BuildContext context) { - return SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.all(20.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), - 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: < - Widget>[ - 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), - CustomButton( - icon: const Icon(Icons.chevron_right, color: Colors.white), - onPressed: () async { - try { - 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), - ); - widget.handleButtonPress(); - } catch (e) { - Fluttertoast.showToast( - msg: "Slow internet connection, please try again!"); - } - - // Wait for the event to complete and get the result - // bool failed = await _waitForAddPropertyInfoToComplete(); - - // if (failed) { - // // Proceed to the next step or perform an action - // Fluttertoast.showToast( - // msg: "Slow internet connection, please try again!"); - // } else { - // // Stay or show an error message - // widget.handleButtonPress(); - // } - }, - ) - ]), - ), - ); - } - - 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 unsuccessful - 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/edit_building.dart b/lib/screens/passo/Building/edit_building.dart deleted file mode 100644 index 326dd35..0000000 --- a/lib/screens/passo/Building/edit_building.dart +++ /dev/null @@ -1,211 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; - -import 'package: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/screens/passo/Building/edit_building/structural_materials_edit.dart'; -import 'package:unit2/screens/passo/Land/add_land.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 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 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: StatefulBuilder(builder: - (BuildContext context, StateSetter setState) { - return Container( - child: 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 StructuralMaterialsEditPage(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/additional_items.dart b/lib/screens/passo/Building/edit_building/additional_items.dart deleted file mode 100644 index 1f8ff0d..0000000 --- a/lib/screens/passo/Building/edit_building/additional_items.dart +++ /dev/null @@ -1,328 +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: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 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 AdditionalItemsEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AdditionalItemsEditLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is AdditionalItemsEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - 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 deleted file mode 100644 index f0d70b7..0000000 --- a/lib/screens/passo/Building/edit_building/bldgloc_landref.dart +++ /dev/null @@ -1,419 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package: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 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 LocationLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - - if (state is LocationErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - 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 LandrefErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - 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 MunicipalityErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, 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(); - } - }, 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 ?? "", - '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< - City>( - 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 ?? "", - "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 deleted file mode 100644 index 6fbfc23..0000000 --- a/lib/screens/passo/Building/edit_building/general_description.dart +++ /dev/null @@ -1,362 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:shared_preferences/shared_preferences.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 Scaffold( - body: Column( - children: [ - Expanded( - child: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: - BlocConsumer( - listener: (context, state) async { - if (state is GenDescLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is GenDescLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - - final tempID = await SharedPreferences.getInstance(); - await tempID.setInt( - 'totalValue', int.parse(state.gendesc.totalFloorArea!)); - await tempID.setString( - 'actualUse', state.gendesc.actualUse!); - - } - if (state is GenDescErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - 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 deleted file mode 100644 index aa6a967..0000000 --- a/lib/screens/passo/Building/edit_building/property_appraisal.dart +++ /dev/null @@ -1,1244 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package: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; - // int totalAreas = 0; - // String actualUse = ""; - - // @override - // void initState() { - // super.initState(); - // _loadDataFromSharedPreferences(); // Call the method to load data - // } - - // Method to load data from SharedPreferences - // _loadDataFromSharedPreferences() async { - // SharedPreferences prefs = await SharedPreferences.getInstance(); - // setState(() { - // actualUse = prefs.getString('actualUse') ?? ''; - // totalAreas = prefs.getInt('totalArea') ?? - // 0; // Provide a default value if the key doesn't exist - // }); - // } - - 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 ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: - BlocConsumer( - listener: (context, state) { - if (state is PropertyAppraisalEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - - if (state is PropertyAppraisalEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is PropertyAppraisalEditLoaded) { - final appraisal = state.appraisalEdit; - return BlocConsumer(listener: (context, state) { - if (state is PropertyAppraisalEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AdditionalItemsEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is AdditionalItemsEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, builder: (context, state) { - if (state is AdditionalItemsEditLoaded) { - final item = state.items; - - return BlocConsumer( - listener: (context, state) { - if (state is GenDescLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is GenDescLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is GenDescErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is GenDescLoaded) { - double totalArea = double.tryParse( - (state.gendesc.totalFloorArea ?? - appraisal.totalArea) - ?.toString() ?? - '0.0') ?? - 0.0; - - double bldgUnitValue = double.tryParse(keys.currentState - ?.value['bldg_type']?.unitValue ?? - appraisal.unitconstructCost) ?? - 0.0; - return Column( - children: [ - 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: const 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: const Text( - "Building Core", - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 13), - textAlign: TextAlign.left, - ), - ), - Container( - child: const Text( - '', - textAlign: TextAlign.right, - ), - ) - ], - ), - const SizedBox(height: 40), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Container( - child: const 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: const Text( - "Cost of Additional Items", - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 13), - textAlign: TextAlign.left, - ), - ), - Container( - child: const Text( - '', - textAlign: TextAlign.right, - ), - ) - ], - ), - const SizedBox(height: 15), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Container( - child: const Text( - "Sub-total", - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 13), - textAlign: TextAlign.left, - ), - ), - Container( - child: Text( - appraisal.addItemsSubtotal ?? - '0.00', - textAlign: TextAlign.right, - ), - ) - ], - ), - const SizedBox(height: 15), - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - Container( - child: const 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: const 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: const 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: const 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: const 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: - const 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: - const 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: - const 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: - const 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< - PropertyAppraisalEditBloc>() - .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 deleted file mode 100644 index dd4dea0..0000000 --- a/lib/screens/passo/Building/edit_building/property_assessement_edit.dart +++ /dev/null @@ -1,1156 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package: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 ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: - BlocConsumer( - listener: (context, state) { - if (state is PropertyAssessmentEditLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is PropertyAssessmentEditLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is PropertyAssessmentEditErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is PropertyAssessmentEditLoaded) { - final assessment = state.assessmentsEdit; - return BlocConsumer( - listener: (context, state) { - if (state is SignatoriesLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - - if (state is SignatoriesErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is SignatoriesLoaded) { - 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(); - } - }, - builder: (context, state) { - if (state is MemorandaLoaded) { - return FormBuilder( - key: keys, - initialValue: { - 'qtr': assessment.qtr?.toString() ?? '', - 'yr': assessment.qtr?.toString() ?? '', - 'app_date': - assessment.appraisedbyDate?.toString() ?? '', - 'rec_date': - assessment.recommendapprDate?.toString() ?? '', - '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< - PropertyAssessmentEdit> - 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: state.error, - 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 deleted file mode 100644 index 5a32955..0000000 --- a/lib/screens/passo/Building/edit_building/property_owner_info.dart +++ /dev/null @@ -1,258 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_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) { - if (state is PropertyInfoLoaded) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (state is PropertyInfoLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - - if (state is PropertyInfoErrorState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, builder: (context, state) { - if (state is PropertyInfoLoaded) { - return SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - children: [ - Padding( - padding: const EdgeInsets.all(15.0), - 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 deleted file mode 100644 index 24580b3..0000000 --- a/lib/screens/passo/Building/edit_building/structural_materials.dart +++ /dev/null @@ -1,448 +0,0 @@ -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 SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - children: [ - Expanded( - 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/Building/edit_building_new/property_owner_info.dart b/lib/screens/passo/Building/edit_building_new/property_owner_info.dart deleted file mode 100644 index 33490b5..0000000 --- a/lib/screens/passo/Building/edit_building_new/property_owner_info.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flutter/material.dart'; - -class PropertyOwnerPage extends StatefulWidget { - @override - _PropertyOwnerPage createState() => _PropertyOwnerPage(); -} - -class _PropertyOwnerPage extends State { - @override - Widget build(BuildContext context) { - return Scaffold(body: Container()); - } -} diff --git a/lib/screens/passo/Land/add_land.dart b/lib/screens/passo/Land/add_land.dart deleted file mode 100644 index 4b7e3aa..0000000 --- a/lib/screens/passo/Land/add_land.dart +++ /dev/null @@ -1,120 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; - -import 'package: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/AddLandValueAdjustmentModal.dart b/lib/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart deleted file mode 100644 index 64a53b6..0000000 --- a/lib/screens/passo/Land/add_land/AddLandValueAdjustmentModal.dart +++ /dev/null @@ -1,467 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package: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/land_appraisal.dart b/lib/screens/passo/Land/add_land/land_appraisal.dart deleted file mode 100644 index e881636..0000000 --- a/lib/screens/passo/Land/add_land/land_appraisal.dart +++ /dev/null @@ -1,260 +0,0 @@ -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/utils/text_container.dart'; -import 'package:unit2/widgets/error_state.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()), - ], - ), - ), - ); - } - if (state is LandAppraisalErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context.read().add(LoadLandAppraisal()); - }, - ); - } - 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 deleted file mode 100644 index e81d200..0000000 --- a/lib/screens/passo/Land/add_land/location_and_boundaries.dart +++ /dev/null @@ -1,143 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:shared_preferences/shared_preferences.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: () async { - final tempID = await SharedPreferences.getInstance(); - print(tempID.getInt('landid')); - var boundaries = LandPropertyBoundaries( - id: tempID.getInt('landid')! - 1, - north: landKey.currentState?.value['north'], - east: landKey.currentState?.value['east'], - west: landKey.currentState?.value['west'], - south: landKey.currentState?.value['south'], - ); - var location = LandPropertyLoc( - id: tempID.getInt('landid')! - 1, - 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 deleted file mode 100644 index 295e1b7..0000000 --- a/lib/screens/passo/Land/add_land/other_improvements.dart +++ /dev/null @@ -1,263 +0,0 @@ -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 deleted file mode 100644 index 19f43bf..0000000 --- a/lib/screens/passo/Land/add_land/property_assessment.dart +++ /dev/null @@ -1,243 +0,0 @@ -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 deleted file mode 100644 index ad1f710..0000000 --- a/lib/screens/passo/Land/add_land/property_assessment_cont.dart +++ /dev/null @@ -1,541 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package: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 deleted file mode 100644 index f8fea59..0000000 --- a/lib/screens/passo/Land/add_land/property_owner_info.dart +++ /dev/null @@ -1,170 +0,0 @@ -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( - 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 deleted file mode 100644 index 35dbaf2..0000000 --- a/lib/screens/passo/Land/add_land/value_adjustments.dart +++ /dev/null @@ -1,246 +0,0 @@ -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/Test Envi/multi_dropdown.dart b/lib/screens/passo/Test Envi/multi_dropdown.dart deleted file mode 100644 index 61a88e4..0000000 --- a/lib/screens/passo/Test Envi/multi_dropdown.dart +++ /dev/null @@ -1,94 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:multiselect/multiselect.dart'; - -class Multi_Select extends StatelessWidget { - const Multi_Select(); - - // This widget is the root of your application. - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'Flutter Demo', - theme: ThemeData( - brightness: Brightness.light, - primarySwatch: Colors.red, - primaryColor: Colors.red, - primaryColorLight: Colors.redAccent, - inputDecorationTheme: const InputDecorationTheme( - filled: true, - fillColor: Color(0xFFEEEEEE), - ), - ), - themeMode: ThemeMode.dark, - darkTheme: ThemeData( - brightness: Brightness.dark, - primarySwatch: Colors.red, - primaryColor: Colors.red, - primaryColorLight: Colors.redAccent, - appBarTheme: const AppBarTheme(backgroundColor: Color(0xFF1b1926)), - snackBarTheme: const SnackBarThemeData(backgroundColor: Colors.red), - canvasColor: const Color(0xFF272537), - dialogBackgroundColor: const Color(0xFF343346), - inputDecorationTheme: const InputDecorationTheme( - filled: true, - fillColor: Color(0xFF383849), - enabledBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.all( - Radius.circular(35.0), - ), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - borderRadius: BorderRadius.all( - Radius.circular(35.0), - ), - ), - ), - ), - home: const _Multi_Select(title: 'Flutter Demo Home Page'), - ); - } -} - -class _Multi_Select extends StatefulWidget { - const _Multi_Select({required this.title}); - final String title; - - @override - State<_Multi_Select> createState() => _Multi_SelectState(); -} - -class _Multi_SelectState extends State<_Multi_Select> { - int _counter = 0; - - void _incrementCounter() { - setState(() { - _counter++; - }); - } - - List selected = []; - - @override - Widget build(BuildContext context) { - return Scaffold( - body: Center( - child: Padding( - padding: const EdgeInsets.all(20.0), - // DropDownMultiSelect comes from multiselect - child: DropDownMultiSelect( - selected_values_style: TextStyle(color: Colors.white), - onChanged: (List x) { - setState(() { - selected = x; - }); - }, - options: ['a', 'b', 'c', 'd'], - selectedValues: selected, - whenEmpty: 'Select Something', - ), - ), - )); - } -} diff --git a/lib/screens/passo/Test Envi/speed_dial.dart b/lib/screens/passo/Test Envi/speed_dial.dart deleted file mode 100644 index 7d4c1c9..0000000 --- a/lib/screens/passo/Test Envi/speed_dial.dart +++ /dev/null @@ -1,529 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter_speed_dial/flutter_speed_dial.dart'; - -void main() => runApp(const SpeedDial()); - -class SpeedDials extends StatefulWidget { - const SpeedDials({Key? key}) : super(key: key); - @override - _SpeedDials createState() => _SpeedDials(); -} - -class _SpeedDials extends State { - var theme = ValueNotifier(ThemeMode.dark); - - @override - Widget build(BuildContext context) { - const appTitle = 'Flutter Speed Dial Example'; - return ValueListenableBuilder( - valueListenable: theme, - builder: (context, value, child) => MaterialApp( - title: appTitle, - home: MyHomePage(theme: theme), - debugShowCheckedModeBanner: false, - theme: ThemeData( - brightness: Brightness.light, - primaryColor: Colors.blue, - ), - darkTheme: ThemeData( - brightness: Brightness.dark, - primaryColor: Colors.lightBlue[900], - ), - themeMode: value, - )); - } -} - -class MyHomePage extends StatefulWidget { - final ValueNotifier theme; - const MyHomePage({Key? key, required this.theme}) : super(key: key); - @override - _MyHomePageState createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State with TickerProviderStateMixin { - var renderOverlay = true; - var visible = true; - var switchLabelPosition = false; - var extend = false; - var mini = false; - var rmicons = false; - var customDialRoot = false; - var closeManually = false; - var useRAnimation = true; - var isDialOpen = ValueNotifier(false); - var speedDialDirection = SpeedDialDirection.up; - var buttonSize = const Size(56.0, 56.0); - var childrenButtonSize = const Size(56.0, 56.0); - var selectedfABLocation = FloatingActionButtonLocation.endDocked; - var items = [ - FloatingActionButtonLocation.startFloat, - FloatingActionButtonLocation.startDocked, - FloatingActionButtonLocation.centerFloat, - FloatingActionButtonLocation.endFloat, - FloatingActionButtonLocation.endDocked, - FloatingActionButtonLocation.startTop, - FloatingActionButtonLocation.centerTop, - FloatingActionButtonLocation.endTop, - ]; - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async { - if (isDialOpen.value) { - isDialOpen.value = false; - return false; - } - return true; - }, - child: Scaffold( - appBar: AppBar( - title: const Text("Flutter Speed Dial Example"), - ), - body: SingleChildScrollView( - padding: const EdgeInsets.all(16), - physics: const BouncingScrollPhysics(), - child: Center( - child: Container( - constraints: const BoxConstraints(maxWidth: 800), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - padding: const EdgeInsets.symmetric( - vertical: 6, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text("SpeedDial Location", - style: Theme.of(context).textTheme.bodyLarge), - const SizedBox(height: 10), - Container( - decoration: BoxDecoration( - color: Theme.of(context).brightness == - Brightness.dark - ? Colors.grey[800] - : Colors.grey[200], - borderRadius: BorderRadius.circular(10)), - child: DropdownButton( - value: selectedfABLocation, - isExpanded: true, - icon: const Icon(Icons.arrow_drop_down), - iconSize: 20, - underline: const SizedBox(), - onChanged: (fABLocation) => setState( - () => selectedfABLocation = fABLocation!), - selectedItemBuilder: (BuildContext context) { - return items.map((item) { - return Align( - alignment: Alignment.centerLeft, - child: Container( - padding: const EdgeInsets.symmetric( - vertical: 4, horizontal: 10), - child: Text(item.value))); - }).toList(); - }, - items: items.map((item) { - return DropdownMenuItem< - FloatingActionButtonLocation>( - value: item, - child: Text( - item.value, - ), - ); - }).toList(), - ), - ), - ], - ), - ), - Container( - padding: const EdgeInsets.symmetric( - vertical: 6, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text("SpeedDial Direction", - style: Theme.of(context).textTheme.bodyLarge), - const SizedBox(height: 10), - Container( - decoration: BoxDecoration( - color: Theme.of(context).brightness == - Brightness.dark - ? Colors.grey[800] - : Colors.grey[200], - borderRadius: BorderRadius.circular(10)), - child: DropdownButton( - value: speedDialDirection, - isExpanded: true, - icon: const Icon(Icons.arrow_drop_down), - iconSize: 20, - underline: const SizedBox(), - onChanged: (sdo) { - setState(() { - speedDialDirection = sdo!; - selectedfABLocation = (sdo.isUp && - selectedfABLocation.value - .contains("Top")) || - (sdo.isLeft && - selectedfABLocation.value - .contains("start")) - ? FloatingActionButtonLocation.endDocked - : sdo.isDown && - !selectedfABLocation.value - .contains("Top") - ? FloatingActionButtonLocation.endTop - : sdo.isRight && - selectedfABLocation.value - .contains("end") - ? FloatingActionButtonLocation - .startDocked - : selectedfABLocation; - }); - }, - selectedItemBuilder: (BuildContext context) { - return SpeedDialDirection.values - .toList() - .map((item) { - return Container( - padding: const EdgeInsets.symmetric( - vertical: 4, horizontal: 10), - child: Align( - alignment: Alignment.centerLeft, - child: Text( - describeEnum(item).toUpperCase())), - ); - }).toList(); - }, - items: SpeedDialDirection.values - .toList() - .map((item) { - return DropdownMenuItem( - value: item, - child: Text(describeEnum(item).toUpperCase()), - ); - }).toList(), - ), - ), - ], - ), - ), - if (!customDialRoot) - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: extend, - title: const Text("Extend Speed Dial"), - onChanged: (val) { - setState(() { - extend = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: visible, - title: const Text("Visible"), - onChanged: (val) { - setState(() { - visible = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: mini, - title: const Text("Mini"), - onChanged: (val) { - setState(() { - mini = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: customDialRoot, - title: const Text("Custom dialRoot"), - onChanged: (val) { - setState(() { - customDialRoot = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: renderOverlay, - title: const Text("Render Overlay"), - onChanged: (val) { - setState(() { - renderOverlay = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: closeManually, - title: const Text("Close Manually"), - onChanged: (val) { - setState(() { - closeManually = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: rmicons, - title: const Text("Remove Icons (for children)"), - onChanged: (val) { - setState(() { - rmicons = val; - }); - }), - if (!customDialRoot) - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: useRAnimation, - title: const Text("Use Rotation Animation"), - onChanged: (val) { - setState(() { - useRAnimation = val; - }); - }), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 6, - ), - value: switchLabelPosition, - title: const Text("Switch Label Position"), - onChanged: (val) { - setState(() { - switchLabelPosition = val; - if (val) { - if ((selectedfABLocation.value.contains("end") || - selectedfABLocation.value - .toLowerCase() - .contains("top")) && - speedDialDirection.isUp) { - selectedfABLocation = - FloatingActionButtonLocation.startDocked; - } else if ((selectedfABLocation.value - .contains("end") || - !selectedfABLocation.value - .toLowerCase() - .contains("top")) && - speedDialDirection.isDown) { - selectedfABLocation = - FloatingActionButtonLocation.startTop; - } - } - }); - }), - const Text("Button Size"), - Slider( - value: buttonSize.width, - min: 50, - max: 500, - label: "Button Size", - onChanged: (val) { - setState(() { - buttonSize = Size(val, val); - }); - }, - ), - const Text("Children Button Size"), - Slider( - value: childrenButtonSize.height, - min: 50, - max: 500, - onChanged: (val) { - setState(() { - childrenButtonSize = Size(val, val); - }); - }, - ), - Container( - padding: const EdgeInsets.symmetric( - vertical: 6, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text("Navigation", - style: Theme.of(context).textTheme.bodyLarge), - const SizedBox(height: 10), - ElevatedButton( - onPressed: () { - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => - MyHomePage(theme: widget.theme), - ), - ); - }, - child: const Text("Push Duplicate Page")), - ], - ), - ), - ], - ), - ), - )), - floatingActionButtonLocation: selectedfABLocation, - floatingActionButton: SpeedDial( - // animatedIcon: AnimatedIcons.menu_close, - // animatedIconTheme: IconThemeData(size: 22.0), - // / This is ignored if animatedIcon is non null - // child: Text("open"), - // activeChild: Text("close"), - icon: Icons.add, - activeIcon: Icons.close, - spacing: 3, - mini: mini, - openCloseDial: isDialOpen, - childPadding: const EdgeInsets.all(5), - spaceBetweenChildren: 4, - dialRoot: customDialRoot - ? (ctx, open, toggleChildren) { - return ElevatedButton( - onPressed: toggleChildren, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.blue[900], - padding: const EdgeInsets.symmetric( - horizontal: 22, vertical: 18), - ), - child: const Text( - "Custom Dial Root", - style: TextStyle(fontSize: 17), - ), - ); - } - : null, - buttonSize: - buttonSize, // it's the SpeedDial size which defaults to 56 itself - // iconTheme: IconThemeData(size: 22), - label: extend - ? const Text("Open") - : null, // The label of the main button. - /// The active label of the main button, Defaults to label if not specified. - activeLabel: extend ? const Text("Close") : null, - - /// Transition Builder between label and activeLabel, defaults to FadeTransition. - // labelTransitionBuilder: (widget, animation) => ScaleTransition(scale: animation,child: widget), - /// The below button size defaults to 56 itself, its the SpeedDial childrens size - childrenButtonSize: childrenButtonSize, - visible: visible, - direction: speedDialDirection, - switchLabelPosition: switchLabelPosition, - - /// If true user is forced to close dial manually - closeManually: closeManually, - - /// If false, backgroundOverlay will not be rendered. - renderOverlay: renderOverlay, - // overlayColor: Colors.black, - // overlayOpacity: 0.5, - onOpen: () => debugPrint('OPENING DIAL'), - onClose: () => debugPrint('DIAL CLOSED'), - useRotationAnimation: useRAnimation, - tooltip: 'Open Speed Dial', - heroTag: 'speed-dial-hero-tag', - // foregroundColor: Colors.black, - // backgroundColor: Colors.white, - // activeForegroundColor: Colors.red, - // activeBackgroundColor: Colors.blue, - elevation: 8.0, - animationCurve: Curves.elasticInOut, - isOpenOnStart: false, - shape: customDialRoot - ? const RoundedRectangleBorder() - : const StadiumBorder(), - // childMargin: EdgeInsets.symmetric(horizontal: 10, vertical: 5), - children: [ - SpeedDialChild( - child: !rmicons ? const Icon(Icons.accessibility) : null, - backgroundColor: Colors.red, - foregroundColor: Colors.white, - label: 'First', - onTap: () => setState(() => rmicons = !rmicons), - onLongPress: () => debugPrint('FIRST CHILD LONG PRESS'), - ), - SpeedDialChild( - child: !rmicons ? const Icon(Icons.brush) : null, - backgroundColor: Colors.deepOrange, - foregroundColor: Colors.white, - label: 'Second', - onTap: () => debugPrint('SECOND CHILD'), - ), - SpeedDialChild( - child: !rmicons ? const Icon(Icons.margin) : null, - backgroundColor: Colors.indigo, - foregroundColor: Colors.white, - label: 'Show Snackbar', - visible: true, - onTap: () => ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text(("Third Child Pressed")))), - onLongPress: () => debugPrint('THIRD CHILD LONG PRESS'), - ), - ], - ), - bottomNavigationBar: BottomAppBar( - shape: const CircularNotchedRectangle(), - notchMargin: 8.0, - child: Row( - mainAxisAlignment: selectedfABLocation == - FloatingActionButtonLocation.startDocked - ? MainAxisAlignment.end - : selectedfABLocation == FloatingActionButtonLocation.endDocked - ? MainAxisAlignment.start - : MainAxisAlignment.center, - mainAxisSize: MainAxisSize.max, - children: [ - IconButton( - icon: const Icon(Icons.nightlight_round), - tooltip: "Switch Theme", - onPressed: () => { - widget.theme.value = widget.theme.value.index == 2 - ? ThemeMode.light - : ThemeMode.dark - }, - ), - ValueListenableBuilder( - valueListenable: isDialOpen, - builder: (ctx, value, _) => IconButton( - icon: const Icon(Icons.open_in_browser), - tooltip: (!value ? "Open" : "Close") + (" Speed Dial"), - onPressed: () => {isDialOpen.value = !isDialOpen.value}, - )) - ], - ), - ), - ), - ); - } -} - -extension EnumExt on FloatingActionButtonLocation { - /// Get Value of The SpeedDialDirection Enum like Up, Down, etc. in String format - String get value => toString().split(".")[1]; -} diff --git a/lib/screens/passo/building_home.dart b/lib/screens/passo/building_home.dart deleted file mode 100644 index 08d7cbd..0000000 --- a/lib/screens/passo/building_home.dart +++ /dev/null @@ -1,438 +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/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'; -import '../../utils/alerts.dart'; - -class BuildingHome extends StatelessWidget { - const BuildingHome({super.key}); - - @override - Widget build(BuildContext context) { - int? profileId; - String? token; - Profile profile; - - void deleteItem(int itemId) { - context.read().add(DeleteBuildingFaas(id: itemId)); - } - - return Scaffold( - body: ProgressHUD( - 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) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - if (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: Column( - children: [ - Expanded( - child: ListView.builder( - shrinkWrap: true, - itemCount: propertyList.length, - itemBuilder: (BuildContext context, int index) { - return _listCard(propertyList[index], context, - index, deleteItem); - }, - ), - ), - ], - ), - ); - } - if (state is PropertyInfoErrorState) { - return SomethingWentWrong( - message: onError, - onpressed: () { - context - .read() - .add(LoadPropertyInfo()); - }, - ); - } - if (state is BuildingFaasDeletedState) { - if (state.success) { - WidgetsBinding.instance.addPostFrameCallback((_) { - successAlert(context, "Deletion Successful", - "Building FAAS Data has been deleted successfully", - () { - Navigator.of(context).pop(); - context - .read() - .add(const 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, deleteItem) { - 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: () { - deleteItem(property_info.id); - }, - icon: const Icon(Icons.delete_rounded), - color: primary, - ), - ], - ), - ), - ), - ); -} diff --git a/lib/screens/passo/land_home .dart b/lib/screens/passo/land_home .dart deleted file mode 100644 index a101d7e..0000000 --- a/lib/screens/passo/land_home .dart +++ /dev/null @@ -1,426 +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/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_boundaries_edit/land_boundaries_edit_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_ext_bloc/land_ext_edit_bloc.dart'; -import 'package:unit2/bloc/passo/land/land_location_edit/land_location_edit_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_appr.dart'; -import 'package:unit2/model/passo/land_ext.dart'; -import 'package:unit2/model/passo/land_property_assessment.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/model/passo/land_ref.dart'; -import 'package:unit2/model/passo/land_value_adjustment.dart'; -import 'package:unit2/model/passo/other_improvements.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/Land/edit_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: Column( - children: [ - 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(const 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) => - LandPropertyOwnerInfoBloc()..add(LoadLand())), - BlocProvider( - create: (context) => LandLocationEditBloc() - ..add(LoadLandLocationEdit( - land_loc_edit: LandPropertyLoc(), - id: property_info.id))), - BlocProvider( - create: (context) => LandExtEditBloc() - ..add(LoadLandExtEdit( - land_ext_edit: LandExt(), id: property_info.id))), - BlocProvider( - create: (context) => LandBoundariesEditBloc() - ..add(LoadLandBoundariesEdit( - land_boundaries_edit: LandPropertyBoundaries(), - id: property_info.id))), - BlocProvider( - create: (context) => LandAppraisalBloc() - ..add(LoadLandAppraisalEdit( - land_appr: const [], - id: property_info.id!))), - BlocProvider( - create: (context) => LandClassificationBloc() - ..add(LoadLandClassification())), - BlocProvider( - create: (context) => LandSubClassificationBloc() - ..add(LoadLandSubClassification( - cityCode: "1", classCode: 1))), - BlocProvider( - create: (context) => OtherImprovementsBloc() - ..add(LoadOtherImprovementEdit( - other_imps: const [], - ids: property_info.id!))), - BlocProvider( - create: (context) => - TypeOfLocationBloc()..add(LoadTypeOfLocation())), - BlocProvider( - create: (context) => - TypeOfRoadBloc()..add(LoadTypeOfRoad())), - BlocProvider( - create: (context) => LandPropertyAssessmentBloc() - ..add(LoadLandPropertyAssessmentEdit( - assessment: [], - id: property_info.id!))), - BlocProvider( - create: (context) => LandTreesImprovementsBloc() - ..add(LoadLandTreesImprovements())), - BlocProvider( - create: (context) => LandExtBloc()..add(LoadLandExt())), - BlocProvider( - create: (context) => LandValueAdjustmentsBloc() - ..add(LoadLandValueAdjustmentsEdit( - val_adj: [], - id: property_info.id!))), - 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: EditLand( - 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/profile/components/basic_information/citizenship_screen.dart b/lib/screens/profile/components/basic_information/citizenship_screen.dart index 3980950..913913c 100644 --- a/lib/screens/profile/components/basic_information/citizenship_screen.dart +++ b/lib/screens/profile/components/basic_information/citizenship_screen.dart @@ -23,9 +23,9 @@ import '../../../../utils/alerts.dart'; class CitizenShipScreen extends StatefulWidget { final int profileId; final String token; - + final List citizenships; const CitizenShipScreen( - {super.key, required this.profileId, required this.token}); + {super.key, required this.profileId, required this.token , required this.citizenships}); @override State createState() => _CitizenShipScreenState(); @@ -421,7 +421,9 @@ class _CitizenShipScreenState extends State { if (state is CitizenshipErrorState) { return Scaffold( body: SomethingWentWrong( - message: state.message, onpressed: () {})); + message: state.message, onpressed: () { + context.read().add(GetCitizenship(citizenship: widget.citizenships)); + })); } return Container(); }, diff --git a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart index 0d7d0c2..49be54c 100644 --- a/lib/screens/profile/components/basic_information/contact_information/add_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/add_modal.dart @@ -10,6 +10,7 @@ import 'package:unit2/sevices/profile/contact_services.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; import 'package:unit2/utils/global.dart'; +import 'package:unit2/utils/global_context.dart'; import 'package:unit2/utils/text_container.dart'; import '../../../../../theme-data.dart/colors.dart'; @@ -84,7 +85,7 @@ class _AddContactInformationScreenState serviceTypeId: selectedServiceType!.id!); } catch (e) { - context + NavigationService.navigatorKey.currentContext! .read() .add(CallErrorEvent(message: e.toString())); } @@ -129,6 +130,7 @@ class _AddContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, inputFormatters: [landLineFormatter], name: 'number-mail', @@ -150,7 +152,7 @@ class _AddContactInformationScreenState errorText: "This field is required"), decoration: normalTextFieldStyle( "Mobile number *", - "+63 (9xx) xxx - xxxx"), + "+63 (9xx) xxx - xxxx").copyWith(helperText: "Please input your mobile number excluding the 0"), ) : selectedServiceType!.id == 4 ////Social Media @@ -167,6 +169,7 @@ class _AddContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', validator: FormBuilderValidators diff --git a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart index f2e713d..e1c9187 100644 --- a/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart +++ b/lib/screens/profile/components/basic_information/contact_information/edit_modal.dart @@ -37,7 +37,7 @@ class _EditContactInformationScreenState var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$')}, type: MaskAutoCompletionType.lazy, initialText: "0"); @@ -149,6 +149,7 @@ class _EditContactInformationScreenState ? selectedServiceType?.id == 2 //// Landline ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [landLineFormatter], @@ -162,6 +163,7 @@ class _EditContactInformationScreenState selectedServiceType!.id == 19 //// Mobile number ? FormBuilderTextField( + keyboardType: TextInputType.number, controller: numberMailController, name: 'number-mail', inputFormatters: [mobileFormatter], @@ -172,10 +174,12 @@ class _EditContactInformationScreenState decoration: normalTextFieldStyle( "Mobile number *", "+63 (9xx) xxx - xxxx"), + ) : selectedServiceType!.id == 4 ////Social Media ? FormBuilderTextField( + controller: numberMailController, name: 'number-mail', validator: @@ -188,6 +192,7 @@ class _EditContactInformationScreenState : selectedServiceType!.id == 3 ////Email Address ? FormBuilderTextField( + keyboardType: TextInputType.emailAddress, controller: numberMailController, name: 'number-mail', diff --git a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart index 21b1560..226b39a 100644 --- a/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart +++ b/lib/screens/profile/components/basic_information/family/add_mobile_modal.dart @@ -1,10 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:flutter/src/widgets/framework.dart'; -import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; - -import '../../../../../bloc/profile/family/family_bloc.dart'; import '../../../../../theme-data.dart/btn-style.dart'; import '../../../../../theme-data.dart/colors.dart'; import '../../../../../theme-data.dart/form-style.dart'; @@ -26,6 +22,7 @@ class AddMobileNumber extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ FormBuilderTextField( + keyboardType: TextInputType.number, name: 'number_mail', inputFormatters: [mobileFormatter], validator: FormBuilderValidators.required( diff --git a/lib/screens/profile/components/learning_and_development_screen.dart b/lib/screens/profile/components/learning_and_development_screen.dart index 1fe52ba..e528c3d 100644 --- a/lib/screens/profile/components/learning_and_development_screen.dart +++ b/lib/screens/profile/components/learning_and_development_screen.dart @@ -45,7 +45,7 @@ class LearningAndDevelopmentScreen extends StatelessWidget { AttachmentCategory? selectedAttachmentCategory; List attachmentCategories = []; return Scaffold( - resizeToAvoidBottomInset: true, + appBar: AppBar( title: context.watch().state is LearningDevelopmentAddingState diff --git a/lib/screens/profile/components/learning_development/add_modal.dart b/lib/screens/profile/components/learning_development/add_modal.dart index facf278..32756bd 100644 --- a/lib/screens/profile/components/learning_development/add_modal.dart +++ b/lib/screens/profile/components/learning_development/add_modal.dart @@ -107,19 +107,6 @@ class _AddLearningAndDevelopmentScreenState final selectedTrainingController = TextEditingController(); DateTime? from; DateTime? to; - @override - void dispose() { - // fromDateController.dispose(); - // toDateController.dispose(); - // addTrainingController.dispose(); - // addTopicController.dispose(); - // topicFocusNode.dispose(); - - // addSponsorAgencyController.dispose(); - // sponsorByFocusNode.dispose(); - // sponsorAgencyCategoryFocusNode.dispose(); - super.dispose(); - } @override Widget build(BuildContext context) { @@ -132,37 +119,25 @@ class _AddLearningAndDevelopmentScreenState padding: const EdgeInsets.all(24), child: StatefulBuilder(builder: (context, setState) { return ListView( + shrinkWrap: true, children: [ ////Training SearchField SizedBox( child: show ? SearchableDropdownFormField.paginated( errorWidget: (value) { - return SomethingWentWrong( - message: value, - onpressed: () { - context - .read< - LearningDevelopmentBloc>() - .add( - GetLearningDevelopments( - profileId: widget - .profileId, - token: - widget.token)); - }); + return Text(value!); }, noRecordTex: SizedBox( width: double.infinity, - height: 300, + height: 100, child: EmptyWidget( controller: addTrainingController, onpressed: () { setState(() { show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = addTrainingController.text .toUpperCase(); selectedTraining = @@ -171,8 +146,7 @@ class _AddLearningAndDevelopmentScreenState title: selectedTrainingController .text); - addTrainingController.text = - ""; + addTrainingController.text = ""; Navigator.of(context).pop(); Navigator.of(context).pop(); }); @@ -187,20 +161,16 @@ class _AddLearningAndDevelopmentScreenState width: double.infinity, child: Card( child: Padding( - padding: - const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: child), ), ); }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - paginatedRequest: (int page, - String? searchKey) async { - List - paginatedList=[]; + validator: FormBuilderValidators.required( + errorText: "This field is required"), + paginatedRequest: + (int page, String? searchKey) async { + List paginatedList = []; try { paginatedList = await LearningDevelopmentServices @@ -209,12 +179,9 @@ class _AddLearningAndDevelopmentScreenState page: page, key: searchKey ??= ""); } catch (e) { - context - .read() - .add(CallErrorState( - message: e.toString())); + debugPrint(e.toString()); } - return paginatedList.map((e) { + return paginatedList.map((e) { return SearchableDropdownMenuItem( value: e, onTap: () {}, @@ -234,17 +201,14 @@ class _AddLearningAndDevelopmentScreenState selectedTraining = LearningDevelopmentType( id: null, - title: e.title! - .title); + title: e.title!.title); } show = false; showOtherInputs = true; - selectedTrainingController - .text = + selectedTrainingController.text = e.title!.title!; - Navigator.of(context) - .pop(); + Navigator.of(context).pop(); }); }, e: e, @@ -276,31 +240,25 @@ class _AddLearningAndDevelopmentScreenState ? FormBuilderTextField( maxLines: 5, readOnly: true, - controller: - selectedTrainingController, + controller: selectedTrainingController, name: "", decoration: - normalTextFieldStyle("", "") - .copyWith( - labelText: "Training", - suffixIcon: IconButton( - onPressed: () { - setState(() { - selectedConductedTraining = - null; - selectedTrainingController - .text = ""; - show = true; - showTrainingDetails = - false; - showOtherInputs = - false; - selectedTraining = - null; - }); - }, - icon: const Icon( - Icons.close))), + normalTextFieldStyle("", "").copyWith( + labelText: "Training", + suffixIcon: IconButton( + onPressed: () { + setState(() { + selectedConductedTraining = + null; + selectedTrainingController + .text = ""; + show = true; + showTrainingDetails = false; + showOtherInputs = false; + selectedTraining = null; + }); + }, + icon: const Icon(Icons.close))), ) : const SizedBox()), @@ -308,20 +266,15 @@ class _AddLearningAndDevelopmentScreenState SizedBox( child: showTrainingDetails ? TrainingDetails( - trainingTitle: - selectedConductedTraining! - .learningDevelopmentType! - .title!, - totalHours: selectedConductedTraining! - .totalHours!, + trainingTitle: selectedConductedTraining! + .learningDevelopmentType!.title!, + totalHours: + selectedConductedTraining!.totalHours!, trainingTopic: - selectedConductedTraining! - .topic!.title!, - toDate: selectedConductedTraining! - .toDate + selectedConductedTraining!.topic!.title!, + toDate: selectedConductedTraining!.toDate .toString(), - fromDate: selectedConductedTraining! - .fromDate! + fromDate: selectedConductedTraining!.fromDate! .toString(), conductedBy: selectedConductedTraining! .conductedBy!.name!) @@ -340,22 +293,17 @@ class _AddLearningAndDevelopmentScreenState FormBuilderDropdown< LearningDevelopmentType>( decoration: normalTextFieldStyle( - "Learning Development Type *", - ""), - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + "Learning Development Type *", ""), + validator: FormBuilderValidators.required( + errorText: "This field is required"), name: "types", items: state.types .map((e) => DropdownMenuItem< LearningDevelopmentType>( - value: e, - child: Text(e.title!))) + value: e, child: Text(e.title!))) .toList(), onChanged: (value) { - selectedLearningDevelopmentType = - value; + selectedLearningDevelopmentType = value; }, ), @@ -371,7 +319,8 @@ class _AddLearningAndDevelopmentScreenState ], focusNode: topicFocusNode, itemHeight: 100, - suggestionsDecoration: searchFieldDecoration(), + suggestionsDecoration: + searchFieldDecoration(), suggestions: state.topics .map((LearningDevelopmentType topic) => @@ -379,28 +328,24 @@ class _AddLearningAndDevelopmentScreenState topic.title!, item: topic, child: Padding( - padding: const EdgeInsets + padding: + const EdgeInsets .symmetric( - horizontal: - 10), + horizontal: 10), child: ListTile( title: Text( - topic - .title!, - softWrap: - true, + topic.title!, + softWrap: true, ), )))) .toList(), searchInputDecoration: - normalTextFieldStyle( - "Topic *", "") + normalTextFieldStyle("Topic *", "") .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons.arrow_drop_down), + suffixIcon: IconButton( + icon: + const Icon(Icons.arrow_drop_down), onPressed: () { topicFocusNode.unfocus(); }, @@ -415,8 +360,7 @@ class _AddLearningAndDevelopmentScreenState selectedTopic = LearningDevelopmentType( id: null, - title: topic - .item!.title); + title: topic.item!.title); } setState(() { topicFocusNode.unfocus(); @@ -425,23 +369,21 @@ class _AddLearningAndDevelopmentScreenState ////EMPTY WIDGET emptyWidget: EmptyWidget( title: "Add Topic", - controller: - addTopicController, + controller: addTopicController, onpressed: () { setState(() { LearningDevelopmentType newTopic = LearningDevelopmentType( id: null, - title: addTopicController - .text - .toUpperCase()); - state.topics.insert( - 0, newTopic); - topicFocusNode - .unfocus(); - addTopicController - .text = ""; + title: + addTopicController + .text + .toUpperCase()); + state.topics + .insert(0, newTopic); + topicFocusNode.unfocus(); + addTopicController.text = ""; Navigator.pop(context); }); }), @@ -461,56 +403,47 @@ class _AddLearningAndDevelopmentScreenState width: screenWidth, child: StatefulBuilder( builder: (context, setState) { - return StatefulBuilder(builder: - (context, setState) { + return StatefulBuilder( + builder: (context, setState) { return Row( children: [ //// FROM DATE Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - use24HourFormat: - false, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + use24HourFormat: false, icon: const Icon( - Icons - .date_range), + Icons.date_range), controller: fromDateController, - firstDate: - DateTime(1990), - lastDate: - DateTime(2100), - + firstDate: DateTime(1990), + lastDate: DateTime(2100), onChanged: (value) { setState(() { - from = DateTime - .parse( - value); + from = DateTime.parse( + value); }); }, - initialDate: to == - null + initialDate: to == null ? DateTime.now() : to!.subtract( const Duration( - days: - 1)), + days: 1)), timeHintText: "Date of Examination/Conferment", - decoration: normalTextFieldStyle( - "From *", - "From *") - .copyWith( - prefixIcon: - const Icon( + decoration: + normalTextFieldStyle( + "From *", + "From *") + .copyWith( + prefixIcon: + const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, )), initialValue: null, )), @@ -521,40 +454,31 @@ class _AddLearningAndDevelopmentScreenState Flexible( flex: 1, child: DateTimePicker( - validator: - FormBuilderValidators - .required( - errorText: - "This field is required"), - controller: - toDateController, - firstDate: - DateTime(1990), - + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + controller: toDateController, + firstDate: DateTime(1990), onChanged: (value) { setState(() { - to = DateTime - .parse(value); + to = + DateTime.parse(value); }); }, - initialDate: from == - null + initialDate: from == null ? DateTime.now() : from!.add( const Duration( days: 1)), - lastDate: - DateTime(2100), + lastDate: DateTime(2100), decoration: normalTextFieldStyle( - "To *", - "To *") + "To *", "To *") .copyWith( - prefixIcon: - const Icon( + prefixIcon: const Icon( Icons.date_range, - color: Colors - .black87, + color: Colors.black87, ), ), initialValue: null, @@ -573,10 +497,8 @@ class _AddLearningAndDevelopmentScreenState validator: numericRequired, name: "total_hours", decoration: normalTextFieldStyle( - "Total Hours Conducted *", - "0"), - keyboardType: - TextInputType.number, + "Total Hours Conducted *", "0"), + keyboardType: TextInputType.number, ), const SizedBox( height: 12, @@ -595,19 +517,14 @@ class _AddLearningAndDevelopmentScreenState overseas = value!; }); }, - decoration: - normalTextFieldStyle( - "Overseas Address?", - ''), + decoration: normalTextFieldStyle( + "Overseas Address?", ''), name: 'overseas', - title: Text(overseas - ? "YES" - : "NO"), + title: + Text(overseas ? "YES" : "NO"), ), SizedBox( - height: overseas == true - ? 8 - : 0, + height: overseas == true ? 8 : 0, ), SizedBox( child: overseas == false @@ -622,16 +539,16 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), onChanged: (Region? region) async { if (selectedRegion != region) { - setState( - () { + setState(() { provinceCall = true; }); @@ -640,8 +557,7 @@ class _AddLearningAndDevelopmentScreenState getProvinces(); } }, - initialValue: - null, + initialValue: null, decoration: normalTextFieldStyle( "Region*", @@ -653,11 +569,9 @@ class _AddLearningAndDevelopmentScreenState region) { return DropdownMenuItem< Region>( - value: - region, - child: Text( - region - .description!)); + value: region, + child: Text(region + .description!)); }).toList(), ), const SizedBox( @@ -666,8 +580,7 @@ class _AddLearningAndDevelopmentScreenState //// PROVINCE DROPDOWN SizedBox( height: 60, - child: - ModalProgressHUD( + child: ModalProgressHUD( color: Colors .transparent, inAsyncCall: @@ -677,11 +590,11 @@ class _AddLearningAndDevelopmentScreenState autovalidateMode: AutovalidateMode .onUserInteraction, - validator: (value) => value == null - ? 'required' - : null, - isExpanded: - true, + validator: (value) => + value == null + ? 'required' + : null, + isExpanded: true, value: selectedProvince, onChanged: @@ -689,8 +602,7 @@ class _AddLearningAndDevelopmentScreenState province) { if (selectedProvince != province) { - setState( - () { + setState(() { cityCall = true; }); @@ -702,42 +614,45 @@ class _AddLearningAndDevelopmentScreenState items: provinces == null ? [] - : provinces!.map>((Province + : provinces!.map< + DropdownMenuItem< + Province>>((Province province) { return DropdownMenuItem( - value: province, - child: FittedBox( - child: Text(province.description!), + value: + province, + child: + FittedBox( + child: + Text(province.description!), )); }).toList(), - decoration: normalTextFieldStyle( - "Province*", - "Province")), + decoration: + normalTextFieldStyle( + "Province*", + "Province")), ), ), ////CITY MUNICIPALITY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, - inAsyncCall: - cityCall, + child: ModalProgressHUD( + color: Colors.white, + inAsyncCall: cityCall, child: DropdownButtonFormField< CityMunicipality>( - validator: FormBuilderValidators.required( - errorText: - "This field is required"), - isExpanded: - true, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + isExpanded: true, onChanged: (CityMunicipality? city) { if (selectedMunicipality != city) { - setState( - () { + setState(() { barangayCall = true; }); @@ -755,12 +670,15 @@ class _AddLearningAndDevelopmentScreenState null ? [] : citymuns!.map< - DropdownMenuItem< - CityMunicipality>>((CityMunicipality - c) { + DropdownMenuItem< + CityMunicipality>>( + (CityMunicipality + c) { return DropdownMenuItem( - value: c, - child: Text(c.description!)); + value: + c, + child: Text( + c.description!)); }).toList(), ), ), @@ -768,25 +686,24 @@ class _AddLearningAndDevelopmentScreenState //// BARANGAY SizedBox( height: 60, - child: - ModalProgressHUD( - color: Colors - .white, + child: ModalProgressHUD( + color: Colors.white, inAsyncCall: barangayCall, - child: DropdownButtonFormField< - Barangay>( - isExpanded: - true, + child: + DropdownButtonFormField< + Barangay>( + isExpanded: true, onChanged: (Barangay? baragay) { selectedBarangay = baragay; }, - decoration: normalTextFieldStyle( - "Barangay*", - "Barangay"), + decoration: + normalTextFieldStyle( + "Barangay*", + "Barangay"), value: selectedBarangay, items: barangays == @@ -797,8 +714,10 @@ class _AddLearningAndDevelopmentScreenState Barangay>>((Barangay barangay) { return DropdownMenuItem( - value: barangay, - child: Text(barangay.description!)); + value: + barangay, + child: Text( + barangay.description!)); }).toList(), ), ), @@ -808,28 +727,25 @@ class _AddLearningAndDevelopmentScreenState //// COUNTRY DROPDOWN : SizedBox( height: 60, - child: - FormBuilderDropdown< - Country>( - initialValue: - null, - validator: FormBuilderValidators - .required( - errorText: - "This field is required"), - items: state - .countries - .map< + child: FormBuilderDropdown< + Country>( + initialValue: null, + validator: + FormBuilderValidators + .required( + errorText: + "This field is required"), + items: state.countries.map< DropdownMenuItem< - Country>>((Country - country) { + Country>>( + (Country country) { return DropdownMenuItem< Country>( - value: - country, + value: country, child: FittedBox( child: Text( - country.name!))); + country + .name!))); }).toList(), name: 'country', decoration: @@ -837,10 +753,8 @@ class _AddLearningAndDevelopmentScreenState "Country*", "Country"), onChanged: - (Country? - value) { - selectedCountry = - value; + (Country? value) { + selectedCountry = value; }, ), ), @@ -866,28 +780,24 @@ class _AddLearningAndDevelopmentScreenState itemHeight: 100, focusNode: conductedByFocusNode, - suggestions: state - .conductedBy - .map((Agency - agency) => + suggestions: state.conductedBy + .map((Agency agency) => SearchFieldListItem( - agency - .name!, - item: - agency, - child: - ListTile( - title: - Text( - agency - .name!, + agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, overflow: - TextOverflow.visible, + TextOverflow + .visible, ), - subtitle: Text(agency.privateEntity == + subtitle: Text(agency + .privateEntity == true ? "Private" - : agency.privateEntity == false + : agency.privateEntity == + false ? "Government" : ""), ))) @@ -900,33 +810,29 @@ class _AddLearningAndDevelopmentScreenState suffixIcon: GestureDetector( child: const Icon( - Icons - .arrow_drop_down, + Icons.arrow_drop_down, ), onTap: () => conductedByFocusNode .unfocus(), )), ////SELETECTED - onSuggestionTap: - (agency) { + onSuggestionTap: (agency) { setState(() { - if (agency.item - ?.id != + if (agency.item?.id != null) { selectedConductedByAgency = Agency( - name: - null, + name: null, id: agency - .item! - .id); + .item!.id); } else { - selectedConductedByAgency = Agency( - id: null, - name: agency - .item! - .name); + selectedConductedByAgency = + Agency( + id: null, + name: agency + .item! + .name); } if (agency.item! @@ -947,45 +853,37 @@ class _AddLearningAndDevelopmentScreenState }); }, validator: (agency) { - if (agency! - .isEmpty) { + if (agency!.isEmpty) { return "This field is required"; } return null; }, ////conducter empty widget - emptyWidget: - EmptyWidget( - controller: - addConductedByController, - onpressed: - () { - setState( - () { - Agency newAgency = Agency( - id: - null, - name: addConductedByController - .text - .toUpperCase(), - category: - null, - privateEntity: - null); - state - .conductedBy - .insert( - 0, - newAgency); + emptyWidget: EmptyWidget( + controller: + addConductedByController, + onpressed: () { + setState(() { + Agency newAgency = Agency( + id: null, + name: addConductedByController + .text + .toUpperCase(), + category: null, + privateEntity: + null); + state.conductedBy + .insert( + 0, newAgency); - addConductedByController - .text = ""; - Navigator.pop( - context); - }); - }, - title: - "Add Conducted By Agency")), + addConductedByController + .text = ""; + Navigator.pop( + context); + }); + }, + title: + "Add Conducted By Agency")), SizedBox( height: showConductedByAgencyCategory @@ -1002,37 +900,40 @@ class _AddLearningAndDevelopmentScreenState .up, focusNode: conductedByAgencyCategoryFocusNode, - itemHeight: - 70, + itemHeight: 70, suggestions: state .agencyCategory - .map((Category category) => SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: Text(category.name!), - subtitle: Text(category.industryClass!.name!), - ))) + .map((Category + category) => + SearchFieldListItem( + category + .name!, + item: + category, + child: + ListTile( + title: + Text(category.name!), + subtitle: Text(category + .industryClass! + .name!), + ))) .toList(), emptyWidget: Container( - height: - 100, + height: 100, decoration: box1(), child: const Center( - child: - Text("No result found ...")), + child: Text( + "No result found ...")), ), onSuggestionTap: (agencyCategory) { - setState( - () { + setState(() { selectedConductedByAgencyCategory = - agencyCategory.item; + agencyCategory + .item; selectedConductedByAgency = Agency( id: selectedConductedByAgency ?.id, @@ -1046,23 +947,21 @@ class _AddLearningAndDevelopmentScreenState .unfocus(); }); }, - searchInputDecoration: normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: - () { + searchInputDecoration: + normalTextFieldStyle( + "Category *", + "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon(Icons + .arrow_drop_down), + onPressed: () { conductedByAgencyCategoryFocusNode .unfocus(); }, )), - validator: - (value) { + validator: (value) { if (value! .isEmpty) { return "This field is required"; @@ -1080,45 +979,46 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: showConductedByAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - conductedByCategoryIsPrivate, - title: Text( - conductedByCategoryIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( - "Private Entity?", - 'Private Entity?'), + child: + showConductedByAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + conductedByCategoryIsPrivate, + title: Text( + conductedByCategoryIsPrivate + ? "YES" + : "NO"), + decoration: normalTextFieldStyle( + "Private Entity?", + 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState( - () { - conductedByCategoryIsPrivate = - value!; - selectedConductedByAgency = Agency( - category: selectedConductedByAgency - ?.category, - id: selectedConductedByAgency - ?.id, - name: selectedConductedByAgency! - .name, - privateEntity: - conductedByCategoryIsPrivate); - conductedByAgencyCategoryFocusNode - .unfocus(); - }); - }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + ////onvhange private sector + onChanged: + (value) { + setState(() { + conductedByCategoryIsPrivate = + value!; + selectedConductedByAgency = Agency( + category: + selectedConductedByAgency + ?.category, + id: selectedConductedByAgency + ?.id, + name: selectedConductedByAgency! + .name, + privateEntity: + conductedByCategoryIsPrivate); + conductedByAgencyCategoryFocusNode + .unfocus(); + }); + }, + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), )), ], @@ -1144,8 +1044,8 @@ class _AddLearningAndDevelopmentScreenState hasSponsor = value!; }); }, - decoration: normalTextFieldStyle( - "Has Sponsor?", ''), + decoration: + normalTextFieldStyle("Has Sponsor?", ''), name: 'sponsor', title: Text(hasSponsor ? "YES" : "NO"), ), @@ -1162,18 +1062,15 @@ class _AddLearningAndDevelopmentScreenState UpperCaseTextFormatter() ], itemHeight: 110, - focusNode: - sponsorByFocusNode, - suggestions: state - .sponsorAgencies + focusNode: sponsorByFocusNode, + suggestions: state.sponsorAgencies .map((Agency agency) => SearchFieldListItem( agency.name!, item: agency, child: ListTile( title: Text( - agency - .name!, + agency.name!, overflow: TextOverflow .visible, @@ -1190,8 +1087,7 @@ class _AddLearningAndDevelopmentScreenState .toList(), searchInputDecoration: normalTextFieldStyle( - " Sponsor Agency *", - "") + " Sponsor Agency *", "") .copyWith( suffixIcon: GestureDetector( @@ -1199,30 +1095,25 @@ class _AddLearningAndDevelopmentScreenState Icons.arrow_drop_down, ), onTap: () => - sponsorByFocusNode - .unfocus(), + sponsorByFocusNode.unfocus(), )), ////SELETECTED onSuggestionTap: (agency) { setState(() { - if (agency.item?.id != - null) { + if (agency.item?.id != null) { selectedSponsorAgency = Agency( name: null, - id: agency - .item! - .id); + id: agency.item!.id); } else { selectedSponsorAgency = Agency( id: null, name: agency - .item! - .name); + .item!.name); } - if (agency.item! - .privateEntity == + if (agency + .item!.privateEntity == null) { showSponsorCategoryAgency = true; @@ -1234,8 +1125,7 @@ class _AddLearningAndDevelopmentScreenState showSponsorAgencyPrivateRadio = false; } - sponsorByFocusNode - .unfocus(); + sponsorByFocusNode.unfocus(); }); }, validator: (agency) { @@ -1252,112 +1142,99 @@ class _AddLearningAndDevelopmentScreenState setState(() { Agency newAgency = Agency( id: null, - name: addSponsorAgencyController - .text - .toUpperCase(), + name: + addSponsorAgencyController + .text + .toUpperCase(), category: null, - privateEntity: - null); - state - .sponsorAgencies - .insert(0, - newAgency); + privateEntity: null); + state.sponsorAgencies + .insert(0, newAgency); addSponsorAgencyController .text = ""; - Navigator.pop( - context); + Navigator.pop(context); }); }, - title: - "Add Sponsor Agency")), + title: "Add Sponsor Agency")), SizedBox( - height: - showSponsorCategoryAgency - ? 12 - : 0, + height: showSponsorCategoryAgency + ? 12 + : 0, ), ////Sponsor Agency Category SizedBox( - child: - showSponsorCategoryAgency - ? SearchField( - suggestionDirection: - SuggestionDirection - .up, - focusNode: - sponsorAgencyCategoryFocusNode, - itemHeight: 70, - suggestions: state - .agencyCategory - .map((Category - category) => - SearchFieldListItem( - category - .name!, - item: - category, - child: - ListTile( - title: - Text(category.name!), - subtitle: - Text(category.industryClass!.name!), - ))) - .toList(), - emptyWidget: - Container( - height: 100, - decoration: - box1(), - child: const Center( - child: Text( - "No result found ...")), - ), - onSuggestionTap: - (agencyCategory) { - setState(() { - selectedSponsorAgencyCategory = - agencyCategory - .item; - selectedSponsorAgency = Agency( - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + child: showSponsorCategoryAgency + ? SearchField( + suggestionDirection: + SuggestionDirection.up, + focusNode: + sponsorAgencyCategoryFocusNode, + itemHeight: 70, + suggestions: state + .agencyCategory + .map((Category + category) => + SearchFieldListItem( + category.name!, + item: category, + child: ListTile( + title: Text( + category + .name!), + subtitle: Text( + category + .industryClass! + .name!), + ))) + .toList(), + emptyWidget: Container( + height: 100, + decoration: box1(), + child: const Center( + child: Text( + "No result found ...")), + ), + onSuggestionTap: + (agencyCategory) { + setState(() { + selectedSponsorAgencyCategory = + agencyCategory.item; + selectedSponsorAgency = Agency( + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - category: - selectedSponsorAgencyCategory, - privateEntity: - sponsorAgencyIsPrivate); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, - searchInputDecoration: - normalTextFieldStyle( - "Category *", - "") - .copyWith( - suffixIcon: - IconButton( - icon: const Icon( - Icons - .arrow_drop_down), - onPressed: () { - sponsorAgencyCategoryFocusNode - .unfocus(); - }, - )), - validator: - (value) { - if (value! - .isEmpty) { - return "This field is required"; - } - return null; - }, - ) - : const SizedBox(), + category: + selectedSponsorAgencyCategory, + privateEntity: + sponsorAgencyIsPrivate); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, + searchInputDecoration: + normalTextFieldStyle( + "Category *", "") + .copyWith( + suffixIcon: + IconButton( + icon: const Icon( + Icons.arrow_drop_down), + onPressed: () { + sponsorAgencyCategoryFocusNode + .unfocus(); + }, + )), + validator: (value) { + if (value!.isEmpty) { + return "This field is required"; + } + return null; + }, + ) + : const SizedBox(), ), ////Sponsor Agency Private Radio @@ -1367,47 +1244,48 @@ class _AddLearningAndDevelopmentScreenState ? 12 : 0), SizedBox( - child: - showSponsorAgencyPrivateRadio - ? FormBuilderSwitch( - initialValue: - sponsorAgencyIsPrivate, - title: Text( - sponsorAgencyIsPrivate - ? "YES" - : "NO"), - decoration: normalTextFieldStyle( + child: showSponsorAgencyPrivateRadio + ? FormBuilderSwitch( + initialValue: + sponsorAgencyIsPrivate, + title: Text( + sponsorAgencyIsPrivate + ? "YES" + : "NO"), + decoration: + normalTextFieldStyle( "Private Entity?", 'Private Entity?'), - ////onvhange private sector - onChanged: - (value) { - setState(() { - sponsorAgencyIsPrivate = - value!; - selectedSponsorAgency = Agency( - category: - selectedSponsorAgency - ?.category, - id: selectedSponsorAgency - ?.id, - name: selectedSponsorAgency! + ////onvhange private sector + onChanged: (value) { + setState(() { + sponsorAgencyIsPrivate = + value!; + selectedSponsorAgency = Agency( + category: + selectedSponsorAgency + ?.category, + id: selectedSponsorAgency + ?.id, + name: + selectedSponsorAgency! .name, - privateEntity: - selectedSponsorAgency?.privateEntity); - sponsorAgencyCategoryFocusNode - .unfocus(); - }); - }, + privateEntity: + selectedSponsorAgency + ?.privateEntity); + sponsorAgencyCategoryFocusNode + .unfocus(); + }); + }, - name: - 'sponsorAgencyPrivate', - validator: - FormBuilderValidators - .required(), - ) - : const SizedBox()), + name: + 'sponsorAgencyPrivate', + validator: + FormBuilderValidators + .required(), + ) + : const SizedBox()), ]), ) : const SizedBox(), @@ -1424,16 +1302,17 @@ class _AddLearningAndDevelopmentScreenState name: "total_hours_attended", keyboardType: TextInputType.number, decoration: normalTextFieldStyle( - "Total Hours Attended *", - "Total Hours Attended *"), + "Total Hours Attended *", "Total Hours Attended *"), ), - const SizedBox(height: 16,), - SizedBox( + const SizedBox( + height: 16, + ), + SizedBox( width: double.infinity, height: 60, child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), + style: + mainBtnStyle(primary, Colors.transparent, second), child: const Text(submit), onPressed: () { if (formKey.currentState!.saveAndValidate()) { @@ -1477,8 +1356,8 @@ class _AddLearningAndDevelopmentScreenState venue: venue, toDate: DateTime.parse(toDateController.text), - fromDate: DateTime.parse( - fromDateController.text), + fromDate: + DateTime.parse(fromDateController.text), totalHours: double.parse(formKey .currentState!.value['total_hours']), conductedBy: selectedConductedByAgency, diff --git a/lib/screens/profile/profile.dart b/lib/screens/profile/profile.dart index fe9d5a4..ee5583e 100644 --- a/lib/screens/profile/profile.dart +++ b/lib/screens/profile/profile.dart @@ -44,364 +44,398 @@ import '../../bloc/profile/voluntary_works/voluntary_work_bloc.dart'; import '../../bloc/profile/workHistory/workHistory_bloc.dart'; import '../../bloc/user/user_bloc.dart'; import '../../model/profile/basic_information/primary-information.dart'; -import '../unit2/homepage.dart/components/menu.dart'; import 'components/main_menu.dart'; import 'components/submenu.dart'; -class ProfileInfo extends StatelessWidget { +class ProfileInfo extends StatefulWidget { const ProfileInfo({super.key}); + @override + State createState() => _ProfileInfoState(); +} + +class _ProfileInfoState extends State { @override Widget build(BuildContext context) { int? profileId; String? token; Profile profile; - return Scaffold( - appBar: AppBar( - backgroundColor: primary, - centerTitle: true, - title: const Text('Profile'), - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocBuilder(builder: (context, state) { - if (state is UserLoggedIn) { - profileId = state.userData!.user!.login!.user!.profileId; - token = state.userData!.user!.login!.token!; - if (globalCurrentProfile == null) { - profile = state.userData!.employeeInfo!.profile!; - } else { - profile = globalCurrentProfile!; - } - print(profile.lastName); - return BlocConsumer( - listener: ( - context, - state, - ) { - if (state is ProfileLoading) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is ProfileLoaded || - state is ProfileErrorState || - state is BasicInformationEditingState) { - final progress = ProgressHUD.of(context); - progress?.dismiss(); - } - }, - builder: (context, state) { - if (state is ProfileLoaded) { - return Container( - padding: const EdgeInsets.symmetric( - vertical: 12, horizontal: 12), - child: ListView( - children: [ - Text( - "View and Update your Profile Information", - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyLarge, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Elusive.address_book, - color: primary, + return WillPopScope( + onWillPop: () async { + setState(() {}); + return true; + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: primary, + centerTitle: true, + title: const Text('Profile'), + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocBuilder(builder: (context, state) { + if (state is UserLoggedIn) { + profileId = state.userData!.user!.login!.user!.profileId; + token = state.userData!.user!.login!.token!; + if (globalCurrentProfile == null) { + profile = state.userData!.employeeInfo!.profile!; + globalCurrentProfile = profile; + } else { + profile = globalCurrentProfile!; + } + return BlocConsumer( + listener: ( + context, + state, + ) { + if (state is ProfileLoading) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is ProfileLoaded || + state is ProfileErrorState || + state is BasicInformationEditingState) { + final progress = ProgressHUD.of(context); + progress?.dismiss(); + } + }, + builder: (context, state) { + if (state is ProfileLoaded) { + return Container( + padding: const EdgeInsets.symmetric( + vertical: 12, horizontal: 12), + child: ListView( + children: [ + Text( + "View and Update your Profile Information", + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: + const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Elusive.address_book, + color: primary, + ), + title: Text( + "Basic Information", + style: + TextStyle(fontWeight: FontWeight.bold), + ), ), - title: Text( - "Basic Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu(Icons.person, "Primary", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider.value( - value: ProfileBloc() - ..add(GetPrimaryBasicInfo( - primaryBasicInformation: profile)), - child: PrimaryInfo( - token: token!, - profileId: profileId!, - ), - ); - })); - }), - subMenu(Icons.home, "Addresses", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => AddressBloc() - ..add(GetAddress( - addresses: state.profileInformation - .basicInfo.addresses)), - child: const AddressScreen(), - ); - })); - }), - subMenu(Icons.contact_mail, "Identifications", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => IdentificationBloc() - ..add(GetIdentifications( - identificationInformation: state + items: [ + subMenu(Icons.person, "Primary", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider.value( + value: ProfileBloc() + ..add(GetPrimaryBasicInfo( + primaryBasicInformation: + profile)), + child: PrimaryInfo( + token: token!, + profileId: profileId!, + ), + ); + })); + }), + subMenu(Icons.home, "Addresses", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => AddressBloc() + ..add(GetAddress( + addresses: state + .profileInformation + .basicInfo + .addresses)), + child: const AddressScreen(), + ); + })); + }), + subMenu(Icons.contact_mail, "Identifications", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + IdentificationBloc() + ..add(GetIdentifications( + identificationInformation: + state + .profileInformation + .basicInfo + .identifications)), + child: const IdentificationsScreen(), + ); + })); + }), + subMenu(Icons.contact_phone, "Contact Info", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ContactBloc() + ..add(GetContacts( + contactInformations: state + .profileInformation + .basicInfo + .contactInformation)), + child: const ContactInformationScreen(), + ); + })); + }), + subMenu(Icons.flag, "Citizenships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => CitizenshipBloc() + ..add(GetCitizenship( + citizenship: state + .profileInformation + .basicInfo + .citizenships)), + child: CitizenShipScreen( + citizenships: state .profileInformation .basicInfo - .identifications)), - child: const IdentificationsScreen(), - ); - })); - }), - subMenu(Icons.contact_phone, "Contact Info", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ContactBloc() - ..add(GetContacts( - contactInformations: state - .profileInformation - .basicInfo - .contactInformation)), - child: const ContactInformationScreen(), - ); - })); - }), - subMenu(Icons.flag, "Citizenships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => CitizenshipBloc() - ..add(GetCitizenship( - citizenship: state - .profileInformation - .basicInfo - .citizenships)), - child: CitizenShipScreen( - profileId: profileId!, token: token!), - ); - })); - }), - ]), - const Divider(), - MainMenu( - icon: Elusive.group, - title: "Family", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => FamilyBloc() - ..add(GetFamilies( - profileId: profileId!, token: token!)), - child: const FamilyBackgroundScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.graduation_cap, - title: "Education", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EducationBloc() - ..add(GetEducationalBackground( - profileId: profileId!, token: token!)), - child: const EducationScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Icons.stars, - title: "Eligibility", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => EligibilityBloc() - ..add(GetEligibilities( - profileId: profileId!, token: token!)), - child: const EligibiltyScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.shopping_bag, - title: "Work History", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => WorkHistoryBloc() - ..add(GetWorkHistories( - profileId: profileId!, token: token!)), - child: const WorkHistoryScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: FontAwesome5.walking, - title: "Voluntary Work & Civic Services", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => VoluntaryWorkBloc() - ..add(GetVoluntarWorks( - profileId: profileId!, token: token!)), - child: const VolunataryWorkScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Elusive.lightbulb, - title: "Learning & Development", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => LearningDevelopmentBloc() - ..add(GetLearningDevelopments( - profileId: profileId!, token: token!)), - child: const LearningAndDevelopmentScreen(), - ); - })); - }, - ), - const Divider(), - MainMenu( - icon: Brandico.codepen, - title: "Personal References", - onTap: () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => ReferencesBloc() - ..add(GetReferences( - profileId: profileId!, token: token!)), - child: const ReferencesScreen(), - ); - })); - }, - ), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - Icons.info, - color: primary, - ), - title: Text( - "Other Information", - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - items: [ - subMenu( - Icons.fitness_center, "Skills & Hobbies", - () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => HoobiesBloc() - ..add(GetSkillsHobbies( + .citizenships, profileId: profileId!, - token: token!)), - child: const SkillHobbiesScreen(), - ); - })); - }), - subMenu(FontAwesome5.certificate, - "Organization Memberships", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - OrganizationMembershipBloc() - ..add(GetOrganizationMembership( - profileId: profileId!, - token: token!)), - child: const OrgMembershipsScreen(), - ); - })); - }), - subMenu(Entypo.doc_text, - "Non-Academic Recognitions", () { - Navigator.push(context, MaterialPageRoute( - builder: (BuildContext context) { - return BlocProvider( - create: (context) => - NonAcademicRecognitionBloc() - ..add(GetNonAcademicRecognition( - profileId: profileId!, - token: token!)), - child: - const NonAcademicRecognitionScreen(), - ); - })); - }), - ]), - ExpandableGroup( - collapsedIcon: - const Icon(Icons.keyboard_arrow_down), - expandedIcon: const Icon(Icons.keyboard_arrow_up), - header: const ListTile( - leading: Icon( - FontAwesome5.laptop_house, - color: primary, + token: token!), + ); + })); + }), + ]), + const Divider(), + MainMenu( + icon: Elusive.group, + title: "Family", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => FamilyBloc() + ..add(GetFamilies( + profileId: profileId!, + token: token!)), + child: const FamilyBackgroundScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.graduation_cap, + title: "Education", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EducationBloc() + ..add(GetEducationalBackground( + profileId: profileId!, + token: token!)), + child: const EducationScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Icons.stars, + title: "Eligibility", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => EligibilityBloc() + ..add(GetEligibilities( + profileId: profileId!, + token: token!)), + child: const EligibiltyScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.shopping_bag, + title: "Work History", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => WorkHistoryBloc() + ..add(GetWorkHistories( + profileId: profileId!, + token: token!)), + child: const WorkHistoryScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: FontAwesome5.walking, + title: "Voluntary Work & Civic Services", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => VoluntaryWorkBloc() + ..add(GetVoluntarWorks( + profileId: profileId!, + token: token!)), + child: const VolunataryWorkScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Elusive.lightbulb, + title: "Learning & Development", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + LearningDevelopmentBloc() + ..add(GetLearningDevelopments( + profileId: profileId!, + token: token!)), + child: const LearningAndDevelopmentScreen(), + ); + })); + }, + ), + const Divider(), + MainMenu( + icon: Brandico.codepen, + title: "Personal References", + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => ReferencesBloc() + ..add(GetReferences( + profileId: profileId!, + token: token!)), + child: const ReferencesScreen(), + ); + })); + }, + ), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: + const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + Icons.info, + color: primary, + ), + title: Text( + "Other Information", + style: + TextStyle(fontWeight: FontWeight.bold), + ), ), - title: Text( - "Assets", - style: TextStyle(fontWeight: FontWeight.bold), + items: [ + subMenu( + Icons.fitness_center, "Skills & Hobbies", + () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => HoobiesBloc() + ..add(GetSkillsHobbies( + profileId: profileId!, + token: token!)), + child: const SkillHobbiesScreen(), + ); + })); + }), + subMenu(FontAwesome5.certificate, + "Organization Memberships", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + OrganizationMembershipBloc() + ..add(GetOrganizationMembership( + profileId: profileId!, + token: token!)), + child: const OrgMembershipsScreen(), + ); + })); + }), + subMenu(Entypo.doc_text, + "Non-Academic Recognitions", () { + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + NonAcademicRecognitionBloc() + ..add(GetNonAcademicRecognition( + profileId: profileId!, + token: token!)), + child: + const NonAcademicRecognitionScreen(), + ); + })); + }), + ]), + ExpandableGroup( + collapsedIcon: + const Icon(Icons.keyboard_arrow_down), + expandedIcon: + const Icon(Icons.keyboard_arrow_up), + header: const ListTile( + leading: Icon( + FontAwesome5.laptop_house, + color: primary, + ), + title: Text( + "Assets", + style: + TextStyle(fontWeight: FontWeight.bold), + ), ), - ), - items: [ - subMenu(ModernPictograms.home, - "Real Property Tax", () {}), - ]), - ], - ), - ); - } - if (state is ProfileLoading) { - return const LoadingScreen(); - } - if (state is ProfileErrorState) { - return SomethingWentWrong( - message: state.mesage, - onpressed: () { - BlocProvider.of(context).add( - LoadProfile(token: token!, userID: profileId!)); - }); - } + items: [ + subMenu(ModernPictograms.home, + "Real Property Tax", () {}), + ]), + ], + ), + ); + } + if (state is ProfileLoading) { + return const LoadingScreen(); + } + if (state is ProfileErrorState) { + return SomethingWentWrong( + message: state.mesage, + onpressed: () { + BlocProvider.of(context).add( + LoadProfile(token: token!, userID: profileId!)); + }); + } - return Container(); - }, - ); - } - return Container(); - }), - )); + return Container(); + }, + ); + } + return Container(); + }), + )), + ); } } diff --git a/lib/screens/sos/add_mobile.dart b/lib/screens/sos/add_mobile.dart index 8fb0d22..c8632ae 100644 --- a/lib/screens/sos/add_mobile.dart +++ b/lib/screens/sos/add_mobile.dart @@ -68,7 +68,7 @@ class AddMobile extends StatelessWidget { ), Text(addMobileCaption, textAlign: TextAlign.center, - style: Theme.of(context).textTheme.caption), + style: Theme.of(context).textTheme.bodyMedium), const SizedBox( height: 24, ), @@ -81,16 +81,16 @@ class AddMobile extends StatelessWidget { name: 'mobile1', validator: mobileNumberValidator, maxLength: 11, - decoration: - normalTextFieldStyle(mobile1, "sfdfsdfsd")), + decoration: normalTextFieldStyle( + mobile1, "sfdfsdfsd")), const SizedBox( height: 12, ), FormBuilderTextField( name: 'mobile2', maxLength: 11, - decoration: - normalTextFieldStyle(mobile2, "0900000000000")), + decoration: normalTextFieldStyle( + mobile2, "0900000000000")), SizedBox( height: isMobile() @@ -108,9 +108,7 @@ class AddMobile extends StatelessWidget { ), onPressed: () { if (_formKey.currentState! - .saveAndValidate()) { - - } + .saveAndValidate()) {} // } }, diff --git a/lib/screens/sos/components/acknnowledge.dart b/lib/screens/sos/components/acknnowledge.dart index 8a771ba..ccdf796 100644 --- a/lib/screens/sos/components/acknnowledge.dart +++ b/lib/screens/sos/components/acknnowledge.dart @@ -11,113 +11,115 @@ import '../../../utils/global.dart'; class SosAcknowledged extends StatelessWidget { final Function() onpressed; final SessionData sessionData; - const SosAcknowledged({super.key, required this.onpressed, required this.sessionData}); + const SosAcknowledged( + {super.key, required this.onpressed, required this.sessionData}); @override Widget build(BuildContext context) { - - return Container( - padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 35), - height: screenHeight, - child: Stack( - children: [ - Positioned( - bottom: 0, + return Container( + padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 35), + height: screenHeight, + child: Stack( + children: [ + Positioned( + bottom: 0, + child: SizedBox( + width: screenWidth, + height: screenHeight / 2, + child: Opacity( + opacity: .2, + child: Image.asset( + "assets/pngs/emergency.png", + fit: BoxFit.cover, + ), + ), + )), + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const SizedBox( + height: 18, + ), + SlideInDown( + child: AutoSizeText( + "SOS Acknowledged!", + maxLines: 2, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.displayMedium!.copyWith( + fontSize: 40, + color: success2, + fontWeight: FontWeight.w600), + ), + ), + const SizedBox( + height: 5, + ), + SlideInDown( + child: const Icon( + Iconic.ok_circle, + color: success2, + size: 120, + ), + ), + const SizedBox( + height: 22, + ), + SlideInUp( + child: Container( + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.all(Radius.circular(15))), + child: Column( + children: [ + ListTile( + title: AutoSizeText( + sessionData.acknowledgedBy!.toUpperCase(), + maxLines: 2, + style: Theme.of(context) + .textTheme + .headlineMedium! + .copyWith( + fontSize: 22, + fontWeight: FontWeight.bold, + color: third), + ), + subtitle: Text( + "Acknowledge by", + style: Theme.of(context).textTheme.labelLarge, + ), + ), + Container( + padding: const EdgeInsets.all(15), + child: Text( + "NOTE: Please ensure that the mobile numbers you provided are still active, and look for an area with stable network. The response team will contact your mobile number.", + textAlign: TextAlign.justify, + style: + Theme.of(context).textTheme.bodyMedium!.copyWith( + fontSize: 14, + color: Colors.black87, + ), + ), + ), + ], + ), + ), + ), + Expanded(child: Container()), + SlideInUp( child: SizedBox( - width: screenWidth, - height: screenHeight / 2, - child: Opacity( - opacity: .2, - child: Image.asset( - "assets/pngs/emergency.png", - fit: BoxFit.cover, - ), - ), - )), - Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const SizedBox( - height: 18, + height: 50, + width: double.infinity, + child: ElevatedButton( + style: mainBtnStyle( + second, Colors.transparent, Colors.white54), + onPressed: onpressed, + child: const Text("DONE!")), ), - SlideInDown( - child: AutoSizeText( - "SOS Acknowledged!", - maxLines: 2, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.displayMedium!.copyWith( - fontSize: 40, - color: success2, - fontWeight: FontWeight.w600), - ), - ), - const SizedBox( - height: 5, - ), - SlideInDown( - child: const Icon( - Iconic.ok_circle, - color: success2, - size: 120, - ), - ), - const SizedBox( - height: 22, - ), - SlideInUp( - child: Container( - decoration: const BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.all(Radius.circular(15))), - child: Column( - children: [ - - - ListTile( - title: AutoSizeText( - sessionData.acknowledgedBy!.toUpperCase(), - maxLines: 2, - style: Theme.of(context).textTheme.headline4!.copyWith( - fontSize: 22, - fontWeight: FontWeight.bold, - color: third), - ), - subtitle: Text( - "Acknowledge by", - style: Theme.of(context).textTheme.labelLarge, - ), - ), - Container( - padding: const EdgeInsets.all(15), - child: Text( - "NOTE: Please ensure that the mobile numbers you provided are still active, and look for an area with stable network. The response team will contact your mobile number.", - textAlign: TextAlign.justify, - style: Theme.of(context).textTheme.caption!.copyWith( - fontSize: 14, - color: Colors.black87, - ), - ), - ), - ], - ), - ), - ), - Expanded(child: Container()), - SlideInUp( - child: SizedBox( - height: 50, - width: double.infinity, - child: ElevatedButton( - style: - mainBtnStyle(second, Colors.transparent, Colors.white54), - onPressed: onpressed, - child: const Text("DONE!")), - ), - ) - ], - ), - ], - ), + ) + ], + ), + ], + ), ); } -} \ No newline at end of file +} diff --git a/lib/screens/sos/components/mobile.dart b/lib/screens/sos/components/mobile.dart index bd0c522..ca2be12 100644 --- a/lib/screens/sos/components/mobile.dart +++ b/lib/screens/sos/components/mobile.dart @@ -24,7 +24,7 @@ class Mobile extends StatelessWidget { title: Text(title), subtitle: Text( subtitle, - style: Theme.of(context).textTheme.caption, + style: Theme.of(context).textTheme.bodyMedium, ), trailing: IconButton( icon: const Icon(Icons.edit), diff --git a/lib/screens/sos/components/sos_received.dart b/lib/screens/sos/components/sos_received.dart index a8bad17..881d960 100644 --- a/lib/screens/sos/components/sos_received.dart +++ b/lib/screens/sos/components/sos_received.dart @@ -10,124 +10,123 @@ import '../../../utils/global.dart'; class SOSreceived extends StatelessWidget { final Function() onpressed; - const SOSreceived({super.key, required this.onpressed}); + const SOSreceived({super.key, required this.onpressed}); @override Widget build(BuildContext context) { - - return Container( - padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 35), - height: screenHeight, - child: Stack( - children: [ - Positioned( - bottom: 0, - child: SizedBox( - width: screenWidth, - height: screenHeight / 2, - child: Opacity( - opacity: .2, - child: Image.asset( - "assets/pngs/emergency.png", - fit: BoxFit.cover, - ), - ), - )), - Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox( - height: blockSizeVertical * 6, - ), - Bounce( - from: 20, - infinite: true, - delay: const Duration(milliseconds: 800), - child: Stack( - alignment: AlignmentDirectional.topCenter, - children: [ - Container( - margin: const EdgeInsets.only(top: 20), - child: CircleAvatar( - radius: blockSizeVertical * 8, - backgroundColor: second, - child: Container( - margin: const EdgeInsets.only(top: 25), - child: SvgPicture.asset( - 'assets/svgs/sos.svg', - height: blockSizeHorizontal * 17, - color: Colors.white, - allowDrawingOutsideViewBox: true, - alignment: Alignment.bottomCenter, - ), - ), - ), - ), - Positioned( - top: blockSizeVertical * 3, - child: const SpinKitPulse( - color: primary, - size: 120, - ), - ), - ], + return Container( + padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 35), + height: screenHeight, + child: Stack( + children: [ + Positioned( + bottom: 0, + child: SizedBox( + width: screenWidth, + height: screenHeight / 2, + child: Opacity( + opacity: .2, + child: Image.asset( + "assets/pngs/emergency.png", + fit: BoxFit.cover, ), ), - const SizedBox(height: 16), - SlideInUp( - from: 50, - child: AutoSizeText( - sosReceived, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.displayMedium!.copyWith( - fontSize: 40, - color: third, - fontWeight: FontWeight.w500, - ), - ), - ), - const SizedBox( - height: 8, - ), - SlideInUp( - from: 50, - child: Container( - padding: const EdgeInsets.all(15), - decoration: const BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.all(Radius.circular(15))), - child: AutoSizeText( - sOSReceivedMessage, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.caption!.copyWith( - fontSize: 16, - color: Colors.black87, - ), - ), - ), - ), - const SizedBox( - height: 40, - ), - Expanded(child: Container()), - SlideInUp( - child: SizedBox( - height: 50, - width: 200, - child: TextButton( - style: mainBtnStyle(second, Colors.transparent, second), - onPressed: onpressed, - child: const Text(cancelRequest, - style: TextStyle( + )), + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + height: blockSizeVertical * 6, + ), + Bounce( + from: 20, + infinite: true, + delay: const Duration(milliseconds: 800), + child: Stack( + alignment: AlignmentDirectional.topCenter, + children: [ + Container( + margin: const EdgeInsets.only(top: 20), + child: CircleAvatar( + radius: blockSizeVertical * 8, + backgroundColor: second, + child: Container( + margin: const EdgeInsets.only(top: 25), + child: SvgPicture.asset( + 'assets/svgs/sos.svg', + height: blockSizeHorizontal * 17, color: Colors.white, - )), + allowDrawingOutsideViewBox: true, + alignment: Alignment.bottomCenter, + ), + ), + ), ), + Positioned( + top: blockSizeVertical * 3, + child: const SpinKitPulse( + color: primary, + size: 120, + ), + ), + ], + ), + ), + const SizedBox(height: 16), + SlideInUp( + from: 50, + child: AutoSizeText( + sosReceived, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.displayMedium!.copyWith( + fontSize: 40, + color: third, + fontWeight: FontWeight.w500, + ), + ), + ), + const SizedBox( + height: 8, + ), + SlideInUp( + from: 50, + child: Container( + padding: const EdgeInsets.all(15), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.all(Radius.circular(15))), + child: AutoSizeText( + sOSReceivedMessage, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium!.copyWith( + fontSize: 16, + color: Colors.black87, + ), ), - ) - ], - ), - ], - ), + ), + ), + const SizedBox( + height: 40, + ), + Expanded(child: Container()), + SlideInUp( + child: SizedBox( + height: 50, + width: 200, + child: TextButton( + style: mainBtnStyle(second, Colors.transparent, second), + onPressed: onpressed, + child: const Text(cancelRequest, + style: TextStyle( + color: Colors.white, + )), + ), + ), + ) + ], + ), + ], + ), ); } } diff --git a/lib/screens/superadmin/agency/agency_screen.dart b/lib/screens/superadmin/agency/agency_screen.dart index 57c88dc..d2eaf07 100644 --- a/lib/screens/superadmin/agency/agency_screen.dart +++ b/lib/screens/superadmin/agency/agency_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:fluttericon/font_awesome_icons.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:searchfield/searchfield.dart'; import 'package:unit2/bloc/rbac/rbac_operations/agency/agency_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; @@ -28,6 +29,7 @@ class RbacAgencyScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + List agencies = []; List agencyCategory = []; Category? selectedAgencyCategory; bool? isPrivate; @@ -38,7 +40,37 @@ class RbacAgencyScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Agencies"), - actions: [ + actions: context.watch().state is AgencyLoadingState || context.watch().state is AgencyErrorState || context.watch().state is AgencyAddesState?[]:[ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: primary), + builder: (Agency rbac) { + return Column( + children: [ + ListTile( + title: Text(rbac.name!), + ), + const Divider(), + ], + ); + }, + filter: (Agency rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Agency found :("), + ), + items: agencies, + searchLabel: "Search Agency", + suggestion: const Center( + child: Text("Search agency by name"), + )), + ); + }, + icon: const Icon(Icons.search)), AddLeading(onPressed: () { parent = context; showDialog( @@ -220,6 +252,7 @@ class RbacAgencyScreen extends StatelessWidget { builder: (context, state) { final parent = context; if (state is AgenciesLoaded) { + agencies = state.agencies; agencyCategory = state.agencyCategory; if (state.agencies.isNotEmpty) { return ListView.builder( @@ -262,7 +295,7 @@ class RbacAgencyScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Object available. Please click + to add."); + message: "No Agency available. Please click + to add."); } }if (state is AgencyErrorState) { return SomethingWentWrong( diff --git a/lib/screens/superadmin/assign_area/assign_area_screen.dart b/lib/screens/superadmin/assign_area/assign_area_screen.dart index c9fcd6d..0293f21 100644 --- a/lib/screens/superadmin/assign_area/assign_area_screen.dart +++ b/lib/screens/superadmin/assign_area/assign_area_screen.dart @@ -82,7 +82,7 @@ class _RbacAssignedAreaScreenState extends State { areaType = null; return AlertDialog( - title: const Text("Add New Role"), + title: const Text("Add New Assigned area"), content: FormBuilder( key: formKey, child: StatefulBuilder(builder: (context, setState) { @@ -1005,7 +1005,7 @@ class _RbacAssignedAreaScreenState extends State { if (state is AssignedAreaDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Assign Area Deleted Successfully", () { Navigator.of(context).pop(); context .read() @@ -1013,7 +1013,7 @@ class _RbacAssignedAreaScreenState extends State { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", + context, "Delete Failed", "Assign Area Deletion Failed", () { Navigator.of(context).pop(); context diff --git a/lib/screens/superadmin/module/module_screen.dart b/lib/screens/superadmin/module/module_screen.dart index 98d287f..554f1e4 100644 --- a/lib/screens/superadmin/module/module_screen.dart +++ b/lib/screens/superadmin/module/module_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/module/module_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/Leadings/add_leading.dart'; import 'package:unit2/widgets/error_state.dart'; @@ -23,83 +25,283 @@ class RbacModuleScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List modules = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Module Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Module name *", "Module name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacModule( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ModuleLoadingState || + context.watch().state is ModuleErrorState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleDeletedState || + context.watch().state is ModuleAddedState || + context.watch().state is ModuleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + const SizedBox( + width: 12, + ), + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Module name *", + "Module name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + ////Update + bloc.add(UpdateRbacModule( + moduleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + ////delete + Navigator.pop(context); + confirmAlert(context, () { + context + .read() + .add(DeleteRbacModule( + moduleId: + rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Module found :("), + ), + items: modules, + searchLabel: "Search Module", + suggestion: const Center( + child: Text("Search module by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Module name *", "Module name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacModule( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +364,7 @@ class RbacModuleScreen extends StatelessWidget { context.read().add(GetModule()); }); } else { - errorAlert(context, "Delete Failed", "Module Delete Failed", + errorAlert(context, "Delete Failed", "Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModule()); @@ -174,6 +376,7 @@ class RbacModuleScreen extends StatelessWidget { final parent = context; if (state is ModuleLoaded) { if (state.module.isNotEmpty) { + modules = state.module; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +393,22 @@ class RbacModuleScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.module[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.module[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +418,8 @@ class RbacModuleScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Module"), + title: + const Text("Update Module"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +563,7 @@ class RbacModuleScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Module available. Please click + to add."); } } if (state is ModuleErrorState) { diff --git a/lib/screens/superadmin/module_objects/module_objects_screen.dart b/lib/screens/superadmin/module_objects/module_objects_screen.dart index 30007d0..9cf11bb 100644 --- a/lib/screens/superadmin/module_objects/module_objects_screen.dart +++ b/lib/screens/superadmin/module_objects/module_objects_screen.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -33,106 +32,121 @@ class RbacModuleObjectsScreen extends StatelessWidget { List selectedValueItemObjects = []; final formKey = GlobalKey(); return Scaffold( - appBar: AppBar( centerTitle: true, elevation: 0, backgroundColor: primary, title: const Text("Module Object Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemObjects = objects.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add New Module Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "module", - decoration: - normalTextFieldStyle("Module", "Module"), - items: modules.isEmpty - ? [] - : modules.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedModule = object; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemObjects = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Objects", - padding: const EdgeInsets.all(8), - options: valueItemObjects, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemObjects.isNotEmpty) { - int assignerId = id; - int moduleId = selectedModule!.id!; - List objectId = []; - for (var object in objects) { - selectedValueItemObjects - .forEach((element) { - if (element.label.toLowerCase() == - object.name?.toLowerCase()) { - objectId.add(object.id!); + actions: context.watch().state + is ModuleObjectLoadingState || + context.watch().state + is ModuleObjectsErrorState || + context.watch().state + is ModuleObjectAddedState || + context.watch().state + is ModuleObjectDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemObjects = objects.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add New Module Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "module", + decoration: normalTextFieldStyle( + "Module", "Module"), + items: modules.isEmpty + ? [] + : modules.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedModule = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemObjects = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Objects", + padding: const EdgeInsets.all(8), + options: valueItemObjects, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemObjects + .isNotEmpty) { + int assignerId = id; + int moduleId = selectedModule!.id!; + List objectId = []; + for (var object in objects) { + selectedValueItemObjects + .forEach((element) { + if (element.label + .toLowerCase() == + object.name + ?.toLowerCase()) { + objectId.add(object.id!); + } + }); + } + Navigator.of(context).pop(); + parent + .read() + .add(AddRbacModuleObjects( + assignerId: assignerId, + moduleId: moduleId, + objectsId: objectId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRbacModuleObjects( - assignerId: assignerId, - moduleId: moduleId, - objectsId: objectId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -140,7 +154,6 @@ class RbacModuleObjectsScreen extends StatelessWidget { indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer( listener: (context, state) { - if (state is ModuleObjectLoadingState) { final progress = ProgressHUD.of(context); progress!.showWithText("Please wait..."); @@ -157,13 +170,13 @@ class RbacModuleObjectsScreen extends StatelessWidget { if (state is ModuleObjectDeletedState) { if (state.success) { successAlert( - context, "Delete Successfull!", "Role Deleted Successfully", + context, "Delete Successfull!", "Module Object Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); } else { - errorAlert(context, "Delete Failed", "Role Delete Failed", () { + errorAlert(context, "Delete Failed", "Module Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetModuleObjects()); }); @@ -270,20 +283,23 @@ class RbacModuleObjectsScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: + "No Module Object available. Please click + to add."); } } if (state is ModuleObjectsErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent.read().add(GetModuleObjects()); + message: state.message, + onpressed: () { + parent.read().add(GetModuleObjects()); }); } return Container(); diff --git a/lib/screens/superadmin/object/object_screen.dart b/lib/screens/superadmin/object/object_screen.dart index 7a4640c..a042645 100644 --- a/lib/screens/superadmin/object/object_screen.dart +++ b/lib/screens/superadmin/object/object_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,83 +26,274 @@ class RbacObjectScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List objects = []; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: primary, title: const Text("Objects Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Object"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Object name *", "Object name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacObject( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is ObjectLoadingState || + context.watch().state is ObjectAddedState || + context.watch().state is ObjectErrorState || + context.watch().state is ObjectDeletedState || + context.watch().state is ObjectUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Object name *", + "Object name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacObject( + objectId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacObject( + objectId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: objects, + searchLabel: "Search Object", + suggestion: const Center( + child: Text("Search object by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Object"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Object name *", "Object name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacObject( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,7 +355,7 @@ class RbacObjectScreen extends StatelessWidget { context.read().add(GetObjects()); }); } else { - errorAlert(context, "Delete Failed", "Object Delete Failed", + errorAlert(context, "Delete Failed", "Object Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetObjects()); @@ -174,6 +367,7 @@ class RbacObjectScreen extends StatelessWidget { final parent = context; if (state is ObjectLoaded) { if (state.objects.isNotEmpty) { + objects = state.objects; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), diff --git a/lib/screens/superadmin/operation/operation_screen.dart b/lib/screens/superadmin/operation/operation_screen.dart index 6b4a6bb..f00a3c9 100644 --- a/lib/screens/superadmin/operation/operation_screen.dart +++ b/lib/screens/superadmin/operation/operation_screen.dart @@ -5,7 +5,9 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; +import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/widgets/error_state.dart'; import '../../../theme-data.dart/box_shadow.dart'; @@ -24,82 +26,276 @@ class RbacOperationScreen extends StatelessWidget { @override Widget build(BuildContext context) { final formKey = GlobalKey(); + final bloc = BlocProvider.of(context); + List operations = []; return Scaffold( appBar: AppBar( backgroundColor: primary, title: const Text("Operations Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Operation"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Operation name *", "Operation name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), + centerTitle: true, + actions: context.watch().state + is OperationLoadingState || + context.watch().state is OperationErrorState || + context.watch().state is OperationAddedState || + context.watch().state is OperationDeletedState || + context.watch().state is OperationUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: + (BuildContext context) { + return AlertDialog( + title: const Text( + "Update Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize.min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Operation name *", + "Operation name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: rbac + .shorthand, + validator: FormBuilderValidators + .maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: + normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: + ElevatedButton( + style: mainBtnStyle( + primary, + Colors + .transparent, + second), + onPressed: + () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacOperation( + operationId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text( + "Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + context + .read() + .add(DeleteRbacOperation( + operationId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Operation found :("), + ), + items: operations, + searchLabel: "Search Operation", + suggestion: const Center( + child: Text("Search operation by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Operation"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Operation name *", "Operation name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: FormBuilderValidators.maxLength(50, + errorText: "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey.currentState! + .value['object_name']; + String? slug = formKey + .currentState!.value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacOperation( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add( - AddRbacOperation( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -162,8 +358,8 @@ class RbacOperationScreen extends StatelessWidget { context.read().add(GetOperations()); }); } else { - errorAlert(context, "Delete Failed", "Operation Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Operation Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetOperations()); }); @@ -174,6 +370,7 @@ class RbacOperationScreen extends StatelessWidget { final parent = context; if (state is OperationsLoaded) { if (state.operations.isNotEmpty) { + operations = state.operations; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -190,18 +387,22 @@ class RbacOperationScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar(child: Text('${index+1}'),), - const SizedBox(width: 12,), - Text(state.operations[index].name!, - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ], - )), + children: [ + CircleAvatar( + child: Text('${index + 1}'), + ), + const SizedBox( + width: 12, + ), + Text(state.operations[index].name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, @@ -211,7 +412,8 @@ class RbacOperationScreen extends StatelessWidget { context: context, builder: (BuildContext context) { return AlertDialog( - title: const Text("Update Operation"), + title: const Text( + "Update Operation"), content: FormBuilder( key: formKey, child: Column( @@ -355,7 +557,7 @@ class RbacOperationScreen extends StatelessWidget { }); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Operation available. Please click + to add."); } } if (state is OperationErrorState) { diff --git a/lib/screens/superadmin/permission/permission_screen.dart b/lib/screens/superadmin/permission/permission_screen.dart index 0400599..90d25ea 100644 --- a/lib/screens/superadmin/permission/permission_screen.dart +++ b/lib/screens/superadmin/permission/permission_screen.dart @@ -7,7 +7,9 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:search_page/search_page.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/model/rbac/permission.dart'; import 'package:unit2/model/rbac/rbac.dart'; import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -32,6 +34,8 @@ class RbacPermissionScreen extends StatelessWidget { List operations = []; List valueItemOperations = []; List selectedValueItemOperations = []; + List permissions = []; + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); BuildContext? parent; return Scaffold( @@ -39,105 +43,189 @@ class RbacPermissionScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Permissions Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemOperations = operations.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Permission"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "object", - decoration: - normalTextFieldStyle("Permission", "Permission"), - items: objects.isEmpty - ? [] - : objects.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? object) { - selectedObject = object; - }, + actions: context.watch().state is PermissonLoadingState || + context.watch().state is PermissionErrorState || + context.watch().state is PermissionDeletedState || + context.watch().state is PermissionAddedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBACPermission rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Text( + "${rbac.object?.name} - ${rbac.operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight.w500, + color: primary)), + ), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc.add(DeleteRbacPermission( + permissionId: rbac.id!)); + }, "Delete?", "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBACPermission rbac) { + return [ + rbac.object!.name! + rbac.operation!.name! + ]; + }, + failure: const Center( + child: Text("No permission found :("), ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemOperations = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Operations", - padding: const EdgeInsets.all(8), - options: valueItemOperations, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemOperations - .isNotEmpty) { - int assignerId = id; - int objectId = selectedObject!.id!; + items: permissions, + searchLabel: "Search Permission", + suggestion: const Center( + child: Text("Search permission by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemOperations = operations.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "object", + decoration: normalTextFieldStyle( + "Permission", "Permission"), + items: objects.isEmpty + ? [] + : objects.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? object) { + selectedObject = object; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemOperations = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemOperations, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemOperations + .isNotEmpty) { + int assignerId = id; + int objectId = selectedObject!.id!; - List opIds = []; - for (var operation in operations) { - selectedValueItemOperations - .forEach((element) { - if (element.label.toLowerCase() == - operation.name?.toLowerCase()) { - opIds.add(operation.id!); + List opIds = []; + for (var operation in operations) { + selectedValueItemOperations + .forEach((element) { + if (element.label + .toLowerCase() == + operation.name + ?.toLowerCase()) { + opIds.add(operation.id!); + } + }); + } + + Navigator.pop(context); + parent!.read().add( + AddRbacPermission( + assignerId: assignerId, + objectId: objectId, + operationIds: opIds)); } - }); - } - opIds.forEach((element) { - print(element); - }); - Navigator.pop(context); - parent!.read().add( - AddRbacPermission( - assignerId: assignerId, - objectId: objectId, - operationIds: opIds)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -181,8 +269,8 @@ class RbacPermissionScreen extends StatelessWidget { context.read().add(GetPermissions()); }); } else { - errorAlert(context, "Delete Failed", "Permission Delete Failed", - () { + errorAlert( + context, "Delete Failed", "Permission Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetPermissions()); }); @@ -195,6 +283,7 @@ class RbacPermissionScreen extends StatelessWidget { objects = state.objects; operations = state.operations; if (state.permissions.isNotEmpty) { + permissions = state.permissions; return ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10), @@ -211,41 +300,39 @@ class RbacPermissionScreen extends StatelessWidget { children: [ Expanded( child: Row( - children: [ - CircleAvatar( + children: [ + CircleAvatar( child: Text('${index + 1}'), ), const SizedBox( width: 12, ), - Flexible( - child: Text( - "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith( - fontWeight: FontWeight.w500, - color: primary)), - ), - ], - )), + Flexible( + child: Text( + "${state.permissions[index].object?.name} - ${state.permissions[index].operation?.name}", + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + )), AppPopupMenu( offset: const Offset(-10, -10), elevation: 3, onSelected: (value) { - if (value == 1) { - + if (value == 1) { confirmAlert(context, () { - context.read().add( - DeleteRbacPermission( - permissionId: state.permissions[index].id!)); + context.read().add( + DeleteRbacPermission( + permissionId: state + .permissions[index].id!)); }, "Delete?", "Confirm Delete?"); - } }, menuItems: [ - popMenuItem( text: "Remove", value: 1, @@ -273,8 +360,9 @@ class RbacPermissionScreen extends StatelessWidget { } if (state is PermissionErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - parent!.read().add(GetPermissions()); + message: state.message, + onpressed: () { + parent!.read().add(GetPermissions()); }); } return Container(); diff --git a/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart new file mode 100644 index 0000000..07aa98d --- /dev/null +++ b/lib/screens/superadmin/permission_assignment/permission_assignment_screen.dart @@ -0,0 +1,325 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart'; +import 'package:unit2/model/rbac/permission.dart'; +import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/theme-data.dart/btn-style.dart'; +import 'package:unit2/theme-data.dart/colors.dart'; +import 'package:unit2/theme-data.dart/form-style.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/empty_data.dart'; +import 'package:unit2/widgets/error_state.dart'; + +class RbacPermissionAssignmentScreen extends StatelessWidget { + final int id; + const RbacPermissionAssignmentScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> permissionAssignments = {}; + List permissions = []; + List valueItemPermission = []; + List selectedValueItemPermission = []; + List roles = []; + RBAC? selectedRole; + + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Permission Assignment"), + actions: context.watch().state + is PermissionAssignmentLoadingScreen || + context.watch().state + is PermissionAssignmentErrorState || + context.watch().state + is PermissionAssignmentAddedState || + context.watch().state + is PermissionAssignmentDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + valueItemPermission = permissions.map((e) { + return ValueItem( + label: "${e.object!.name} - ${e.operation!.name}", + value: e.id.toString()); + }).toList(); + return AlertDialog( + title: const Text("Add Permission"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemPermission = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Operations", + padding: const EdgeInsets.all(8), + options: valueItemPermission, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemPermission + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List opIds = + selectedValueItemPermission + .map((e) { + return int.parse(e.value!); + }).toList(); + Navigator.pop(context); + parent + .read< + PermissionAssignmentBloc>() + .add(AddPersmissionAssignment( + assignerId: assignerId, + opsId: opIds, + roleId: roleId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: + BlocConsumer( + listener: (context, state) { + if (state is PermissionAssignmentLoadingScreen) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is PermissionAssignmentErrorState || + state is PermissionAssignmentLoadedState || + state is PermissionAssignmentAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + if (state is PermissionAssignmentDeletedState) { + if (state.success) { + successAlert(context, "Delete Successfull!", + "Permission Assignment Deleted Successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } else { + errorAlert(context, "Delete Failed", + "Permission Assignment Deletion Failed", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } + } + if (state is PermissionAssignmentAddedState) { + if (state.status['success']) { + successAlert(context, "Add Successfull!", + "Permission Assignment Added Successfully", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } else { + errorAlert(context, "Adding Failed", + "Permission Assignment Adding Failed", () { + Navigator.of(context).pop(); + context + .read() + .add(GetPermissionAssignments()); + }); + } + } + }, + builder: (context, state) { + if (state is PermissionAssignmentLoadedState) { + if (state.permissionAssignments.isNotEmpty) { + permissions = state.permissions; + roles = state.roles; + permissionAssignments = {}; + for (var permissionAssignment in state.permissionAssignments) { + if (!permissionAssignments.keys.contains( + permissionAssignment.role!.name!.toLowerCase())) { + permissionAssignments.addAll( + {permissionAssignment.role!.name!.toLowerCase(): []}); + permissionAssignments[ + permissionAssignment.role!.name!.toLowerCase()]! + .add(Content( + id: permissionAssignment.id!, + name: + "${permissionAssignment.permission!.object!.name} - ${permissionAssignment.permission!.operation!.name} ")); + } else { + permissionAssignments[ + permissionAssignment.role!.name!.toLowerCase()]! + .add(Content( + id: permissionAssignment.id!, + name: + "${permissionAssignment.permission!.object!.name} - ${permissionAssignment.permission!.operation!.name} ")); + } + } + return GroupListView( + sectionsCount: permissionAssignments.keys.toList().length, + countOfItemInSection: (int section) { + return permissionAssignments.values + .toList()[section] + .length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + dense: true, + trailing: IconButton( + color: Colors.grey.shade600, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context, () { + context.read().add( + DeletePermissionAssignment( + id: permissionAssignments.values + .toList()[index.section][index.index] + .id)); + }, "Delete?", "Confirm Delete?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + permissionAssignments.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: primary), + ), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: Colors.white, + title: Text( + permissionAssignments.keys + .toList()[section] + .toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + const EmptyData( + message: + "Permission Assignment available. Please click + to add", + ); + } + } + if (state is PermissionAssignmentErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context + .read() + .add(GetPermissionAssignments()); + }); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/role/role_screen.dart b/lib/screens/superadmin/role/role_screen.dart index 03e055c..f6553e9 100644 --- a/lib/screens/superadmin/role/role_screen.dart +++ b/lib/screens/superadmin/role/role_screen.dart @@ -25,6 +25,7 @@ class RbacRoleScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final bloc = BlocProvider.of(context); final formKey = GlobalKey(); List roles = []; return Scaffold( @@ -32,102 +33,274 @@ class RbacRoleScreen extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("Role Screen"), - actions: [ - IconButton( - onPressed: () { - showSearch( - context: context, - delegate: SearchPage( - barTheme: ThemeData(cardColor: primary), - builder: (RBAC rbac) { - return ListTile( - title: Text(rbac.name!), - ); - }, - filter: (RBAC rbac) { - return [rbac.name]; - }, - failure: const Center( - child: Text("No Role found :("), - ), - items: roles, - searchLabel: "Search Role", - suggestion: const Center( - child: Text("Search role by name"), - )), - ); - }, - icon: const Icon(Icons.search)), - AddLeading(onPressed: () { - BuildContext parent = context; - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Role"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderTextField( - name: "object_name", - decoration: normalTextFieldStyle( - "Role name *", "Role name "), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - name: "slug", - decoration: normalTextFieldStyle("Slug ", "Slug"), - ), - const SizedBox( - height: 8, - ), - FormBuilderTextField( - validator: FormBuilderValidators.maxLength(50, - errorText: "Max characters only 50"), - name: "shorthand", - decoration: - normalTextFieldStyle("Shorthand ", "Shorthand"), - ), - const SizedBox( - height: 12, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate()) { - String name = formKey - .currentState!.value['object_name']; - String? slug = - formKey.currentState!.value['slug']; - String? short = formKey - .currentState!.value['shorthand']; - parent.read().add(AddRbacRole( - id: id, - name: name, - shorthand: short, - slug: slug)); - Navigator.pop(context); - } - }, - child: const Text("Add"))), - ], - ), - ), - ); - }); - }) - ], + actions: + context.watch().state is RoleLoadingState || + context.watch().state is RoleErrorState || + context.watch().state is RoleDeletedState? || + context.watch().state is RoleAddedState? || + context.watch().state is RoleUpdatedState + ? [] + : [ + IconButton( + onPressed: () { + showSearch( + context: context, + delegate: SearchPage( + barTheme: ThemeData(cardColor: Colors.white), + builder: (RBAC rbac) { + return Column( + children: [ + Container( + width: screenWidth, + decoration: box1(), + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + Flexible( + child: Text(rbac.name!, + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + fontWeight: + FontWeight + .w500, + color: primary)), + ), + ], + )), + AppPopupMenu( + offset: const Offset(-10, -10), + elevation: 3, + onSelected: (value) { + if (value == 2) { + showDialog( + context: context, + builder: (BuildContext + context) { + return AlertDialog( + title: const Text( + "Update Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: + MainAxisSize + .min, + children: [ + FormBuilderTextField( + initialValue: + rbac.name, + name: + "object_name", + decoration: normalTextFieldStyle( + "Role name *", + "Role name "), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.slug, + name: "slug", + decoration: + normalTextFieldStyle( + "Slug ", + "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + initialValue: + rbac.shorthand, + validator: FormBuilderValidators + .maxLength( + 50, + errorText: + "Max characters only 50"), + name: + "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", + "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double + .infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, Colors.transparent, second), + onPressed: () { + if (formKey + .currentState! + .saveAndValidate()) { + Navigator.pop(context); + String + name = + formKey.currentState!.value['object_name']; + String? + slug = + formKey.currentState!.value['slug']; + String? + short = + formKey.currentState!.value['shorthand']; + + bloc.add(UpdateRbacRole( + roleId: rbac.id!, + name: name, + slug: slug, + short: short, + createdBy: rbac.createdBy?.id, + updatedBy: id)); + Navigator.pop(context); + } + }, + child: const Text("Update"))), + ], + ), + ), + ); + }); + } + if (value == 1) { + confirmAlert(context, () { + Navigator.pop(context); + bloc + .add(DeleteRbacRole( + roleId: rbac.id!)); + }, "Delete?", + "Confirm Delete?"); + } + }, + menuItems: [ + popMenuItem( + text: "Update", + value: 2, + icon: Icons.edit), + popMenuItem( + text: "Remove", + value: 1, + icon: Icons.delete), + ], + icon: const Icon( + Icons.more_vert, + color: Colors.grey, + ), + tooltip: "Options", + ), + ], + ), + ), + const SizedBox( + height: 5, + ) + ], + ); + }, + filter: (RBAC rbac) { + return [rbac.name]; + }, + failure: const Center( + child: Text("No Role found :("), + ), + items: roles, + searchLabel: "Search Role", + suggestion: const Center( + child: Text("Search role by name"), + )), + ); + }, + icon: const Icon(Icons.search)), + AddLeading(onPressed: () { + BuildContext parent = context; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Role"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderTextField( + name: "object_name", + decoration: normalTextFieldStyle( + "Role name *", "Role name "), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + name: "slug", + decoration: + normalTextFieldStyle("Slug ", "Slug"), + ), + const SizedBox( + height: 8, + ), + FormBuilderTextField( + validator: + FormBuilderValidators.maxLength(50, + errorText: + "Max characters only 50"), + name: "shorthand", + decoration: normalTextFieldStyle( + "Shorthand ", "Shorthand"), + ), + const SizedBox( + height: 12, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate()) { + String name = formKey + .currentState! + .value['object_name']; + String? slug = formKey + .currentState! + .value['slug']; + String? short = formKey + .currentState! + .value['shorthand']; + parent.read().add( + AddRbacRole( + id: id, + name: name, + shorthand: short, + slug: slug)); + Navigator.pop(context); + } + }, + child: const Text("Add"))), + ], + ), + ), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), diff --git a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart index b09f086..39004ea 100644 --- a/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart +++ b/lib/screens/superadmin/role_assignment.dart/role_assignment_screen.dart @@ -36,7 +36,7 @@ class RbacRoleAssignment extends StatelessWidget { centerTitle: true, backgroundColor: primary, title: const Text("User Roles Screens"), - actions: [ + actions: context.watch().state is RoleAssignmentLoadingState || context.watch().state is RoleAssignmentErrorState || context.watch().state is UserNotExistError || context.watch().state is RoleAddedState? []: [ AddLeading(onPressed: () { BuildContext parent = context; showDialog( @@ -131,13 +131,13 @@ class RbacRoleAssignment extends StatelessWidget { if (state is AssignedRoleDeletedState) { if (state.success) { successAlert(context, "Delete Successfull!", - "Role Module Deleted Successfully", () { + "Role Deleted Successfully", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Deletion Failed", () { Navigator.of(context).pop(); context.read().add(LoadAssignedRole()); }); diff --git a/lib/screens/superadmin/role_extend/role_extend_screen.dart b/lib/screens/superadmin/role_extend/role_extend_screen.dart index 2640660..3c5787a 100644 --- a/lib/screens/superadmin/role_extend/role_extend_screen.dart +++ b/lib/screens/superadmin/role_extend/role_extend_screen.dart @@ -36,7 +36,7 @@ class RbacRoleExtendScreen extends StatelessWidget { elevation: 0, backgroundColor: primary, title: const Text("Role Extend"), - actions: [ + actions: context.watch().state is RoleExtendLoadingState || context.watch().state is RoleExtendErrorState || context.watch().state is RoleExtendAddedState || context.watch().state is RoleExtendDeletedState? []:[ AddLeading(onPressed: () { showDialog( context: NavigationService.navigatorKey.currentState!.context, @@ -49,6 +49,7 @@ class RbacRoleExtendScreen extends StatelessWidget { content: FormBuilder( key: formKey, child: Column( + mainAxisSize: MainAxisSize.min, children: [ FormBuilderDropdown( diff --git a/lib/screens/superadmin/role_module/role_module_scree.dart b/lib/screens/superadmin/role_module/role_module_scree.dart index a71ae81..8a97b7f 100644 --- a/lib/screens/superadmin/role_module/role_module_scree.dart +++ b/lib/screens/superadmin/role_module/role_module_scree.dart @@ -34,100 +34,114 @@ class RbacRoleModuleScreen extends StatelessWidget { return Scaffold( appBar: AppBar( backgroundColor: primary, - title: const Text("Role Modules Screen"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemModules = modules.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Module"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle("Role", "Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemModules = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Modules", - padding: const EdgeInsets.all(8), - options: valueItemModules, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemModules.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List modulesId = []; - for (var module in modules) { - selectedValueItemModules - .forEach((element) { - if (element.label.toLowerCase() == - module.name?.toLowerCase()) { - modulesId.add(module.id!); + title: const Text("Role Module Screen" ), + centerTitle: true, + actions: context.watch().state + is RoleModuleLoadingState || + context.watch().state is RoleModuleErrorState || + context.watch().state is RoleModuleAddedState || + context.watch().state is RoleModuleDeletedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemModules = modules.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Module"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: + normalTextFieldStyle("Role", "Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemModules = + selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Modules", + padding: const EdgeInsets.all(8), + options: valueItemModules, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemModules + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List modulesId = []; + for (var module in modules) { + selectedValueItemModules + .forEach((element) { + if (element.label + .toLowerCase() == + module.name + ?.toLowerCase()) { + modulesId.add(module.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleModule( + assignerId: assignerId, + roleId: roleId, + moduleIds: modulesId)); } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleModule( - assignerId: assignerId, - roleId: roleId, - moduleIds: modulesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -156,7 +170,7 @@ class RbacRoleModuleScreen extends StatelessWidget { }); } else { errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { + context, "Delete Failed", "Role Module Deletion Failed", () { Navigator.of(context).pop(); context.read().add(GetRoleModules()); }); @@ -258,20 +272,22 @@ class RbacRoleModuleScreen extends StatelessWidget { style: Theme.of(context) .textTheme .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), + .copyWith( + color: primary, fontWeight: FontWeight.bold), ), ); }, ); } else { return const EmptyData( - message: "No Role available. Please click + to add."); + message: "No Role Module available. Please click + to add."); } } if (state is RoleModuleErrorState) { return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRoleModules()); + message: state.message, + onpressed: () { + context.read().add(GetRoleModules()); }); } return Container(); diff --git a/lib/screens/superadmin/roles_under/assignable_roles.dart b/lib/screens/superadmin/roles_under/assignable_roles.dart new file mode 100644 index 0000000..5698cc7 --- /dev/null +++ b/lib/screens/superadmin/roles_under/assignable_roles.dart @@ -0,0 +1,307 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:flutter_spinkit/flutter_spinkit.dart'; +import 'package:form_builder_validators/form_builder_validators.dart'; +import 'package:group_list_view/group_list_view.dart'; +import 'package:multi_dropdown/multiselect_dropdown.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; +import 'package:unit2/widgets/Leadings/add_leading.dart'; +import 'package:unit2/widgets/error_state.dart'; +import '../../../model/rbac/rbac.dart'; +import '../../../theme-data.dart/btn-style.dart'; +import '../../../theme-data.dart/colors.dart'; +import '../../../theme-data.dart/form-style.dart'; +import '../../../utils/alerts.dart'; +import '../../../utils/global_context.dart'; +import '../../../widgets/empty_data.dart'; + +class RbacRoleUnderScreen extends StatelessWidget { + final int id; + const RbacRoleUnderScreen({super.key, required this.id}); + + @override + Widget build(BuildContext context) { + final parent = context; + Map> rolesUnder = {}; + List roles = []; + RBAC? selectedRole; + List valueItemRoles = []; + List selectedValueItemRoles = []; + final formKey = GlobalKey(); + return Scaffold( + appBar: AppBar( + centerTitle: true, + backgroundColor: primary, + title: const Text("Assignable Roles"), + actions: context.watch().state + is RoleUnderLoadingState? || + context.watch().state is RoleUnderErrorState || + context.watch().state + is RoleUnderDeletedState || + context.watch().state is RoleUnderAddedState + ? [] + : [ + AddLeading(onPressed: () { + showDialog( + context: + NavigationService.navigatorKey.currentState!.context, + builder: (BuildContext context) { + valueItemRoles = roles.map((e) { + return ValueItem(label: e.name!, value: e.name); + }).toList(); + return AlertDialog( + title: const Text("Add Role Under"), + content: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FormBuilderDropdown( + validator: FormBuilderValidators.required( + errorText: "This field is required"), + name: "role", + decoration: normalTextFieldStyle( + "Main Role", "Main Role"), + items: roles.isEmpty + ? [] + : roles.map((e) { + return DropdownMenuItem( + value: e, child: Text(e.name!)); + }).toList(), + onChanged: (RBAC? role) { + selectedRole = role; + }, + ), + const SizedBox( + height: 12, + ), + MultiSelectDropDown( + onOptionSelected: + (List selectedOptions) { + selectedValueItemRoles = selectedOptions; + }, + borderColor: Colors.grey, + borderWidth: 1, + borderRadius: 5, + hint: "Roles Under", + padding: const EdgeInsets.all(8), + options: valueItemRoles, + selectionType: SelectionType.multi, + chipConfig: const ChipConfig( + wrapType: WrapType.wrap), + dropdownHeight: 300, + optionTextStyle: + const TextStyle(fontSize: 16), + selectedOptionIcon: + const Icon(Icons.check_circle), + ), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.maxFinite, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + if (formKey.currentState! + .saveAndValidate() && + selectedValueItemRoles + .isNotEmpty) { + int assignerId = id; + int roleId = selectedRole!.id!; + List rolesId = []; + for (var role in roles) { + selectedValueItemRoles + .forEach((element) { + if (element.label + .toLowerCase() == + role.name?.toLowerCase()) { + rolesId.add(role.id!); + } + }); + } + Navigator.of(context).pop(); + parent.read().add( + AddRoleUnder( + roleId: roleId, + roleUnderIds: rolesId)); + } + }, + child: const Text("Submit")), + ) + ], + )), + ); + }); + }) + ], + ), + body: ProgressHUD( + padding: const EdgeInsets.all(24), + backgroundColor: Colors.black87, + indicatorWidget: const SpinKitFadingCircle(color: Colors.white), + child: BlocConsumer( + listener: (context, state) { + if (state is RoleUnderLoadingState) { + final progress = ProgressHUD.of(context); + progress!.showWithText("Please wait..."); + } + if (state is RoleUnderLoadedState || + state is RoleUnderErrorState || + state is RoleUnderDeletedState || + state is RoleUnderAddedState) { + final progress = ProgressHUD.of(context); + progress!.dismiss(); + } + + ////Deleted State + if (state is RoleUnderDeletedState) { + if (state.success) { + successAlert( + context, "Delete Successfull!", "Role Deleted Successfully", + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert( + context, "Delete Failed", "Role Module Delete Failed", () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + ////Added State + if (state is RoleUnderAddedState) { + if (state.response['success']) { + successAlert( + context, "Adding Successfull!", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } else { + errorAlert(context, "Adding Failed", state.response['message'], + () { + Navigator.of(context).pop(); + context.read().add(GetRolesUnder()); + }); + } + } + }, + builder: (context, state) { + if (state is RoleUnderLoadedState) { + rolesUnder = {}; + roles = state.roles; + + if (state.rolesUnder.isNotEmpty) { + for (var roleUnder in state.rolesUnder) { + if (!rolesUnder.keys + .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { + rolesUnder.addAll( + {roleUnder.roleUnderMain.name!.toLowerCase(): []}); + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } else { + rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! + .add(Content( + id: roleUnder.id, + name: roleUnder.roleUnderChild.name!)); + } + } + } + + if (state.rolesUnder.isNotEmpty) { + return GroupListView( + sectionsCount: rolesUnder.keys.toList().length, + countOfItemInSection: (int section) { + return rolesUnder.values.toList()[section].length; + }, + itemBuilder: (BuildContext context, IndexPath index) { + return ListTile( + trailing: IconButton( + color: Colors.grey.shade500, + icon: const Icon(Icons.delete), + onPressed: () { + confirmAlert(context,(){ + context.read().add(DeleteRoleUnder(roleUnderId:rolesUnder.values .toList()[index.section][index.index].id)); + }, "Delete", "Delete Role?"); + }, + ), + title: Row( + children: [ + CircleAvatar( + child: Text("${index.index + 1}", + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith(color: Colors.white))), + const SizedBox( + width: 20, + ), + Expanded( + child: Text( + rolesUnder.values + .toList()[index.section][index.index] + .name + .toUpperCase(), + style: Theme.of(context) + .textTheme + .labelLarge! + .copyWith( + fontWeight: FontWeight.w500, + color: primary)), + ), + ], + ), + ); + }, + separatorBuilder: (context, index) { + return const Divider(); + }, + groupHeaderBuilder: (BuildContext context, int section) { + return ListTile( + tileColor: Colors.white, + dense: true, + title: Text( + rolesUnder.keys.toList()[section].toUpperCase(), + style: Theme.of(context) + .textTheme + .titleMedium! + .copyWith( + color: primary, fontWeight: FontWeight.bold), + ), + ); + }, + ); + } else { + return const EmptyData( + message: "No Role available. Please click + to add."); + } + } + if (state is RoleUnderErrorState) { + return SomethingWentWrong( + message: state.message, + onpressed: () { + context.read().add(GetRolesUnder()); + }); + } + return Container(); + }, + ), + ), + ); + } +} + +class Content { + final int id; + final String name; + const Content({required this.id, required this.name}); +} diff --git a/lib/screens/superadmin/roles_under/roles_under_screen.dart b/lib/screens/superadmin/roles_under/roles_under_screen.dart deleted file mode 100644 index 6f82a78..0000000 --- a/lib/screens/superadmin/roles_under/roles_under_screen.dart +++ /dev/null @@ -1,296 +0,0 @@ - -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_progress_hud/flutter_progress_hud.dart'; -import 'package:flutter_spinkit/flutter_spinkit.dart'; -import 'package:form_builder_validators/form_builder_validators.dart'; -import 'package:group_list_view/group_list_view.dart'; -import 'package:multi_dropdown/multiselect_dropdown.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/roles_under/roles_under_bloc.dart'; -import 'package:unit2/widgets/Leadings/add_leading.dart'; -import 'package:unit2/widgets/error_state.dart'; -import '../../../model/rbac/rbac.dart'; -import '../../../theme-data.dart/btn-style.dart'; -import '../../../theme-data.dart/colors.dart'; -import '../../../theme-data.dart/form-style.dart'; -import '../../../utils/alerts.dart'; -import '../../../utils/global_context.dart'; -import '../../../widgets/empty_data.dart'; - -class RbacRoleUnderScreen extends StatelessWidget { - final int id; - const RbacRoleUnderScreen({super.key, required this.id}); - - @override - Widget build(BuildContext context) { - final parent = context; - Map> rolesUnder = {}; - List roles = []; - RBAC? selectedRole; - List valueItemRoles = []; - List selectedValueItemRoles = []; - final formKey = GlobalKey(); - return Scaffold( - appBar: AppBar( - centerTitle: true, - backgroundColor: primary, - title: const Text("Assignable Roles"), - actions: [ - AddLeading(onPressed: () { - showDialog( - context: NavigationService.navigatorKey.currentState!.context, - builder: (BuildContext context) { - valueItemRoles = roles.map((e) { - return ValueItem(label: e.name!, value: e.name); - }).toList(); - return AlertDialog( - title: const Text("Add Role Under"), - content: FormBuilder( - key: formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FormBuilderDropdown( - validator: FormBuilderValidators.required( - errorText: "This field is required"), - name: "role", - decoration: normalTextFieldStyle( - "Main Role", "Main Role"), - items: roles.isEmpty - ? [] - : roles.map((e) { - return DropdownMenuItem( - value: e, child: Text(e.name!)); - }).toList(), - onChanged: (RBAC? role) { - selectedRole = role; - }, - ), - const SizedBox( - height: 12, - ), - MultiSelectDropDown( - onOptionSelected: - (List selectedOptions) { - selectedValueItemRoles = selectedOptions; - }, - borderColor: Colors.grey, - borderWidth: 1, - borderRadius: 5, - hint: "Roles Under", - padding: const EdgeInsets.all(8), - options: valueItemRoles, - selectionType: SelectionType.multi, - chipConfig: - const ChipConfig(wrapType: WrapType.wrap), - dropdownHeight: 300, - optionTextStyle: const TextStyle(fontSize: 16), - selectedOptionIcon: - const Icon(Icons.check_circle), - ), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.maxFinite, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - if (formKey.currentState! - .saveAndValidate() && - selectedValueItemRoles.isNotEmpty) { - int assignerId = id; - int roleId = selectedRole!.id!; - List rolesId = []; - for (var role in roles) { - selectedValueItemRoles - .forEach((element) { - if (element.label.toLowerCase() == - role.name?.toLowerCase()) { - rolesId.add(role.id!); - } - }); - } - Navigator.of(context).pop(); - parent.read().add( - AddRoleUnder( - roleId: roleId, - roleUnderIds: rolesId)); - } - }, - child: const Text("Submit")), - ) - ], - )), - ); - }); - }) - ], - ), - body: ProgressHUD( - padding: const EdgeInsets.all(24), - backgroundColor: Colors.black87, - indicatorWidget: const SpinKitFadingCircle(color: Colors.white), - child: BlocConsumer( - listener: (context, state) { - if (state is RoleUnderLoadingState) { - final progress = ProgressHUD.of(context); - progress!.showWithText("Please wait..."); - } - if (state is RoleUnderLoadedState || - state is RoleUnderErrorState || - state is RoleUnderDeletedState || - state is RoleUnderAddedState) { - final progress = ProgressHUD.of(context); - progress!.dismiss(); - } - - ////Deleted State - if (state is RoleUnderDeletedState) { - if (state.success) { - successAlert(context, "Delete Successfull!", - "Role Deleted Successfully", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert( - context, "Delete Failed", "Role Module Delete Failed", () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - ////Added State - if (state is RoleUnderAddedState) { - if (state.response['success']) { - successAlert( - context, "Adding Successfull!", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } else { - errorAlert(context, "Adding Failed", state.response['message'], - () { - Navigator.of(context).pop(); - context.read().add(GetRolesUnder()); - }); - } - } - }, - builder: (context, state) { - if (state is RoleUnderLoadedState) { - rolesUnder = {}; - roles = state.roles; - - if (state.rolesUnder.isNotEmpty) { - for (var roleUnder in state.rolesUnder) { - if (!rolesUnder.keys - .contains(roleUnder.roleUnderMain.name!.toLowerCase())) { - rolesUnder.addAll( - {roleUnder.roleUnderMain.name!.toLowerCase(): []}); - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } else { - rolesUnder[roleUnder.roleUnderMain.name!.toLowerCase()]! - .add(Content( - id: roleUnder.id, - name: roleUnder.roleUnderChild.name!)); - } - } - } - - if (state.rolesUnder.isNotEmpty) { - return GroupListView( - sectionsCount: rolesUnder.keys.toList().length, - countOfItemInSection: (int section) { - return rolesUnder.values.toList()[section].length; - }, - itemBuilder: (BuildContext context, IndexPath index) { - return ListTile( - trailing: IconButton( - color: Colors.grey.shade500, - icon: const Icon(Icons.delete), - onPressed: () { - context.read().add(DeleteRoleUnder( - roleUnderId: rolesUnder.values - .toList()[index.section][index.index] - .id)); - }, - ), - title: Row( - children: [ - CircleAvatar( - child: Text("${index.index + 1}", - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith(color: Colors.white))), - const SizedBox( - width: 20, - ), - Expanded( - child: Text( - rolesUnder.values - .toList()[index.section][index.index] - .name - .toUpperCase(), - style: Theme.of(context) - .textTheme - .labelLarge! - .copyWith( - fontWeight: FontWeight.w500, - color: primary) - ), - ), - ], - ), - ); - }, - separatorBuilder: (context, index) { - return const Divider(); - }, - groupHeaderBuilder: (BuildContext context, int section) { - return ListTile( -tileColor: Colors.white, - dense: true, - title: Text( - rolesUnder.keys.toList()[section].toUpperCase(), - style: Theme.of(context) - .textTheme - .titleMedium! - .copyWith(color: primary,fontWeight: FontWeight.bold), - ), - ); - }, - ); - } else { - return const EmptyData( - message: "No Role available. Please click + to add."); - } - } - if (state is RoleUnderErrorState) { - return SomethingWentWrong( - message: state.message, onpressed: () { - context.read().add(GetRolesUnder()); - }); - } - return Container(); - }, - ), - ), - ); - } -} - -class Content { - final int id; - final String name; - const Content({required this.id, required this.name}); -} diff --git a/lib/screens/superadmin/stations/stations_screen.dart b/lib/screens/superadmin/stations/stations_screen.dart index a26e34b..533e55a 100644 --- a/lib/screens/superadmin/stations/stations_screen.dart +++ b/lib/screens/superadmin/stations/stations_screen.dart @@ -5,7 +5,6 @@ import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:searchfield/searchfield.dart'; -import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart'; import 'package:unit2/model/rbac/rbac_station.dart'; import 'package:unit2/model/utils/agency.dart'; @@ -62,436 +61,469 @@ class _RbacStationScreenState extends State { centerTitle: true, backgroundColor: primary, title: const Text("Station Screen"), - actions: [ - AddLeading(onPressed: () { - BuildContext parent = context; - mainParentStations = []; - mainParent = stations.isEmpty ? true : false; - for (RbacStation station in stations) { - if (station.hierarchyOrderNo == 1) { - mainParentStations.add(station); - } - } + actions: context.watch().state is StationLoadingState || + context.watch().state is StationErrorState || + context.watch().state is RbacStationAddedState || + context.watch().state is FilterStationState + ? [] + : [ + AddLeading(onPressed: () { + BuildContext parent = context; + mainParentStations = []; + mainParent = stations.isEmpty ? true : false; + for (RbacStation station in stations) { + if (station.hierarchyOrderNo == 1) { + mainParentStations.add(station); + } + } - /////Add new tation - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text("Add New Station"), - content: SingleChildScrollView( - child: FormBuilder( - key: formKey, - child: StatefulBuilder(builder: (context, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - ////is main parent - FormBuilderSwitch( - initialValue: mainParent, - activeColor: second, - onChanged: (value) { - setState(() { - mainParent = !mainParent; - }); - }, - decoration: normalTextFieldStyle( - "is Main Parent?", 'is Main Parent?'), - name: 'main-parent', - title: Text(mainParent ? "YES" : "NO"), - validator: FormBuilderValidators.required( - errorText: "This field is required"), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - //// selected main parent - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Main Parent Station", - "Main Parent Station"), - name: "parent-stations", - items: mainParentStations.isEmpty - ? [] - : mainParentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - onChanged: (RbacStation? e) { - setState(() { - selectedMainParentStation = e; - parentStations = []; - for (RbacStation station - in stations) { - if (station.mainParentStation == - selectedMainParentStation! - .id) { - parentStations.add(station); - } - } - parentStations.add( - selectedMainParentStation!); - }); - }, - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - SizedBox( - height: mainParent ? 0 : 8, - ), - ////parent station - SizedBox( - child: mainParent == true - ? const SizedBox.shrink() - : FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Parent Station", "Parent Station"), - name: "parent-stations", - onChanged: (RbacStation? e) { - setState(() { - selectedParentStation = e; - }); - }, - items: parentStations.isEmpty - ? [] - : parentStations.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.stationName!), - ); - }).toList(), - validator: - FormBuilderValidators.required( - errorText: - "This field is required"), - ), - ), - const SizedBox( - height: 12, - ), - ////Station Type - SearchField( - itemHeight: 50, - suggestionsDecoration: searchFieldDecoration(), - - suggestions: stationTypes - .map((StationType stationType) => - SearchFieldListItem( - stationType.typeName!, - item: stationType, - child: Padding( - padding: - const EdgeInsets.symmetric( - horizontal: 10), - child: ListTile( - title: Text( - stationType.typeName!, - overflow: TextOverflow.visible, - )), - ))) - .toList(), - validator: (station) { - if (station!.isEmpty) { - return "This field is required"; - } - return null; - }, - focusNode: stationTypeFocusNode, - searchInputDecoration: - normalTextFieldStyle("Station Type *", "") - .copyWith( - suffixIcon: GestureDetector( - onTap: () => stationTypeFocusNode.unfocus(), - child: const Icon(Icons.arrow_drop_down), - )), - onSuggestionTap: (position) { - setState(() { - selectedStationType = position.item!; - stationTypeFocusNode.unfocus(); - }); - }, - emptyWidget: EmptyWidget( - title: "Add StationType", - controller: addStationTypeController, - onpressed: () { - setState(() { - StationType stationType = StationType( - id: null, - typeName: - addStationTypeController.text, - color: null, - order: null, - isActive: null, - group: null); - stationTypes.add(stationType); - Navigator.pop(context); - }); - }), - ), - const SizedBox( - height: 12, - ), - ////Position title - FormBuilderDropdown( - decoration: normalTextFieldStyle( - "Head Position", "Head Position"), - name: "head-position", - items: positions.map((e) { - return DropdownMenuItem( - value: e, - child: Text(e.title!), - ); - }).toList(), - onChanged: (title) { - selectedPositiontitle = title; - }, - ), - const SizedBox( - height: 12, - ), - ////is within parent - FormBuilderSwitch( - initialValue: true, - activeColor: second, - onChanged: (value) { - setState(() { - isWithinParent = value!; - }); - }, - decoration: normalTextFieldStyle( - "Location of the station within this parent?", - 'Location of the station within this parent?'), - name: 'isWithinParent', - title: Text(isWithinParent ? "YES" : "NO"), - ), - const SizedBox( - height: 12, - ), - Row( - //// Station Name - children: [ - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Station name", "Station name"), - name: "station-name"), - ), - const SizedBox( - width: 12, - ), - //// Acronym - Flexible( - child: FormBuilderTextField( - validator: - FormBuilderValidators.required( - errorText: - "This Field is required"), - decoration: normalTextFieldStyle( - "Acronym", "Acronym"), - name: "acronym"), - ), - ], - ), - const SizedBox( - height: 12, - ), - FormBuilderTextField( - ////Description - decoration: normalTextFieldStyle( - "Station description", - "Station description"), - name: "station-description"), - const SizedBox( - height: 12, - ), - Row( - children: [ - Flexible( - ////Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Code", "Code"), - name: "code"), - ), - const SizedBox( - width: 12, - ), - Flexible( - //// Full Code - child: FormBuilderTextField( - decoration: normalTextFieldStyle( - "Full Code", "Full Code"), - name: "fullcode"), - ), - ], - ), - const SizedBox( - height: 12, - ), - ////is Hospital - FormBuilderSwitch( - initialValue: isHospital, - activeColor: second, - onChanged: (value) { - setState(() { - isHospital = !isHospital; - }); - }, - decoration: - normalTextFieldStyle("Is Hospital", ''), - name: 'isHospital', - title: Text(isHospital == true ? "YES" : "NO"), - ), - const SizedBox( - height: 20, - ), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - onPressed: () { - RbacStation? newStation; - if (formKey.currentState! - .saveAndValidate()) { - String? stationName = formKey - .currentState! - .value['station-name']; - String? acronym = formKey - .currentState!.value['acronym']; - String? code = formKey - .currentState!.value['code']; - String? fullcode = formKey - .currentState!.value['fullcode']; - String? description = formKey - .currentState! - .value['station-description']; - newStation = RbacStation( - id: null, - stationName: stationName, - stationType: selectedStationType, - hierarchyOrderNo: mainParent - ? 1 - : selectedParentStation! - .hierarchyOrderNo! + - 1, - headPosition: - selectedPositiontitle?.title, - governmentAgency: - GovernmentAgency( - agencyid: - selectedAgencyId, - agencyname: null, - agencycatid: null, - privateEntity: null, - contactinfoid: null), - acronym: acronym, - parentStation: mainParent - ? null - : selectedParentStation!.id!, - code: code, - fullcode: fullcode, - childStationInfo: null, - islocationUnderParent: - isWithinParent, - mainParentStation: mainParent - ? null - : selectedMainParentStation! - .id!, - description: description, - ishospital: isHospital, - isactive: true, - sellingStation: null); - Navigator.pop(context); - rbacStationBloc.add(AddRbacStation( - station: newStation)); - } + /////Add new tation + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text("Add New Station"), + content: SingleChildScrollView( + child: FormBuilder( + key: formKey, + child: + StatefulBuilder(builder: (context, setState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + ////is main parent + FormBuilderSwitch( + initialValue: mainParent, + activeColor: second, + onChanged: (value) { + setState(() { + mainParent = !mainParent; + }); }, - child: const Text("Add"))), - ], - ); - }), - ), - ), - ); - }); - }), - ////Filter - IconButton( - onPressed: () { - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text( - "Select agency to filter stations", - textAlign: TextAlign.center, - ), - content: SizedBox( - child: // //// Filter Agencies - Padding( - padding: const EdgeInsets.all(8), - child: SearchField( - inputFormatters: [UpperCaseTextFormatter()], - itemHeight: 100, - focusNode: agencyFocusNode, - suggestions: agencies - .map((Agency agency) => - SearchFieldListItem(agency.name!, - item: agency, - child: ListTile( - title: Text( - agency.name!, - overflow: TextOverflow.visible, - ), - ))) - .toList(), - searchInputDecoration: - normalTextFieldStyle("Filter", "").copyWith( - suffixIcon: IconButton( - icon: const Icon(Icons.arrow_drop_down), - onPressed: () { - agencyFocusNode.unfocus(); - }, - )), - onSuggestionTap: (agency) { - agencyFocusNode.unfocus(); - - selectedAgencyId = agency.item!.id!; - print(selectedAgencyId); - Navigator.pop(context); - rbacStationBloc.add(FilterStation( - agencyId: selectedAgencyId)); - }, - validator: (agency) { - if (agency!.isEmpty) { - return "This field is required"; - } - return null; - }, - emptyWidget: const Center( - child: Text("No result found..."), - )), + decoration: normalTextFieldStyle( + "is Main Parent?", 'is Main Parent?'), + name: 'main-parent', + title: Text(mainParent ? "YES" : "NO"), + validator: FormBuilderValidators.required( + errorText: "This field is required"), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + //// selected main parent + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Main Parent Station", + "Main Parent Station"), + name: "parent-stations", + items: mainParentStations.isEmpty + ? [] + : mainParentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + onChanged: (RbacStation? e) { + setState(() { + selectedMainParentStation = e; + parentStations = []; + for (RbacStation station + in stations) { + if (station + .mainParentStation == + selectedMainParentStation! + .id) { + parentStations + .add(station); + } + } + parentStations.add( + selectedMainParentStation!); + }); + }, + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + SizedBox( + height: mainParent ? 0 : 8, + ), + ////parent station + SizedBox( + child: mainParent == true + ? const SizedBox.shrink() + : FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Parent Station", + "Parent Station"), + name: "parent-stations", + onChanged: (RbacStation? e) { + setState(() { + selectedParentStation = e; + }); + }, + items: parentStations.isEmpty + ? [] + : parentStations.map((e) { + return DropdownMenuItem( + value: e, + child: Text( + e.stationName!), + ); + }).toList(), + validator: FormBuilderValidators + .required( + errorText: + "This field is required"), + ), + ), + const SizedBox( + height: 12, + ), + ////Station Type + SearchField( + itemHeight: 50, + suggestionsDecoration: + searchFieldDecoration(), + suggestions: stationTypes + .map((StationType stationType) => + SearchFieldListItem( + stationType.typeName!, + item: stationType, + child: Padding( + padding: const EdgeInsets + .symmetric( + horizontal: 10), + child: ListTile( + title: Text( + stationType.typeName!, + overflow: + TextOverflow.visible, + )), + ))) + .toList(), + validator: (station) { + if (station!.isEmpty) { + return "This field is required"; + } + return null; + }, + focusNode: stationTypeFocusNode, + searchInputDecoration: + normalTextFieldStyle( + "Station Type *", "") + .copyWith( + suffixIcon: GestureDetector( + onTap: () => + stationTypeFocusNode.unfocus(), + child: + const Icon(Icons.arrow_drop_down), + )), + onSuggestionTap: (position) { + setState(() { + selectedStationType = position.item!; + stationTypeFocusNode.unfocus(); + }); + }, + emptyWidget: EmptyWidget( + title: "Add StationType", + controller: addStationTypeController, + onpressed: () { + setState(() { + StationType stationType = + StationType( + id: null, + typeName: + addStationTypeController + .text, + color: null, + order: null, + isActive: null, + group: null); + stationTypes.add(stationType); + Navigator.pop(context); + }); + }), + ), + const SizedBox( + height: 12, + ), + ////Position title + FormBuilderDropdown( + decoration: normalTextFieldStyle( + "Head Position", "Head Position"), + name: "head-position", + items: positions.map((e) { + return DropdownMenuItem( + value: e, + child: Text(e.title!), + ); + }).toList(), + onChanged: (title) { + selectedPositiontitle = title; + }, + ), + const SizedBox( + height: 12, + ), + ////is within parent + FormBuilderSwitch( + initialValue: true, + activeColor: second, + onChanged: (value) { + setState(() { + isWithinParent = value!; + }); + }, + decoration: normalTextFieldStyle( + "Location of the station within this parent?", + 'Location of the station within this parent?'), + name: 'isWithinParent', + title: + Text(isWithinParent ? "YES" : "NO"), + ), + const SizedBox( + height: 12, + ), + Row( + //// Station Name + children: [ + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Station name", + "Station name"), + name: "station-name"), + ), + const SizedBox( + width: 12, + ), + //// Acronym + Flexible( + child: FormBuilderTextField( + validator: FormBuilderValidators + .required( + errorText: + "This Field is required"), + decoration: normalTextFieldStyle( + "Acronym", "Acronym"), + name: "acronym"), + ), + ], + ), + const SizedBox( + height: 12, + ), + FormBuilderTextField( + ////Description + decoration: normalTextFieldStyle( + "Station description", + "Station description"), + name: "station-description"), + const SizedBox( + height: 12, + ), + Row( + children: [ + Flexible( + ////Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Code", "Code"), + name: "code"), + ), + const SizedBox( + width: 12, + ), + Flexible( + //// Full Code + child: FormBuilderTextField( + decoration: normalTextFieldStyle( + "Full Code", "Full Code"), + name: "fullcode"), + ), + ], + ), + const SizedBox( + height: 12, + ), + ////is Hospital + FormBuilderSwitch( + initialValue: isHospital, + activeColor: second, + onChanged: (value) { + setState(() { + isHospital = !isHospital; + }); + }, + decoration: normalTextFieldStyle( + "Is Hospital", ''), + name: 'isHospital', + title: Text( + isHospital == true ? "YES" : "NO"), + ), + const SizedBox( + height: 20, + ), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + style: mainBtnStyle(primary, + Colors.transparent, second), + onPressed: () { + RbacStation? newStation; + if (formKey.currentState! + .saveAndValidate()) { + String? stationName = formKey + .currentState! + .value['station-name']; + String? acronym = formKey + .currentState! + .value['acronym']; + String? code = formKey + .currentState! + .value['code']; + String? fullcode = formKey + .currentState! + .value['fullcode']; + String? description = + formKey.currentState!.value[ + 'station-description']; + newStation = RbacStation( + id: null, + stationName: stationName, + stationType: + selectedStationType, + hierarchyOrderNo: mainParent + ? 1 + : selectedParentStation! + .hierarchyOrderNo! + + 1, + headPosition: + selectedPositiontitle + ?.title, + governmentAgency: + GovernmentAgency( + agencyid: + selectedAgencyId, + agencyname: null, + agencycatid: null, + privateEntity: null, + contactinfoid: + null), + acronym: acronym, + parentStation: + mainParent + ? null + : selectedParentStation! + .id!, + code: code, + fullcode: fullcode, + childStationInfo: null, + islocationUnderParent: + isWithinParent, + mainParentStation: mainParent + ? null + : selectedMainParentStation! + .id!, + description: description, + ishospital: isHospital, + isactive: true, + sellingStation: null); + Navigator.pop(context); + rbacStationBloc.add( + AddRbacStation( + station: newStation)); + } + }, + child: const Text("Add"))), + ], + ); + }), + ), ), - ), - ); - }); - }, - icon: const Icon(Icons.filter_list)) - ], + ); + }); + }), + ////Filter + IconButton( + onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text( + "Select agency to filter stations", + textAlign: TextAlign.center, + ), + content: SizedBox( + child: // //// Filter Agencies + Padding( + padding: const EdgeInsets.all(8), + child: SearchField( + inputFormatters: [ + UpperCaseTextFormatter() + ], + itemHeight: 100, + focusNode: agencyFocusNode, + suggestions: agencies + .map((Agency agency) => + SearchFieldListItem(agency.name!, + item: agency, + child: ListTile( + title: Text( + agency.name!, + overflow: + TextOverflow.visible, + ), + ))) + .toList(), + searchInputDecoration: + normalTextFieldStyle("Filter", "") + .copyWith( + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_drop_down), + onPressed: () { + agencyFocusNode.unfocus(); + }, + )), + onSuggestionTap: (agency) { + agencyFocusNode.unfocus(); + + selectedAgencyId = agency.item!.id!; + print(selectedAgencyId); + Navigator.pop(context); + rbacStationBloc.add(FilterStation( + agencyId: selectedAgencyId)); + }, + validator: (agency) { + if (agency!.isEmpty) { + return "This field is required"; + } + return null; + }, + emptyWidget: const Center( + child: Text("No result found..."), + )), + ), + ), + ); + }); + }, + icon: const Icon(Icons.filter_list)) + ], ), body: ProgressHUD( padding: const EdgeInsets.all(24), @@ -643,7 +675,7 @@ class _RbacStationScreenState extends State { boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 30), child: Row( children: [ @@ -652,7 +684,8 @@ class _RbacStationScreenState extends State { children: [ Padding( padding: - const EdgeInsets.all( + const EdgeInsets + .all( 6), child: Text( @@ -720,7 +753,7 @@ class _RbacStationScreenState extends State { box1() .copyWith(boxShadow: []), padding: const EdgeInsets - .only( + .only( left: 50), child: @@ -873,7 +906,9 @@ class _RbacStationScreenState extends State { return SomethingWentWrong( message: state.message, onpressed: () { - context.read().add(GetStations(agencyId: selectedAgencyId)); + context + .read() + .add(GetStations(agencyId: selectedAgencyId)); }); } diff --git a/lib/screens/unit2/basic-info/basic-info.dart b/lib/screens/unit2/basic-info/basic-info.dart index de6e77b..58997be 100644 --- a/lib/screens/unit2/basic-info/basic-info.dart +++ b/lib/screens/unit2/basic-info/basic-info.dart @@ -6,9 +6,9 @@ import 'package:flutter_svg/svg.dart'; import 'package:fluttericon/font_awesome5_icons.dart'; import 'package:intl/intl.dart'; import 'package:qr_flutter/qr_flutter.dart'; -import 'package:signature/signature.dart'; import 'package:unit2/model/login_data/user_info/user_data.dart'; import 'package:unit2/screens/unit2/basic-info/components/qr_image.dart'; + import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/text_container.dart'; @@ -46,45 +46,45 @@ class BasicInfo extends StatelessWidget { alignment: Alignment.center, children: [ const CoverImage(), - // Positioned( - // top: blockSizeVertical * 15.5, - // child: Stack( - // alignment: Alignment.center, - // children: [ - // CachedNetworkImage( - // imageUrl: fileUrl, - // imageBuilder: (context, imageProvider) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.black26, width: 3), - // shape: BoxShape.circle, - // image: DecorationImage( - // image: imageProvider, - // fit: BoxFit.cover), - // ), - // ), - // placeholder: (context, url) => - // const CircularProgressIndicator(), - // errorWidget: (context, url, error) => - // Container( - // width: 160, - // height: 160, - // decoration: BoxDecoration( - // border: Border.all( - // color: Colors.white, width: 3), - // shape: BoxShape.circle, - // ), - // child: SvgPicture.asset( - // 'assets/svgs/male.svg', - // ), - // ), - // ), - // ], - // ), - // ), + Positioned( + top: blockSizeVertical * 15.5, + child: Stack( + alignment: Alignment.center, + children: [ + CachedNetworkImage( + imageUrl: fileUrl, + imageBuilder: (context, imageProvider) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.black26, width: 3), + shape: BoxShape.circle, + image: DecorationImage( + image: imageProvider, + fit: BoxFit.cover), + ), + ), + placeholder: (context, url) => + const CircularProgressIndicator(), + errorWidget: (context, url, error) => + Container( + width: 160, + height: 160, + decoration: BoxDecoration( + border: Border.all( + color: Colors.white, width: 3), + shape: BoxShape.circle, + ), + child: SvgPicture.asset( + 'assets/svgs/male.svg', + ), + ), + ), + ], + ), + ), Positioned( top: 10, left: 20, @@ -137,13 +137,14 @@ class BuildInformation extends StatelessWidget { @override Widget build(BuildContext context) { DateFormat dteFormat2 = DateFormat.yMMMMd('en_US'); - globalFistname = globalFistname ?? userData.user!.login!.user!.firstName!.toUpperCase(); - globalLastname =globalLastname ?? userData.user!.login!.user!.lastName!.toUpperCase(); - globalMiddleName = globalMiddleName == null - ? (userData.employeeInfo == null + globalFistname = globalFistname ?? + userData.employeeInfo!.profile!.firstName!.toUpperCase(); + globalLastname = globalLastname ?? + userData.employeeInfo!.profile!.lastName!.toUpperCase(); + globalMiddleName = globalMiddleName ?? + (userData.employeeInfo == null ? '' - : userData.employeeInfo!.profile?.middleName?.toUpperCase()) - : ''; + : userData.employeeInfo!.profile?.middleName?.toUpperCase()); globalSex = globalSex ?? userData.employeeInfo!.profile!.sex!.toUpperCase(); globalBday = globalBday ?? userData.employeeInfo!.profile!.birthdate; final uuid = userData.employeeInfo!.uuid; diff --git a/lib/screens/unit2/basic-info/components/qr_image.dart b/lib/screens/unit2/basic-info/components/qr_image.dart index 3a45bae..6aa76fb 100644 --- a/lib/screens/unit2/basic-info/components/qr_image.dart +++ b/lib/screens/unit2/basic-info/components/qr_image.dart @@ -1,5 +1,4 @@ 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'; @@ -14,12 +13,12 @@ class QRFullScreenImage extends StatelessWidget { return Scaffold( appBar: AppBar( centerTitle: true, - backgroundColor: primary,title: const Text("Profile QR Code"),), - body: Center( - child: QrImageView( - data: uuid, - size: blockSizeVertical * 50 - ), - ),); + backgroundColor: primary, + title: const Text("Profile QR Code"), + ), + body: Center( + child: QrImageView(data: uuid, size: blockSizeVertical * 50), + ), + ); } -} \ No newline at end of file +} diff --git a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart index bb638b9..64c287a 100644 --- a/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart +++ b/lib/screens/unit2/homepage.dart/components/dashboard/superadmin_expanded_menu.dart @@ -10,6 +10,7 @@ import 'package:unit2/bloc/rbac/rbac_operations/module_objects/module_objects_bl import 'package:unit2/bloc/rbac/rbac_operations/object/object_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/operation/operation_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/permission/permission_bloc.dart'; +import 'package:unit2/bloc/rbac/rbac_operations/permission_assignment/permission_assignment_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role_extend/role_extend_bloc.dart'; import 'package:unit2/bloc/rbac/rbac_operations/role_module/role_module_bloc.dart'; @@ -21,10 +22,11 @@ import 'package:unit2/screens/superadmin/module/module_screen.dart'; import 'package:unit2/screens/superadmin/object/object_screen.dart'; import 'package:unit2/screens/superadmin/operation/operation_screen.dart'; import 'package:unit2/screens/superadmin/permission/permission_screen.dart'; +import 'package:unit2/screens/superadmin/permission_assignment/permission_assignment_screen.dart'; import 'package:unit2/screens/superadmin/role/role_screen.dart'; import 'package:unit2/screens/superadmin/role_assignment.dart/role_assignment_screen.dart'; import 'package:unit2/screens/superadmin/role_extend/role_extend_screen.dart'; -import 'package:unit2/screens/superadmin/roles_under/roles_under_screen.dart'; +import 'package:unit2/screens/superadmin/roles_under/assignable_roles.dart'; import 'package:unit2/screens/superadmin/stations/stations_screen.dart'; import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart'; import 'package:unit2/theme-data.dart/btn-style.dart'; @@ -77,7 +79,7 @@ class SuperAdminMenu extends StatelessWidget { object.moduleName == 'superadmin' ? CardLabel( icon: iconGenerator(name: object.object.name!), - title: object.object.name!, + title: object.object.name!.toLowerCase() == 'role based access control'? 'RBAC': object.object.name!, ontap: () { if (object.object.name == 'Role') { Navigator.push(context, MaterialPageRoute( @@ -196,7 +198,21 @@ class SuperAdminMenu extends StatelessWidget { ); })); } - + if(object.object.name == 'Role Based Access Control'){ + Navigator.pushNamed(context, '/rbac'); + } + if(object.object.name == 'Permission Assignment'){ + Navigator.push(context, MaterialPageRoute( + builder: (BuildContext context) { + return BlocProvider( + create: (context) => + PermissionAssignmentBloc()..add(GetPermissionAssignments()), + child: RbacPermissionAssignmentScreen( + id: id, + ), + ); + })); + } if (object.object.name == 'Station') { Navigator.push(context, MaterialPageRoute( builder: (BuildContext context) { diff --git a/lib/screens/unit2/homepage.dart/components/drawer-screen.dart b/lib/screens/unit2/homepage.dart/components/drawer-screen.dart index 4f0d609..f621a67 100644 --- a/lib/screens/unit2/homepage.dart/components/drawer-screen.dart +++ b/lib/screens/unit2/homepage.dart/components/drawer-screen.dart @@ -14,7 +14,10 @@ class DrawerScreen extends StatefulWidget { } class _DrawerScreenState extends State { + + final zoomDrawerController = ZoomDrawerController(); + @override Widget build(BuildContext context) { return BlocBuilder( @@ -38,7 +41,7 @@ class _DrawerScreenState extends State { menuBackgroundColor: Colors.grey, ); } - return const UniTSplashScreen(); + return Container(); }, ); } diff --git a/lib/screens/unit2/homepage.dart/components/empty_module.dart b/lib/screens/unit2/homepage.dart/components/empty_module.dart index e7c9590..04f1d54 100644 --- a/lib/screens/unit2/homepage.dart/components/empty_module.dart +++ b/lib/screens/unit2/homepage.dart/components/empty_module.dart @@ -43,7 +43,7 @@ class NoModule extends StatelessWidget { noModuleSubTitle, style: Theme.of(context) .textTheme - .caption! + .bodySmall! .copyWith(fontSize: blockSizeVertical * 1.5), textAlign: TextAlign.center, ) diff --git a/lib/screens/unit2/homepage.dart/components/menu-screen.dart b/lib/screens/unit2/homepage.dart/components/menu-screen.dart index fe13218..e6d88eb 100644 --- a/lib/screens/unit2/homepage.dart/components/menu-screen.dart +++ b/lib/screens/unit2/homepage.dart/components/menu-screen.dart @@ -1,9 +1,16 @@ import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:unit2/bloc/offline/offline_bloc/offline_bloc.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/screens/offline/homepage/drawer.dart'; +import 'package:unit2/screens/offline/homepage/menu_screen.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/drawer-screen.dart'; +import 'package:unit2/screens/unit2/homepage.dart/components/menu_tile.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:fluttericon/web_symbols_icons.dart'; import 'package:fluttericon/font_awesome5_icons.dart'; +import 'package:unit2/utils/global_context.dart'; import '../../../../model/login_data/user_info/user_data.dart'; -import 'menu.dart'; import '../../../../utils/global.dart'; class MenuScreen extends StatefulWidget { @@ -17,10 +24,6 @@ class MenuScreen extends StatefulWidget { class _MenuScreenState extends State { @override Widget build(BuildContext context) { - final String firstName =globalFistname?? - widget.userData!.user!.login!.user!.firstName!.toUpperCase(); - final String lastname = globalLastname?? - widget.userData!.user!.login!.user!.lastName!.toUpperCase(); return Drawer( child: SizedBox( height: screenHeight, @@ -28,49 +31,75 @@ class _MenuScreenState extends State { mainAxisSize: MainAxisSize.max, children: [ Column( - // ignore: prefer_const_literals_to_create_immutables children: [ UserAccountsDrawerHeader( + currentAccountPictureSize: const Size.square(90), decoration: const BoxDecoration( color: primary, image: DecorationImage( image: AssetImage('assets/pngs/bg.png'), fit: BoxFit.cover)), - accountName: Text("$firstName $lastname"), + accountName: null, accountEmail: null, currentAccountPicture: CircleAvatar( - radius: 40, + radius: 100, backgroundColor: fifth, child: CircleAvatar( - radius: 33, - backgroundColor: third, - child: //Icon(Icons.person, size: 40, color: fifth), - Text( - firstName[0].toUpperCase(), - style: const TextStyle(fontSize: 45.0, color: fifth), - ), - ), + radius: 100, + backgroundColor: third, + child: Image.asset( + 'assets/pngs/capitol.png', + )), ), ), getTile(FontAwesome5.user, "Basic Info", '/basic-info', context, widget.userData!), const Divider(), - getTile(FontAwesome5.user_circle, "Profile", - '/profile', context, widget.userData!), - const Divider(), - getTile(FontAwesome5.life_ring, "Request SOS", '/sos', + getTile(FontAwesome5.user_circle, "Profile", '/profile', context, widget.userData!), - + const Divider(), + getTile(FontAwesome5.life_ring, "Request SOS", '/sos', context, + widget.userData!), + const Divider(), + SizedBox( + child: globalOfflineAvailable == true + ? ListTile( + dense: true, + leading: const Icon( + Icons.exit_to_app, + color: primary, + ), + title: const Text( + "Offline Mode", + style: TextStyle(color: Colors.black), + ), + onTap: () async { + Navigator.pushReplacement( + NavigationService + .navigatorKey.currentState!.context, + MaterialPageRoute(builder: ((context) { + return BlocProvider( + create: (context) => + OfflineBloc()..add(SwitchOffline()), + child: const OfflineDrawerScreen(), + ); + }))); + ; + }, + ) + : Container()) ], ), - const Expanded(child: SizedBox()), - const Divider(), - Align( - alignment: FractionalOffset.bottomLeft, - child: getTile(WebSymbols.logout, "Logout", '/', context, - widget.userData!), - ), - const SizedBox(height: 10,), + const Expanded(child: SizedBox()), + const Divider(), + Align( + alignment: FractionalOffset.bottomLeft, + child: getTile( + WebSymbols.logout, "Logout", '/', context, widget.userData!), + ), + const SizedBox( + height: 10, + ), ], ), ), diff --git a/lib/screens/unit2/homepage.dart/components/menu.dart b/lib/screens/unit2/homepage.dart/components/menu.dart deleted file mode 100644 index abb12bc..0000000 --- a/lib/screens/unit2/homepage.dart/components/menu.dart +++ /dev/null @@ -1,44 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:unit2/model/login_data/user_info/user_data.dart'; -import 'package:unit2/utils/alerts.dart'; -import 'package:unit2/utils/global_context.dart'; -import '../../../../theme-data.dart/colors.dart'; -import '../../../../utils/global.dart'; - -Widget getTile( - IconData icondata, String title, String route, BuildContext context,UserData userData) { - return ListTile( - dense: true, - leading: Icon( - icondata, - color: primary, - ), - title: Text( - title, - style: const TextStyle(color: Colors.black), - ), - onTap: () async { - if (title.toLowerCase() == "logout") { - confirmAlert(context, () async{ - await CREDENTIALS!.clear(); - await CREDENTIALS!.deleteAll(['username','password','saved']); - Navigator.pushReplacementNamed (NavigationService.navigatorKey.currentContext!,"/"); - },"Logout","Are You sure you want to logout?"); - }if(title.toLowerCase() == 'profile'){ - ProfileArguments profileArguments = ProfileArguments(token: userData.user!.login!.token!, userID:userData.user!.login!.user!.profileId!); - Navigator.pushNamed(context, route,arguments: profileArguments); - }if(title.toLowerCase() == 'basic info'){ - Navigator.pushNamed(context, '/basic-info'); - }if(title.toLowerCase() == 'request sos'){ - Navigator.pushNamed(context, '/sos'); - } - - }, - ); -} - -class ProfileArguments{ - final int userID; - final String token; - const ProfileArguments({required this.token, required this.userID}); -} diff --git a/lib/screens/unit2/homepage.dart/components/menu_tile.dart b/lib/screens/unit2/homepage.dart/components/menu_tile.dart new file mode 100644 index 0000000..daa5e73 --- /dev/null +++ b/lib/screens/unit2/homepage.dart/components/menu_tile.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; +import 'package:unit2/model/login_data/user_info/user_data.dart'; +import 'package:unit2/utils/alerts.dart'; +import 'package:unit2/utils/global_context.dart'; +import '../../../../theme-data.dart/colors.dart'; +import '../../../../utils/global.dart'; + +Widget getTile(IconData icondata, String title, String route, + BuildContext context, UserData userData) { + return ListTile( + dense: true, + leading: Icon( + icondata, + color: primary, + ), + title: Text( + title, + style: const TextStyle(color: Colors.black), + ), + onTap: () async { + if (title.toLowerCase() == "logout") { + confirmAlert(context, () async { + await CREDENTIALS!.clear(); + await OFFLINE!.clear(); + await CREDENTIALS!.deleteAll(['username', 'password', 'saved']); + Navigator.pushReplacementNamed( + NavigationService.navigatorKey.currentContext!, "/"); + }, "Logout", "Are You sure you want to logout?"); + } + if (title.toLowerCase() == 'profile') { + ProfileArguments profileArguments = ProfileArguments( + token: userData.user!.login!.token!, + userID: userData.user!.login!.user!.profileId!); + Navigator.pushNamed(context, route, arguments: profileArguments); + } + if (title.toLowerCase() == 'basic info') { + Navigator.pushNamed(context, '/basic-info'); + } + if (title.toLowerCase() == 'request sos') { + Navigator.pushNamed(context, '/sos'); + } + }, + ); +} + +class ProfileArguments { + final int userID; + final String token; + const ProfileArguments({required this.token, required this.userID}); +} diff --git a/lib/screens/unit2/homepage.dart/module-screen.dart b/lib/screens/unit2/homepage.dart/module-screen.dart index f614ff0..a0e95c2 100644 --- a/lib/screens/unit2/homepage.dart/module-screen.dart +++ b/lib/screens/unit2/homepage.dart/module-screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_zoom_drawer/flutter_zoom_drawer.dart'; +import 'package:unit2/model/login_data/user_info/module_object.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'; diff --git a/lib/screens/unit2/login/components/update_required.dart b/lib/screens/unit2/login/components/update_required.dart index 5048aef..d2bb586 100644 --- a/lib/screens/unit2/login/components/update_required.dart +++ b/lib/screens/unit2/login/components/update_required.dart @@ -17,8 +17,6 @@ import 'package:unit2/theme-data.dart/btn-style.dart'; import '../../../../bloc/user/user_bloc.dart'; import '../../../../theme-data.dart/colors.dart'; -import '../../../../utils/cpu_architecture.dart'; -import '../../../../utils/text_container.dart'; import '../../../../widgets/wave.dart'; class Update extends StatefulWidget { @@ -113,7 +111,7 @@ class _UpdateState extends State { Container( child: downloading ? FittedBox( - child: Text( + child: Text( 'Downloading application $progressRating%', textAlign: TextAlign.center, style: Theme.of(context) diff --git a/lib/screens/unit2/login/login.dart b/lib/screens/unit2/login/login.dart index 1aa35f9..97aada5 100644 --- a/lib/screens/unit2/login/login.dart +++ b/lib/screens/unit2/login/login.dart @@ -7,6 +7,9 @@ import 'package:fluttericon/font_awesome5_icons.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; +import 'package:unit2/bloc/offline/offline_bloc/offline_bloc.dart'; +import 'package:unit2/model/offline/offlane_modules.dart'; +import 'package:unit2/screens/offline/homepage/drawer.dart'; import 'package:unit2/screens/unit2/login/components/update_required.dart'; import 'package:unit2/screens/unit2/login/qr_login.dart'; import 'package:unit2/utils/alerts.dart'; @@ -36,27 +39,31 @@ class _UniT2LoginState extends State { bool _showPassword = true; String? password; String? username; - DateTime? ctime; + DateTime? ctime; @override Widget build(BuildContext context) { return WillPopScope( - onWillPop: () { - DateTime now = DateTime.now(); - if (ctime == null || now.difference(ctime!) > const Duration(seconds: 2)) { - ctime = now; - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Press Again to Exit',textAlign: TextAlign.center,)) - ); - return Future.value(false); - } + onWillPop: () { + DateTime now = DateTime.now(); + if (ctime == null || + now.difference(ctime!) > const Duration(seconds: 2)) { + ctime = now; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text( + 'Press Again to Exit', + textAlign: TextAlign.center, + ))); + return Future.value(false); + } - return Future.value(true); - }, + return Future.value(true); + }, child: Scaffold( body: ProgressHUD( backgroundColor: Colors.black87, indicatorWidget: const SpinKitFadingCircle(color: Colors.white), child: BlocConsumer(listener: (context, state) { + print(state); if (state is UserLoggedIn || state is UuidLoaded || state is LoginErrorState) { @@ -107,8 +114,6 @@ class _UniT2LoginState extends State { } }, builder: (context, state) { if (state is VersionLoaded) { - print(state.versionInfo!.id); - print(state.apkVersion); return Builder(builder: (context) { if (state.versionInfo?.id == state.apkVersion) { return SizedBox( @@ -133,7 +138,7 @@ class _UniT2LoginState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( - 'assets/svgs/logo.svg', + 'assets/svgs/rpass_logo.svg', height: blockSizeVertical * 12, allowDrawingOutsideViewBox: true, color: primary, @@ -357,7 +362,7 @@ class _UniT2LoginState extends State { //New update available return Update( apkVersion: state.apkVersion!, - versionInfo: state.versionInfo!, + versionInfo: state.versionInfo!, ); } }); @@ -368,13 +373,57 @@ class _UniT2LoginState extends State { onpressed: () { BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(LoadVersion(username: username, password: password)); + .add(GetApkVersion( + username: username, password: password)); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); }, ); } + if (state is ErrorWithOfflineMode) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SomethingWentWrong( + message: onError, + onpressed: () { + BlocProvider.of( + NavigationService.navigatorKey.currentContext!) + .add(GetApkVersion( + username: username, password: password)); + return MaterialPageRoute(builder: (_) { + return const UniT2Login(); + }); + }, + ), + const SizedBox( + height: 14, + ), + SizedBox( + width: 200, + height: 50, + child: ElevatedButton.icon( + icon: const Icon(Icons.signal_cellular_alt), + style: + mainBtnStyle(second, Colors.transparent, primary), + onPressed: () async { + Navigator.pushReplacement( + NavigationService + .navigatorKey.currentState!.context, + MaterialPageRoute(builder: ((context) { + return BlocProvider( + create: (context) => + OfflineBloc()..add(SwitchOffline()), + child: const OfflineDrawerScreen(), + ); + }))); + }, + label: const Text("Offline Mode")), + ) + ], + ); + } if (state is InternetTimeout) { return const TimeOutError(); } @@ -387,14 +436,15 @@ class _UniT2LoginState extends State { onpressed: () { BlocProvider.of( NavigationService.navigatorKey.currentContext!) - .add(LoadVersion(username: username, password: password)); + .add(GetApkVersion( + username: username, password: password)); return MaterialPageRoute(builder: (_) { return const UniT2Login(); }); }, ); } - return Container(); + return Container(); }), ), ), diff --git a/lib/screens/unit2/roles/qr_code_scanner.dart/components/save_settings.dart b/lib/screens/unit2/roles/qr_code_scanner.dart/components/save_settings.dart index ce4b27c..cef0d6e 100644 --- a/lib/screens/unit2/roles/qr_code_scanner.dart/components/save_settings.dart +++ b/lib/screens/unit2/roles/qr_code_scanner.dart/components/save_settings.dart @@ -5,7 +5,8 @@ import '../../../../../theme-data.dart/colors.dart'; class SelectedState extends StatelessWidget { final String title; final String subtitle; - const SelectedState({Key? key,required this.subtitle, required this.title}) : super(key: key); + const SelectedState({Key? key, required this.subtitle, required this.title}) + : super(key: key); @override Widget build(BuildContext context) { @@ -24,7 +25,7 @@ class SelectedState extends StatelessWidget { Text( title, textAlign: TextAlign.center, - style: Theme.of(context).textTheme.button!.copyWith( + style: Theme.of(context).textTheme.titleMedium!.copyWith( color: third, fontWeight: FontWeight.bold, fontSize: 18), ), Text( @@ -32,7 +33,6 @@ class SelectedState extends StatelessWidget { style: Theme.of(context).textTheme.labelMedium, ), const Divider(), - ]), ], ), diff --git a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart index f773615..213aab0 100644 --- a/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart +++ b/lib/screens/unit2/roles/qr_code_scanner.dart/scan.dart @@ -1,5 +1,6 @@ import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:audioplayers/audioplayers.dart'; +import 'package:awesome_dialog/awesome_dialog.dart'; import 'package:cool_alert/cool_alert.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -35,13 +36,13 @@ class _QRCodeScannerState extends State { player = AudioPlayer(); super.initState(); } + @override void dispose() { player?.dispose(); super.dispose(); } - @override Widget build(BuildContext context) { return Scaffold( @@ -73,83 +74,86 @@ class _QRCodeScannerState extends State { progress!.dismiss(); } if (state is ScanSuccess) { - Future.delayed(const Duration(seconds: 1), () async{ - await player?.play(AssetSource("success.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("success.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is QRInvalid) { - Future.delayed(const Duration(seconds: 1), ()async { + Future.delayed(const Duration(seconds: 1), () async { await player?.play(AssetSource("invalid.mp3")); }); context.read().add(ScanQr(token: state.token)); } if (state is ScanFailed) { - Future.delayed(const Duration(seconds: 1), ()async { - await player?.play(AssetSource("fail.mp3")); + Future.delayed(const Duration(seconds: 1), () async { + await player?.play(AssetSource("fail.mp3")); }); - + context.read().add(ScanQr(token: state.token)); } if (state is IncomingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Temperature", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: FormBuilder( - key: formKey, - child: Column( - children: [ - const SizedBox( - height: 24, + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), + child: FormBuilder( + key: formKey, + child: Column( + children: [ + const Text("Enter Temperature",style: TextStyle(color: Colors.black),), + const SizedBox( + height: 24, + ), + FormBuilderTextField( + keyboardType: TextInputType.number, + name: "temp", + decoration: + normalTextFieldStyle("Temperature", ""), + validator: numericRequired), + const SizedBox( + height: 12, + ), + SizedBox( + height: 50, + width: double.infinity, + child: ElevatedButton( + style: mainBtnStyle( + primary, Colors.transparent, second), + child: const Text(submit), + onPressed: () { + if (formKey.currentState!.saveAndValidate()) { + double temperature = double.parse( + formKey.currentState!.value['temp']); + context.read().add( + PerformIncomingPostLog( + temp: temperature)); + Navigator.of(context).pop(); + } + }, ), - FormBuilderTextField( - keyboardType: TextInputType.number, - name: "temp", - decoration: - normalTextFieldStyle("Temperature", ""), - validator: numericRequired), - const SizedBox( - height: 12, - ), - SizedBox( - height: 50, - width: double.infinity, - child: ElevatedButton( - style: mainBtnStyle( - primary, Colors.transparent, second), - child: const Text(submit), - onPressed: () { - if (formKey.currentState!.saveAndValidate()) { - double temperature = double.parse( - formKey.currentState!.value['temp']); - context.read().add( - PerformIncomingPostLog( - temp: temperature)); - Navigator.of(context).pop(); - } - }, - ), - ) - ], - )), - )); + ) + ], + )), + ), + ).show(); } if (state is OutGoingScanState) { - CoolAlert.show( - barrierDismissible: false, - context: context, - type: CoolAlertType.loading, - text: "Enter Destination", - widget: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), + AwesomeDialog( + dismissOnBackKeyPress: false, + context: context, + dialogType: DialogType.info, + dismissOnTouchOutside: false, + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24,vertical: 24), child: FormBuilder( key: formKey, child: Column( children: [ + const Text("Enter Destination"), const SizedBox( height: 24, ), @@ -185,7 +189,8 @@ class _QRCodeScannerState extends State { ) ], )), - )); + )).show(); + } }, builder: (context, state) { @@ -302,28 +307,56 @@ class _QRCodeScannerState extends State { children: [ SelectedState( //TODO add api data - title: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + title: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? state.assignedArea.stationName - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? state.assignedArea.brgydesc - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? state.assignedArea.purokdesc - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", - subtitle: state.roleIdRoleName.roleName.toLowerCase() == "41" || - state.roleIdRoleName.roleName.toLowerCase() == 'qr code scanner' || - state.roleIdRoleName.roleName.toLowerCase() == 'office/branch chief' || - state.roleIdRoleName.roleName.toLowerCase() == 'registration in-charge' + subtitle: state.roleIdRoleName.roleName + .toLowerCase() == + "41" || + state.roleIdRoleName.roleName + .toLowerCase() == + 'qr code scanner' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'office/branch chief' || + state.roleIdRoleName.roleName + .toLowerCase() == + 'registration in-charge' ? "Station" - : state.roleIdRoleName.roleName.toLowerCase() == 'barangay chairperson' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'barangay chairperson' ? "Barangay" - : state.roleIdRoleName.roleName.toLowerCase() == 'purok president' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'purok president' ? "Purok" - : state.roleIdRoleName.roleName.toLowerCase() == 'establishment point-person' + : state.roleIdRoleName.roleName + .toLowerCase() == + 'establishment point-person' ? "Agency" : "", ), diff --git a/lib/screens/unit2/roles/registration_in_charge/components/view.dart b/lib/screens/unit2/roles/registration_in_charge/components/view.dart index a103af9..12a5ecf 100644 --- a/lib/screens/unit2/roles/registration_in_charge/components/view.dart +++ b/lib/screens/unit2/roles/registration_in_charge/components/view.dart @@ -82,7 +82,7 @@ class _ViewListState extends State { dense: true, subtitle: Text( "December 15 1994", - style: Theme.of(context).textTheme.caption, + style: Theme.of(context).textTheme.bodyMedium, ), leading: Checkbox( onChanged: (value) { diff --git a/lib/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart new file mode 100644 index 0000000..b848fae --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/barangay_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; +import 'dart:core'; + +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class BrgyAdminApiServices { + static final BrgyAdminApiServices _instance = BrgyAdminApiServices(); + static BrgyAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future fetch() async { + String path = Url.instance.getBarangay(); + 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(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart new file mode 100644 index 0000000..b2e5fe3 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/class_components_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/request.dart'; +import '../../../../../utils/urls.dart'; +import 'package:http/http.dart' as http; + +class ClassComponentAdminApiServices { + static final ClassComponentAdminApiServices _instance = + ClassComponentAdminApiServices(); + static ClassComponentAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + 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); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/land_classification_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/land_classification_api_services.dart new file mode 100644 index 0000000..f14f4b9 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/land_classification_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class LandClassificationAdminApiServices { + static final LandClassificationAdminApiServices _instance = + LandClassificationAdminApiServices(); + static LandClassificationAdminApiServices 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/land_sub_classification_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/land_sub_classification_api_services.dart new file mode 100644 index 0000000..e91bb45 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/land_sub_classification_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class LandSubClassificationAdminApiServices { + static final LandSubClassificationAdminApiServices _instance = + LandSubClassificationAdminApiServices(); + static LandSubClassificationAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future fetch() async { + String path = Url.instance.getLandSubClassification(); + 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(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart new file mode 100644 index 0000000..b437c8a --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/memoranda_api_services.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; +import 'dart:core'; + +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class MemorandaAdminApiServices { + static final MemorandaAdminApiServices _instance = + MemorandaAdminApiServices(); + static MemorandaAdminApiServices 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); + + print(response.body); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart new file mode 100644 index 0000000..3140720 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; +import 'dart:core'; + +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import 'package:unit2/sevices/passo/municipality.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class MunicipalityAdminApiServices { + static final MunicipalityAdminApiServices _instance = + MunicipalityAdminApiServices(); + static MunicipalityAdminApiServices 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/signatories.dart b/lib/sevices/offline/offline_passo/admin/api_services/signatories.dart new file mode 100644 index 0000000..9380f46 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/signatories.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; +import 'dart:core'; + +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart'; +import 'package:unit2/sevices/passo/municipality.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class SignatoriesAdminApiServices { + static final SignatoriesAdminApiServices _instance = + SignatoriesAdminApiServices(); + static SignatoriesAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + 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(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/trees_improvements_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/trees_improvements_api_services.dart new file mode 100644 index 0000000..8edb94c --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/trees_improvements_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class TreesImprovementsAdminApiServices { + static final TreesImprovementsAdminApiServices _instance = + TreesImprovementsAdminApiServices(); + static TreesImprovementsAdminApiServices 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/type_of_location.dart b/lib/sevices/offline/offline_passo/admin/api_services/type_of_location.dart new file mode 100644 index 0000000..f03a510 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/type_of_location.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class TypeOfLocationAdminApiServices { + static final TypeOfLocationAdminApiServices _instance = + TypeOfLocationAdminApiServices(); + static TypeOfLocationAdminApiServices 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/type_of_road_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/type_of_road_api_services.dart new file mode 100644 index 0000000..bba5b0d --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/type_of_road_api_services.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class TypeOfRoadAdminApiServices { + static final TypeOfRoadAdminApiServices _instance = + TypeOfRoadAdminApiServices(); + static TypeOfRoadAdminApiServices 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/unit_construction_api_services.dart b/lib/sevices/offline/offline_passo/admin/api_services/unit_construction_api_services.dart new file mode 100644 index 0000000..c1c4d3d --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/unit_construction_api_services.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; +import 'dart:core'; + +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class UnitConstructionAdminApiServices { + static final UnitConstructionAdminApiServices _instance = + UnitConstructionAdminApiServices(); + static UnitConstructionAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + 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); + + print(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/api_services/value_adjustments.dart b/lib/sevices/offline/offline_passo/admin/api_services/value_adjustments.dart new file mode 100644 index 0000000..de8ba33 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/api_services/value_adjustments.dart @@ -0,0 +1,38 @@ +import 'dart:convert'; + +import '../../../../../utils/urls.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:http/http.dart' as http; + +class ValueAdjustmentsAdminApiServices { + static final ValueAdjustmentsAdminApiServices _instance = + ValueAdjustmentsAdminApiServices(); + static ValueAdjustmentsAdminApiServices get instance => _instance; + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future fetch() async { + String path = Url.instance.getValueAdjustmentss(); + 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(response.statusCode); + if (response.statusCode == 200) { + final List result = jsonDecode(response.body)['data']; + print(result); + return result; + } else { + throw Exception(response.reasonPhrase); + } + } catch (e) { + throw Exception(e.toString()); + } + } +} diff --git a/lib/sevices/offline/offline_passo/admin/sql_services/sql_services.dart b/lib/sevices/offline/offline_passo/admin/sql_services/sql_services.dart new file mode 100644 index 0000000..2d3d0b6 --- /dev/null +++ b/lib/sevices/offline/offline_passo/admin/sql_services/sql_services.dart @@ -0,0 +1,2056 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:path/path.dart'; +import 'package:unit2/model/passo/bldg_loc.dart'; +import 'package:unit2/model/passo/city.dart'; +import 'package:unit2/model/passo/class_components.dart'; +import 'package:unit2/model/passo/land_property_assessment.dart'; +import 'package:unit2/model/passo/land_property_boundaries.dart'; +import 'package:unit2/model/passo/land_ref.dart'; +import 'package:unit2/model/passo/other_improvements.dart'; +import 'package:unit2/model/passo/signatories.dart'; +import 'package:unit2/model/passo/structural_materials_ii.dart'; +import 'package:unit2/model/passo/type_of_road.dart'; +import 'package:unit2/model/passo/unit_construct.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +import '../../../../../model/passo/additional_items.dart'; +import '../../../../../model/passo/barangay.dart'; +import '../../../../../model/passo/building_and_structure.dart'; +import '../../../../../model/passo/class_components _offline.dart'; +import '../../../../../model/passo/floor_sketch.dart'; +import '../../../../../model/passo/general_description.dart'; +import '../../../../../model/passo/land_appr.dart'; +import '../../../../../model/passo/land_classification.dart'; +import '../../../../../model/passo/land_ext.dart'; +import '../../../../../model/passo/land_property_loc.dart'; +import '../../../../../model/passo/land_property_owner.dart'; +import '../../../../../model/passo/land_subclassification.dart'; +import '../../../../../model/passo/land_value_adjustment.dart'; +import '../../../../../model/passo/memoranda.dart'; +import '../../../../../model/passo/property_appraisal.dart'; +import '../../../../../model/passo/property_assessment.dart'; +import '../../../../../model/passo/property_info.dart'; +import '../../../../../model/passo/structureMaterial.dart'; +import '../../../../../model/passo/trees_improvements.dart'; +import '../../../../../model/passo/type_of_location.dart'; + +class SQLServices { + static final SQLServices instance = SQLServices._init(); + static Database? _database; + SQLServices._init(); + + Future get database async { + if (_database != null) return _database!; + + _database = await _initDB('passo.db'); + return _database!; + } + + Future _initDB(String filePath) async { + final dbPath = await getDatabasesPath(); + final path = join(dbPath, filePath); + + return await openDatabase(path, version: 1, onCreate: _createDB); + } + + Future _createDB(Database db, int version) async { + await db.execute(''' + CREATE TABLE municipalities ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + cityCode TEXT NOT NULL, + cityDescription TEXT NOT NULL, + gen_code TEXT + ) + '''); + await db.execute(''' + CREATE TABLE barangay ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + barangayId INTEGER NOT NULL, + barangayCode TEXT NOT NULL, + cityCode TEXT NOT NULL, + barangayDescription TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE class_components ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + componentName TEXT NOT NULL, + minBaseUnitvalPercent TEXT NOT NULL, + maxBaseUnitvalPercent TEXT NOT NULL, + minUnitvalSqrmtr TEXT NOT NULL, + maxUnitvalSqrmtr TEXT NOT NULL, + minAddBaseunitval TEXT NOT NULL, + maxAddBaseunitval TEXT NOT NULL, + minDeductBaserate TEXT NOT NULL, + maxDeductBaserate TEXT NOT NULL, + minLinearMeter TEXT NOT NULL, + maxLinearMeter TEXT NOT NULL, + minSpacing TEXT NOT NULL, + maxSpacing TEXT NOT NULL, + roughFinish TEXT NOT NULL, + highFinish TEXT NOT NULL, + withoutBucc INTEGER NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE unit_construction ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgType TEXT NOT NULL, + building TEXT NOT NULL, + unitValue TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE signatories ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + signatoryId INTEGER NOT NULL, + firstname TEXT NOT NULL, + middlename TEXT NOT NULL, + lastname TEXT NOT NULL, + designation TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE memoranda ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + code TEXT NOT NULL, + memoranda TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE land_classification ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + classificationCode TEXT NOT NULL, + description TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_subclassification ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + classificationId INTEGER NOT NULL, + cityCode TEXT NOT NULL, + subclassCode TEXT NOT NULL, + subclassDescription TEXT NOT NULL, + baseUnitMarketval TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE trees_improvement ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + improvement TEXT NOT NULL, + pricePerTree TEXT NOT NULL, + subclassCode TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE type_of_location ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + distanceKm TEXT NOT NULL, + allRoadTypes TEXT NOT NULL, + localTradingCenter TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE type_of_road ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + roadType TEXT NOT NULL, + deduction TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldg_floor_sketch ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgappr_details_id INTEGER NOT NULL, + date_created TEXT NOT NULL, + floor_sketch TEXT NOT NULL, + gen_code TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE value_adjustments ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + baseMarketval TEXT NOT NULL, + adjustmentFactors TEXT NOT NULL, + adjustment TEXT NOT NULL, + valueAdjustment TEXT NOT NULL, + marketValue TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldg_owner ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + transCode TEXT NOT NULL, + tdn TEXT NOT NULL, + pin TEXT NOT NULL, + fname TEXT NOT NULL, + mname TEXT NOT NULL, + lname TEXT NOT NULL, + bday TEXT NOT NULL, + address TEXT NOT NULL, + telno TEXT NOT NULL, + tin TEXT NOT NULL, + adminUser TEXT NOT NULL, + adminAddress TEXT NOT NULL, + adminTelno TEXT NOT NULL, + adminTin TEXT NOT NULL, + faasType TEXT NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + gen_code TEXT, + dateSynced TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE landref ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + owner TEXT NOT NULL, + cloaNo TEXT NOT NULL, + lotNo TEXT NOT NULL, + tdn TEXT NOT NULL, + area TEXT NOT NULL, + surveyNo TEXT NOT NULL, + blkNo TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldgloc ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + street TEXT NOT NULL, + barangay TEXT NOT NULL, + municipality TEXT NOT NULL, + province TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE gendesc ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + bldgKind TEXT NOT NULL, + strucType TEXT NOT NULL, + bldgPermit TEXT NOT NULL, + dateIssued TEXT NOT NULL, + cct TEXT NOT NULL, + certCompletionIssued TEXT NOT NULL, + certOccupancyIssued TEXT NOT NULL, + dateCompleted TEXT NOT NULL, + dateOccupied TEXT NOT NULL, + bldgAge TEXT NOT NULL, + noStoreys TEXT NOT NULL, + area1Stfloor TEXT NOT NULL, + area2Ndfloor TEXT NOT NULL, + area3Rdfloor TEXT NOT NULL, + area4Thfloor TEXT NOT NULL, + totalFloorArea TEXT NOT NULL, + floorSketch TEXT NOT NULL, + actualUse TEXT NOT NULL, + unitValue TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldg_and_structure ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + bldgType TEXT NOT NULL, + strucType TEXT NOT NULL, + description TEXT NOT NULL, + actualUse TEXT NOT NULL, + floorCount TEXT NOT NULL, + bldgArea TEXT NOT NULL, + unitValue TEXT NOT NULL, + buccPercentage TEXT NOT NULL, + depRate TEXT NOT NULL, + marketValue TEXT NOT NULL, + depAmount TEXT NOT NULL, + adjustedMarketValue TEXT NOT NULL, + gen_code TEXT, + dateSync TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE structural_materials ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + foundation TEXT NOT NULL, + columns TEXT NOT NULL, + beams TEXT NOT NULL, + trussFraming TEXT NOT NULL, + roof TEXT NOT NULL, + flooring TEXT NOT NULL, + walls TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldg_appraisal ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + unitconstructCost TEXT NOT NULL, + buildingCore TEXT NOT NULL, + unitconstructSubtotal TEXT NOT NULL, + depreciationRate TEXT NOT NULL, + depreciationCost TEXT NOT NULL, + costAddItems TEXT NOT NULL, + addItemsSubtotal TEXT NOT NULL, + totalpercentDepreciation TEXT NOT NULL, + marketValue TEXT NOT NULL, + totalArea TEXT NOT NULL, + actualUse TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE bldg_assessment ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + actualUse TEXT NOT NULL, + marketValue TEXT NOT NULL, + assessmentLevel TEXT NOT NULL, + assessedValue TEXT NOT NULL, + taxable TEXT NOT NULL, + exempt TEXT NOT NULL, + qtr TEXT NOT NULL, + yr TEXT NOT NULL, + appraisedbyName TEXT NOT NULL, + appraisedbyDate TEXT NOT NULL, + appraisedby_designation TEXT, + recommendapprName TEXT NOT NULL, + recommendapprDate TEXT NOT NULL, + recommendappr_designation TEXT, + approvedbyName TEXT NOT NULL, + approvedby_designation TEXT, + approvedbyDate TEXT, + memoranda TEXT NOT NULL, + swornstatementNo TEXT NOT NULL, + dateReceived TEXT NOT NULL, + entryDateAssessment TEXT NOT NULL, + entryDateBy TEXT NOT NULL, + gen_code TEXT, + note TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE additionalitems ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + classId INTEGER NOT NULL, + className TEXT NOT NULL, + structType TEXT NOT NULL, + unitValue TEXT NOT NULL, + baseUnitValue TEXT NOT NULL, + area TEXT NOT NULL, + marketValue TEXT NOT NULL, + depreciationRate TEXT NOT NULL, + adjustedMarketVal TEXT NOT NULL, + amtDepreciation TEXT NOT NULL, + painted TEXT NOT NULL, + secondhand TEXT NOT NULL, + paintedUnitval TEXT NOT NULL, + secondhandUnitval TEXT NOT NULL, + actualUse TEXT NOT NULL, + gen_code TEXT, + dateSync TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_owner ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + transCode TEXT NOT NULL, + tdn TEXT NOT NULL, + pin TEXT NOT NULL, + cloaNo TEXT NOT NULL, + dated TEXT NOT NULL, + surveyNo TEXT NOT NULL, + lotNo TEXT NOT NULL, + blkNo TEXT NOT NULL, + owner TEXT NOT NULL, + address TEXT NOT NULL, + telno TEXT NOT NULL, + tin TEXT NOT NULL, + adminUser TEXT NOT NULL, + adminTelno TEXT NOT NULL, + adminAddress TEXT NOT NULL, + adminTin TEXT NOT NULL, + faasType TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_location ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + street TEXT NOT NULL, + municipality TEXT NOT NULL, + barangay TEXT NOT NULL, + province TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_boundaries ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + north TEXT NOT NULL, + east TEXT NOT NULL, + south TEXT NOT NULL, + west TEXT NOT NULL, + sketch TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_appr ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + classification TEXT NOT NULL, + subClass TEXT NOT NULL, + area TEXT NOT NULL, + unitValue TEXT NOT NULL, + baseMarketval TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_other_improvements ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + kindsOfTrees TEXT NOT NULL, + subclassAge TEXT NOT NULL, + quantity INTEGER NOT NULL, + unitValue TEXT NOT NULL, + baseMarketval TEXT NOT NULL, + noOfProductive INTEGER NOT NULL, + noOfNonproductive INTEGER NOT NULL, + fruitBearing TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_assessment ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + actualUse TEXT NOT NULL, + marketval TEXT NOT NULL, + assessmentLevel TEXT NOT NULL, + assessedValue TEXT NOT NULL, + totalMarketval TEXT NOT NULL, + totalAssessedval TEXT NOT NULL, + gen_code TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE land_property_ext ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + landapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + dateCreated TEXT NOT NULL, + dateModified TEXT NOT NULL, + taxable TEXT NOT NULL, + exempt TEXT NOT NULL, + qtr TEXT NOT NULL, + yr TEXT NOT NULL, + appraisedbyName TEXT NOT NULL, + appraisedbyDate TEXT NOT NULL, + recommendapprName TEXT NOT NULL, + recommendapprDate TEXT NOT NULL, + approvedbyName TEXT NOT NULL, + approvedbyDate TEXT NOT NULL, + memoranda TEXT NOT NULL, + swornstatementNo TEXT NOT NULL, + dateReceived TEXT NOT NULL, + entryDateAssessment TEXT NOT NULL, + entryDateBy TEXT NOT NULL, + gen_code TEXT + ) + '''); + } + + //Municipalities + + Future createMunicipalities(City city) async { + final db = await instance.database; + + final data = { + "id": city.id, + "cityCode": city.cityCode, + "cityDescription": city.cityDescription, + }; + final id = await db.insert('municipalities', data); + return city.copy(id: id); + } + + Future> readAllMunicipalities() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('municipalities', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => City.fromJson2(json)).toList(); + } + + //Barangay + + Future createBarangay(Brgy brgy) async { + final db = await instance.database; + + final data = { + "barangayId": brgy.barangayId, + "barangayCode": brgy.barangayCode, + "cityCode": brgy.cityCode, + "barangayDescription": brgy.barangayDescription + }; + final id = await db.insert('barangay', data); + return brgy.copy(id: id); + } + + Future> readBrgyInSelectedMunicipality(cityCode) async { + final db = await instance.database; + const orderBy = 'id'; + // Use a placeholder for the WHERE clause and provide the value separately. + final params = [cityCode]; // List of values to substitute + + final result = await db.query('barangay', + orderBy: orderBy, where: 'cityCode = ?', whereArgs: params); + print('result'); + print(cityCode); + print(result.toString()); + + return result.map((json) => Brgy.fromJson2(json)).toList(); + } + + Future> readAllBarangay() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('barangay', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => Brgy.fromJson2(json)).toList(); + } + + //Class components + + Future createClassComponents( + ClassComponentsOffline classes) async { + final db = await instance.database; + + final data = { + "componentName": classes.componentName, + "minBaseUnitvalPercent": classes.minBaseUnitvalPercent, + "maxBaseUnitvalPercent": classes.maxBaseUnitvalPercent, + "minUnitvalSqrmtr": classes.minUnitvalSqrmtr, + "maxUnitvalSqrmtr": classes.maxUnitvalSqrmtr, + "minAddBaseunitval": classes.minAddBaseunitval, + "maxAddBaseunitval": classes.maxAddBaseunitval, + "minDeductBaserate": classes.minDeductBaserate, + "maxDeductBaserate": classes.maxDeductBaserate, + "minLinearMeter": classes.minLinearMeter, + "maxLinearMeter": classes.maxLinearMeter, + "minSpacing": classes.minSpacing, + "maxSpacing": classes.maxSpacing, + "roughFinish": classes.roughFinish, + "highFinish": classes.highFinish, + "withoutBucc": classes.withoutBucc + }; + final id = await db.insert('class_components', data); + return classes.copy(id: id); + } + + Future> readAllClassComponents() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('class_components', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result + .map((json) => ClassComponentsOffline.fromJson2(json)) + .toList(); + } + + //Unit construction + + Future createUnitConstruction(UnitConstruct unit) async { + final db = await instance.database; + + final data = { + "bldgType": unit.bldgType, + "building": unit.building, + "unitValue": unit.unitValue, + "gen_code": unit.genCode + }; + final id = await db.insert('unit_construction', data); + return unit.copy(id: id); + } + + Future> readAllUnitConstruct() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('unit_construction', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => UnitConstruct.fromJson2(json)).toList(); + } + + //Signatories + + Future createSignatories(Signatories signatories) async { + final db = await instance.database; + + final data = { + "signatoryId": signatories.signatoryId, + "firstname": signatories.firstname, + "middlename": signatories.middlename, + "lastname": signatories.lastname, + "designation": signatories.designation, + }; + final id = await db.insert('signatories', data); + return signatories.copy(id: id); + } + + Future> readAllSignatories() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('signatories', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => Signatories.fromJson2(json)).toList(); + } + + // Memoranda + + Future createMemoranda(Memoranda memo) async { + final db = await instance.database; + + final data = { + "id": memo.id, + "code": memo.code, + "memoranda": memo.memoranda + }; + final id = await db.insert('memoranda', data); + return memo.copy(id: id); + } + + Future> readAllMemoranda() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('memoranda', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => Memoranda.fromJson2(json)).toList(); + } + + // Land Classification + + Future createLandClassification( + LandClassification landClass) async { + final db = await instance.database; + + final data = { + // "id": landClass.id, + "classificationCode": landClass.classificationCode, + "description": landClass.description + }; + final id = await db.insert('land_classification', data); + return landClass.copy(id: id); + } + + Future> readAllLandClassification() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('land_classification', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => LandClassification.fromJson2(json)).toList(); + } + + //Land SubClassification + + Future createLandSubClassification( + LandSubClassification landSubClass) async { + final db = await instance.database; + + final data = { + "id": landSubClass.id, + "classificationId": landSubClass.classificationId, + "cityCode": landSubClass.cityCode, + "subclassCode": landSubClass.subclassCode, + "subclassDescription": landSubClass.subclassDescription, + "baseUnitMarketval": landSubClass.baseUnitMarketval + }; + final id = await db.insert('land_subclassification', data); + return landSubClass.copy(id: id); + } + + Future> readAllLandSubClassification() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('land_subclassification', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => LandSubClassification.fromJson2(json)).toList(); + } + + Future> readSpecificLandSubClassification( + cityCode, classificationId) async { + final db = await instance.database; + const orderBy = 'id'; + + // Use placeholders for the WHERE clause and provide the values separately. + final params = [cityCode, classificationId]; // List of values to substitute + + final result = await db.query('land_subclassification', + orderBy: orderBy, + where: 'cityCode = ? AND classificationId = ?', + whereArgs: params); + + print('result'); + print(cityCode); + print(classificationId); + print(result.toString()); + + return result.map((json) => LandSubClassification.fromJson2(json)).toList(); + } + + //Trees Improvements + + Future createTreesImprovements( + TreesImprovements treesImprovements) async { + final db = await instance.database; + + final data = { + // "id": treesImprovements.id, + "improvement": treesImprovements.improvement, + "pricePerTree": treesImprovements.pricePerTree, + "subclassCode": treesImprovements.subclassCode + }; + final id = await db.insert('trees_improvement', data); + return treesImprovements.copy(id: id); + } + + Future> readAllTreesImprovements() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('trees_improvement', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => TreesImprovements.fromJson2(json)).toList(); + } + + //Type of Location + + Future createTypeOfLocation( + TypeOfLocation typeOfLocation) async { + final db = await instance.database; + + final data = { + "id": typeOfLocation.id, + "distanceKm": typeOfLocation.distanceKm, + "allRoadTypes": typeOfLocation.allRoadTypes, + "localTradingCenter": typeOfLocation.localTradingCenter + }; + final id = await db.insert('type_of_location', data); + return typeOfLocation.copy(id: id); + } + + Future> readAllTypeOfLocation() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('type_of_location', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => TypeOfLocation.fromJson2(json)).toList(); + } + + //Type of Road + + Future createTypeOfRoad(TypeOfRoad typeOfRoad) async { + final db = await instance.database; + + final data = { + "id": typeOfRoad.id, + "roadType": typeOfRoad.roadType, + "deduction": typeOfRoad.deduction, + }; + final id = await db.insert('type_of_road', data); + return typeOfRoad.copy(id: id); + } + + Future> readAllTypeOfRoad() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('type_of_road', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => TypeOfRoad.fromJson2(json)).toList(); + } + + //BLDG Owner + + Future createBldgOwner(PropertyInfo propertyInfo) async { + final db = await instance.database; + + final data = { + "id": propertyInfo.id, + "transCode": propertyInfo.transCode, + "tdn": propertyInfo.tdn, + "pin": propertyInfo.pin, + "lname": propertyInfo.lname, + "mname": propertyInfo.mname, + "fname": propertyInfo.fname, + "bday": propertyInfo.bday, + "address": propertyInfo.address, + "telno": propertyInfo.telno, + "tin": propertyInfo.tin, + "adminUser": propertyInfo.adminUser, + "adminAddress": propertyInfo.adminAddress, + "adminTelno": propertyInfo.adminTelno, + "adminTin": propertyInfo.adminTin, + "faasType": propertyInfo.faasType, + "assessedById": propertyInfo.assessedById, + "assessedByName": propertyInfo.assessedByName, + "dateCreated": "000", + "dateModified": "000", + }; + final id = await db.insert('bldg_owner', data); + final tempID = await SharedPreferences.getInstance(); + print(propertyInfo.copy(id: id).toJson()); + await tempID.setInt('tempid', id); + return propertyInfo.copy(id: id); + } + + Future> readAllBldgOwner() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('bldg_owner', orderBy: orderBy); + + return result.map((json) => PropertyInfo.fromJson2(json)).toList(); + } + + Future updateBldgOwner(id, PropertyInfo propertyInfo) async { + final db = await instance.database; + final data = { + "transCode": propertyInfo.transCode, + "tdn": propertyInfo.tdn, + "pin": propertyInfo.pin, + "bday": propertyInfo.bday, + "fname": propertyInfo.fname, + "mname": propertyInfo.mname, + "lname": propertyInfo.lname, + "address": propertyInfo.address, + "telno": propertyInfo.telno, + "tin": propertyInfo.tin, + "adminUser": propertyInfo.adminUser, + "adminAddress": propertyInfo.adminAddress, + "adminTelno": propertyInfo.adminTelno, + "adminTin": propertyInfo.adminTin, + "faasType": propertyInfo.faasType, + "assessedById": propertyInfo.assessedById, + "assessedByName": propertyInfo.assessedByName, + "dateCreated": "000", + "dateModified": "000", + "dateSynced": propertyInfo.dateSynced + }; + + final result = + await db.update('bldg_owner', data, where: "id = ?", whereArgs: [id]); + + if (result > 0) { + print('Bldg Owner Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + Future deleteBldgOwner({required int id}) async { + final db = await instance.database; + + return await db.delete( + 'bldg_owner', + where: 'id = ?', + whereArgs: [id], + ); + } + + //Bldg Land Ref + Future createBldgLandRef(LandRef landref) async { + final db = await instance.database; + + final data = { + "bldgapprDetailsId": landref.bldgapprDetailsId, + "assessedById": landref.assessedById, + "assessedByName": landref.assessedByName, + "dateCreated": "000", + "dateModified": "000", + "owner": landref.owner, + "cloaNo": landref.cloaNo, + "lotNo": landref.lotNo, + "tdn": landref.tdn, + "area": landref.area, + "surveyNo": landref.surveyNo, + "blkNo": landref.blkNo + }; + final id = await db.insert('landref', data); + print(landref.copy(id: id).toJson()); + return landref.copy(id: id); + } + + Future updateLandRef(id, LandRef landref) async { + final db = await instance.database; + final data = { + "bldgapprDetailsId": landref.bldgapprDetailsId, + "assessedById": landref.assessedById, + "assessedByName": landref.assessedByName, + "dateCreated": "000", + "dateModified": "000", + "owner": landref.owner, + "cloaNo": landref.cloaNo, + "lotNo": landref.lotNo, + "tdn": landref.tdn, + "area": landref.area, + "surveyNo": landref.surveyNo, + "blkNo": landref.blkNo + }; + + final result = await db.update('landref', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('LanRef Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + Future>> getLandRef(id) async { + final db = await instance.database; + int ids = id; + print('id'); + print(id); + final result = await db + .query('landref', where: 'bldgapprDetailsId = ?', whereArgs: [ids]); + + print('landref test result'); + + if (result.isNotEmpty) { + final firstRow = result[0]; + print(firstRow); + } else { + print('No data found.'); + } + + return result; + } + + Future> getAllLandRef() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('landref', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => LandRef.fromJson2(json)).toList(); + } + + //Bldg Location + Future createBldglocation(BldgLoc bldgloc) async { + final db = await instance.database; + + final data = { + "bldgapprDetailsId": bldgloc.bldgapprDetailsId, + "assessedById": bldgloc.assessedById, + "assessedByName": bldgloc.assessedByName, + "dateCreated": "000", + "dateModified": "000", + "street": bldgloc.street, + "barangay": bldgloc.barangay, + "municipality": bldgloc.municipality, + "province": bldgloc.province + }; + final id = await db.insert('bldgloc', data); + + print(id); + + return bldgloc.copy(id: id); + } + + Future updateLocation(id, BldgLoc bldgloc) async { + final db = await instance.database; + final data = { + "bldgapprDetailsId": bldgloc.bldgapprDetailsId, + "assessedById": bldgloc.assessedById, + "assessedByName": bldgloc.assessedByName, + "dateCreated": "000", + "dateModified": "000", + "street": bldgloc.street, + "barangay": bldgloc.barangay, + "municipality": bldgloc.municipality, + "province": bldgloc.province + }; + + final result = await db.update('bldgloc', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('Location Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + Future>> getLocation(id) async { + final db = await instance.database; + final results = await db.query('bldgloc', + where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1); + print('loc test result'); + print(results); + + return results; + } + + //Bldg General Description + + Future createBldgGeneralDescription(GeneralDesc gendesc) async { + final db = await instance.database; + + final data = { + "bldgapprDetailsId": gendesc.bldgapprDetailsId, + "assessedById": gendesc.assessedById, + "assessedByName": gendesc.assessedByName, + "dateCreated": 'None', + "dateModified": 'None', + "bldgKind": gendesc.bldgKind, + "strucType": gendesc.strucType, + "bldgPermit": gendesc.bldgPermit, + "dateIssued": gendesc.dateIssued, + "cct": gendesc.cct, + "certCompletionIssued": gendesc.certCompletionIssued, + "certOccupancyIssued": gendesc.certOccupancyIssued, + "dateCompleted": gendesc.dateCompleted, + "dateOccupied": gendesc.dateOccupied, + "bldgAge": gendesc.bldgAge, + "noStoreys": gendesc.noStoreys, + "area1Stfloor": gendesc.area1Stfloor, + "area2Ndfloor": gendesc.area2Ndfloor, + "area3Rdfloor": gendesc.area3Rdfloor, + "area4Thfloor": gendesc.area4Thfloor, + "totalFloorArea": gendesc.totalFloorArea, + "floorSketch": 'None', + "actualUse": gendesc.actualUse, + "unitValue": gendesc.unitValue + }; + final id = await db.insert('gendesc', data); + print(gendesc.copy(id: id)); + return gendesc.copy(id: id); + } + + Future>> getGeneralDescription(id) async { + final db = await instance.database; + final results = await db.query('gendesc', + where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1); + print('gendesc test result'); + print(results); + + return results; + } + + Future updateGeneralDescription(id, GeneralDesc gendesc) async { + final db = await instance.database; + final data = { + "bldgapprDetailsId": gendesc.bldgapprDetailsId, + "assessedById": gendesc.assessedById, + "assessedByName": gendesc.assessedByName, + "dateCreated": 'None', + "dateModified": 'None', + "bldgKind": gendesc.bldgKind, + "strucType": gendesc.strucType, + "bldgPermit": gendesc.bldgPermit, + "dateIssued": gendesc.dateIssued, + "cct": gendesc.cct, + "certCompletionIssued": gendesc.certCompletionIssued, + "certOccupancyIssued": gendesc.certOccupancyIssued, + "dateCompleted": gendesc.dateCompleted, + "dateOccupied": gendesc.dateOccupied, + "bldgAge": gendesc.bldgAge, + "noStoreys": gendesc.noStoreys, + "area1Stfloor": gendesc.area1Stfloor, + "area2Ndfloor": gendesc.area2Ndfloor, + "area3Rdfloor": gendesc.area3Rdfloor, + "area4Thfloor": gendesc.area4Thfloor, + "totalFloorArea": gendesc.totalFloorArea, + "floorSketch": 'None', + "actualUse": gendesc.actualUse, + "unitValue": gendesc.unitValue + }; + + final result = await db.update('gendesc', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('GenDesc Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + // Floor Sketch + + Future createFloorSketch(FloorSketch floorSketch) async { + final db = await instance.database; + + final data = { + // "id": treesImprovements.id, + "bldgappr_details_id": floorSketch.bldgapprDetailsId, + "date_created": floorSketch.dateCreated, + "floor_sketch": floorSketch.floorSketch, + "gen_code": "5TH" + }; + final id = await db.insert('bldg_floor_sketch', data); + return floorSketch.copy(bldgapprDetailsId: id); + } + + Future>> getFloorSketch(id) async { + final db = await instance.database; + final results = await db.query('bldg_floor_sketch', + where: "bldgappr_details_id = ?", whereArgs: [id], limit: 1); + print('floor sketch test result'); + print(results); + + return results; + } + + //Structural Materials + + Future createStructuralMaterials( + StructureMaterialsII materials) async { + final db = await instance.database; + + final data = { + // "id": materials.id, + "bldgapprDetailsId": materials.bldgapprDetailsId, + "foundation": materials.foundation!.join(', ').splitMapJoin(', '), + "columns": materials.columns!.join(', ').splitMapJoin(', '), + "beams": materials.beams!.join(', ').splitMapJoin(', '), + "trussFraming": materials.trussFraming!.join(', ').splitMapJoin(', '), + "roof": materials.roof!.join(', ').splitMapJoin(', '), + "flooring": materials.flooring!.join(', ').splitMapJoin(', '), + "walls": materials.walls!.join(', ').splitMapJoin(', '), + "assessedById": materials.assessedById, + "assessedByName": materials.assessedByName, + "dateCreated": materials.dateCreated, + "dateModified": materials.dateModified, + "gen_code": materials.genCode + }; + final id = await db.insert('structural_materials', data); + print('strct Mat test idcopy'); + print(id); + return materials.copy(id: id); + } + + Future>> getStructuralMaterials(id) async { + final db = await instance.database; + final results = await db.query('structural_materials', + where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1); + print('strucmat test result'); + print(results); + + return results; + } + + Future updateStructuralMaterial( + id, StructureMaterialsII materials) async { + final db = await instance.database; + final data = { + "foundation": materials.foundation?.join(', ').splitMapJoin(', '), + "columns": materials.columns!.join(', ').splitMapJoin(', '), + "beams": materials.beams!.join(', ').splitMapJoin(', '), + "trussFraming": materials.trussFraming!.join(', ').splitMapJoin(', '), + "roof": materials.roof!.join(', ').splitMapJoin(', '), + "flooring": materials.flooring!.join(', ').splitMapJoin(', '), + "walls": materials.walls!.join(', ').splitMapJoin(', '), + }; + + final result = await db.update('structural_materials', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('Structural Materials Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + //Additional Items + + Future createAdditionalItems( + AdditionalItems addItems) async { + final db = await instance.database; + + final data = { + // "id": addItems.id, + "bldgapprDetailsId": addItems.bldgapprDetailsId, + "classId": addItems.classId, + "className": addItems.className, + "structType": addItems.structType, + "unitValue": addItems.unitValue, + "baseUnitValue": addItems.baseUnitValue, + "area": addItems.area, + "marketValue": addItems.marketValue, + "depreciationRate": addItems.depreciationRate, + "adjustedMarketVal": addItems.adjustedMarketVal, + "amtDepreciation": addItems.amtDepreciation, + "painted": addItems.painted == true ? '1' : 0, + "secondhand": addItems.secondhand == true ? '1' : 0, + "paintedUnitval": addItems.paintedUnitval, + "secondhandUnitval": addItems.secondhandUnitval, + "actualUse": addItems.actualUse, + "gen_code": addItems.genCode + }; + final id = await db.insert('additionalitems', data); + return addItems.copy(id: id); + } + + Future> readAdditionalItems() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('additionalitems', orderBy: orderBy); + + return result.map((json) => AdditionalItems.fromJson(json)).toList(); + } + + Future>> getAdditionalItems(id) async { + final db = await instance.database; + final results = await db.query('additionalitems', + where: "bldgapprDetailsId = ?", whereArgs: [id]); + print('add edit test result'); + print(results); + + return results; + } + + Future deleteAdditionalItems({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'additionalitems', + where: 'id = ?', + whereArgs: [id], + ); + } + + // Building and Structure + + Future createBuildingAndStructure( + BldgAndStructure bldgAndStructure) async { + final db = await instance.database; + + final data = { + // "id": bldgAndStructure.id, + "bldgapprDetailsId": bldgAndStructure.bldgapprDetailsId, + "assessedById": 'none', + "assessedByName": 'none', + "dateCreated": 'none', + "dateModified": 'none', + "bldgType": bldgAndStructure.bldgType, + "strucType": bldgAndStructure.structType, + "description": bldgAndStructure.description, + "actualUse": bldgAndStructure.actualUse, + "floorCount": bldgAndStructure.floorCount, + "bldgArea": bldgAndStructure.bldgArea, + "unitValue": bldgAndStructure.unitValue, + "depRate": bldgAndStructure.depRate, + "marketValue": bldgAndStructure.marketValue, + "depAmount": bldgAndStructure.depAmount, + "adjustedMarketValue": bldgAndStructure.adjustedMarketValue, + "buccPercentage": bldgAndStructure.buccPercentage, + }; + final id = await db.insert('bldg_and_structure', data); + return bldgAndStructure.copy(id: id); + } + + Future> readBuildingAndStructure() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('bldg_and_structure', orderBy: orderBy); + + return result.map((json) => BldgAndStructure.fromJson(json)).toList(); + } + + Future>> getBuildingAndStructure(id) async { + final db = await instance.database; + final results = await db.query('bldg_and_structure', + where: "bldgapprDetailsId = ?", whereArgs: [id]); + print('add edit test result'); + print(results); + + return results; + } + + Future deleteBuildingAndStructure({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'bldg_and_structure', + where: 'id = ?', + whereArgs: [id], + ); + } + + //Bldg Appraisal + + Future createBldgAppraisal( + PropertyAppraisal appraisal) async { + final db = await instance.database; + + final data = { + // "id": appraisal.id, + "bldgapprDetailsId": appraisal.bldgapprDetailsId, + "assessedById": appraisal.assessedById, + "assessedByName": appraisal.assessedByName, + "dateCreated": appraisal.dateCreated, + "dateModified": appraisal.dateModified, + "unitconstructCost": appraisal.unitconstructCost, + "buildingCore": appraisal.buildingCore, + "unitconstructSubtotal": appraisal.unitconstructSubtotal, + "depreciationRate": appraisal.depreciationRate, + "depreciationCost": appraisal.depreciationCost, + "costAddItems": appraisal.costAddItems, + "addItemsSubtotal": appraisal.addItemsSubtotal, + "totalpercentDepreciation": appraisal.totalpercentDepreciation, + "marketValue": appraisal.marketValue, + "totalArea": appraisal.totalArea, + "actualUse": appraisal.actualUse + }; + final id = await db.insert('bldg_appraisal', data); + return appraisal.copy(id: id); + } + + Future>> getBldgAppraisal(id) async { + final db = await instance.database; + final results = await db.query('bldg_appraisal', + where: "bldgapprDetailsId = ?", whereArgs: [id]); + print('appraisal edit test result'); + print(results); + + return results; + } + + Future updateAppraisal(id, PropertyAppraisal appraisal) async { + final db = await instance.database; + final data = { + "bldgapprDetailsId": appraisal.bldgapprDetailsId, + "assessedById": appraisal.assessedById, + "assessedByName": appraisal.assessedByName, + "dateCreated": appraisal.dateCreated, + "dateModified": appraisal.dateModified, + "unitconstructCost": appraisal.unitconstructCost, + "buildingCore": appraisal.buildingCore, + "unitconstructSubtotal": appraisal.unitconstructSubtotal, + "depreciationRate": appraisal.depreciationRate, + "depreciationCost": appraisal.depreciationCost, + "costAddItems": appraisal.costAddItems, + "addItemsSubtotal": appraisal.addItemsSubtotal, + "totalpercentDepreciation": appraisal.totalpercentDepreciation, + "marketValue": appraisal.marketValue, + "totalArea": appraisal.totalArea, + "actualUse": appraisal.actualUse + }; + + final result = await db.update('bldg_appraisal', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('Appraisal Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + //Bldg Assessment + Future createBldgAssessment( + PropertyAssessment assessment) async { + final db = await instance.database; + print('assesss'); + print(assessment.toJson()); + + final data = { + // "id": assessment.id, + "bldgapprDetailsId": assessment.bldgapprDetailsId, + "assessedById": assessment.assessedById, + "assessedByName": assessment.assessedByName, + "dateCreated": assessment.dateCreated, + "dateModified": assessment.dateModified, + "actualUse": assessment.actualUse, + "marketValue": assessment.marketValue, + "assessmentLevel": assessment.assessmentLevel, + "assessedValue": assessment.assessedValue, + "taxable": assessment.taxable, + "exempt": assessment.exempt, + "qtr": assessment.qtr, + "yr": assessment.yr, + "appraisedbyName": assessment.appraisedbyName, + "appraisedbyDate": assessment.appraisedbyDate, + "recommendapprName": assessment.recommendapprName, + "recommendapprDate": assessment.recommendapprDate, + "approvedbyName": assessment.approvedbyName, + "approvedbyDate": assessment.approvedbyDate, + "memoranda": assessment.memoranda, + "swornstatementNo": assessment.swornstatementNo, + "dateReceived": assessment.dateReceived, + "entryDateAssessment": assessment.entryDateAssessment, + "entryDateBy": assessment.entryDateBy, + "gen_code": assessment.genCode, + "note": assessment.note, + "appraisedby_designation": assessment.appraisedbyDesignation, + "recommendappr_designation": assessment.recommendapprDesignation, + "approvedby_designation": assessment.approvedbyDesignation + }; + final id = await db.insert('bldg_assessment', data); + return assessment.copy(id: id); + } + + Future>> getBldgAssessment(id) async { + final db = await instance.database; + final results = await db.query('bldg_assessment', + where: "bldgapprDetailsId = ?", whereArgs: [id]); + print('assessment edit test result'); + print(results); + + return results; + } + + Future updateAssessment(id, PropertyAssessment assessment) async { + final db = await instance.database; + final data = { + "bldgapprDetailsId": assessment.bldgapprDetailsId, + "actualUse": assessment.actualUse, + "marketValue": assessment.marketValue, + "assessmentLevel": assessment.assessmentLevel, + "assessedValue": assessment.assessedValue, + "taxable": assessment.taxable, + "exempt": assessment.exempt, + "qtr": assessment.qtr, + "yr": assessment.yr, + "appraisedbyName": assessment.appraisedbyName, + "appraisedbyDate": assessment.appraisedbyDate, + "recommendapprName": assessment.recommendapprName, + "recommendapprDate": assessment.recommendapprDate, + "approvedbyName": assessment.approvedbyName, + "memoranda": assessment.memoranda, + "swornstatementNo": assessment.swornstatementNo, + "dateReceived": assessment.dateReceived, + "entryDateAssessment": assessment.entryDateAssessment, + "entryDateBy": assessment.entryDateBy, + "appraisedby_designation": assessment.appraisedbyDesignation, + "recommendappr_designation": assessment.recommendapprDesignation, + "approvedby_designation": assessment.approvedbyDesignation + }; + + final result = await db.update('bldg_assessment', data, + where: "bldgapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('Assessment Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + +//Land Property Owner + + Future createLandOwner( + LandPropertyOwner landPropertyOwner) async { + final db = await instance.database; + + final data = { + // "id": landPropertyOwner.id, + "assessedById": landPropertyOwner.assessedById, + "assessedByName": landPropertyOwner.assessedByName, + "dateCreated": landPropertyOwner.dateCreated, + "dateModified": landPropertyOwner.dateModified, + "transCode": landPropertyOwner.transCode, + "tdn": landPropertyOwner.tdn, + "pin": landPropertyOwner.pin, + "cloaNo": landPropertyOwner.cloaNo, + "dated": landPropertyOwner.dated, + "surveyNo": landPropertyOwner.surveyNo, + "lotNo": landPropertyOwner.lotNo, + "blkNo": landPropertyOwner.blkNo, + "owner": landPropertyOwner.owner, + "address": landPropertyOwner.address, + "telno": landPropertyOwner.telno, + "tin": landPropertyOwner.tin, + "adminUser": landPropertyOwner.adminUser, + "adminTelno": landPropertyOwner.adminTelno, + "adminAddress": landPropertyOwner.adminAddress, + "adminTin": landPropertyOwner.adminTin, + "faasType": landPropertyOwner.faasType + }; + final id = await db.insert('land_property_owner', data); + final tempID = await SharedPreferences.getInstance(); + print(landPropertyOwner.copy(id: id).toJson()); + await tempID.setInt('landid', id); + return landPropertyOwner.copy(id: id); + } + + Future> getLandPropertyOwner() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('land_property_owner', orderBy: orderBy); + + return result.map((json) => LandPropertyOwner.fromJson2(json)).toList(); + } + + Future updateLandPropertyOwner( + id, LandPropertyOwner landPropertyOwner) async { + final db = await instance.database; + final data = { + // "id": landPropertyOwner.id, + "assessedById": landPropertyOwner.assessedById, + "assessedByName": landPropertyOwner.assessedByName, + "dateCreated": landPropertyOwner.dateCreated, + "dateModified": landPropertyOwner.dateModified, + "transCode": landPropertyOwner.transCode, + "tdn": landPropertyOwner.tdn, + "pin": landPropertyOwner.pin, + "cloaNo": landPropertyOwner.cloaNo, + "dated": landPropertyOwner.dated, + "surveyNo": landPropertyOwner.surveyNo, + "lotNo": landPropertyOwner.lotNo, + "blkNo": landPropertyOwner.blkNo, + "owner": landPropertyOwner.owner, + "address": landPropertyOwner.address, + "telno": landPropertyOwner.telno, + "tin": landPropertyOwner.tin, + "adminUser": landPropertyOwner.adminUser, + "adminTelno": landPropertyOwner.adminTelno, + "adminAddress": landPropertyOwner.adminAddress, + "adminTin": landPropertyOwner.adminTin, + "faasType": landPropertyOwner.faasType + }; + + final result = await db + .update('land_property_owner', data, where: "id = ?", whereArgs: [id]); + + if (result > 0) { + print('Bldg Owner Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + Future deleteLandPropertyOwner({required int id}) async { + final db = await instance.database; + + return await db.delete( + 'land_property_owner', + where: 'id = ?', + whereArgs: [id], + ); + } + + //Land Location + + Future createLandLocation( + LandPropertyLoc landPropertyLoc) async { + final db = await instance.database; + + final data = { + "id": landPropertyLoc.id, + "landapprDetailsId": landPropertyLoc.landapprDetailsId, + "assessedById": landPropertyLoc.assessedById, + "assessedByName": landPropertyLoc.assessedByName, + "dateCreated": landPropertyLoc.dateCreated, + "dateModified": landPropertyLoc.dateModified, + "street": landPropertyLoc.street, + "municipality": landPropertyLoc.municipality, + "barangay": landPropertyLoc.barangay, + "province": landPropertyLoc.province + }; + print('loc test'); + print(data); + final id = await db.insert('land_property_location', data); + final tempID = await SharedPreferences.getInstance(); + + await tempID.setInt('landid', id); + return landPropertyLoc.copy(id: id); + } + + Future>> getLandPropertyLocation(id) async { + final db = await instance.database; + final results = await db.query('land_property_location', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('land_property_location test result'); + print(results); + + return results; + } + + Future updateLandPropertyLocation( + id, LandPropertyLoc landPropertyLoc) async { + final db = await instance.database; + final data = { + "id": landPropertyLoc.id, + "landapprDetailsId": landPropertyLoc.landapprDetailsId, + "assessedById": landPropertyLoc.assessedById, + "assessedByName": landPropertyLoc.assessedByName, + "dateCreated": landPropertyLoc.dateCreated, + "dateModified": landPropertyLoc.dateModified, + "street": landPropertyLoc.street, + "municipality": landPropertyLoc.municipality, + "barangay": landPropertyLoc.barangay, + "province": landPropertyLoc.province + }; + + final result = await db.update('land_property_location', data, + where: "landapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('land_property_location Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + // Land Boundaries + + Future createLandPropertyBoundaries( + LandPropertyBoundaries landPropertyBoundaries) async { + final db = await instance.database; + + final data = { + "id": landPropertyBoundaries.id, + "landapprDetailsId": landPropertyBoundaries.landapprDetailsId, + "assessedById": landPropertyBoundaries.assessedById, + "assessedByName": landPropertyBoundaries.assessedByName, + "dateCreated": landPropertyBoundaries.dateCreated, + "dateModified": landPropertyBoundaries.dateModified, + "north": landPropertyBoundaries.north, + "east": landPropertyBoundaries.east, + "south": landPropertyBoundaries.south, + "west": landPropertyBoundaries.west, + "sketch": landPropertyBoundaries.sketch, + }; + final id = await db.insert('land_property_boundaries', data); + final tempID = await SharedPreferences.getInstance(); + print(landPropertyBoundaries.copy(id: id).toJson()); + await tempID.setInt('tempid', id); + return landPropertyBoundaries.copy(id: id); + } + + Future>> getLandPropertyBoundaries(id) async { + final db = await instance.database; + final results = await db.query('land_property_boundaries', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('get land boundary test result'); + print(results); + + return results; + } + + Future updateLandPropertyBoundaries( + id, LandPropertyBoundaries landPropertyBoundaries) async { + final db = await instance.database; + final data = { + "id": landPropertyBoundaries.id, + "landapprDetailsId": landPropertyBoundaries.landapprDetailsId, + "assessedById": landPropertyBoundaries.assessedById, + "assessedByName": landPropertyBoundaries.assessedByName, + "dateCreated": landPropertyBoundaries.dateCreated, + "dateModified": landPropertyBoundaries.dateModified, + "north": landPropertyBoundaries.north, + "east": landPropertyBoundaries.east, + "south": landPropertyBoundaries.south, + "west": landPropertyBoundaries.west, + "sketch": landPropertyBoundaries.sketch, + }; + + final result = await db.update('land_property_boundaries', data, + where: "landapprDetailsId = ?", whereArgs: [id]); + + if (result > 0) { + print('land_property_boundaries Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } + + //Land Appraisal + + Future createLandAppraisal(LandAppr landPropertyAppr) async { + final db = await instance.database; + + final data = { + "landapprDetailsId": landPropertyAppr.landapprDetailsId, + "classification": landPropertyAppr.classification, + "subClass": landPropertyAppr.subClass, + "area": landPropertyAppr.area, + "unitValue": landPropertyAppr.unitValue, + "baseMarketval": landPropertyAppr.baseMarketval + }; + + print('data'); + print(data); + + final id = await db.insert('land_property_appr', data); + print(id); + + return landPropertyAppr.copy(id: id); + } + + Future> readLandPropertyAppraisal() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('land_property_appr', orderBy: orderBy); + + return result.map((json) => LandAppr.fromJson(json)).toList(); + } + + Future>> getLandPropertyAppraisal(id) async { + final db = await instance.database; + final results = await db.query('land_property_appr', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('add edit test result'); + print(results); + + return results; + } + + Future deleteLandPropertyAppraisal({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'land_property_appr', + where: 'id = ?', + whereArgs: [id], + ); + } + + //Land Adjustments + + Future createValueAdjustments( + ValueAdjustments adjustments) async { + final db = await instance.database; + + final data = { + // "id": adjustments.id, + "landapprDetailsId": adjustments.landapprDetailsId, + "baseMarketval": adjustments.baseMarketval, + "adjustmentFactors": adjustments.adjustmentFactors, + "adjustment": adjustments.adjustment, + "valueAdjustment": adjustments.valueAdjustment, + "marketValue": adjustments.marketValue + }; + final id = await db.insert('value_adjustments', data); + return adjustments.copy(id: id); + } + + Future> readAllValueAdjustments() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('value_adjustments', orderBy: orderBy); + print('result'); + print(result.toString()); + + return result.map((json) => ValueAdjustments.fromJson2(json)).toList(); + } + + Future>> getValueAdjustments(id) async { + final db = await instance.database; + final results = await db.query('value_adjustments', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('land value Adjustments test result'); + print(results); + + return results; + } + + Future deleteValueAdjustment({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'value_adjustments', + where: 'id = ?', + whereArgs: [id], + ); + } + + // Land Other Improvements + + Future createOtherImprovements( + OtherImprovements otherImprovements) async { + final db = await instance.database; + + final data = { + "landapprDetailsId": otherImprovements.landapprDetailsId, + "kindsOfTrees": otherImprovements.kindsOfTrees, + "subclassAge": otherImprovements.subclassAge, + "quantity": otherImprovements.quantity, + "unitValue": otherImprovements.unitValue, + "baseMarketval": otherImprovements.baseMarketval, + "noOfProductive": otherImprovements.noOfProductive, + "noOfNonproductive": otherImprovements.noOfNonproductive, + "fruitBearing": otherImprovements.fruitBearing + }; + final id = await db.insert('land_property_other_improvements', data); + return otherImprovements.copy(id: id); + } + + Future>> getOtherImprovements(id) async { + final db = await instance.database; + final results = await db.query('land_property_other_improvements', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('land other improvement test result'); + print(results); + + return results; + } + + Future deleteOtherImprovements({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'land_property_other_improvements', + where: 'id = ?', + whereArgs: [id], + ); + } + + //Land Property Assessment + + Future createLandPropertyAssessment( + LandPropertyAssessment assessment) async { + final db = await instance.database; + + final data = { + // "id": adjustments.id, + "landapprDetailsId": assessment.landapprDetailsId, + "actualUse": assessment.actualUse, + "marketval": assessment.marketval, + "assessmentLevel": assessment.assessmentLevel, + "assessedValue": assessment.assessedValue, + "totalMarketval": assessment.totalMarketval, + "totalAssessedval": assessment.totalAssessedval + }; + final id = await db.insert('land_property_assessment', data); + return assessment.copy(id: id); + } + + Future>> getLandPropertyAssessment(id) async { + final db = await instance.database; + final results = await db.query('land_property_assessment', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('land_property_assessment test result'); + print(results); + + return results; + } + + Future deleteLandPropertyAssessment({required int id}) async { + final db = await instance.database; + print(id); + + return await db.delete( + 'land_property_assessment', + where: 'id = ?', + whereArgs: [id], + ); + } + +// Land Property Sgnatories + + Future createLandPropertySignatories(LandExt landExt) async { + final db = await instance.database; + + final data = { + // "id": landExt.id, + "landapprDetailsId": landExt.landapprDetailsId, + "assessedById": landExt.assessedById, + "assessedByName": landExt.assessedByName, + "dateCreated": landExt.dateCreated, + "dateModified": landExt.dateModified, + "taxable": landExt.taxable, + "exempt": landExt.exempt, + "qtr": landExt.qtr, + "yr": landExt.yr, + "appraisedbyName": landExt.appraisedbyName, + "appraisedbyDate": landExt.appraisedbyDate, + "appraisedbyDesignation": landExt.appraisedbyDesignation, + "recommendapprName": landExt.recommendapprName, + "recommendapprDate": landExt.recommendapprDate, + "recommendapprDesignation": landExt.recommendapprDesignation, + "approvedbyName": landExt.approvedbyName, + "approvedbyDate": landExt.approvedbyDate, + "approvedbyDesignation": landExt.approvedbyDesignation, + "memoranda": landExt.memoranda, + "swornstatementNo": landExt.swornstatementNo, + "dateReceived": landExt.dateReceived, + "entryDateAssessment": landExt.entryDateAssessment, + "entryDateBy": landExt.entryDateBy, + }; + final id = await db.insert('land_property_ext', data); + final tempID = await SharedPreferences.getInstance(); + print(landExt.copy(id: id).toJson()); + await tempID.setInt('tempid', id); + return landExt.copy(id: id); + } + + Future>> getLandPropertySignature(id) async { + final db = await instance.database; + final results = await db.query('land_property_ext', + where: "landapprDetailsId = ?", whereArgs: [id]); + print('land_property_ext test result'); + print(results); + + return results; + } + + Future updateLandPropertySignature(id, LandExt landExt) async { + final db = await instance.database; + final data = { + // "id": landPropertyOwner.id, + "landapprDetailsId": landExt.landapprDetailsId, + "assessedById": landExt.assessedById, + "assessedByName": landExt.assessedByName, + "dateCreated": landExt.dateCreated, + "dateModified": landExt.dateModified, + "taxable": landExt.taxable, + "exempt": landExt.exempt, + "qtr": landExt.qtr, + "yr": landExt.yr, + "appraisedbyName": landExt.appraisedbyName, + "appraisedbyDate": landExt.appraisedbyDate, + "recommendapprName": landExt.recommendapprName, + "recommendapprDate": landExt.recommendapprDate, + "approvedbyName": landExt.approvedbyName, + "approvedbyDate": landExt.approvedbyDate, + "memoranda": landExt.memoranda, + "swornstatementNo": landExt.swornstatementNo, + "dateReceived": landExt.dateReceived, + "entryDateAssessment": landExt.entryDateAssessment, + "entryDateBy": landExt.entryDateBy, + }; + + final result = await db + .update('land_property_ext', data, where: "id = ?", whereArgs: [id]); + + if (result > 0) { + print('Land Signatory Updated Successfully'); + } else { + throw Exception('Failed to update the Journal.'); + } + return result; + } +} diff --git a/lib/sevices/offline/offline_passo/building/landref_services.dart b/lib/sevices/offline/offline_passo/building/landref_services.dart new file mode 100644 index 0000000..e69de29 diff --git a/lib/sevices/offline/offline_passo/building/location_services.dart b/lib/sevices/offline/offline_passo/building/location_services.dart new file mode 100644 index 0000000..e69de29 diff --git a/lib/sevices/offline/offline_passo/building/property_owner_info_service.dart b/lib/sevices/offline/offline_passo/building/property_owner_info_service.dart new file mode 100644 index 0000000..0d7f13d --- /dev/null +++ b/lib/sevices/offline/offline_passo/building/property_owner_info_service.dart @@ -0,0 +1,291 @@ +import 'package:path/path.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:unit2/model/passo/additional_items.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 '../../../../model/passo/todo.dart'; + +class PropertyOwnerInfoServices { + static final PropertyOwnerInfoServices instance = + PropertyOwnerInfoServices._init(); + static Database? _database; + PropertyOwnerInfoServices._init(); + + Future get database async { + if (_database != null) return _database!; + + _database = await _initDB('passo.db'); + return _database!; + } + + Future _initDB(String filePath) async { + final dbPath = await getDatabasesPath(); + final path = join(dbPath, filePath); + + return await openDatabase(path, version: 1, onCreate: _createDB); + } + + Future _createDB(Database db, int version) async { + // const idType = 'INTEGER PRIMARY KEY AUTOINCREMENT'; + // const textType = 'TEXT NOT NULL'; + // const boolType = 'BOOLEAN NOT NULL'; + // const integerType = 'INTEGER NOT NULL'; + + await db.execute(''' + CREATE TABLE items ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + transCode TEXT NOT NULL, + tdn TEXT NOT NULL, + pin TEXT NOT NULL, + owner TEXT NOT NULL, + address TEXT NOT NULL, + telno TEXT NOT NULL, + tin TEXT NOT NULL, + adminUser TEXT NOT NULL, + adminAddress TEXT NOT NULL, + adminTelno TEXT NOT NULL, + adminTin TEXT NOT NULL, + faasType TEXT NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE landref ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + owner TEXT NOT NULL, + cloaNo TEXT NOT NULL, + lotNo TEXT NOT NULL, + tdn TEXT NOT NULL, + area TEXT NOT NULL, + surveyNo TEXT NOT NULL, + blkNo TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE location ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + street TEXT NOT NULL, + barangay TEXT NOT NULL, + municipality TEXT NOT NULL, + province TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE additionalitems ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + classId TEXT NOT NULL, + className TEXT NOT NULL, + structType TEXT NOT NULL, + unitValue TEXT NOT NULL, + baseUnitValue TEXT NOT NULL, + area TEXT NOT NULL, + marketValue TEXT NOT NULL, + depreciationRate TEXT NOT NULL, + adjustedMarketVal TEXT NOT NULL, + amtDepreciation TEXT NOT NULL, + painted TEXT NOT NULL, + secondhand TEXT NOT NULL, + paintedUnitval TEXT NOT NULL, + secondhandUnitval TEXT NOT NULL, + actualUse TEXT NOT NULL + ) + '''); + } + + Future create(PropertyInfo propertyInfo) async { + final db = await instance.database; + + final data = { + "id": propertyInfo.id, + "transCode": propertyInfo.transCode, + "tdn": propertyInfo.tdn, + "pin": propertyInfo.pin, + "fname": propertyInfo.fname, + "mname": propertyInfo.mname, + "lname": propertyInfo.lname, + "bday": propertyInfo.bday, + "address": propertyInfo.address, + "telno": propertyInfo.telno, + "tin": propertyInfo.tin, + "adminUser": propertyInfo.adminUser, + "adminAddress": propertyInfo.adminAddress, + "adminTelno": propertyInfo.adminTelno, + "adminTin": propertyInfo.adminTin, + "faasType": propertyInfo.faasType, + "assessedById": propertyInfo.assessedById, + "assessedByName": propertyInfo.assessedByName, + }; + final id = await db.insert('items', data); + return propertyInfo.copy(id: id); + } + + Future createLandRef(LandRef landref) async { + final db = await instance.database; + + final data = { + "id": landref.id, + "bldgapprDetailsId": landref.bldgapprDetailsId, + "assessedById": landref.assessedById, + "assessedByName": landref.assessedByName, + "cloaNo": landref.cloaNo, + "lotNo": landref.lotNo, + "tdn": landref.tdn, + "area": landref.area, + "surveyNo": landref.surveyNo, + "blkNo": landref.blkNo + }; + final id = await db.insert('landref', data); + return landref.copy(id: id); + } + + Future createLocation(BldgLoc loc) async { + final db = await instance.database; + + final data = { + "id": loc.id, + "bldgapprDetailsId": loc.bldgapprDetailsId, + "assessedById": loc.assessedById, + "assessedByName": loc.assessedByName, + "street": loc.street, + "barangay": loc.barangay, + "municipality": loc.municipality, + "province": loc.province + }; + final id = await db.insert('location', data); + return loc.copy(id: id); + } + + Future createGenDesc(GeneralDesc gendesc) async { + final db = await instance.database; + + final data = { + "id": gendesc.id, + "bldgapprDetailsId": gendesc.bldgapprDetailsId, + "assessedById": gendesc.assessedById, + "assessedByName": gendesc.assessedByName, + "dateCreated": gendesc.dateCreated, + "dateModified": gendesc.dateModified, + "bldgKind": gendesc.bldgKind, + "strucType": gendesc.strucType, + "bldgPermit": gendesc.bldgPermit, + "dateIssued": gendesc.dateIssued, + "cct": gendesc.cct, + "certCompletionIssued": gendesc.certCompletionIssued, + "certOccupancyIssued": gendesc.certOccupancyIssued, + "dateCompleted": gendesc.dateCompleted, + "dateOccupied": gendesc.dateOccupied, + "bldgAge": gendesc.bldgAge, + "noStoreys": gendesc.noStoreys, + "area1Stfloor": gendesc.area1Stfloor, + "area2Ndfloor": gendesc.area2Ndfloor, + "area3Rdfloor": gendesc.area3Rdfloor, + "area4Thfloor": gendesc.area4Thfloor, + "totalFloorArea": gendesc.totalFloorArea, + "floorSketch": gendesc.floorSketch, + "actualUse": gendesc.actualUse + }; + final id = await db.insert('location', data); + return gendesc.copy(id: id); + } + + Future createAdditionalItems( + AdditionalItems addItems) async { + final db = await instance.database; + + final data = { + "id": addItems.id, + "bldgapprDetailsId": addItems.bldgapprDetailsId, + "classId": addItems.classId, + "className": addItems.className, + "structType": addItems.structType, + "unitValue": addItems.unitValue, + "baseUnitValue": addItems.baseUnitValue, + "area": addItems.area, + "marketValue": addItems.marketValue, + "depreciationRate": addItems.depreciationRate, + "adjustedMarketVal": addItems.adjustedMarketVal, + "amtDepreciation": addItems.amtDepreciation, + "painted": addItems.painted, + "secondhand": addItems.secondhand, + "paintedUnitval": addItems.paintedUnitval, + "secondhandUnitval": addItems.secondhandUnitval, + "actualUse": addItems.actualUse + }; + final id = await db.insert('additionalitems', data); + return addItems.copy(id: id); + } + + Future readTodo({required int id}) async { + final db = await instance.database; + + final maps = await db.query( + todoTable, + columns: TodoFields.values, + where: '${TodoFields.id} = ?', + whereArgs: [id], + ); + + if (maps.isNotEmpty) { + return Todo.fromJson(maps.first); + } else { + throw Exception('ID $id not found'); + } + } + + Future> readAllTodos() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('items', orderBy: orderBy); + + return result.map((json) => PropertyInfo.fromJson(json)).toList(); + } + + Future> readAdditionalItems() async { + final db = await instance.database; + const orderBy = 'id'; + final result = await db.query('additional_items', orderBy: orderBy); + + return result.map((json) => AdditionalItems.fromJson(json)).toList(); + } + + Future update({required Todo todo}) async { + final db = await instance.database; + + return db.update( + todoTable, + todo.toJson(), + where: '${TodoFields.id} = ?', + whereArgs: [todo.id], + ); + } + + Future delete({required int id}) async { + final db = await instance.database; + + return await db.delete( + 'items', + where: 'id = ?', + whereArgs: [id], + ); + } + + Future close() async { + final db = await instance.database; + + db.close(); + } +} diff --git a/lib/sevices/passo/building/building_services.dart b/lib/sevices/passo/building/building_services.dart new file mode 100644 index 0000000..d30f991 --- /dev/null +++ b/lib/sevices/passo/building/building_services.dart @@ -0,0 +1,35 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:unit2/model/passo/building_details.dart'; +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 BuildingServices { + static final BuildingServices _instance = BuildingServices(); + static BuildingServices get instance => _instance; + + String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; + String xClientKeySecret = "unitcYqAN7GGalyz"; + + Future add(details) async { + String path = Url.instance.buildingDetails(); + 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: details, headers: headers); + } catch (e) { + log(e.toString()); + } + return response; + } +} diff --git a/lib/sevices/passo/land/land_property_owner.dart b/lib/sevices/passo/land/land_property_owner.dart index 2f788aa..8c14a3e 100644 --- a/lib/sevices/passo/land/land_property_owner.dart +++ b/lib/sevices/passo/land/land_property_owner.dart @@ -72,4 +72,29 @@ class LandServices { } return response; } + + Future remove(id) async { + String path = Url.instance.getLandOwnerInfo(); + 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/offline/building/property_info.dart b/lib/sevices/passo/offline/building/property_info.dart new file mode 100644 index 0000000..56a1799 --- /dev/null +++ b/lib/sevices/passo/offline/building/property_info.dart @@ -0,0 +1,26 @@ +import 'package:sqflite/sqflite.dart' as sql; + +class SQLHeper { + static Future createTables(sql.Database database) async { + await database.execute("""CREATE TABLE property_info ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + assessed_by_id TEXT, + assessed_by_name TEXT, + date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + date_modified TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + trans_code TEXT, + tdn TEXT, + pin TEXT, + owner TEXT, + address TEXT, + telno TEXT, + tin TEXT, + admin_user TEXT, + admin_address TEXT, + admin_telno TEXT, + admin_tin TEXT, + faas_type TEXT + ) + """); + } +} diff --git a/lib/sevices/roles/rbac_operations/agency_services.dart b/lib/sevices/roles/rbac_operations/agency_services.dart index 5445652..380223a 100644 --- a/lib/sevices/roles/rbac_operations/agency_services.dart +++ b/lib/sevices/roles/rbac_operations/agency_services.dart @@ -1,6 +1,5 @@ import 'dart:convert'; - -import 'package:unit2/screens/profile/components/other_information/org_membership/add_modal.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; @@ -10,17 +9,15 @@ import 'package:http/http.dart' as http; class AgencyServices { static final AgencyServices _instance = AgencyServices(); static AgencyServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + String path = Url.instance.agencies(); + Future> getAgencies() async { List agencies = []; - String path = Url.instance.agencies(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(path: path, headers: headers, param: {}); @@ -38,34 +35,30 @@ class AgencyServices { } return agencies; } - Future>add({required Agency agency})async{ - Map statusResponse = {}; - String path = Url.instance.postAgencies(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + + Future> add({required Agency agency}) async { + Map statusResponse = {}; Map body = { - "name":agency.name, - "category_id":agency.category!.id, - "private_entity":agency.privateEntity, - "contact_info":null, + "name": agency.name, + "category_id": agency.category!.id, + "private_entity": agency.privateEntity, + "contact_info": null, }; - try{ - http.Response response = await Request.instance.postRequest(param: {},path: path, body: body,headers: headers); - if(response.statusCode == 201){ + try { + http.Response response = await Request.instance + .postRequest(param: {}, path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { Map data = jsonDecode(response.body); - statusResponse = data; - }else{ - Map data = jsonDecode(response.body); String message = data['message']; statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); } - }catch(e){ + } catch (e) { throw e.toString(); } return statusResponse; diff --git a/lib/sevices/roles/rbac_operations/assigned_area_services.dart b/lib/sevices/roles/rbac_operations/assigned_area_services.dart index 7dd4962..07972d2 100644 --- a/lib/sevices/roles/rbac_operations/assigned_area_services.dart +++ b/lib/sevices/roles/rbac_operations/assigned_area_services.dart @@ -1,24 +1,22 @@ import 'dart:convert'; import 'package:unit2/model/profile/assigned_area.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/urls.dart'; import 'package:http/http.dart' as http; - import '../../../utils/request.dart'; class RbacAssignedAreaServices { static final RbacAssignedAreaServices _instance = RbacAssignedAreaServices(); static RbacAssignedAreaServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; + String path = Url.instance.getAssignAreas(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getAssignedArea({required int id}) async { List userAssignedAreas = []; - String path = Url.instance.getAssignAreas(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map param = { "assigned_role__user__id": id.toString(), }; @@ -39,20 +37,18 @@ class RbacAssignedAreaServices { } return userAssignedAreas; } - Future deleteAssignedArea({required int areaId}) async { + + Future deleteAssignedArea({required int areaId}) async { bool success = false; - String path = "${Url.instance.getAssignAreas()}$areaId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: "${path + areaId.toString()}/", + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; - }else{ + } else { success = false; } } catch (e) { @@ -60,28 +56,30 @@ class RbacAssignedAreaServices { } return success; } - Future> add ({required int userId, required int roleId, required int areaTypeId, required String areaId}) async{ - String path = Url.instance.getAssignAreas(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; - Map? responseStatus = {}; + + Future> add( + {required int userId, + required int roleId, + required int areaTypeId, + required String areaId}) async { + Map? responseStatus = {}; Map body = { - "user_id":userId, - "role_id":roleId, - "assigned_areas": [{"areatypeid":areaTypeId,"areaid":areaId}] + "user_id": userId, + "role_id": roleId, + "assigned_areas": [ + {"areatypeid": areaTypeId, "areaid": areaId} + ] }; - try{ - http.Response response = await Request.instance.postRequest(path: path, headers: headers, body: body, param: {}); - if(response.statusCode == 201){ - Map data = jsonDecode(response.body); + try { + http.Response response = await Request.instance + .postRequest(path: path, headers: headers, body: body, param: {}); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); responseStatus = data; } else { responseStatus.addAll({'success': false}); } - }catch(e){ + } catch (e) { throw e.toString(); } return responseStatus; diff --git a/lib/sevices/roles/rbac_operations/module_objects_services.dart b/lib/sevices/roles/rbac_operations/module_objects_services.dart index 87e9890..5652367 100644 --- a/lib/sevices/roles/rbac_operations/module_objects_services.dart +++ b/lib/sevices/roles/rbac_operations/module_objects_services.dart @@ -1,7 +1,6 @@ import 'dart:convert'; - -import 'package:unit2/model/login_data/user_info/module.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../model/rbac/rbac_rbac.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; @@ -10,16 +9,14 @@ class RbacModuleObjectsServices { static final RbacModuleObjectsServices _instance = RbacModuleObjectsServices(); static RbacModuleObjectsServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - Future> getModuleObjects() async { - List moduleObjects = []; - String path = Url.instance.getModuleObjects(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret':xClientSecret }; + String path = Url.instance.getModuleObjects(); + Future> getModuleObjects() async { + List moduleObjects = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -38,19 +35,12 @@ class RbacModuleObjectsServices { return moduleObjects; } - ////Add Future> add({ required int assignerId, required int? moduleId, required List objectsId, }) async { - String path = Url.instance.getModuleObjects(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "module_id": moduleId, "objects": objectsId, @@ -76,17 +66,11 @@ class RbacModuleObjectsServices { return statusResponse; } - Future deleteRbacModuleObject({required int moduleObjectId}) async { + Future delete({required int moduleObjectId}) async { bool success = false; - String path = "${Url.instance.getModuleObjects()}$moduleObjectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+moduleObjectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/module_services.dart b/lib/sevices/roles/rbac_operations/module_services.dart index 76ea4a1..1020b70 100644 --- a/lib/sevices/roles/rbac_operations/module_services.dart +++ b/lib/sevices/roles/rbac_operations/module_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacModuleServices { static final RbacModuleServices _instance = RbacModuleServices(); static RbacModuleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacModule() async { - List modules = []; String path = Url.instance.getModules(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Key':xClientKey, + 'X-Client-Secret':xClientSecret }; + Future> getRbacModule() async { + List modules = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacModuleServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getModules(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -88,13 +79,7 @@ class RbacModuleServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getModules()}$moduleId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -106,7 +91,7 @@ class RbacModuleServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: "${path+moduleId.toString()}/", body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -126,15 +111,9 @@ class RbacModuleServices { Future deleteRbacModule({required int moduleId}) async { bool success = false; - String path = "${Url.instance.getModules()}$moduleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+moduleId.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/object_services.dart b/lib/sevices/roles/rbac_operations/object_services.dart index 7e61543..8995600 100644 --- a/lib/sevices/roles/rbac_operations/object_services.dart +++ b/lib/sevices/roles/rbac_operations/object_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacObjectServices { static final RbacObjectServices _instance = RbacObjectServices(); static RbacObjectServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacObjects() async { - List objects = []; - String path = Url.instance.getObject(); - Map headers = { + String path = Url.instance.getObject(); + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRbacObjects() async { + List objects = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacObjectServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getObject(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -67,7 +58,7 @@ class RbacObjectServices { } else { Map data = jsonDecode(response.body); String message = data['message']; - statusResponse.addAll({'message': "Error Adding Object"}); + statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); @@ -87,13 +78,8 @@ class RbacObjectServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getObject()}$objectId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -104,14 +90,14 @@ class RbacObjectServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: "${path+objectId.toString()}/", body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; } else { Map data = jsonDecode(response.body); String message = data['message']; - statusResponse.addAll({'message': "Error Updating Object"}); + statusResponse.addAll({'message': message}); statusResponse.addAll( {'success': false}, ); @@ -124,15 +110,9 @@ class RbacObjectServices { Future deleteRbacRole({required int objectId}) async { bool success = false; - String path = "${Url.instance.getObject()}$objectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+objectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/operation_services.dart b/lib/sevices/roles/rbac_operations/operation_services.dart index f737dc7..7c97b76 100644 --- a/lib/sevices/roles/rbac_operations/operation_services.dart +++ b/lib/sevices/roles/rbac_operations/operation_services.dart @@ -1,24 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacOperationServices { static final RbacOperationServices _instance = RbacOperationServices(); static RbacOperationServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRbacOperations() async { - List roles = []; String path = Url.instance.getOperations(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRbacOperations() async { + List roles = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -43,13 +40,7 @@ class RbacOperationServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getOperations(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -87,13 +78,7 @@ class RbacOperationServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getRbacOperations()}$operationId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -104,7 +89,7 @@ class RbacOperationServices { }; try { http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + .putRequest(path: '${path+operationId.toString()}/', body: body, headers: headers, param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -124,15 +109,9 @@ class RbacOperationServices { Future delete({required int operation}) async { bool success = false; - String path = "${Url.instance.getRbacOperations()}$operation/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+operation.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/permission_assignment_services.dart b/lib/sevices/roles/rbac_operations/permission_assignment_services.dart new file mode 100644 index 0000000..135dbf5 --- /dev/null +++ b/lib/sevices/roles/rbac_operations/permission_assignment_services.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:unit2/model/rbac/permission_assignment.dart'; +import 'package:unit2/utils/global.dart'; +import 'package:unit2/utils/request.dart'; +import 'package:unit2/utils/urls.dart'; +import 'package:http/http.dart' as http; + +class RbacPermissionAssignmentServices { + static final RbacPermissionAssignmentServices _instance = + RbacPermissionAssignmentServices(); + static RbacPermissionAssignmentServices get instance => _instance; + String path = Url.instance.getPermissionAssignment(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; + Future> getPermissionAssignment() async { + List permissionAssignments = []; + try { + http.Response response = await Request.instance + .getRequest(param: {}, path: path, headers: headers); + if (response.statusCode == 200) { + Map data = jsonDecode(response.body); + if (data['data'] != null) { + for (var rbac in data['data']) { + PermissionAssignment permissionAssignment = + PermissionAssignment.fromJson(rbac); + permissionAssignments.add(permissionAssignment); + } + } + } + } catch (e) { + e.toString(); + } + return permissionAssignments; + } + + Future deletePermissionAssignment({required int id}) async { + bool success = false; + try { + http.Response response = await Request.instance + .deleteRequest(path: "${path+id.toString()}/", headers: headers, body: {}, param: {}); + if (response.statusCode == 200) { + success = true; + } + } catch (e) { + throw e.toString(); + } + return success; + } + + Future> addPermissionAssignment( + {required int assignerId, + required List opsId, + required int roleId}) async { + Map statusResponse = {}; + Map body = { + "role_id": roleId, + "permissions": opsId, + "assigner_user_id": assignerId + }; + try { + http.Response response = await Request.instance + .postRequest(param: {}, path: path, body: body, headers: headers); + if (response.statusCode == 201) { + Map data = jsonDecode(response.body); + statusResponse = data; + } else { + Map data = jsonDecode(response.body); + String message = data['message']; + statusResponse.addAll({'message': message}); + statusResponse.addAll( + {'success': false}, + ); + } + } catch (e) { + throw e.toString(); + } + return statusResponse; + } +} diff --git a/lib/sevices/roles/rbac_operations/permission_service.dart b/lib/sevices/roles/rbac_operations/permission_service.dart index aa49ba5..544bf13 100644 --- a/lib/sevices/roles/rbac_operations/permission_service.dart +++ b/lib/sevices/roles/rbac_operations/permission_service.dart @@ -1,25 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/permission.dart'; -import 'package:unit2/model/rbac/rbac.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacPermissionServices { static final RbacPermissionServices _instance = RbacPermissionServices(); static RbacPermissionServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getPersmissions(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key':xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRbacPermission() async { List permissions = []; - String path = Url.instance.getPersmissions(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -46,13 +42,7 @@ class RbacPermissionServices { required int? objectId, required List operationsId, }) async { - String path = Url.instance.getPersmissions(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "object_id": objectId, "operations": operationsId, @@ -80,15 +70,9 @@ class RbacPermissionServices { Future deletePermission ({required int permissionId}) async { bool success = false; - String path = "${Url.instance.getPersmissions()}$permissionId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+permissionId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_assignment_services.dart b/lib/sevices/roles/rbac_operations/role_assignment_services.dart index b9d6eae..e8aceca 100644 --- a/lib/sevices/roles/rbac_operations/role_assignment_services.dart +++ b/lib/sevices/roles/rbac_operations/role_assignment_services.dart @@ -1,30 +1,27 @@ import 'dart:convert'; import 'package:unit2/model/rbac/assigned_role.dart'; -import 'package:unit2/model/rbac/rbac.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; - import 'package:http/http.dart' as http; - import '../../../model/profile/basic_information/primary-information.dart'; class RbacRoleAssignmentServices { static final RbacRoleAssignmentServices _instance = RbacRoleAssignmentServices(); static RbacRoleAssignmentServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getAssignedRoles( - {required String firstname, required String lastname}) async { - List assignedRoles = []; - String path = Url.instance.getRoleAssignment(); + String path = Url.instance.getRoleAssignment(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getAssignedRoles( + {required String firstname, required String lastname}) async { + List assignedRoles = []; + + Map param = { "user__first_name__icontains": firstname, "user__last_name__icontains": lastname @@ -49,15 +46,9 @@ class RbacRoleAssignmentServices { Future deleteAssignedRole({required int roleId}) async { bool success = false; - String path = "${Url.instance.getRoleAssignment()}$roleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: '${path+roleId.toString()}/', headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } @@ -72,13 +63,7 @@ class RbacRoleAssignmentServices { required int? assignerId, required List roles, }) async { - String path = Url.instance.getRoleAssignment(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "user_id": userId, "roles": roles, diff --git a/lib/sevices/roles/rbac_operations/role_extend_services.dart b/lib/sevices/roles/rbac_operations/role_extend_services.dart index b5c0fc9..8200111 100644 --- a/lib/sevices/roles/rbac_operations/role_extend_services.dart +++ b/lib/sevices/roles/rbac_operations/role_extend_services.dart @@ -1,26 +1,23 @@ import 'dart:convert'; import 'package:unit2/model/rbac/role_extend.dart'; -import 'package:unit2/model/rbac/role_under.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleExtendServices { static final RbacRoleExtendServices _instance = RbacRoleExtendServices(); static RbacRoleExtendServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getRoleExtend(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRolesExtend() async { List rolesextend = []; - String path = Url.instance.getRoleExtend(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; - // try { + try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); if (response.statusCode == 200) { @@ -32,9 +29,9 @@ class RbacRoleExtendServices { } } } - // } catch (e) { - // throw e.toString(); - // } + } catch (e) { + throw e.toString(); + } return rolesextend; } @@ -43,13 +40,7 @@ class RbacRoleExtendServices { required int? roleId, required List rolesExtendsId, }) async { - String path = Url.instance.getRoleExtend(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "role_main_id": roleId, "roles_extend": rolesExtendsId, @@ -76,15 +67,12 @@ class RbacRoleExtendServices { Future delete({required int roleExtendId}) async { bool success = false; - String path = "${Url.instance.getRoleExtend()}$roleExtendId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: '${path + roleExtendId.toString()}/', + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_module_services.dart b/lib/sevices/roles/rbac_operations/role_module_services.dart index 27a0779..760a265 100644 --- a/lib/sevices/roles/rbac_operations/role_module_services.dart +++ b/lib/sevices/roles/rbac_operations/role_module_services.dart @@ -1,9 +1,8 @@ import 'dart:convert'; -import 'package:unit2/model/login_data/user_info/module.dart'; import 'package:http/http.dart' as http; import 'package:unit2/model/rbac/role_module.dart'; -import '../../../model/rbac/rbac_rbac.dart'; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; @@ -11,17 +10,14 @@ class RbacRoleModuleServices { static final RbacRoleModuleServices _instance = RbacRoleModuleServices(); static RbacRoleModuleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRoleModules() async { - List roleModules = []; String path = Url.instance.getRoleModules(); - Map headers = { + Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRoleModules() async { + List roleModules = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -46,13 +42,7 @@ class RbacRoleModuleServices { required int? roleId, required List moduleIds, }) async { - String path = Url.instance.getRoleModules(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; Map body = { "role_id": roleId, "modules": moduleIds, @@ -80,15 +70,9 @@ class RbacRoleModuleServices { Future deleteRbacRoleModule({required int moduleObjectId}) async { bool success = false; - String path = "${Url.instance.getRoleModules()}$moduleObjectId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+moduleObjectId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/role_services.dart b/lib/sevices/roles/rbac_operations/role_services.dart index 08a689c..b7609ba 100644 --- a/lib/sevices/roles/rbac_operations/role_services.dart +++ b/lib/sevices/roles/rbac_operations/role_services.dart @@ -1,25 +1,21 @@ import 'dart:convert'; - import 'package:unit2/model/rbac/rbac.dart'; -import 'package:unit2/sevices/profile/education_services.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleServices { static final RbacRoleServices _instance = RbacRoleServices(); static RbacRoleServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - + String path = Url.instance.getRbacRoles(); + Map headers = { + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Client-Key': xClientKey, + 'X-Client-Secret': xClientSecret + }; Future> getRbacRoles() async { List roles = []; - String path = Url.instance.getRbacRoles(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -45,13 +41,7 @@ class RbacRoleServices { required String? slug, required String? short, required int id}) async { - String path = Url.instance.getRbacRoles(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -67,7 +57,7 @@ class RbacRoleServices { Map data = jsonDecode(response.body); statusResponse = data; } else { - Map data = jsonDecode(response.body); + Map data = jsonDecode(response.body); String message = data['message']; statusResponse.addAll({'message': message}); statusResponse.addAll( @@ -89,13 +79,7 @@ class RbacRoleServices { required int? createdBy, required int updatedBy, }) async { - String path = "${Url.instance.getRbacRoles()}$roleId/"; Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String? newSlug = slug?.replaceAll(" ", "-"); Map body = { "name": name, @@ -105,8 +89,11 @@ class RbacRoleServices { "updated_by_id": updatedBy }; try { - http.Response response = await Request.instance - .putRequest(path: path, body: body, headers: headers, param: {}); + http.Response response = await Request.instance.putRequest( + path: "${path + roleId.toString()}/", + body: body, + headers: headers, + param: {}); if (response.statusCode == 200) { Map data = jsonDecode(response.body); statusResponse = data; @@ -126,15 +113,12 @@ class RbacRoleServices { Future deleteRbacRole({required int roleId}) async { bool success = false; - String path = "${Url.instance.getRbacRoles()}$roleId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { - http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + http.Response response = await Request.instance.deleteRequest( + path: "${path + roleId.toString()}/", + headers: headers, + body: {}, + param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/roles_under_services.dart b/lib/sevices/roles/rbac_operations/roles_under_services.dart index 719dab4..e0bacd7 100644 --- a/lib/sevices/roles/rbac_operations/roles_under_services.dart +++ b/lib/sevices/roles/rbac_operations/roles_under_services.dart @@ -2,23 +2,21 @@ import 'dart:convert'; import 'package:unit2/model/rbac/role_under.dart'; import 'package:http/http.dart' as http; +import 'package:unit2/utils/global.dart'; import '../../../utils/request.dart'; import '../../../utils/urls.dart'; class RbacRoleUnderServices { static final RbacRoleUnderServices _instance = RbacRoleUnderServices(); static RbacRoleUnderServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getRolesUnder() async { - List rolesUnder = []; - String path = Url.instance.getRolesUnder(); + String path = Url.instance.getRolesUnder(); Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getRolesUnder() async { + List rolesUnder = []; try { http.Response response = await Request.instance .getRequest(param: {}, path: path, headers: headers); @@ -42,13 +40,8 @@ class RbacRoleUnderServices { required int? roleId, required List rolesId, }) async { - String path = Url.instance.getRolesUnder(); Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; + Map body = { "role_main_id": roleId, "roles_under": rolesId, @@ -76,15 +69,9 @@ class RbacRoleUnderServices { Future deleteRbacRoleUnder({required int roleUnderId}) async { bool success = false; - String path = "${Url.instance.getRolesUnder ()}$roleUnderId/"; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; try { http.Response response = await Request.instance - .deleteRequest(path: path, headers: headers, body: {}, param: {}); + .deleteRequest(path: "${path+roleUnderId.toString()}/", headers: headers, body: {}, param: {}); if (response.statusCode == 200) { success = true; } diff --git a/lib/sevices/roles/rbac_operations/station_services.dart b/lib/sevices/roles/rbac_operations/station_services.dart index 977a1ee..ce06b18 100644 --- a/lib/sevices/roles/rbac_operations/station_services.dart +++ b/lib/sevices/roles/rbac_operations/station_services.dart @@ -1,27 +1,24 @@ import 'dart:convert'; import 'package:unit2/model/utils/position.dart'; +import 'package:unit2/utils/global.dart'; import 'package:unit2/utils/request.dart'; import 'package:unit2/utils/urls.dart'; import 'package:http/http.dart' as http; import '../../../model/rbac/rbac_station.dart'; import '../../../model/rbac/station_type.dart'; -import '../../../model/roles/pass_check/station_assign_area.dart'; class RbacStationServices { static final RbacStationServices _instance = RbacStationServices(); static RbacStationServices get instance => _instance; - String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; - String xClientKeySecret = "unitcYqAN7GGalyz"; - - Future> getStations({required String agencyId}) async { - List stations = []; String path = Url.instance.getStation(); - Map param = {"government_agency_id": agencyId.toString()}; Map headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret + 'X-Client-Secret': xClientSecret }; + Future> getStations({required String agencyId}) async { + List stations = []; + Map param = {"government_agency_id": agencyId.toString()}; try { http.Response response = await Request.instance .getRequest(param: param, path: path, headers: headers); @@ -42,9 +39,6 @@ class RbacStationServices { Future> getStationTypes() async { String path = Url.instance.getStationType(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - }; List stationTypes = []; try { @@ -67,11 +61,7 @@ class RbacStationServices { Future> getPositionTitle() async { String path = Url.instance.getPositionTitle(); - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - }; List positions = []; - try { http.Response response = await Request.instance .getRequest(path: path, param: {}, headers: headers); @@ -93,13 +83,7 @@ class RbacStationServices { Future> addStation( {required RbacStation station}) async { Map statusResponse = {}; - Map headers = { - 'Content-Type': 'application/json; charset=UTF-8', - 'X-Client-Key': xClientKey, - 'X-Client-Secret': xClientKeySecret - }; String path = Url.instance.postStation(); - try { Map body = { "station_name": station.stationName, diff --git a/lib/theme-data.dart/form-style.dart b/lib/theme-data.dart/form-style.dart index 22d1e79..913b4d9 100644 --- a/lib/theme-data.dart/form-style.dart +++ b/lib/theme-data.dart/form-style.dart @@ -9,7 +9,7 @@ InputDecoration normalTextFieldStyle(String labelText, String hintText) { labelStyle: const TextStyle(color: Colors.grey), hintText: hintText, hintStyle: const TextStyle( - color: Colors.grey, + color: Colors.red, ), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( @@ -49,8 +49,6 @@ InputDecoration normalTextFieldStyle(String labelText, String hintText) { filled: false); } - - InputDecoration loginTextFieldStyle() { return InputDecoration( floatingLabelBehavior: FloatingLabelBehavior.never, diff --git a/lib/utils/alerts.dart b/lib/utils/alerts.dart index b10f049..79bb975 100644 --- a/lib/utils/alerts.dart +++ b/lib/utils/alerts.dart @@ -4,7 +4,7 @@ import 'package:unit2/theme-data.dart/btn-style.dart'; import 'package:unit2/theme-data.dart/colors.dart'; import 'package:unit2/utils/global.dart'; -confirmAlert(context, Function() yes,String title, String subtitle) { +confirmAlert(context, Function() yes, String title, String subtitle) { AwesomeDialog( context: context, dialogType: DialogType.question, @@ -37,7 +37,13 @@ confirmAlert(context, Function() yes,String title, String subtitle) { ).show(); } -confirmAlertWithCancel(context, Function() yes,Function() no,String title, String subtitle,) { +confirmAlertWithCancel( + context, + Function() yes, + Function() no, + String title, + String subtitle, +) { AwesomeDialog( context: context, dialogType: DialogType.question, @@ -70,33 +76,78 @@ confirmAlertWithCancel(context, Function() yes,Function() no,String title, Strin ).show(); } +confirmAlertWithCancelCustom(context, Function() yes, Function() no, + String title, String subtitle, okText, cancelText) { + AwesomeDialog( + context: context, + dialogType: DialogType.question, + borderSide: const BorderSide( + color: Colors.green, + width: 0, + ), + width: blockSizeHorizontal * 90, + buttonsBorderRadius: const BorderRadius.all( + Radius.circular(2), + ), + dismissOnTouchOutside: false, + dismissOnBackKeyPress: false, + // onDismissCallback: (type) { + // ScaffoldMessenger.of(context).showSnackBar( + // SnackBar( + // content: Text('Dismissed by $type'), + // ), + // ); + // }, + headerAnimationLoop: false, + animType: AnimType.bottomSlide, + title: title, + desc: subtitle, + btnOkText: okText, + btnCancelText: cancelText, + showCloseIcon: false, + btnCancelOnPress: no, + btnOkOnPress: yes, + ).show(); +} -errorAlert(context, title, description,Function() func) { +errorAlert(context, title, description, Function() func) { AwesomeDialog( - width: blockSizeHorizontal * 90, - context: context, - dialogType: DialogType.error, - animType: AnimType.scale, - headerAnimationLoop: false, - title: title, - desc: description, - btnOk: SizedBox(height: 50,child: ElevatedButton(onPressed:func, style: mainBtnStyle(primary, Colors.transparent, second), child: const Text("OK")), ) - ).show(); + width: blockSizeHorizontal * 90, + context: context, + dialogType: DialogType.error, + animType: AnimType.scale, + headerAnimationLoop: false, + title: title, + desc: description, + btnOk: SizedBox( + height: 50, + child: ElevatedButton( + onPressed: func, + style: mainBtnStyle(primary, Colors.transparent, second), + child: const Text("OK")), + )).show(); } -successAlert(context, title, description,Function() func) { + +successAlert(context, title, description, Function() func) { AwesomeDialog( - width: blockSizeHorizontal * 90, - context: context, - dialogType: DialogType.success, - animType: AnimType.scale, - headerAnimationLoop: false, - title: title, - desc: description, - btnOk: SizedBox(height: 50,child: ElevatedButton(style: mainBtnStyle(success2, Colors.transparent, success), onPressed: func, child: const Text("OK")), ) - ).show(); + width: blockSizeHorizontal * 90, + context: context, + dialogType: DialogType.success, + animType: AnimType.scale, + headerAnimationLoop: false, + title: title, + desc: description, + btnOk: SizedBox( + height: 50, + child: ElevatedButton( + style: mainBtnStyle(success2, Colors.transparent, success), + onPressed: func, + child: const Text("OK")), + )).show(); } -okAlert(context,title,description){ - AwesomeDialog( + +okAlert(context, title, description) { + AwesomeDialog( width: blockSizeHorizontal * 90, context: context, dialogType: DialogType.error, diff --git a/lib/utils/app_router.dart b/lib/utils/app_router.dart index 163aaf2..f31f5f0 100644 --- a/lib/utils/app_router.dart +++ b/lib/utils/app_router.dart @@ -1,15 +1,12 @@ 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/offline/offline_bloc/offline_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/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/offline/homepage/drawer.dart'; import 'package:unit2/screens/sos/index.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'; @@ -18,6 +15,7 @@ import '../bloc/user/user_bloc.dart'; import '../screens/profile/profile.dart'; import '../screens/unit2/basic-info/basic-info.dart'; import '../screens/unit2/homepage.dart/components/drawer-screen.dart'; +import '../screens/unit2/homepage.dart/components/menu_tile.dart'; import '../screens/unit2/login/qr_login.dart'; import '../screens/unit2/roles/qr_code_scanner.dart/settings_screen.dart'; @@ -79,7 +77,10 @@ class AppRouter { }); case '/passo-home': return MaterialPageRoute(builder: (BuildContext context) { - return PassoDashBoard(); + return BlocProvider( + create: (context) => OfflineBloc()..add(SwitchOffline()), + child: const OfflineDrawerScreen(), + ); }); // BlocProvider.of( NavigationService.navigatorKey.currentContext!).add(LoadLoggedInUser()); // return MaterialPageRoute(builder: (_) { @@ -92,6 +93,7 @@ class AppRouter { child: const RBACScreen(), ); }); + default: return MaterialPageRoute(builder: (context) { return Container(); diff --git a/lib/utils/formatters.dart b/lib/utils/formatters.dart index 4db4cd8..154e478 100644 --- a/lib/utils/formatters.dart +++ b/lib/utils/formatters.dart @@ -3,7 +3,8 @@ import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; var mobileFormatter = MaskTextInputFormatter( mask: "+63 (###) ###-####", - filter: {"#": RegExp(r"^[1-9][0-9]*$")}, + filter: {"#": RegExp(r'^[0-9][0-9]*$') +}, type: MaskAutoCompletionType.lazy, initialText: "0"); diff --git a/lib/utils/global.dart b/lib/utils/global.dart index 481f7b9..91ebce2 100644 --- a/lib/utils/global.dart +++ b/lib/utils/global.dart @@ -1,4 +1,5 @@ import 'package:hive/hive.dart'; +import 'package:unit2/model/offline/offline_profile.dart'; import '../model/profile/basic_information/primary-information.dart'; @@ -10,28 +11,18 @@ double safeAreaHorizontal = 0; double safeAreaVertical = 0; double safeBlockHorizontal = 0; double safeBlockVertical = 0; - const xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z"; const xClientSecret = "unitcYqAN7GGalyz"; - String? globalFistname; - String? globalLastname; - String? globalMiddleName; - DateTime? globalBday; - String? globalSex; +String? globalFistname; +String? globalLastname; +String? globalMiddleName; +DateTime? globalBday; +String? globalSex; Profile? globalCurrentProfile; - - -const String urlDownloadArmeabiv7aAPK = - "https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_armeabi-v7a-release.apk?download"; - -const String urlDownloadX8664APK = -"https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_x86_64-release.apk?download"; - -const String urlDownloadarm64v8aAPK = - "https://agusandelnorte.gov.ph/media/public/transparency/downloadables/UniT-App/v1.0.1/beta/unit_app_v1_0_1_beta_arm64-v8a-release.apk?download"; - - - +///offline data +bool? globalOfflineAvailable; +OfflineProfile? globalOfflineProfile; //// hive boxes Box? CREDENTIALS; -Box? SOS; \ No newline at end of file +Box? SOS; +Box? OFFLINE; diff --git a/lib/utils/sql_helper.dart b/lib/utils/sql_helper.dart new file mode 100644 index 0000000..2e12f18 --- /dev/null +++ b/lib/utils/sql_helper.dart @@ -0,0 +1,58 @@ +import 'package:sqflite/sqflite.dart' as sql; +import 'package:sqflite/sqflite.dart'; + +Future _createDB(Database db, int version) async { + // const idType = 'INTEGER PRIMARY KEY AUTOINCREMENT'; + // const textType = 'TEXT NOT NULL'; + // const boolType = 'BOOLEAN NOT NULL'; + // const integerType = 'INTEGER NOT NULL'; + + await db.execute(''' + CREATE TABLE items ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + transCode TEXT NOT NULL, + tdn TEXT NOT NULL, + pin TEXT NOT NULL, + owner TEXT NOT NULL, + address TEXT NOT NULL, + telno TEXT NOT NULL, + tin TEXT NOT NULL, + adminUser TEXT NOT NULL, + adminAddress TEXT NOT NULL, + adminTelno TEXT NOT NULL, + adminTin TEXT NOT NULL, + faasType TEXT NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE landref ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + owner TEXT NOT NULL, + cloaNo TEXT NOT NULL, + lotNo TEXT NOT NULL, + tdn TEXT NOT NULL, + area TEXT NOT NULL, + surveyNo TEXT NOT NULL, + blkNo TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE location ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + bldgapprDetailsId INTEGER NOT NULL, + assessedById TEXT NOT NULL, + assessedByName TEXT NOT NULL, + street TEXT NOT NULL, + barangay TEXT NOT NULL, + municipality TEXT NOT NULL, + province TEXT NOT NULL + ) + '''); +} diff --git a/lib/utils/text_container.dart b/lib/utils/text_container.dart index 79be6de..500bb07 100644 --- a/lib/utils/text_container.dart +++ b/lib/utils/text_container.dart @@ -16,7 +16,7 @@ const String sOSReceivedMessage = "your SOS request has been received. Please wait for respondent's acknowledgement."; const String unit2ModuleScreen = "uniT Dashboard"; const String welcome = "Welcome to!"; -const String unitApp = 'uniT-App'; +const String unitApp = 'Rpass-App'; const String loginToContinue = "Please login to continue."; const String loginViaQr = "Login via QR code"; const String emergencyReponseLabel = " Request Emergency Response "; diff --git a/lib/utils/urls.dart b/lib/utils/urls.dart index 544a406..eb57b81 100644 --- a/lib/utils/urls.dart +++ b/lib/utils/urls.dart @@ -4,18 +4,23 @@ class Url { static Url get instance => _instance; String host() { - // return '192.168.10.183:3000'; + // // // return '192.168.10.183:3000'; return 'agusandelnorte.gov.ph'; // return "192.168.10.219:3000"; - // return "192.168.10.241"; + // return "192.168.10.241"; + // return "192.168.10.185"; // return "192.168.10.221:3004"; // return "playweb.agusandelnorte.gov.ph"; // return 'devapi.agusandelnorte.gov.ph:3004'; - // return "192.168.10.218:8000"; + // return "192.168.80.21:8000"; + // return "192.168.10.247"; + // return "playcensys.agusandelnorte.gov.ph"; + // return "10.10.10.110:8000"; + // return "192.168.80.20:8000"; } String prefixHost() { - return "https"; + return "http"; // return "http"; } @@ -309,7 +314,11 @@ class Url { } String getRoleAssignment() { - return "api/account/auth/role_assignment/"; + return "/api/account/auth/role_assignment/"; + } + + String getPermissionAssignment() { + return "/api/account/auth/permission_assignment/"; } String getStationType() { @@ -334,7 +343,7 @@ class Url { } String getProvinces() { - return "api/web_app/location/province/"; + return "/api/web_app/location/province/"; } String getCities() { @@ -344,7 +353,8 @@ class Url { String getBarangays() { return "/api/web_app/location/barangay/"; } - String getPurok(){ + + String getPurok() { return "/api/web_app/location/purok/"; } @@ -358,6 +368,10 @@ class Url { return "/api/rptass_app/additional_items/"; } + String buildingDetails() { + return "/api/rptass_app/bldgappr_details/"; + } + String generalDescription() { return "/api/rptass_app/bldgappr_gendesc/"; } diff --git a/lib/widgets/error_state.dart b/lib/widgets/error_state.dart index b23027f..672182c 100644 --- a/lib/widgets/error_state.dart +++ b/lib/widgets/error_state.dart @@ -36,6 +36,7 @@ class SomethingWentWrong extends StatelessWidget { height: 20, ), SizedBox( + width: 200, height: 50, child: ElevatedButton.icon( style: mainBtnStyle( diff --git a/lib/widgets/passo/custom_formBuilder_fields.dart b/lib/widgets/passo/custom_formBuilder_fields.dart index 5adec45..1ebe173 100644 --- a/lib/widgets/passo/custom_formBuilder_fields.dart +++ b/lib/widgets/passo/custom_formBuilder_fields.dart @@ -3,11 +3,13 @@ import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; import 'package:unit2/theme-data.dart/form-style.dart'; -Widget customTextField(String labelText, String hintText, String keyText) { +Widget customTextField( + String labelText, String hintText, String keyText, TextInputType type) { return Container( margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0), child: FormBuilderTextField( name: keyText, + keyboardType: type, decoration: normalTextFieldStyle(labelText, hintText), validator: FormBuilderValidators.compose([]), ), diff --git a/lib/widgets/passo/custom_text.dart b/lib/widgets/passo/custom_text.dart new file mode 100644 index 0000000..1a3bd0f --- /dev/null +++ b/lib/widgets/passo/custom_text.dart @@ -0,0 +1,14 @@ +import 'package:flutter/material.dart'; + +class CustomText extends StatelessWidget { + final String text; + const CustomText({Key? key, required this.text}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Text( + text, + style: const TextStyle(fontSize: 21), + ); + } +} diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index fcad7d4..bc29a93 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -7,6 +7,7 @@ #include "generated_plugin_registrant.h" #include +#include #include #include #include @@ -15,6 +16,9 @@ void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); g_autoptr(FlPluginRegistrar) modal_progress_hud_nsn_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "ModalProgressHudNsnPlugin"); modal_progress_hud_nsn_plugin_register_with_registrar(modal_progress_hud_nsn_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 54e72c5..dc0f3a6 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST audioplayers_linux + file_selector_linux modal_progress_hud_nsn platform_device_id_linux url_launcher_linux diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index b1f7d47..a288f75 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -9,6 +9,7 @@ import assets_audio_player import assets_audio_player_web import audioplayers_darwin import device_info_plus +import file_selector_macos import location import modal_progress_hud_nsn import package_info_plus @@ -27,6 +28,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { AssetsAudioPlayerWebPlugin.register(with: registry.registrar(forPlugin: "AssetsAudioPlayerWebPlugin")) AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) LocationPlugin.register(with: registry.registrar(forPlugin: "LocationPlugin")) ModalProgressHudNsnPlugin.register(with: registry.registrar(forPlugin: "ModalProgressHudNsnPlugin")) FLTPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FLTPackageInfoPlusPlugin")) diff --git a/pubspec.lock b/pubspec.lock index 0b02b78..1b51c18 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,18 +5,26 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: "4897882604d919befd350648c7f91926a9d5de99e67b455bf0917cc2362f4bb8" + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 url: "https://pub.dev" source: hosted - version: "47.0.0" + version: "64.0.0" + accordion: + dependency: "direct main" + description: + name: accordion + sha256: "0eca3d1c619c6df63d6e384010fd2ef1164e7385d7102f88a6b56f658f160cd0" + url: "https://pub.dev" + source: hosted + version: "2.6.0" analyzer: dependency: transitive description: name: analyzer - sha256: "690e335554a8385bc9d787117d9eb52c0c03ee207a607e593de3c9d71b1cfe80" + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" url: "https://pub.dev" source: hosted - version: "4.7.0" + version: "6.2.0" animate_do: dependency: "direct main" description: @@ -25,6 +33,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + animated_splash_screen: + dependency: "direct main" + description: + name: animated_splash_screen + sha256: f45634db6ec4e8cf034c53e03f3bd83898a16fe3c9286bf5510b6831dfcf2124 + url: "https://pub.dev" + source: hosted + version: "1.3.0" app_popup_menu: dependency: "direct main" description: @@ -37,10 +53,10 @@ packages: dependency: transitive description: name: archive - sha256: "0c8368c9b3f0abbc193b9d6133649a614204b528982bebc7026372d61677ce3a" + sha256: "06a96f1249f38a00435b3b0c9a3246d934d7dbc8183fc7c9e56989860edb99d4" url: "https://pub.dev" source: hosted - version: "3.3.7" + version: "3.4.4" args: dependency: transitive description: @@ -77,58 +93,58 @@ packages: dependency: "direct main" description: name: audioplayers - sha256: "8e94499b5c123df14cf17c16639de5ff3373e57e537f727e367487fbb7491363" + sha256: d9f6ca8e9b3e5af5e73d4c814404566f72698ee7ba35487bdf2baa6749e7503f url: "https://pub.dev" source: hosted - version: "5.1.0" + version: "5.2.0" audioplayers_android: dependency: transitive description: name: audioplayers_android - sha256: "1c12b60cc10a3b8617ca3f88b927e7e03768f470d9b4f747efd3d58a8a07ee1b" + sha256: fb01b9481f431fe04ac60f1f97ce8158383f2dc754558820592f795d81ca9d53 url: "https://pub.dev" source: hosted - version: "4.0.1" + version: "4.0.2" audioplayers_darwin: dependency: transitive description: name: audioplayers_darwin - sha256: "2fb6133ffcf28fb3f9d3e11f8a3ef190e5fedb2b7b95ea865b56a21d1163e670" + sha256: "3034e99a6df8d101da0f5082dcca0a2a99db62ab1d4ddb3277bed3f6f81afe08" url: "https://pub.dev" source: hosted - version: "5.0.1" + version: "5.0.2" audioplayers_linux: dependency: transitive description: name: audioplayers_linux - sha256: cca3f272c7186dd2e0025b8864e1413ac5e081d74b17e28b02ceb2df4c110235 + sha256: "60787e73fefc4d2e0b9c02c69885402177e818e4e27ef087074cf27c02246c9e" url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "3.1.0" audioplayers_platform_interface: dependency: transitive description: name: audioplayers_platform_interface - sha256: "47eae55e99ced11589998cf27e4eaabf5b475a7bd8bea7516ee6c2536a2e1abf" + sha256: "365c547f1bb9e77d94dd1687903a668d8f7ac3409e48e6e6a3668a1ac2982adb" url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "6.1.0" audioplayers_web: dependency: transitive description: name: audioplayers_web - sha256: "9f155590c6ba9ba469df637f4729264e4234dc3941ece4690dad63ffac19b5af" + sha256: "22cd0173e54d92bd9b2c80b1204eb1eb159ece87475ab58c9788a70ec43c2a62" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.1.0" audioplayers_windows: dependency: transitive description: name: audioplayers_windows - sha256: "8813b712ba919bb324bde5e3ba97edc81bface945953a54a3dea70b5608bcc70" + sha256: "9536812c9103563644ada2ef45ae523806b0745f7a78e89d1b5fb1951de90e1a" url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "3.1.0" auto_size_text: dependency: "direct main" description: @@ -197,10 +213,10 @@ packages: dependency: transitive description: name: build - sha256: "3fbda25365741f8251b39f3917fb3c8e286a96fd068a5a242e11c2012d495777" + sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" url: "https://pub.dev" source: hosted - version: "2.3.1" + version: "2.4.1" build_config: dependency: transitive description: @@ -213,34 +229,34 @@ packages: dependency: transitive description: name: build_daemon - sha256: "757153e5d9cd88253cb13f28c2fb55a537dc31fefd98137549895b5beb7c6169" + sha256: "5f02d73eb2ba16483e693f80bee4f088563a820e47d1027d4cdfe62b5bb43e65" url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "4.0.0" build_resolvers: dependency: transitive description: name: build_resolvers - sha256: "687cf90a3951affac1bd5f9ecb5e3e90b60487f3d9cdc359bb310f8876bb02a6" + sha256: "64e12b0521812d1684b1917bc80945625391cb9bdd4312536b1d69dcb6133ed8" url: "https://pub.dev" source: hosted - version: "2.0.10" + version: "2.4.1" build_runner: dependency: "direct dev" description: name: build_runner - sha256: b0a8a7b8a76c493e85f1b84bffa0588859a06197863dba8c9036b15581fd9727 + sha256: "10c6bcdbf9d049a0b666702cf1cee4ddfdc38f02a19d35ae392863b47519848b" url: "https://pub.dev" source: hosted - version: "2.3.3" + version: "2.4.6" build_runner_core: dependency: transitive description: name: build_runner_core - sha256: "0671ad4162ed510b70d0eb4ad6354c249f8429cab4ae7a4cec86bbc2886eb76e" + sha256: c9e32d21dd6626b5c163d48b037ce906bbe428bc23ab77bcd77bb21e593b6185 url: "https://pub.dev" source: hosted - version: "7.2.7+1" + version: "7.2.11" built_collection: dependency: transitive description: @@ -253,34 +269,34 @@ packages: dependency: transitive description: name: built_value - sha256: ff627b645b28fb8bdb69e645f910c2458fd6b65f6585c3a53e0626024897dedf + sha256: a8de5955205b4d1dbbbc267daddf2178bd737e4bab8987c04a500478c9651e74 url: "https://pub.dev" source: hosted - version: "8.6.2" + version: "8.6.3" cached_network_image: dependency: "direct main" description: name: cached_network_image - sha256: fd3d0dc1d451f9a252b32d95d3f0c3c487bc41a75eba2e6097cb0b9c71491b15 + sha256: f98972704692ba679db144261172a8e20feb145636c617af0eb4022132a6797f url: "https://pub.dev" source: hosted - version: "3.2.3" + version: "3.3.0" cached_network_image_platform_interface: dependency: transitive description: name: cached_network_image_platform_interface - sha256: bb2b8403b4ccdc60ef5f25c70dead1f3d32d24b9d6117cfc087f496b178594a7 + sha256: "56aa42a7a01e3c9db8456d9f3f999931f1e05535b5a424271e9a38cabf066613" url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "3.0.0" cached_network_image_web: dependency: transitive description: name: cached_network_image_web - sha256: b8eb814ebfcb4dea049680f8c1ffb2df399e4d03bf7a352c775e26fa06e02fa0 + sha256: "759b9a9f8f6ccbb66c185df805fac107f05730b1dab9c64626d1008cca532257" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.1.0" characters: dependency: transitive description: @@ -309,12 +325,12 @@ packages: dependency: transitive description: name: code_builder - sha256: "315a598c7fbe77f22de1c9da7cfd6fd21816312f16ffa124453b4fc679e540f1" + sha256: "1be9be30396d7e4c0db42c35ea6ccd7cc6a1e19916b5dc64d6ac216b5544d677" url: "https://pub.dev" source: hosted - version: "4.6.0" + version: "4.7.0" collection: - dependency: transitive + dependency: "direct main" description: name: collection sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 @@ -365,10 +381,18 @@ packages: dependency: transitive description: name: dart_style - sha256: "7a03456c3490394c8e7665890333e91ae8a49be43542b616e414449ac358acd4" + sha256: abd7625e16f51f554ea244d090292945ec4d4be7bfbaf2ec8cccea568919d334 url: "https://pub.dev" source: hosted - version: "2.2.4" + version: "2.3.3" + date_format: + dependency: "direct main" + description: + name: date_format + sha256: "8e5154ca363411847220c8cbc43afcf69c08e8debe40ba09d57710c25711760c" + url: "https://pub.dev" + source: hosted + version: "2.0.7" date_time_picker: dependency: "direct main" description: @@ -417,6 +441,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.3.3" + dropdown_button2: + dependency: "direct main" + description: + name: dropdown_button2 + sha256: b0fe8d49a030315e9eef6c7ac84ca964250155a6224d491c1365061bc974a9e1 + url: "https://pub.dev" + source: hosted + version: "2.3.9" easy_app_installer: dependency: "direct main" description: @@ -461,10 +493,10 @@ packages: dependency: transitive description: name: ffi - sha256: ed5337a5660c506388a9f012be0288fb38b49020ce2b45fe1f8b8323fe429f99 + sha256: "7bf0adc28a23d395f19f3f1eb21dd7cfd1dd9f8e1c50051c069122e6853bc878" url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "2.1.0" file: dependency: transitive description: @@ -481,6 +513,38 @@ packages: url: "https://pub.dev" source: hosted version: "5.5.0" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "045d372bf19b02aeb69cacf8b4009555fb5f6f0b7ad8016e5f46dd1387ddd492" + url: "https://pub.dev" + source: hosted + version: "0.9.2+1" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: f42eacb83b318e183b1ae24eead1373ab1334084404c8c16e0354f9a3e55d385 + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "0aa47a725c346825a2bd396343ce63ac00bda6eff2fbc43eabe99737dede8262" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: d3547240c20cabf205c7c7f01a50ecdbc413755814d6677f3cb366f04abcead0 + url: "https://pub.dev" + source: hosted + version: "0.9.3+1" file_utils: dependency: transitive description: @@ -526,14 +590,6 @@ packages: url: "https://pub.dev" source: hosted version: "8.1.3" - flutter_blurhash: - dependency: transitive - description: - name: flutter_blurhash - sha256: "05001537bd3fac7644fa6558b09ec8c0a3f2eba78c0765f88912882b1331a5c6" - url: "https://pub.dev" - source: hosted - version: "0.7.0" flutter_cache_manager: dependency: transitive description: @@ -558,6 +614,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.0.3" + flutter_drawing_board: + dependency: "direct main" + description: + name: flutter_drawing_board + sha256: "82700847d7f367c9af1eaf186c88f74a6be821dbe783871e4736bf724f015192" + url: "https://pub.dev" + source: hosted + version: "0.7.0+2" flutter_form_builder: dependency: "direct main" description: @@ -579,6 +643,14 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_painter_v2: + dependency: "direct main" + description: + name: flutter_painter_v2 + sha256: "5f9589670fb2385b69daf60ad1919c4f2b9ae2c5ee5199c0172c674032020470" + url: "https://pub.dev" + source: hosted + version: "2.0.1" flutter_plugin_android_lifecycle: dependency: transitive description: @@ -685,6 +757,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.0" + get: + dependency: transitive + description: + name: get + sha256: e4e7335ede17452b391ed3b2ede016545706c01a02292a6c97619705e7d2a85e + url: "https://pub.dev" + source: hosted + version: "4.6.6" glob: dependency: transitive description: @@ -777,10 +857,74 @@ packages: dependency: transitive description: name: image - sha256: a72242c9a0ffb65d03de1b7113bc4e189686fc07c7147b8b41811d0dd0e0d9bf + sha256: "028f61960d56f26414eb616b48b04eb37d700cbe477b7fb09bf1d7ce57fd9271" url: "https://pub.dev" source: hosted - version: "4.0.17" + version: "4.1.3" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "1f498d086203360cca099d20ffea2963f48c39ce91bdd8a3b6d4a045786b02c8" + url: "https://pub.dev" + source: hosted + version: "1.0.8" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "42c098e7fb6334746be37cdc30369ade356ed4f14d48b7a0313f95a9159f4321" + url: "https://pub.dev" + source: hosted + version: "0.8.9+5" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: e2423c53a68b579a7c37a1eda967b8ae536c3d98518e5db95ca1fe5719a730a3 + url: "https://pub.dev" + source: hosted + version: "3.0.2" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: fadafce49e8569257a0cad56d24438a6fa1f0cbd7ee0af9b631f7492818a4ca3 + url: "https://pub.dev" + source: hosted + version: "0.8.9+1" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "4ed1d9bb36f7cd60aa6e6cd479779cc56a4cb4e4de8f49d487b1aaad831300fa" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "3f5ad1e8112a9a6111c46d0b57a7be2286a9a07fc6e1976fdf5be2bd31d4ff62" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "0e827c156e3a90edd3bbe7f6de048b39247b16e58173b08a835b7eb00aba239e" + url: "https://pub.dev" + source: hosted + version: "2.9.2" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: "6ad07afc4eb1bc25f3a01084d28520496c4a3bb0cb13685435838167c9dcedeb" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" intl: dependency: "direct main" description: @@ -801,10 +945,10 @@ packages: dependency: transitive description: name: js - sha256: "5528c2f391ededb7775ec1daa69e65a2d61276f7552de2b5f7b8d34ee9fd4ab7" + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted - version: "0.6.5" + version: "0.6.7" json_annotation: dependency: transitive description: @@ -817,10 +961,10 @@ packages: dependency: transitive description: name: lints - sha256: "5e4a9cd06d447758280a8ac2405101e0e2094d2a1dbdd3756aec3fe7775ba593" + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "2.1.1" location: dependency: "direct main" description: @@ -870,7 +1014,7 @@ packages: source: hosted version: "2.5.0" matcher: - dependency: transitive + dependency: "direct main" description: name: matcher sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" @@ -878,7 +1022,7 @@ packages: source: hosted version: "0.12.16" material_color_utilities: - dependency: transitive + dependency: "direct main" description: name: material_color_utilities sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" @@ -886,7 +1030,7 @@ packages: source: hosted version: "0.5.0" meta: - dependency: transitive + dependency: "direct main" description: name: meta sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" @@ -953,10 +1097,10 @@ packages: dependency: transitive description: name: octo_image - sha256: "107f3ed1330006a3bea63615e81cf637433f5135a52466c7caa0e7152bca9143" + sha256: "45b40f99622f11901238e18d48f5f12ea36426d8eced9f4cbf58479c7aa2430d" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "2.0.0" package_config: dependency: transitive description: @@ -981,8 +1125,16 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" - path: + page_transition: dependency: transitive + description: + name: page_transition + sha256: dee976b1f23de9bbef5cd512fe567e9f6278caee11f5eaca9a2115c19dc49ef6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: "direct main" description: name: path sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" @@ -1057,10 +1209,10 @@ packages: dependency: transitive description: name: permission_handler_android - sha256: f2543a236584a5e8be79076f858022f100ce690e31530e6fa4c32ac94f276d3a + sha256: ace7d15a3d1a4a0b91c041d01e5405df221edb9de9116525efc773c74e6fc790 url: "https://pub.dev" source: hosted - version: "11.0.3" + version: "11.0.5" permission_handler_apple: dependency: transitive description: @@ -1093,6 +1245,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.4.0" + phosphor_flutter: + dependency: "direct main" + description: + name: phosphor_flutter + sha256: "82aee69109d55518abbc5d77aeb893bfd2d39796aa51b871cadf2e56d03fa8e3" + url: "https://pub.dev" + source: hosted + version: "1.4.0" platform: dependency: transitive description: @@ -1245,6 +1405,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.27.7" + scroll_to_index: + dependency: transitive + description: + name: scroll_to_index + sha256: b707546e7500d9f070d63e5acf74fd437ec7eeeb68d3412ef7b0afada0b4f176 + url: "https://pub.dev" + source: hosted + version: "3.0.1" scrollable_positioned_list: dependency: transitive description: @@ -1390,18 +1558,18 @@ packages: dependency: transitive description: name: source_gen - sha256: "2d79738b6bbf38a43920e2b8d189e9a3ce6cc201f4b8fc76be5e4fe377b1c38d" + sha256: fc0da689e5302edb6177fdd964efcb7f58912f43c28c2047a808f5bfff643d16 url: "https://pub.dev" source: hosted - version: "1.2.6" + version: "1.4.0" source_helper: dependency: transitive description: name: source_helper - sha256: "3b67aade1d52416149c633ba1bb36df44d97c6b51830c2198e934e3fca87ca1f" + sha256: "6adebc0006c37dd63fe05bca0a929b99f06402fc95aa35bf36d67f5c06de01fd" url: "https://pub.dev" source: hosted - version: "1.3.3" + version: "1.3.4" source_span: dependency: transitive description: @@ -1411,23 +1579,23 @@ packages: source: hosted version: "1.10.0" sqflite: - dependency: transitive + dependency: "direct main" description: name: sqflite - sha256: b4d6710e1200e96845747e37338ea8a819a12b51689a3bcf31eff0003b37a0b9 + sha256: "591f1602816e9c31377d5f008c2d9ef7b8aca8941c3f89cc5fd9d84da0c38a9a" url: "https://pub.dev" source: hosted - version: "2.2.8+4" + version: "2.3.0" sqflite_common: dependency: transitive description: name: sqflite_common - sha256: "8f7603f3f8f126740bc55c4ca2d1027aab4b74a1267a3e31ce51fe40e3b65b8f" + sha256: "1b92f368f44b0dee2425bb861cfa17b6f6cf3961f762ff6f941d20b33355660a" url: "https://pub.dev" source: hosted - version: "2.4.5+1" + version: "2.5.0" stack_trace: - dependency: transitive + dependency: "direct main" description: name: stack_trace sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 @@ -1443,7 +1611,7 @@ packages: source: hosted version: "6.3.0" stream_channel: - dependency: transitive + dependency: "direct main" description: name: stream_channel sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" @@ -1470,66 +1638,66 @@ packages: dependency: transitive description: name: syncfusion_flutter_core - sha256: aea119c8117953fa5decf4a313b431e556b0959cd35ff88f8fbdc0eda9bedb06 + sha256: "295954bc4bda923c88f361da35611801b56f4258179aa355730b236e4ae3ec60" url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_flutter_pdf: dependency: transitive description: name: syncfusion_flutter_pdf - sha256: "76a50a1d580714c078e2827adbd8b00d5f5c606879d07c44c5d99f0e864edda1" + sha256: "567d42bd3421f1d3691c5c40741cc921e12b5fc4cc665be170716cca1c1ab824" url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_flutter_pdfviewer: dependency: "direct main" description: name: syncfusion_flutter_pdfviewer - sha256: e5eaabd0a31fff16caead0d6d66d4c9946de7e46c89da7736de23cd4b2e6f676 + sha256: f3ae48a1b9d0c2a153be292751f84d3ff4f09a33ab38bc7d934340cb656c4e0c url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_flutter_signaturepad: dependency: transitive description: name: syncfusion_flutter_signaturepad - sha256: ea6b218d127e0315b3309ee072a1d304c76aa7c497a196b3474f9c6b38c01f82 + sha256: f61d7fb1c8776f8acfb6dba48c9dd770e41a41759011729770a20671ee1e79ee url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_pdfviewer_macos: dependency: transitive description: name: syncfusion_pdfviewer_macos - sha256: "6f928bee1f786b8d1939d3c4142c5cc2de2c13d19262d302878935a2bc33850c" + sha256: "083f31cea51c8ca1fe98ee8381e48117a892936ad480b5a1787ef9af4a14eac9" url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_pdfviewer_platform_interface: dependency: transitive description: name: syncfusion_pdfviewer_platform_interface - sha256: "0251864fb82e2bd92a1b17e8562fe342e78cd530e26b0d2f54e94a441ccb4584" + sha256: acd26577d5b14b230521fc362e9acd0c1a9c8b1a60de89294689772819be5d9d url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_pdfviewer_web: dependency: transitive description: name: syncfusion_pdfviewer_web - sha256: eb224f52e86326dbf08ea12978c3db0b4e376866a84d4fcb131fc06ec93cbe20 + sha256: "255ead74a256d7fdcee8b7eb48530beaa6373ef65cdb5db592b59e187fb505f2" url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" syncfusion_pdfviewer_windows: dependency: transitive description: name: syncfusion_pdfviewer_windows - sha256: aca74797a97512f4d3ca2be0ed49193fae7e5fd29a9b1b1139429d39c9216bf9 + sha256: "5778d9005cd3d81d8a0324dba9676f33bb58ce1062b7ca726d1423b245197511" url: "https://pub.dev" source: hosted - version: "23.1.36" + version: "23.1.38" synchronized: dependency: transitive description: @@ -1638,10 +1806,10 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: ba140138558fcc3eead51a1c42e92a9fb074a1b1149ed3c73e66035b2ccd94f2 + sha256: "2942294a500b4fa0b918685aff406773ba0a4cd34b7f42198742a94083020ce5" url: "https://pub.dev" source: hosted - version: "2.0.19" + version: "2.0.20" url_launcher_windows: dependency: transitive description: @@ -1694,10 +1862,10 @@ packages: dependency: transitive description: name: watcher - sha256: "6a7f46926b01ce81bfc339da6a7f20afbe7733eff9846f6d6a5466aa4c6667c0" + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.1.0" web: dependency: transitive description: @@ -1718,18 +1886,18 @@ packages: dependency: transitive description: name: win32 - sha256: f2add6fa510d3ae152903412227bda57d0d5a8da61d2c39c1fb022c9429a41c0 + sha256: "350a11abd2d1d97e0cc7a28a81b781c08002aa2864d9e3f192ca0ffa18b06ed3" url: "https://pub.dev" source: hosted - version: "5.0.6" + version: "5.0.9" win32_registry: dependency: transitive description: name: win32_registry - sha256: e4506d60b7244251bc59df15656a3093501c37fb5af02105a944d73eb95be4c9 + sha256: "41fd8a189940d8696b1b810efb9abcf60827b6cbfab90b0c43e8439e3a39d85a" url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" xdg_directories: dependency: transitive description: @@ -1756,4 +1924,4 @@ packages: version: "3.1.2" sdks: dart: ">=3.1.0 <4.0.0" - flutter: ">=3.10.0" + flutter: ">=3.13.0" diff --git a/pubspec.yaml b/pubspec.yaml index 676905e..db2c360 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -96,8 +96,24 @@ dependencies: syncfusion_flutter_pdfviewer: ^23.1.36 url_launcher: ^6.1.14 share_plus: ^7.1.0 + animated_splash_screen: ^1.3.0 + sqflite: ^2.3.0 + accordion: ^2.6.0 + dropdown_button2: ^2.3.9 + phosphor_flutter: ^1.4.0 device_info_plus: ^9.0.3 better_open_file: ^3.6.4 + date_format: ^2.0.7 + flutter_drawing_board: ^0.7.0+2 + flutter_painter_v2: ^2.0.1 + image_picker: ^1.0.8 + collection: ^1.17.2 + matcher: ^0.12.16 + material_color_utilities: ^0.5.0 + meta: ^1.9.1 + path: ^1.8.3 + stack_trace: ^1.11.0 + stream_channel: ^2.1.1 dependency_overrides: intl: ^0.18.0 diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index fe3ce53..b9baf02 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -7,6 +7,7 @@ #include "generated_plugin_registrant.h" #include +#include #include #include #include @@ -18,6 +19,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { AudioplayersWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); ModalProgressHudNsnPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("ModalProgressHudNsnPluginCApi")); PermissionHandlerWindowsPluginRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 6d2ce89..931a16f 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST audioplayers_windows + file_selector_windows modal_progress_hud_nsn permission_handler_windows platform_device_id_windows