diff --git a/README.md b/README.md index 1a459e3..3fea310 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ +# Translation prompt & Command + +Read the context for both files & generate translations strings in the en-US.json & ar-SA.json files for the strings containing "needTranslation". Also replace the strings in the dart with the generated Strings. Also do not remove existing properties & do no generate duplicate strings in the json files + +flutter3_32 pub run easy_localization:generate -O ./lib/generated -f keys -o locale_keys.g.dart --source-dir ./assets/langs + + + # HMG Patient App A comprehensive Flutter-based mobile application for HMG (Habib Medical Group) patients, diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 2987d3b..5d74c4d 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -160,6 +160,7 @@ dependencies { annotationProcessor("com.github.bumptech.glide:compiler:4.16.0") implementation("com.mapbox.maps:android:11.5.0") + implementation("com.mapbox.mapboxsdk:mapbox-sdk-turf:7.3.1") // implementation("com.mapbox.maps:android:11.4.0") // AARs diff --git a/android/app/src/main/kotlin/com/ejada/hmg/penguin/PenguinNavigator.kt b/android/app/src/main/kotlin/com/ejada/hmg/penguin/PenguinNavigator.kt index b822d67..70889d3 100644 --- a/android/app/src/main/kotlin/com/ejada/hmg/penguin/PenguinNavigator.kt +++ b/android/app/src/main/kotlin/com/ejada/hmg/penguin/PenguinNavigator.kt @@ -21,7 +21,7 @@ class PenguinNavigator() { val postToken = PostToken(clientID, clientKey) getToken(mContext, postToken, object : RefIdDelegate { override fun onRefByIDSuccess(PoiId: String?) { - Log.e("navigateTo", "PoiId is+++++++ $PoiId") + Log.e("navigateTo", "PoiId is+++++++ $refID") PlugAndPlaySDK.navigateTo(mContext, refID, object : RefIdDelegate { override fun onRefByIDSuccess(PoiId: String?) { diff --git a/assets/images/clinicIcons/1.svg b/assets/images/clinicIcons/1.svg new file mode 100644 index 0000000..70f4171 --- /dev/null +++ b/assets/images/clinicIcons/1.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/104.svg b/assets/images/clinicIcons/104.svg new file mode 100644 index 0000000..3fd875f --- /dev/null +++ b/assets/images/clinicIcons/104.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/assets/images/clinicIcons/105.svg b/assets/images/clinicIcons/105.svg new file mode 100644 index 0000000..a9f4bd1 --- /dev/null +++ b/assets/images/clinicIcons/105.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/106.svg b/assets/images/clinicIcons/106.svg new file mode 100644 index 0000000..bd103ad --- /dev/null +++ b/assets/images/clinicIcons/106.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/107.svg b/assets/images/clinicIcons/107.svg new file mode 100644 index 0000000..b1946db --- /dev/null +++ b/assets/images/clinicIcons/107.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/assets/images/clinicIcons/108.svg b/assets/images/clinicIcons/108.svg new file mode 100644 index 0000000..a29fe00 --- /dev/null +++ b/assets/images/clinicIcons/108.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/11.svg b/assets/images/clinicIcons/11.svg new file mode 100644 index 0000000..1c276aa --- /dev/null +++ b/assets/images/clinicIcons/11.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/110.svg b/assets/images/clinicIcons/110.svg new file mode 100644 index 0000000..6d533e2 --- /dev/null +++ b/assets/images/clinicIcons/110.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/111.svg b/assets/images/clinicIcons/111.svg new file mode 100644 index 0000000..46ba92f --- /dev/null +++ b/assets/images/clinicIcons/111.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/118.svg b/assets/images/clinicIcons/118.svg new file mode 100644 index 0000000..238cd5a --- /dev/null +++ b/assets/images/clinicIcons/118.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/12.svg b/assets/images/clinicIcons/12.svg new file mode 100644 index 0000000..cb6a23f --- /dev/null +++ b/assets/images/clinicIcons/12.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/images/clinicIcons/126.svg b/assets/images/clinicIcons/126.svg new file mode 100644 index 0000000..9d26d97 --- /dev/null +++ b/assets/images/clinicIcons/126.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/128.svg b/assets/images/clinicIcons/128.svg new file mode 100644 index 0000000..0888a5f --- /dev/null +++ b/assets/images/clinicIcons/128.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/130.svg b/assets/images/clinicIcons/130.svg new file mode 100644 index 0000000..5598ebb --- /dev/null +++ b/assets/images/clinicIcons/130.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/131.svg b/assets/images/clinicIcons/131.svg new file mode 100644 index 0000000..dbf94b5 --- /dev/null +++ b/assets/images/clinicIcons/131.svg @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/clinicIcons/134.svg b/assets/images/clinicIcons/134.svg new file mode 100644 index 0000000..42f8417 --- /dev/null +++ b/assets/images/clinicIcons/134.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/14.svg b/assets/images/clinicIcons/14.svg new file mode 100644 index 0000000..46ba92f --- /dev/null +++ b/assets/images/clinicIcons/14.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/140.svg b/assets/images/clinicIcons/140.svg new file mode 100644 index 0000000..56c7a53 --- /dev/null +++ b/assets/images/clinicIcons/140.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/148.svg b/assets/images/clinicIcons/148.svg new file mode 100644 index 0000000..bd103ad --- /dev/null +++ b/assets/images/clinicIcons/148.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/149.svg b/assets/images/clinicIcons/149.svg new file mode 100644 index 0000000..0888a5f --- /dev/null +++ b/assets/images/clinicIcons/149.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/16.svg b/assets/images/clinicIcons/16.svg new file mode 100644 index 0000000..e1ed316 --- /dev/null +++ b/assets/images/clinicIcons/16.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/17.svg b/assets/images/clinicIcons/17.svg new file mode 100644 index 0000000..44bad05 --- /dev/null +++ b/assets/images/clinicIcons/17.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/18.svg b/assets/images/clinicIcons/18.svg new file mode 100644 index 0000000..1148ad6 --- /dev/null +++ b/assets/images/clinicIcons/18.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/19.svg b/assets/images/clinicIcons/19.svg new file mode 100644 index 0000000..5b7d43b --- /dev/null +++ b/assets/images/clinicIcons/19.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/2.svg b/assets/images/clinicIcons/2.svg new file mode 100644 index 0000000..b4b1521 --- /dev/null +++ b/assets/images/clinicIcons/2.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/20.svg b/assets/images/clinicIcons/20.svg new file mode 100644 index 0000000..9e6db60 --- /dev/null +++ b/assets/images/clinicIcons/20.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/21.svg b/assets/images/clinicIcons/21.svg new file mode 100644 index 0000000..9b9ee82 --- /dev/null +++ b/assets/images/clinicIcons/21.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/23.svg b/assets/images/clinicIcons/23.svg new file mode 100644 index 0000000..4f8b915 --- /dev/null +++ b/assets/images/clinicIcons/23.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/24.svg b/assets/images/clinicIcons/24.svg new file mode 100644 index 0000000..70f4171 --- /dev/null +++ b/assets/images/clinicIcons/24.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/25.svg b/assets/images/clinicIcons/25.svg new file mode 100644 index 0000000..70f4171 --- /dev/null +++ b/assets/images/clinicIcons/25.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/250.svg b/assets/images/clinicIcons/250.svg new file mode 100644 index 0000000..b4b1521 --- /dev/null +++ b/assets/images/clinicIcons/250.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/252.svg b/assets/images/clinicIcons/252.svg new file mode 100644 index 0000000..9545d24 --- /dev/null +++ b/assets/images/clinicIcons/252.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/253.svg b/assets/images/clinicIcons/253.svg new file mode 100644 index 0000000..7118231 --- /dev/null +++ b/assets/images/clinicIcons/253.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/254.svg b/assets/images/clinicIcons/254.svg new file mode 100644 index 0000000..5e24ad4 --- /dev/null +++ b/assets/images/clinicIcons/254.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/255.svg b/assets/images/clinicIcons/255.svg new file mode 100644 index 0000000..e9ccd2b --- /dev/null +++ b/assets/images/clinicIcons/255.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/257.svg b/assets/images/clinicIcons/257.svg new file mode 100644 index 0000000..b4b1521 --- /dev/null +++ b/assets/images/clinicIcons/257.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/26.svg b/assets/images/clinicIcons/26.svg new file mode 100644 index 0000000..b82e118 --- /dev/null +++ b/assets/images/clinicIcons/26.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/260.svg b/assets/images/clinicIcons/260.svg new file mode 100644 index 0000000..60ed9c2 --- /dev/null +++ b/assets/images/clinicIcons/260.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/262.svg b/assets/images/clinicIcons/262.svg new file mode 100644 index 0000000..371c0ba --- /dev/null +++ b/assets/images/clinicIcons/262.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/assets/images/clinicIcons/264.svg b/assets/images/clinicIcons/264.svg new file mode 100644 index 0000000..b1f231e --- /dev/null +++ b/assets/images/clinicIcons/264.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/27.svg b/assets/images/clinicIcons/27.svg new file mode 100644 index 0000000..6da1ed7 --- /dev/null +++ b/assets/images/clinicIcons/27.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/28.svg b/assets/images/clinicIcons/28.svg new file mode 100644 index 0000000..483893c --- /dev/null +++ b/assets/images/clinicIcons/28.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/29.svg b/assets/images/clinicIcons/29.svg new file mode 100644 index 0000000..009a406 --- /dev/null +++ b/assets/images/clinicIcons/29.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/3.svg b/assets/images/clinicIcons/3.svg new file mode 100644 index 0000000..7a313ee --- /dev/null +++ b/assets/images/clinicIcons/3.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/30.svg b/assets/images/clinicIcons/30.svg new file mode 100644 index 0000000..d16a33a --- /dev/null +++ b/assets/images/clinicIcons/30.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/31.svg b/assets/images/clinicIcons/31.svg new file mode 100644 index 0000000..93becf0 --- /dev/null +++ b/assets/images/clinicIcons/31.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/32.svg b/assets/images/clinicIcons/32.svg new file mode 100644 index 0000000..9256566 --- /dev/null +++ b/assets/images/clinicIcons/32.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/34.svg b/assets/images/clinicIcons/34.svg new file mode 100644 index 0000000..b592ad8 --- /dev/null +++ b/assets/images/clinicIcons/34.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/35.svg b/assets/images/clinicIcons/35.svg new file mode 100644 index 0000000..c5ac879 --- /dev/null +++ b/assets/images/clinicIcons/35.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/36.svg b/assets/images/clinicIcons/36.svg new file mode 100644 index 0000000..1d171d4 --- /dev/null +++ b/assets/images/clinicIcons/36.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/images/clinicIcons/38.svg b/assets/images/clinicIcons/38.svg new file mode 100644 index 0000000..9448feb --- /dev/null +++ b/assets/images/clinicIcons/38.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/images/clinicIcons/4.svg b/assets/images/clinicIcons/4.svg new file mode 100644 index 0000000..beb7239 --- /dev/null +++ b/assets/images/clinicIcons/4.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/40.svg b/assets/images/clinicIcons/40.svg new file mode 100644 index 0000000..168ece6 --- /dev/null +++ b/assets/images/clinicIcons/40.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/41.svg b/assets/images/clinicIcons/41.svg new file mode 100644 index 0000000..93becf0 --- /dev/null +++ b/assets/images/clinicIcons/41.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/42.svg b/assets/images/clinicIcons/42.svg new file mode 100644 index 0000000..5b7d43b --- /dev/null +++ b/assets/images/clinicIcons/42.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/44.svg b/assets/images/clinicIcons/44.svg new file mode 100644 index 0000000..e9edf9a --- /dev/null +++ b/assets/images/clinicIcons/44.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/46.svg b/assets/images/clinicIcons/46.svg new file mode 100644 index 0000000..926ad19 --- /dev/null +++ b/assets/images/clinicIcons/46.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/5.svg b/assets/images/clinicIcons/5.svg new file mode 100644 index 0000000..d25576e --- /dev/null +++ b/assets/images/clinicIcons/5.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/50.svg b/assets/images/clinicIcons/50.svg new file mode 100644 index 0000000..662a64e --- /dev/null +++ b/assets/images/clinicIcons/50.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/51.svg b/assets/images/clinicIcons/51.svg new file mode 100644 index 0000000..8ef6791 --- /dev/null +++ b/assets/images/clinicIcons/51.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/53.svg b/assets/images/clinicIcons/53.svg new file mode 100644 index 0000000..56c7a53 --- /dev/null +++ b/assets/images/clinicIcons/53.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/55.svg b/assets/images/clinicIcons/55.svg new file mode 100644 index 0000000..a94748c --- /dev/null +++ b/assets/images/clinicIcons/55.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/images/clinicIcons/56.svg b/assets/images/clinicIcons/56.svg new file mode 100644 index 0000000..be81445 --- /dev/null +++ b/assets/images/clinicIcons/56.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/58.svg b/assets/images/clinicIcons/58.svg new file mode 100644 index 0000000..4987166 --- /dev/null +++ b/assets/images/clinicIcons/58.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/59.svg b/assets/images/clinicIcons/59.svg new file mode 100644 index 0000000..87e2269 --- /dev/null +++ b/assets/images/clinicIcons/59.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/6.svg b/assets/images/clinicIcons/6.svg new file mode 100644 index 0000000..50e0c7b --- /dev/null +++ b/assets/images/clinicIcons/6.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/67.svg b/assets/images/clinicIcons/67.svg new file mode 100644 index 0000000..4f8b915 --- /dev/null +++ b/assets/images/clinicIcons/67.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/68.svg b/assets/images/clinicIcons/68.svg new file mode 100644 index 0000000..d16a33a --- /dev/null +++ b/assets/images/clinicIcons/68.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/69.svg b/assets/images/clinicIcons/69.svg new file mode 100644 index 0000000..70f4171 --- /dev/null +++ b/assets/images/clinicIcons/69.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/7.svg b/assets/images/clinicIcons/7.svg new file mode 100644 index 0000000..b1ec62e --- /dev/null +++ b/assets/images/clinicIcons/7.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/74.svg b/assets/images/clinicIcons/74.svg new file mode 100644 index 0000000..6237181 --- /dev/null +++ b/assets/images/clinicIcons/74.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/78.svg b/assets/images/clinicIcons/78.svg new file mode 100644 index 0000000..60ed9c2 --- /dev/null +++ b/assets/images/clinicIcons/78.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/79.svg b/assets/images/clinicIcons/79.svg new file mode 100644 index 0000000..1decce9 --- /dev/null +++ b/assets/images/clinicIcons/79.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/8.svg b/assets/images/clinicIcons/8.svg new file mode 100644 index 0000000..d16a33a --- /dev/null +++ b/assets/images/clinicIcons/8.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/clinicIcons/83.svg b/assets/images/clinicIcons/83.svg new file mode 100644 index 0000000..87e2269 --- /dev/null +++ b/assets/images/clinicIcons/83.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/84.svg b/assets/images/clinicIcons/84.svg new file mode 100644 index 0000000..ed242ec --- /dev/null +++ b/assets/images/clinicIcons/84.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/85.svg b/assets/images/clinicIcons/85.svg new file mode 100644 index 0000000..076d201 --- /dev/null +++ b/assets/images/clinicIcons/85.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/86.svg b/assets/images/clinicIcons/86.svg new file mode 100644 index 0000000..4615e67 --- /dev/null +++ b/assets/images/clinicIcons/86.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/87.svg b/assets/images/clinicIcons/87.svg new file mode 100644 index 0000000..d0b95ae --- /dev/null +++ b/assets/images/clinicIcons/87.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/88.svg b/assets/images/clinicIcons/88.svg new file mode 100644 index 0000000..93f3042 --- /dev/null +++ b/assets/images/clinicIcons/88.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/89.svg b/assets/images/clinicIcons/89.svg new file mode 100644 index 0000000..768ef4a --- /dev/null +++ b/assets/images/clinicIcons/89.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/images/clinicIcons/9.svg b/assets/images/clinicIcons/9.svg new file mode 100644 index 0000000..aa0acfb --- /dev/null +++ b/assets/images/clinicIcons/9.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/90.svg b/assets/images/clinicIcons/90.svg new file mode 100644 index 0000000..6f8a44b --- /dev/null +++ b/assets/images/clinicIcons/90.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/91.svg b/assets/images/clinicIcons/91.svg new file mode 100644 index 0000000..4234428 --- /dev/null +++ b/assets/images/clinicIcons/91.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/93.svg b/assets/images/clinicIcons/93.svg new file mode 100644 index 0000000..be1b4a6 --- /dev/null +++ b/assets/images/clinicIcons/93.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/98.svg b/assets/images/clinicIcons/98.svg new file mode 100644 index 0000000..93f3042 --- /dev/null +++ b/assets/images/clinicIcons/98.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/Cardiac Surgery.svg b/assets/images/clinicIcons/Cardiac Surgery.svg new file mode 100644 index 0000000..2075871 --- /dev/null +++ b/assets/images/clinicIcons/Cardiac Surgery.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/Colorectal Oncology Clinic 2.svg b/assets/images/clinicIcons/Colorectal Oncology Clinic 2.svg new file mode 100644 index 0000000..b3898e5 --- /dev/null +++ b/assets/images/clinicIcons/Colorectal Oncology Clinic 2.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/Dental Employee Clinic.svg b/assets/images/clinicIcons/Dental Employee Clinic.svg new file mode 100644 index 0000000..44bad05 --- /dev/null +++ b/assets/images/clinicIcons/Dental Employee Clinic.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/ENT Oncology Clinic 2.svg b/assets/images/clinicIcons/ENT Oncology Clinic 2.svg new file mode 100644 index 0000000..7defb9c --- /dev/null +++ b/assets/images/clinicIcons/ENT Oncology Clinic 2.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/ER CLINIC.svg b/assets/images/clinicIcons/ER CLINIC.svg new file mode 100644 index 0000000..cb239be --- /dev/null +++ b/assets/images/clinicIcons/ER CLINIC.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/EXCELLENCE CLINIC.svg b/assets/images/clinicIcons/EXCELLENCE CLINIC.svg new file mode 100644 index 0000000..b6cc121 --- /dev/null +++ b/assets/images/clinicIcons/EXCELLENCE CLINIC.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Frame.svg b/assets/images/clinicIcons/Frame.svg new file mode 100644 index 0000000..c573a48 --- /dev/null +++ b/assets/images/clinicIcons/Frame.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Gynecology oncology Clinic.svg b/assets/images/clinicIcons/Gynecology oncology Clinic.svg new file mode 100644 index 0000000..9bef9cb --- /dev/null +++ b/assets/images/clinicIcons/Gynecology oncology Clinic.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Interventional Radiology Clinic.svg b/assets/images/clinicIcons/Interventional Radiology Clinic.svg new file mode 100644 index 0000000..5b7d43b --- /dev/null +++ b/assets/images/clinicIcons/Interventional Radiology Clinic.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/LIVER , GALLBLADDER, PANCREATIC CLINIC.svg b/assets/images/clinicIcons/LIVER , GALLBLADDER, PANCREATIC CLINIC.svg new file mode 100644 index 0000000..117b29b --- /dev/null +++ b/assets/images/clinicIcons/LIVER , GALLBLADDER, PANCREATIC CLINIC.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Maternal-Fetal Medicine Clinic.svg b/assets/images/clinicIcons/Maternal-Fetal Medicine Clinic.svg new file mode 100644 index 0000000..708d85f --- /dev/null +++ b/assets/images/clinicIcons/Maternal-Fetal Medicine Clinic.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/clinicIcons/Maxilliofacial Surgery.svg b/assets/images/clinicIcons/Maxilliofacial Surgery.svg new file mode 100644 index 0000000..66a0fbd --- /dev/null +++ b/assets/images/clinicIcons/Maxilliofacial Surgery.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/OB-GYNE physiotherapy clinic-1.svg b/assets/images/clinicIcons/OB-GYNE physiotherapy clinic-1.svg new file mode 100644 index 0000000..5e24ad4 --- /dev/null +++ b/assets/images/clinicIcons/OB-GYNE physiotherapy clinic-1.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/Occupational Therapy Clinic.svg b/assets/images/clinicIcons/Occupational Therapy Clinic.svg new file mode 100644 index 0000000..3181519 --- /dev/null +++ b/assets/images/clinicIcons/Occupational Therapy Clinic.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/clinicIcons/Orthopedic Oncology Surgery Clinic.svg b/assets/images/clinicIcons/Orthopedic Oncology Surgery Clinic.svg new file mode 100644 index 0000000..226d56c --- /dev/null +++ b/assets/images/clinicIcons/Orthopedic Oncology Surgery Clinic.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/images/clinicIcons/RRT Clinic 2.svg b/assets/images/clinicIcons/RRT Clinic 2.svg new file mode 100644 index 0000000..f4e451a --- /dev/null +++ b/assets/images/clinicIcons/RRT Clinic 2.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/Radiation Oncology Clinic 2.svg b/assets/images/clinicIcons/Radiation Oncology Clinic 2.svg new file mode 100644 index 0000000..ac8e5e1 --- /dev/null +++ b/assets/images/clinicIcons/Radiation Oncology Clinic 2.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Retinopathy of prematurity(ROP).svg b/assets/images/clinicIcons/Retinopathy of prematurity(ROP).svg new file mode 100644 index 0000000..814b1a7 --- /dev/null +++ b/assets/images/clinicIcons/Retinopathy of prematurity(ROP).svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/SKIN AND HAIR CARE.svg b/assets/images/clinicIcons/SKIN AND HAIR CARE.svg new file mode 100644 index 0000000..dbe3972 --- /dev/null +++ b/assets/images/clinicIcons/SKIN AND HAIR CARE.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/clinicIcons/SPA SKIN CARE.svg b/assets/images/clinicIcons/SPA SKIN CARE.svg new file mode 100644 index 0000000..55ce473 --- /dev/null +++ b/assets/images/clinicIcons/SPA SKIN CARE.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/clinicIcons/Smell Clinic 2.svg b/assets/images/clinicIcons/Smell Clinic 2.svg new file mode 100644 index 0000000..5341759 --- /dev/null +++ b/assets/images/clinicIcons/Smell Clinic 2.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/images/clinicIcons/Surgical Oncology Clinic.svg b/assets/images/clinicIcons/Surgical Oncology Clinic.svg new file mode 100644 index 0000000..7e7f1db --- /dev/null +++ b/assets/images/clinicIcons/Surgical Oncology Clinic.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/clinicIcons/Thoracic Clinic.svg b/assets/images/clinicIcons/Thoracic Clinic.svg new file mode 100644 index 0000000..9d26d97 --- /dev/null +++ b/assets/images/clinicIcons/Thoracic Clinic.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/clinicIcons/Urology Oncology Clinic.svg b/assets/images/clinicIcons/Urology Oncology Clinic.svg new file mode 100644 index 0000000..935af2e --- /dev/null +++ b/assets/images/clinicIcons/Urology Oncology Clinic.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/jpg/report.jpg b/assets/images/jpg/report.jpg new file mode 100644 index 0000000..5846cd5 Binary files /dev/null and b/assets/images/jpg/report.jpg differ diff --git a/assets/images/png/smartwatches/Huawei_Watch.png b/assets/images/png/smartwatches/Huawei_Watch.png new file mode 100644 index 0000000..97c416e Binary files /dev/null and b/assets/images/png/smartwatches/Huawei_Watch.png differ diff --git a/assets/images/png/smartwatches/Whoop_Watch.png b/assets/images/png/smartwatches/Whoop_Watch.png new file mode 100644 index 0000000..b3ac20c Binary files /dev/null and b/assets/images/png/smartwatches/Whoop_Watch.png differ diff --git a/assets/images/svg/ar_lang_icon.svg b/assets/images/svg/ar_lang_icon.svg new file mode 100644 index 0000000..d1c2be0 --- /dev/null +++ b/assets/images/svg/ar_lang_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/arrow-back_new.svg b/assets/images/svg/arrow-back_new.svg new file mode 100644 index 0000000..cae9694 --- /dev/null +++ b/assets/images/svg/arrow-back_new.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/back_top_nav_icon.svg b/assets/images/svg/back_top_nav_icon.svg new file mode 100644 index 0000000..62bf96b --- /dev/null +++ b/assets/images/svg/back_top_nav_icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/blood_pressure_icon.svg b/assets/images/svg/blood_pressure_icon.svg new file mode 100644 index 0000000..0b027ad --- /dev/null +++ b/assets/images/svg/blood_pressure_icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/blood_sugar_only_icon.svg b/assets/images/svg/blood_sugar_only_icon.svg new file mode 100644 index 0000000..f81cee8 --- /dev/null +++ b/assets/images/svg/blood_sugar_only_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/blood_type.svg b/assets/images/svg/blood_type.svg new file mode 100644 index 0000000..5aded31 --- /dev/null +++ b/assets/images/svg/blood_type.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/book_appo_bottom.svg b/assets/images/svg/book_appo_bottom.svg index d09107e..18b65b8 100644 --- a/assets/images/svg/book_appo_bottom.svg +++ b/assets/images/svg/book_appo_bottom.svg @@ -1,3 +1,3 @@ - - + + diff --git a/assets/images/svg/change_language_home_page.svg b/assets/images/svg/change_language_home_page.svg new file mode 100644 index 0000000..716a3b0 --- /dev/null +++ b/assets/images/svg/change_language_home_page.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/images/svg/close_bottom_nav_new.svg b/assets/images/svg/close_bottom_nav_new.svg new file mode 100644 index 0000000..1b7b937 --- /dev/null +++ b/assets/images/svg/close_bottom_nav_new.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/close_bottom_nav_trans.svg b/assets/images/svg/close_bottom_nav_trans.svg new file mode 100644 index 0000000..e00aaf9 --- /dev/null +++ b/assets/images/svg/close_bottom_nav_trans.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/close_bottom_sheet_icon.svg b/assets/images/svg/close_bottom_sheet_icon.svg index 599ce85..e00aaf9 100644 --- a/assets/images/svg/close_bottom_sheet_icon.svg +++ b/assets/images/svg/close_bottom_sheet_icon.svg @@ -1,4 +1,3 @@ - - - + + diff --git a/assets/images/svg/colored_dots_icon.svg b/assets/images/svg/colored_dots_icon.svg new file mode 100644 index 0000000..7f05dc5 --- /dev/null +++ b/assets/images/svg/colored_dots_icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/doctor_response_icon.svg b/assets/images/svg/doctor_response_icon.svg new file mode 100644 index 0000000..1c4b156 --- /dev/null +++ b/assets/images/svg/doctor_response_icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/en_lang_icon.svg b/assets/images/svg/en_lang_icon.svg new file mode 100644 index 0000000..fa1c143 --- /dev/null +++ b/assets/images/svg/en_lang_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/feedback_fill.svg b/assets/images/svg/feedback_fill.svg new file mode 100644 index 0000000..bb7c6a2 --- /dev/null +++ b/assets/images/svg/feedback_fill.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/forward_top_nav_icon.svg b/assets/images/svg/forward_top_nav_icon.svg new file mode 100644 index 0000000..089161c --- /dev/null +++ b/assets/images/svg/forward_top_nav_icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/genderInputIcon.svg b/assets/images/svg/genderInputIcon.svg new file mode 100644 index 0000000..4482ae3 --- /dev/null +++ b/assets/images/svg/genderInputIcon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/home_bottom.svg b/assets/images/svg/home_bottom.svg index 1bf82f9..70c3f1f 100644 --- a/assets/images/svg/home_bottom.svg +++ b/assets/images/svg/home_bottom.svg @@ -1,3 +1,4 @@ - - + + + diff --git a/assets/images/svg/home_bottom_fill.svg b/assets/images/svg/home_bottom_fill.svg new file mode 100644 index 0000000..30ed655 --- /dev/null +++ b/assets/images/svg/home_bottom_fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/insurance_history_icon.svg b/assets/images/svg/insurance_history_icon.svg index 4ae2a1c..e81bd87 100644 --- a/assets/images/svg/insurance_history_icon.svg +++ b/assets/images/svg/insurance_history_icon.svg @@ -1,4 +1,4 @@ - - - + + + diff --git a/assets/images/svg/location_fill.svg b/assets/images/svg/location_fill.svg new file mode 100644 index 0000000..a5afffb --- /dev/null +++ b/assets/images/svg/location_fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/low_indicator_icon.svg b/assets/images/svg/low_indicator_icon.svg new file mode 100644 index 0000000..f2ca09f --- /dev/null +++ b/assets/images/svg/low_indicator_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/my_child_vaccine.svg b/assets/images/svg/my_child_vaccine.svg new file mode 100644 index 0000000..f671baf --- /dev/null +++ b/assets/images/svg/my_child_vaccine.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/images/svg/my_files_bottom.svg b/assets/images/svg/my_files_bottom.svg index 813805e..a21fb4b 100644 --- a/assets/images/svg/my_files_bottom.svg +++ b/assets/images/svg/my_files_bottom.svg @@ -1,4 +1,4 @@ - - + + diff --git a/assets/images/svg/my_files_bottom_fill.svg b/assets/images/svg/my_files_bottom_fill.svg new file mode 100644 index 0000000..e4916e0 --- /dev/null +++ b/assets/images/svg/my_files_bottom_fill.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/news.svg b/assets/images/svg/news.svg index 82f9dcf..6ed40d3 100644 --- a/assets/images/svg/news.svg +++ b/assets/images/svg/news.svg @@ -1,6 +1,6 @@ - - - - - + + + + + diff --git a/assets/images/svg/news_fill.svg b/assets/images/svg/news_fill.svg new file mode 100644 index 0000000..ed9697c --- /dev/null +++ b/assets/images/svg/news_fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/normal_status_green_icon.svg b/assets/images/svg/normal_status_green_icon.svg new file mode 100644 index 0000000..b3f2619 --- /dev/null +++ b/assets/images/svg/normal_status_green_icon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/svg/send_email_icon.svg b/assets/images/svg/send_email_icon.svg new file mode 100644 index 0000000..eb8684a --- /dev/null +++ b/assets/images/svg/send_email_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/services_bottom.svg b/assets/images/svg/services_bottom.svg index baa3d6b..2b0733f 100644 --- a/assets/images/svg/services_bottom.svg +++ b/assets/images/svg/services_bottom.svg @@ -1,6 +1,6 @@ - - - - + + + + diff --git a/assets/images/svg/services_bottom_fill.svg b/assets/images/svg/services_bottom_fill.svg new file mode 100644 index 0000000..41f4f5b --- /dev/null +++ b/assets/images/svg/services_bottom_fill.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/images/svg/symptom_bottom_icon.svg b/assets/images/svg/symptom_bottom_icon.svg index bc72971..e9b3bd0 100644 --- a/assets/images/svg/symptom_bottom_icon.svg +++ b/assets/images/svg/symptom_bottom_icon.svg @@ -1,3 +1,3 @@ - + diff --git a/assets/images/svg/symptom_bottom_icon_fill.svg b/assets/images/svg/symptom_bottom_icon_fill.svg new file mode 100644 index 0000000..7192ae8 --- /dev/null +++ b/assets/images/svg/symptom_bottom_icon_fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/images/svg/weight_icon.svg b/assets/images/svg/weight_icon.svg new file mode 100644 index 0000000..f93c662 --- /dev/null +++ b/assets/images/svg/weight_icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index cde290e..737aeba 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -408,7 +408,7 @@ "brand": "العلامة التجارية", "power": "القوة", "diameter": "القطر", - "remarks": "ملاحظات", + "remarks": "ملاحظات: ", "activeMedications": "الأدوية النشطة", "expDate": "تاريخ انتهاء الصلاحية النشط:", "route": "الطريق", @@ -525,7 +525,7 @@ "payOnline": "الدفع عبر الإنترنت", "cancelOrder": "إلغاء الطلب", "confirmAddress": "تأكيد العنوان ", - "confirmLocation": "��أكيد الموقع ", + "confirmLocation": "أكيد الموقع ", "conditionsHMG": "الشروط والأحكام ", "conditions": "الشروط والأحكام لكوم", "confirmDeleteMsg": "هل أنت متأكد! تريد الحذف ", @@ -694,11 +694,7 @@ "bikini": "بيكيني", "totalMinutes": "إجمالي الدقائق", "feedback": "ملاحظات", - "send": "أرسل", - "status": "الحالة", "likeToHear": "نود سماع ملاحظاتك، ومخاوفك بشأن خدمات الرعاية الصحية وتجربة الخدمات الإلكترونية. يرجى استخدام النموذج أدناه", - "subject": "الموضوع", - "message": "رسالة", "emptySubject": "يرجى إدخال الموضوع", "emptyMessage": "يرجى إدخال الرسالة", "selectAttachment": "اختر المرفق", @@ -878,8 +874,657 @@ "laserClinic": "عيادة الليزر", "continueString": "يكمل", "covid_info": "تجري مستشفيات د. سليمان الحبيب فحص فيروس كورونا المستجد وتصدر شهادات السفر على مدار الساعة، طوال أيام الأسبوع، وبسرعة ودقة عالية. يمكن للراغبين في الاستفادة من هذه الخدمة زيارة أحد فروع مستشفيات د. سليمان الحبيب وإجراء فحص كورونا خلال بضع دقائق والحصول على النتائج خلال عدة ساعات خدمة فحص فيروس كورونا Covid 19 بتقنية PCR للكشف عن الفيروس وفقاً لأعلى المعايير العالمية وبأحدث أجهزة RT-PCR عالية الدقة (GeneXpert الأمريكي وغيره)، وهي طرق معتمدة من قبل هيئة الغذاء والدواء وكذلك من قبل المركز السعودي للوقاية من الأمراض المُعدية", + + "appointmentDetails": "تفاصيل الموعد", + "checkingDoctorAvailability": "جاري التحقق من توفر الطبيب...", + "cancellingAppointmentPleaseWait": "جاري إلغاء الموعد، يرجى الانتظار...", + "appointmentCancelledSuccessfully": "تم إلغاء الموعد بنجاح", + "notConfirmed": "غير مؤكد", + "appointmentStatus": "حالة الموعد", + "doctorWillCallYou": "سيتصل بك الطبيب عندما يقترب موعدك.", + "getDirections": "الحصول على الاتجاهات", + "notifyMeBeforeAppointment": "أبلغني قبل الموعد", + "fetchingLabResults": "جاري جلب نتائج المختبر...", + "fetchingRadiologyResults": "جاري جلب نتائج الأشعة...", + "fetchingAppointmentPrescriptions": "جاري جلب وصفات الموعد...", + "noPrescriptionsForAppointment": "ليس لديك أي وصفات طبية لهذا الموعد.", + "amountBeforeTax": "المبلغ قبل الضريبة", + "rebookAppointment": "إعادة حجز الموعد", + "fetchingDoctorSchedulePleaseWait": "جاري جلب جدول الطبيب، يرجى الانتظار...", + "pickADate": "اختر تاريخاً", + "confirmingAppointmentPleaseWait": "جاري تأكيد الموعد، يرجى الانتظار...", + "appointmentConfirmedSuccessfully": "تم تأكيد الموعد بنجاح", + "appointmentPayment": "دفع الموعد", + "checkingPaymentStatusPleaseWait": "جاري التحقق من حالة الدفع، يرجى الانتظار...", + "paymentFailedPleaseTryAgain": "فشل الدفع! يرجى المحاولة مرة أخرى.", + "appointmentCheckIn": "تسجيل حضور الموعد", + "insuranceExpiredOrInactive": "التأمين منتهي الصلاحية أو غير نشط", + "totalAmountToPay": "المبلغ الإجمالي المستحق", + "vat15": "ضريبة القيمة المضافة 15%", + "general": "عام", + "liveCare": "لايف كير", + "recentVisits": "الزيارات الأخيرة", + "searchByClinic": "البحث حسب العيادة", + "tapToSelectClinic": "انقر لاختيار العيادة", + "searchByDoctor": "البحث حسب الطبيب", + "tapToSelect": "انقر للاختيار", + "searchByRegion": "البحث حسب المنطقة", + "centralRegion": "المنطقة الوسطى", + "immediateConsultation": "استشارة فورية", + "scheduledConsultation": "استشارة مجدولة", + "pharmaLiveCare": "لايف كير الصيدلية", + "notSureHelpMeChooseClinic": "غير متأكد؟ ساعدني في اختيار عيادة!", + "mentionYourSymptomsAndFindDoctors": "اذكر أعراضك واعثر على قائمة الأطباء وفقاً لذلك", + "immediateService": "خدمة فورية", + "noNeedToWaitGetMedicalConsultation": "لا حاجة للانتظار، ستحصل على استشارة طبية فورية عبر مكالمة فيديو", + "noVisitRequired": "لا حاجة للزيارة", + "doctorWillContact": "سيتصل بك الطبيب", + "specialisedDoctorWillContactYou": "سيتصل بك طبيب متخصص وسيكون قادراً على الاطلاع على تاريخك الطبي", + "freeMedicineDelivery": "توصيل مجاني للأدوية", + "offersFreeMedicineDelivery": "يوفر توصيل مجاني للأدوية لموعد لايف كير", + "dentalChiefComplaints": "الشكاوى الرئيسة للأسنان", + "viewAvailableAppointments": "عرض المواعيد المتاحة", + "doctorProfile": "الملف للطبيب", + "waitingAppointment": "موعد الانتظار", + "hospitalInformation": "معلومات المستشفى", + "fetchingAppointmentShare": "جاري جلب تفاصيل الموعد...", + "bookingYourAppointment": "جاري حجز موعدك...", + "selectLiveCareClinic": "اختر عيادة لايف كير", + "checkingForExistingDentalPlan": "جاري التحقق من وجود خطة أسنان حالية، يرجى الانتظار...", + "dentalTreatmentPlan": "خطة علاج الأسنان", + "youHaveExistingTreatmentPlan": "لديك خطة علاج حالية: ", + "mins": "دقيقة", + "totalTimeRequired": "إجمالي الوقت المطلوب", + "wouldYouLikeToContinue": "هل تريد متابعتها؟", + "chooseDoctor": "اختر الطبيب", + "viewNearestAppos": "عرض أقرب المواعيد المتاحة", + "noDoctorFound": "لم يتم العثور على طبيب مطابق للمعايير المحددة...", + "yesPleasImInAHurry": "نعم من فضلك، أنا في عجلة من أمري", + "fetchingFeesPleaseWait": "جاري جلب الرسوم، يرجى الانتظار...", + "noThanksPhysicalVisit": "لا، شكراً. أفضل الزيارة الشخصية", + "offline": "غير متصل", + "videoCall": "مكالمة فيديو", + "liveVideoCallWithHMGDoctors": "مكالمة فيديو مباشرة مع أطباء مجموعة الحبيب الطبية", + "audioCall": "مكالمة صوتية", + "phoneCall": "مكالمة هاتفية", + "livePhoneCallWithHMGDoctors": "مكالمة هاتفية مباشرة مع أطباء مجموعة الحبيب الطبية", + "reviewLiveCareRequest": "مراجعة طلب لايف كير", + "selectedLiveCareType": "نوع لايف كير المحدد", + "selectLiveCareCallType": "اختر نوع مكالمة لايف كير", + "confirmingLiveCareRequest": "جاري تأكيد طلب لايف كير، يرجى الانتظار...", + "unknownErrorOccurred": "حدث خطأ غير معروف...", + "liveCarePermissionsMessage": "يتطلب لايف كير أذونات الكاميرا والميكروفون والموقع والإشعارات لتمكين الاستشارة الافتراضية بين المريض والطبيب، يرجى السماح بهذه الأذونات للمتابعة.", + "liveCarePayment": "دفع لايف كير", + "mada": "مدى", + "visaOrMastercard": "فيزا أو ماستركارد", + "tamara": "تمارا", + "fetchingApplePayDetails": "جاري جلب تفاصيل Apple Pay، يرجى الانتظار...", + "liveCarePendingRequest": "لايف كير حية معلق", + "callLiveCareSupport": "اتصل بدعم لايف كير", + "whatIsWaitingAppointment": "ما هو موعد الانتظار؟", + "waitingAppointmentsFeature": "تتيح لك ميزة مواعيد الانتظار حجز موعد أثناء تواجدك داخل مبنى المستشفى، وفي حال عدم توفر فتحة متاحة في جدول الطبيب.", + "appointmentWithDoctorConfirmed": "الموعد مع الطبيب مؤكد، ولكن وقت الدخول غير محدد.", + "paymentWithinTenMinutes": "ملاحظة: يجب عليك الدفع خلال 10 دقائق من الحجز، وإلا سيتم إلغاء موعدك تلقائياً", + "liveLocation": "الموقع المباشر", + "verifyYourLocationAtHospital": "تحقق من موقعك في المستشفى لتسجيل الحضور", + "error": "خطأ", + "ensureWithinHospitalLocation": "يرجى التأكد من أنك داخل موقع المستشفى لإجراء تسجيل الحضور عبر الإنترنت.", + "nfcNearFieldCommunication": "NFC (الاتصال قريب المدى)", + "scanPhoneViaNFC": "امسح هاتفك عبر لوحة NFC لتسجيل الحضور", + "qrCode": "رمز QR", + "scanQRCodeToCheckIn": "امسح رمز QR بالكاميرا لتسجيل الحضور", + "processingCheckIn": "جاري معالجة تسجيل الحضور...", + "bookingWaitingAppointment": "جاري حجز موعد الانتظار، يرجى الانتظار...", + "enterValidIDorIqama": "يرجى إدخال رقم هوية وطنية أو رقم ملف صالح", + "selectAppointment": "حدد الموعد", + "rebookSameDoctor": "أعد الحجز مع نفس الطبيب", + "queueing": "قائمة الانتظار", + "inQueue": "في قائمة الانتظار", + "yourTurn": "دورك", + "halaFirstName": "هلا {firstName}!!!", + "thankYouForPatience": "شكراً لصبرك، هذا هو رقم قائمة الانتظار الخاص بك.", + "servingNow": "يُخدم الآن", + "callForVitalSigns": "نداء للعلامات الحيوية", + "thingsToAskDoctor": "أشياء تسأل طبيبك عنها اليوم", + "improveOverallHealth": "ماذا يمكنني أن أفعل لتحسين صحتي العامة؟", + "routineScreenings": "هل هناك أي فحوصات روتينية يجب أن أجريها؟", + "whatIsThisMedicationFor": "لماذا هذا الدواء؟", + "sideEffectsToKnow": "هل هناك أي آثار جانبية يجب أن أعرفها؟", + "whenFollowUp": "متى يجب أن أعود للمتابعة؟", + "goToHomepage": "الذهاب إلى الصفحة الرئيسية", + "appointmentsList": "قائمة المواعيد", + "allAppt": "جميع المواعيد", + "upcoming": "القادمة", + "completed": "المكتملة", + "noAppointmentsYet": "ليس لديك أي مواعيد بعد.", + "viewProfile": "عرض الملف الشخصي", + "choosePreferredHospitalForService": "اختر المستشفى المفضل لديك للخدمة", + "noHospitalsFound": "لم يتم العثور على مستشفيات", + "cancelOrderConfirmation": "هل أنت متأكد أنك تريد إلغاء هذا الطلب؟", + "orderCancelledSuccessfully": "تم إلغاء الطلب بنجاح", + "requestID": "معرف الطلب:", + "noCMCOrdersYet": "ليس لديك أي طلبات فحص شامل بعد.", + "cmcOrders": "طلبات الفحص الشامل", + "summary": "الملخص", + "selectedService": "الخدمة المحددة", + "requestSubmittedSuccessfully": "تم إرسال طلبك بنجاح.", + "hereIsYourRequestNumber": "هذا هو رقم طلبك #: ", + "pleaseSelectHospitalToContinue": "يرجى اختيار مستشفى للمتابعة", + "confirmSubmitRequest": "هل أنت متأكد أنك تريد إرسال هذا الطلب؟", + "pendingOrderWait": "لديك طلب معلق. يرجى الانتظار حتى تتم معالجته.", + "noServicesAvailable": "لا توجد خدمات متاحة", + "selectAService": "اختر خدمة", + "comprehensiveCheckup": "الفحص الشامل", + "viewNearestHMGLocations": "عرض أقرب مواقع مجموعة الحبيب الطبية", + "provideFeedbackOnServices": "قدم ملاحظاتك على خدماتنا", + "liveChatWithHMG": "خيار الدردشة المباشرة مع مجموعة الحبيب الطبية", + "send": "إرسال", + "status": "الحالة", + "sendingFeedback": "جاري إرسال الملاحظات...", + "selectFeedbackType": "اختر نوع الملاحظات", + "loadingAppointmentsList": "جاري تحميل قائمة المواعيد...", + "noAppointmentsForFeedback": "ليس لديك أي مواعيد لتقديم ملاحظات عنها.", + "selectedAppointment": "الموعد المحدد:", + "subject": "الموضوع", + "enterSubjectHere": "أدخل الموضوع هنا", + "message": "الرسالة", + "enterMessageHere": "أدخل الرسالة هنا", + "filesSelected": "تم تحديد {count} ملف(ات)", + "otherDetails": "تفاصيل أخرى", + "medicalReport": "التقرير الطبي", + "medicalReportNumber": "التقرير الطبي {number}", + "patientIsInsured": "المريض مؤمن عليه", + "insuranceDocument": "وثيقة التأمين", + "selectBranch": "اختر الفرع", + "patientInformation": "معلومات المريض", + "patientLocation": "أين يتواجد المريض", + "identificationNumber": "رقم الهوية", + "enterIdentificationNumber": "أدخل رقم الهوية*", + "patientName": "اسم المريض*", + "referralRequesterInformation": "معلومات مقدم طلب الإحالة", + "enterReferralRequesterName": "أدخل اسم مقدم طلب الإحالة*", + "requesterName": "اسم مقدم الطلب", + "relationship": "العلاقة", + "selectRelation": "اختر العلاقة", + "otherName": "اسم آخر", + "otherNameHint": "اسم آخر*", + "requesterNameRequired": "اسم مقدم طلب الإحالة مطلوب", + "selectRelationshipRequired": "يرجى اختيار العلاقة", + "otherRelationshipNameRequired": "اسم العلاقة الأخرى مطلوب", + "identificationNumberRequired": "رقم الهوية مطلوب", + "patientNameRequired": "اسم المريض مطلوب", + "enterPatientPhoneRequired": "يرجى إدخال رقم هاتف المريض", + "selectPatientCityRequired": "يرجى اختيار مدينة المريض", + "medicalReportRequired": "مطلوب تقرير طبي واحد على الأقل", + "selectBranchRequired": "يرجى اختيار الفرع", + "insuranceDocumentRequired": "وثيقة التأمين مطلوبة للمرضى المؤمن عليهم", + "searchResult": "نتيجة البحث", + "referralNo": "رقم الإحالة {number}", + "eReferral": "الإحالة الإلكترونية", + "referralCreatedSuccessfully": "تم إنشاء إحالتك بنجاح.", + "hereIsYourReferralNumber": "هذا هو رقم الإحالة الخاص بك #: ", + "searchEReferral": "البحث عن إحالة إلكترونية", + "enterRequiredInfoToSearch": "يرجى إدخال المعلومات المطلوبة للبحث عن إحالة إلكترونية", + "selectPickupDirection": "اختر اتجاه الاستلام", + "selectDirection": "اختر الاتجاه", + "toHospital": "إلى المستشفى", + "fromHospital": "من المستشفى", + "selectWay": "اختر الطريقة", + "oneWay": "اتجاه واحد", + "twoWay": "اتجاهين", + "selectPickupDetails": "اختر تفاصيل الاستلام", + "pleaseSelectDetailsOfPickup": " يرجى تحديد تفاصيل الاستلام", + "selectDetails": "اختر التفاصيل", + "work": "العمل", + "pick": "استلام", + "insideTheHome": "داخل المنزل", + "haveAnyAppointment": "هل لديك أي موعد", + "amountPaidAtHospital": "سيتم دفع المبلغ في المستشفى", + "submitRequest": "إرسال الطلب", + "enterPickupLocationManually": "أدخل موقع الاستلام يدوياً", + "enterPickupLocation": "أدخل موقع الاستلام", + "trackingDetails": "تفاصيل التتبع", + "cancelRequest": "إلغاء الطلب", + "shareLocationWhatsapp": "مشاركة موقعك المباشر على واتساب", + "pleaseWaitForCall": "يرجى انتظار المكالمة", + "toHospitalLower": "إلى المستشفى", + "contact": "اتصال", + "failed": "فشل", + "confirmationCall": "مكالمة التأكيد", + "pickupFromHome": "الاستلام من المنزل", + "onTheWayToHospital": " في الطريق إلى المستشفى", + "arrivedAtHospital": "وصل إلى المستشفى", + "orderCancel": "إلغاء الطلب", + "emergencyCheckIn": "تسجيل الطوارئ الإلكتروني", + "erOnlineCheckInDescription": "تتيح هذه الخدمة للمرضى تسجيل موعد الطوارئ قبل الوصول.", + "erOnlineCheckInSuccess": "تم تسجيل وصول الطوارئ بنجاح. الرجاء التوجه إلى منطقة الانتظار.", + "erOnlineCheckInError": "حدث خطأ غير متوقع أثناء عملية التسجيل. يرجى التواصل مع الدعم.", + "fetchingHospitalsList": "جاري جلب قائمة المستشفيات...", + "fetchingPaymentInformation": "جاري جلب معلومات الدفع...", + "erVisitDetails": "تفاصيل زيارة الطوارئ", + "erClinic": "عيادة الطوارئ", + "vatWithAmount": "الضريبة 15% ({amount})", + "erAppointmentBookedSuccess": "تم حجز موعدك بنجاح. يرجى إتمام إجراءات تسجيل الوصول عند وصولك إلى المستشفى.", + "underProcessing": "قيد المعالجة", + "canceledByPatient": "ملغى بواسطة المريض", + "rapidResponseTeam": "فريق الاستجابة السريع", + "allFacilities": "جميع المرافق", + "selectLocation": "اختر الموقع", + "pleaseSelectTheLocation": "يرجى اختيار الموقع", + "viewLocationGoogleMaps": "عرض الموقع على خرائط جوجل", + "callAmbulance": "استدعاء سيارة إسعاف", + "requestAmbulanceInEmergency": "طلب سيارة إسعاف في حالة الطوارئ من المنزل أو المستشفى", + "confirmation": "تأكيد", + "areYouSureYouWantToCallAmbulance": "هل أنت متأكد أنك تريد استدعاء سيارة إسعاف؟", + "getDetailsOfNearestBranch": "احصل على تفاصيل أقرب فرع بما في ذلك الاتجاهات", + "areYouSureYouWantToCallRRT": "هل أنت متأكد أنك تريد استدعاء فريق الاستجابة السريعة (RRT)؟", + "priorERCheckInToSkipLine": "تسجيل الوصول المسبق في الطوارئ لتجاوز الطابور والدفع في الاستقبال.", + "areYouSureYouWantToMakeERCheckIn": "هل أنت متأكد أنك تريد إجراء تسجيل وصول الطوارئ؟", + "checkingYourERAppointmentStatus": "جاري التحقق من حالة موعد الطوارئ الخاص بك...", + "transportOptions": "خيارات النقل", + "selectHospitalForAdvancePayment": "يرجى اختيار المستشفى الذي ترغب في دفع مبلغ مقدم له.", + "recharge": "إعادة الشحن", + "activityLevel": "مستوى النشاط", + "selectActivityLevel": "حدد مستوى النشاط", + "caloriesPerDay": "السعرات الحرارية في اليوم الواحد", + "dietType": "نوع النظام الغذائي", + "selectDietType": "حدد نوع النظام الغذائي", + "bodyFrameSize": "حجم إطار الجسم", + "selectBodyFrameSize": "حدد حجم إطار الجسم", + "averageCycleLength": "متوسط طول الدورة الشهرية (عادةً 28 يومًا)", + "averageLutealPhase": "متوسط طول المرحلة الأصفرية (عادةً 14 يومًا)", + "convert": "يتحول", + "calculate": "احسب", + "healthCalculators": "حاسبات الصحة", + "healthConverters": "محولات الصحة", + "generalHealth": "الصحة العامة", + "relatedToBMICalories": "متعلق بمؤشر كتلة الجسم والسعرات الحرارية ودهون الجسم وما إلى ذلك للبقاء على اطلاع دائم بصحتك.", + "selectCalculator": "اختر الآلة الحاسبة", + "womensHealth": "صحة المرأة", + "relatedToPeriodsOvulation": "متعلق بالدورة الشهرية والإباضة والحمل ومواضيع أخرى.", + "bloodSugar": "سكر الدم", + "trackYourGlucoseLevels": "تتبع مستويات الجلوكوز لديك، وفهم الاتجاهات، واحصل على رؤى مخصصة لصحة أفضل.", + "bloodCholesterol": "كوليسترول الدم", + "monitorCholesterolLevels": "راقب مستويات الكوليسترول، وقيّم مخاطر صحة القلب، واتخذ خطوات استباقية للرفاهية.", + "triglyceridesFatBlood": "الدهون الثلاثية في الدم", + "understandTriglyceridesImpact": "افهم تأثير الدهون الثلاثية على صحة القلب مع رؤى مخصصة وتوصيات الخبراء.", + "bmiCalculator": "حاسبة\nمؤشر كتلة الجسم", + "caloriesCalculator": "حاسبة\nالسعرات الحرارية", + "bmrCalculator": "حاسبة\nمعدل الأيض الأساسي", + "idealBodyWeight": "الوزن المثالي\nللجسم", + "bodyFatCalculator": "حاسبة\nدهون الجسم", + "carbsProteinFat": "الكربوهيدرات\nالبروتين والدهون", + "ovulationPeriod": "فترة\nالإباضة", + "deliveryDueDate": "تاريخ الولادة\nالمتوقع", + "low": "منخفض", + "preDiabetic": "ما قبل السكري", + "high": "مرتفع", + "elevated": "مرتفع قليلاً", + "recorded": "مسجل", + "noRecordsYet": "لا توجد سجلات بعد", + "lastRecord": "آخر سجل", + "addBloodSugar": "إضافة سكر الدم", + "addBloodPressure": "إضافة ضغط الدم", + "addWeight": "إضافة الوزن", + "bloodSugarDataSavedSuccessfully": "تم حفظ بيانات سكر الدم بنجاح", + "bloodPressureDataSavedSuccessfully": "تم حفظ بيانات ضغط الدم بنجاح", + "weightDataSavedSuccessfully": "تم حفظ بيانات الوزن بنجاح", + "pleaseWait": "يرجى الانتظار", + "selectUnit": "اختر الوحدة", + "selectMeasureTime": "اختر وقت القياس", + "selectArm": "اختر الذراع", + "enterBloodSugar": "أدخل سكر الدم", + "enterSystolicValue": "أدخل القيمة الانقباضية", + "enterDiastolicValue": "أدخل القيمة الانبساطية", + "enterWeight": "أدخل الوزن", + "selectDuration": "اختر المدة", + "systolic": "الانقباضي", + "diastolic": "الانبساطي", + "sendReportByEmail": "إرسال التقرير عبر البريد الإلكتروني", + "enterYourEmailToReceiveReport": "أدخل عنوان بريدك الإلكتروني لاستلام التقرير", + "addNewRecord": "إضافة سجل جديد", + "healthTrackers": "متتبعات الصحة", + "monitorBloodPressureLevels": "راقب مستويات ضغط الدم لديك، وتتبع القراءات الانقباضية والانبساطية، وحافظ على صحة قلبك.", + "trackWeightProgress": "تتبع تقدم وزنك، وضع الأهداف، وحافظ على كتلة جسم صحية من أجل العافية الشاملة.", + "bookAppointment": "حجز\nموعد", + "completeCheckup": "الفحص الشامل", + "indoorNavigation": "الملاحة الداخلية", + "eReferralServices": "خدمات الإحالة الإلكترونية", + "bloodDonation": "التبرع بالدم", + "dailyWaterMonitor": "مراقب الماء اليومي", + "fetchingYourWaterIntakeDetails": "جاري جلب تفاصيل استهلاك الماء الخاص بك.", + "healthCalculatorsServices": "حاسبات\nالصحة", + "healthConvertersServices": "محولات\nالصحة", + "smartWatchesServices": "الساعات\nالذكية", + "exploreServices": "استكشف الخدمات", + "medicalAndCareServices": "الخدمات الطبية والرعاية", + "hmgServices": "خدمات مجموعة الحبيب الطبية", + "personalServices": "الخدمات الشخصية", + "habibWallet": "محفظة الحبيب", + "loginToViewWalletBalance": "سجل الدخول لعرض رصيد محفظتك", + "recharge": "إعادة الشحن", + "loginToViewMedicalFile": "سجل الدخول لعرض ملفك الطبي", + "addMember": "إضافة عضو", + "addFamilyMember": "إضافة فرد من العائلة", + "pleaseFillBelowFieldToAddNewFamilyMember": "يرجى ملء الحقل أدناه لإضافة فرد جديد من العائلة إلى ملفك الشخصي", + "healthTools": "أدوات الصحة", + "supportServices": "خدمات الدعم", + "virtualTour": "جولة افتراضية", + "carParking": "موقف السيارات", + "latestNews": "آخر الأخبار", + "hmgContact": "اتصل بمجموعة الحبيب الطبية", + "durationCannotExceed90": "لا يجوز أن تتجاوز المدة 90 دقيقة", + "unexpectedError": "حدث خطأ غير متوقع", + "gettingAmbulanceTransportOption": "جاري الحصول على خيارات نقل الإسعاف", + "fetchingAppointment": "جاري جلب الموعد", + "doYouWantToCancelTheRequest": "هل تريد إلغاء الطلب", + "cancellingRequest": "جاري إلغاء الطلب", + "fetchingTermsAndConditions": "جاري جلب الشروط والأحكام", + "selectLocationPrescriptionDelivery": "يرجى تحديد موقع توصيل الوصفة الطبية", + "noRadiologyOrders": "لم يتم العثور على أي طلبات تصوير شعاعي", + "ageIsRequired": "العمر مطلوب", + "invalidAge": "العمر غير صالح", + "ageMustBeBetween11And120": "يجب أن يكون العمر بين 11 و 120", + "heightIsRequired": "الطول مطلوب", + "invalidHeight": "الطول غير صالح", + "weightIsRequired": "الوزن مطلوب", + "invalidWeight": "الوزن غير صالح", + "timeToDrinkWater": "حان وقت شرب الماء! 💧", + "stayHydratedDrinkWater": "ابق رطبًا! اشرب {amount} مل من الماء.", + "visitPharmacyOnline": "زيارة الصيدلة على الانترنت", + "howAreYouFeelingToday": "كيف حالك اليوم؟", + "checkYourSymptomsWithScale": "تحقق من أعراضك باستخدام ذا المقياس", + "checkYourSymptoms": "تحقق من أعراضك", + "noUpcomingAppointmentPleaseBook": "ليس لديك أي مواعيد قادمة. يرجى حجز موعد", + "youHaveEROnlineCheckInRequest": "لديك طلب تسجيل وصول عبر الإنترنت للطوارئ", + "quickLinks": "روابط سريعة", + "viewMedicalFileLandingPage": "عرض الملف الطبي", + "immediateLiveCareRequest": "طلب LiveCare الفوري", + "yourTurnIsAfterPatients": "دورك بعد {count} مريض.", + "dontHaveHHCOrders": "ليس لديك أي أوامر رعاية صحية منزلية حتى الآن.", + "hhcOrders": "أوامر الرعاية الصحية المنزلية", + "requestedServices": "الخدمات المطلوبة", + "selectServices": "اختر الخدمات", + "selectedServices": "الخدمات المختارة", + "createNewRequest": "إنشاء طلب جديد", + "youHaveNoPendingRequests": "ليس لديك أي طلبات معلقة.", + "noInsuranceDataFound": "لم يتم العثور على بيانات التأمين...", + "noInsuranceUpdateRequest": "لم يتم العثور على أي طلبات لتحديث بيانات التأمين.", + "policyNumberInsurancePage": "الوثيقة: {number}", + "insuranceExpired": "التأمين منتهي الصلاحية", + "insuranceActive": "التأمين نشط", + "patientCardID": "رقم بطاقة المريض: {id}", + "noInsuranceApprovals": "لم تحصل على أي موافقات تأمينية حتى الآن.", + "noInsuranceWithHMG": "ليس لديك تأمين مسجل لدى مجموعة حبيب الطبية.", + "referenceRange": "النطاق المرجعي", + "downloadReport": "تنزيل التقرير", + "generatingReport": "جارٍ إنشاء التقرير، يرجى الانتظار...", + "noLabResults": "ليس لديك أي نتائج مختبرية حتى الآن.", + "labResultDetails": "تفاصيل نتائج المختبر", + "resultOf": "نتيجة", + "whatIsThisResult": "ما هي هذه النتيجة؟", + "lastTested": "آخر اختبار", + "byVisit": "حسب الزيارة", + "byTest": "حسب التحليل", + "results": "نتائج", + "viewResults": "عرض النتائج", + "rebook": "إعادة الحجز", + "noOphthalmologyAppointments": "لم يتم العثور على أي مواعيد في قسم طب العيون...", + "noVitalSignsRecordedYet": "لا توجد علامات حيوية مسجلة بعد", + "appointmentsAndVisits": "المواعيد والزيارات", + "labAndRadiology": "المختبر والأشعة", + "activeMedicationsAndPrescriptions": "الأدوية النشطة والوصفات الطبية", + "allPrescriptions": "جميع الوصفات", + "allMedications": "جميع الأدوية", + "youDontHaveAnyPrescriptionsYet": "ليس لديك أي وصفات طبية بعد.", + "youDontHaveAnyCompletedVisitsYet": "ليس لديك أي زيارات مكتملة بعد", + "others": "أخرى", + "allergyInfo": "معلومات الحساسية", + "vaccineInfo": "معلومات اللقاحات", + "updateInsuranceInfo": "تحديث التأمين", + "myInvoicesList": "قائمة فواتيري", + "ancillaryOrdersList": "قائمة الطلبات المساعدة", + "youDontHaveAnySickLeavesYet": "ليس لديك أي إجازات مرضية بعد.", + "medicalReports": "التقارير الطبية", + "sickLeaveReport": "تقرير الإجازة المرضية", + "weightTracker": "متتبع الوزن", + "askYourDoctor": "اسأل طبيبك", + "internetPairing": "الاقتران بالإنترنت", + "requested": "مطلوب", + "youDontHaveAnyMedicalReportsYet": "ليس لديك أي تقارير طبية بعد.", + "requestMedicalReport": "طلب تقرير طبي", + "youDoNotHaveAnyAppointmentsToRequestMedicalReport": "ليس لديك أي مواعيد لطلب تقرير طبي.", + "areYouSureYouWantToRequestMedicalReport": "هل أنت متأكد أنك تريد طلب تقرير طبي لهذا الموعد؟", + "yourMedicalReportRequestSubmittedSuccessfully": "تم إرسال طلب التقرير الطبي بنجاح.", + "monthlyHealthSummaryReportDisclaimer": "يعكس تقرير الملخص الصحي الشهري هذا المؤشرات الصحية ونتائج التحليل لأحدث الزيارات. يرجى ملاحظة أن هذا سيتم إرساله تلقائيًا من النظام ولا يعتبر تقريرًا رسميًا لذا لا ينبغي اتخاذ أي قرار طبي بناءً عليه", + "updatingMonthlyReportStatus": "جاري تحديث حالة التقرير الشهري...", + "monthlyReportStatusUpdatedSuccessfully": "تم تحديث حالة التقرير الشهري بنجاح", + "whoCanViewMyMedicalFile": "من يمكنه عرض ملفي الطبي؟", + "acceptedYourRequestToBeYourFamilyMember": "{status} طلبك لتكون فردًا من عائلتك", + "canViewYourFile": "يمكنه عرض ملفك", + "hasARequestPendingToBeYourFamilyMember": "لديه طلب {status} ليكون فردًا من عائلتك", + "wantsToAddYouAsTheirFamilyMember": "يريد إضافتك كفرد من عائلته", + "rejectedYourRequestToBeYourFamilyMember": "{status} طلبك لتكون فردًا من عائلتك", + "rejectedYourFamilyMemberRequest": "{status} طلب فرد عائلتك", + "notAvailable": "غير متاح", + "selectAProfile": "الرجاء تحديد ملف تعريف", + "switchFamilyFile": "قم بالتبديل من قائمة الملفات الطبية أدناه", + "medicalFiles": "الملفات الطبية", + "addANewFamilyMember": "إضافة فرد جديد من العائلة", + "viewInvoiceDetails": "عرض تفاصيل الفاتورة", + "outPatient": "مريض خارجي", + "invoiceDetails": "تفاصيل الفاتورة", + "sendingEmailPleaseWait": "جاري إرسال ال��ريد الإلكتروني، يرجى الانتظار...", + "emailSentSuccessfullyMessage": "تم إرسال البريد الإلكتروني بنجاح.", + "discount": "خصم", + "paid": "مدفوع", + "fetchingInvoiceDetails": "جارٍ جلب تفاصيل الفاتورة، يرجى الانتظار...", + "scanQRCode": "مسح رمز الاستجابة السريعة", + "parkingSlotDetails": "تفاصيل موقف السيارة", + "slotNumber": "رقم الموقف: {code}", + "basement": "الطابق: {description}", + "parkingDate": "التاريخ: {date}", + "parkedSince": "متوقف منذ: {time}", + "resetDirection": "إعادة تعيين الاتجاه", + "noPrescriptionOrdersYet": "ليس لديك أي طلبات وصفات طبية حتى الآن.", + "fetchingPrescriptionPDFPleaseWait": "جاري جلب ملف الوصفة الطبية، يرجى الانتظار...", + "ratingValue": "التقييم: {rating}", + "downloadPrescription": "تحميل الوصفة الطبية", + "fetchingPrescriptionDetails": "جاري جلب تفاصيل الوصفة الطبية...", + "switchBackFamilyFile": "العودة إلى ملف العائلة", + "profileAndSettings": "الملف الشخصي والإعدادات", + "quickActions": "إجراءات سريعة", + "notificationsSettings": "إعدادات الإشعارات", + "touchIDFaceIDServices": "خدمات Touch ID / Face ID", + "personalInformation": "المعلومات الشخصية", + "updateEmailAddress": "تحديث عنوان البريد الإلكتروني", + "helpAndSupport": "المساعدة والدعم", + "permissionsProfile": "الأذونات", + "privacyPolicy": "سياسة الخصوصية", + "deactivateAccount": "إلغاء تنشيط الحساب", + "ageYearsOld": "{age} {yearsOld}", + "youDontHaveRadiologyOrders": "ليس لديك أي نتائج للأشعة حتى الآن.", + "radiologyResult": "نتيجة الأشعة", + "viewRadiologyImage": "عرض صورة الأشعة", + "rateClinic": "تقييم العيادة", + "back": "رجوع", + "rateDoctor": "تقييم الطبيب", + "howWasYourLastVisitWithDoctor": "كيف كانت زيارتك الأخيرة مع الطبيب؟", + "dateOfBirthSymptoms": "ما هو تاريخ ميلادك؟", + "genderSymptoms": "ما هو جنسك؟", + "heightSymptoms": "كم طولك؟", + "weightSymptoms": "ما هو وزنك؟", + "femaleGender": "أنثى", + "previous": "سابق", + "selectedOrgans": "الهيئات المختارة", + "noOrgansSelected": "لم يتم تحديد أي أعضاء بعد", + "organSelector": "محدد الأعضاء", + "noPredictionsAvailable": "لا توجد تنبؤات متاحة", + "areYouSureYouWantToRestartOrganSelection": "هل أنت متأكد أنك تريد إعادة تشغيل اختيار الأعضاء؟", + "possibleConditions": "الحالات المحتملة", + "pleaseSelectAtLeastOneRiskBeforeProceeding": "يرجى اختيار عامل خطر واحد على الأقل قبل المتابعة", + "aboveYouSeeCommonRiskFactors": "أعلاه ترى عوامل الخطر الأكثر شيوعًا. على الرغم من أن /diagnosis قد تعيد أسئلة حول عوامل الخطر، ", + "readMore": "اقرأ المزيد", + "riskFactors": "عوامل الخطر", + "noRiskFactorsFound": "لم يتم العثور على عوامل خطر", + "basedOnYourSelectedSymptomsNoRiskFactors": "بناءً على الأعراض المحددة، لم يتم تحديد عوامل خطر إضافية.", + "messageNotification": "الرسالة", + "attachedImage": "الصورة المرفقة", + "failedToLoadImage": "فشل تحميل الصورة", + "typeNotification": "النوع", + "pleaseSelectAtLeastOneOptionBeforeProceeding": "يرجى اختيار خيار واحد على الأقل قبل المتابعة", + "suggestions": "الاقتراحات", + "pleaseGoBackAndSelectOrgansFirst": "يرجى العودة واختيار الأعضاء أولاً", + "symptomsSelector": "محدد الأعراض", + "possibleSymptomsRelatedTo": "الأعراض المحتملة المتعلقة بـ", + "suggestionAIListDescription": "هذه قائمة بالأعراض المقترحة من قبل الذكاء الاصطناعي، بناءً على المعلومات التي تم جمعها حتى الآن خلال المقابلة", + "analyzing": "جاري التحليل...", + "seekMedicalAdvice": "اطلب المشورة الطبية", + "monitorDescription": "لا حاجة لطلب المشورة الطبية. فقط حافظ على روتين صحي.", + "seekMedicalAdviceDescription": "ليست حالة طوارئ ولكن من الأفضل مراقبة الأعراض.", + "emergencyDescription": "تحتاج إلى استشارة الطبيب في أقرب وقت ممكن قبل فوات الأوان.", + "colorScience": "دلالات الألوان", + "noNeedToVisitDoctor": "لا حاجة لزيرة الطبيب", + "commonSymptom": "الأعراض الشائعة", + "bookAppointment": "احجز موعد", + "notApplicable": "لا ينطبق", + "emergencyTriage": "طوارئ", + "emergencyEvidenceDetected": "تم اكتشاف دليل طوارئ. يرجى طلب العناية الطبية.", + "noQuestionItemsAvailable": "لا توجد عناصر أسئلة متاحة", + "pleaseAnswerAllQuestionsBeforeProceeding": "يرجى الإجابة على جميع الأسئلة قبل المتابعة", + "triage": "الفرز", + "areYouSureYouWantToExitProgress": "هل أنت متأكد أنك تريد الخروج؟ سيتم فقدان تقدمك.", + "noQuestionAvailable": "لا يوجد سؤال متاح", + "possibleSymptom": "عرض محتمل: ", + "symptomsCheckerFindingScore": "- درجة نتائج فاحص الأعراض", + "notSet": "غير محدد", + "years": "سنوات", + "symptomsChecker": "فاحص الأعراض", + "helloIsYourInformationUpToDate": "مرحباً {name}، هل معلوماتك محدثة؟", + "noEditAll": "لا، تعديل الكل", + "yesItIs": "نعم، إنها كذلك", + "age": "العمر", + "youDontHaveAnyAncillaryOrdersYet": "ليس لديك أي طلبات مساعدة بعد.", + "invoiceWithNumber": "الفاتورة: {invoiceNo}", + "queued": "في قائمة الانتظار", + "checkInReady": "جاهز للتسجيل", + "checkIn": "تسجيل الوصول", + "viewDetails": "عرض التفاصيل", + "selectPaymentMethod": "اختر طريقة الدفع", + "processingPaymentPleaseWait": "جاري معالجة الدفع، يرجى الانتظار...", + "finalizingPaymentPleaseWait": "جاري إتمام الدفع، يرجى الانتظار...", + "generatingInvoicePleaseWait": "جاري إنشاء الفاتورة، يرجى الانتظار...", + "hereIsYourInvoiceNumber": "هذا هو رقم فاتورتك #: ", + "paymentCompletedSuccessfully": "تم الدفع بنجاح", + "failedToInitializeApplePay": "فشل في تهيئة Apple Pay. يرجى المحاولة مرة أخرى.", + "cash": "نقدي", + "approved": "موافق عليه", + "approvalRejectedPleaseVisitReceptionist": "تم رفض الموافقة - يرجى زيارة موظف الاستقبال", + "sentForApproval": "تم إرساله للموافقة", + "ancillaryOrderDetails": "تفاصيل الطلب المساعد", + "noProceduresAvailableForSelectedOrder": "لا توجد إجراءات متاحة للطلب المحدد.", + "procedures": "الإجراءات", + "totalAmount": "المبلغ الإجمالي", + "covered": "مغطى", + "vatPercent": "ضريبة القيمة المضافة (15%)", + "proceedToPayment": "المتابعة للدفع", + "supportedSmartWatches": "الساعات الذكية المدعومة", + "pleaseMakeSureSamsungWatchConnected": "يرجى التأكد من أن ساعة Samsung الخاصة بك متصلة بهاتفك، ومتزامنة ومحدثة بشكل نشط.", + "beforeSyncingDataFollowInstructions": "قبل مزامنة البيانات، يرجى التأكد من اتباع التعليمات بشكل صحيح.", + "viewWatchInstructions": "عرض تعليمات الساعة", + "healthConnectAppNotInstalled": "يبدو أنه ليس لديك تطبيق Health Connect مثبتًا. يرجى تثبيته من متجر Play لمزامنة بيانات صحتك.", + "setTimerOfReminder": "ضبط مؤقت التذكير", + "youHaveAppointmentWithDr": "لديك موعد مع د. ", + "hours": "ساعات", + "secs": "ثواني", + "noAllergiesDataFound": "لم يتم العثور على بيانات الحساسية...", + "heartRateDescription": "معدل ضربات قلبك يشير إلى عدد المرات التي ينبض فيها قلبك في الدقيقة", + "bloodOxygenDescription": "مستوى الأكسجين في الدم يشير إلى كمية الأكسجين التي تحملها خلايا الدم الحمراء", + "stepsDescription": "عدد الخطوات المتخذة على مدار اليوم", + "caloriesDescription": "السعرات الحرارية المحروقة أثناء النشاط البدني", + "distanceDescription": "المسافة المقطوعة على مدار اليوم", + "overview": "نظرة عامة", + "details": "التفاصيل", + "healthy": "صحي", + "warning": "تحذير", + "vitalSignDetails": "تفاصيل العلامات الحيوية", + "resultOf": "نتيجة {date}", + "resultOfNoDate": "نتيجة --", + "referenceRangeBetween": "النطاق المرجعي: {low} – {high} {unit}", + "referenceRangeMin": "النطاق المرجعي: ≥ {low} {unit}", + "referenceRangeMax": "النطاق المرجعي: ≤ {high} {unit}", + "noHistoryAvailable": "لا يوجد تاريخ متاح", + "bmiDescription": "مؤشر كتلة الجسم هو قياس يعتمد على الطول والوزن لتقدير دهون الجسم.", + "heightDescription": "يقاس الطول بالسنتيمتر ويستخدم لحساب مؤشر كتلة الجسم وتوصيات الجرعات.", + "weightDescription": "الوزن يساعد في تتبع الصحة العامة والتغذية والتغيرات مع مرور الوقت.", + "bloodPressureDescription": "ضغط الدم يعكس قوة الدم على جدران الشرايين. يظهر كانقباضي/انبساطي.", + "temperatureDescription": "درجة حرارة الجسم تعكس مدى سخونة جسمك وقد تتغير مع العدوى أو الالتهاب.", + "heartRateDescriptionVital": "معدل ضربات القلب يشير إلى عدد نبضات القلب في الدقيقة.", + "respiratoryRateDescription": "معدل التنفس هو عدد الأنفاس المأخوذة في الدقيقة.", + "bmiAdvice": "حافظ على نظام غذائي متوازن ونشاط منتظم. إذا كان مؤشر كتلة جسمك مرتفعًا أو منخفضًا، فكر في استشارة طبيبك.", + "heightAdvice": "لا حاجة لاتخاذ أي إجراء إلا إذا بدا قياسك غير صحيح. قم بتحديثه في زيارتك القادمة.", + "weightAdvice": "راقب تغيرات الوزن. الزيادة أو الخسارة المفاجئة قد تتطلب استشارة طبية.", + "bloodPressureAdvice": "استمر في تتبع ضغط دمك. يجب مناقشة القراءات المرتفعة أو المنخفضة مع طبيبك.", + "temperatureAdvice": "إذا كان لديك حمى مستمرة أو أعراض، اتصل بمقدم الرعاية الصحية.", + "heartRateAdvice": "تتبع اتجاهات معدل ضربات قلبك. إذا شعرت بدوار أو ألم في الصدر، اطلب الرعاية الطبية.", + "respiratoryRateAdvice": "إذا لاحظت ضيقًا في التنفس أو تنفسًا غير طبيعي، اطلب المشورة الطبية.", + "whatShouldIDoNext": "ماذا يجب أن أفعل بعد ذلك؟", + "customizeDrinkCup": "قم بتخصيص كوب مشروبك", + "tipsToStayHydrated": "نصائح للبقاء رطبًا", + "drinkBeforeYouFeelThirsty": "اشرب قبل أن تشعر بالعطش", + "keepRefillableBottleNextToYou": "احتفظ بزجاجة قابلة لإعادة التعبئة بجانبك", + "trackYourDailyIntakeToStayMotivated": "تتبع كمية الماء اليومية للحفاظ على الحافز", + "chooseSparklingWaterInsteadOfSoda": "اختر الماء الفوار بدلاً من الصودا", + "switchCup": "تبديل الكوب", + "plainWater": "ماء عادي", + "yourGoal": "هدفك", + "remaining": "المتبقي", + "hydrationStatus": "حالة الترطيب", + "areYouSureYouWantToCancelAllWaterReminders": "هل أنت متأكد أنك تريد إلغاء جميع تذكيرات الماء؟", + "remindersSet": "تم ضبط التذكيرات!", + "dailyWaterRemindersScheduledAt": "تم جدولة تذكيرات الماء اليومية في:", + "waterConsumption": "استهلاك المياه", + "selectNumberOfReminders": "حدد عدد التذكيرات", + "h2oSettings": "إعدادات H20", + "settingsSavedSuccessfully": "تم حفظ الإعدادات بنجاح", + "yourName": "اسمك", + "ageYears": "العمر (11-120) سنة", + "numberOfRemindersInADay": "عدد التذكيرات في اليوم", + + "medications": "الأدوية", + "someRemarksAboutPrescription": "ستجدون هنا بعض الملاحظات حول الوصفة الطبية", + "notifyMeBeforeConsumptionTime": "أبلغني قبل وقت الاستهلاك", + "noMedicationsToday": "لا أدوية اليوم", + "reminders": "تذكيرات", + "reminderAddedToCalendar": "تمت إضافة تذكير إلى التقويم ✅", + "errorWhileSettingCalendar": "حدث خطأ أثناء ضبط التقويم:{error}", + "instructions": "التعليمات", + "requests": "الطلبات", + "thisWeek": "هذا الأسبوع", + "lastMonth": "الشهر الماضي", + "lastSixMonths": "آخر 6 أشهر", + "selectTime": "حدد الوقت", + "pleaseWaitYouWillBeCalledForVitalSigns": "يرجى الانتظار! سيتم استدعاؤك لقياس العلامات الحيوية", + "pleaseVisitRoomForVitalSigns": "يرجى زيارة الغرفة {roomNumber} لقياس العلامات الحيوية", + "pleaseVisitRoomToTheDoctor": "يرجى زيارة الغرفة {roomNumber} لمقابلة الطبيب", + "erOnlineCheckInRequest": "طلب تسجيل الوصول عبر الإنترنت لقسم الطوارئ", + "indoor": "داخلي", + "navigation": "الملاحة", + "health": "الصحة", + "calculators": "الحاسبات", + "converters": "المحولات", + "guide": "الدليل", + "liveCareServiceDesc": "احصل على استشارة طبية من طبيب متخصص عبر مكالمة فيديو", + "bloodGroup": "فصيلة الدم: {bloodType}", + "medicalServices": "الخدمات الطبية", + "insuranceAndPayments": "التأمين والمدفوعات", + "trackerAndOthers": "المتتبع وأخرى", + "bmi": "مؤشر كتلة الجسم", + "yesPleaseINeedHelp": "نعم، من فضلك أريد المساعدة", + "noThanksIKnowTheClinic": "لا شكراً، أعرف العيادة", + "unableToSendOTP": "تعذر إرسال رمز التحقق لمرة واحدة" "callForVitalSign": "استدعاء لأخذ العلامات الحيوية", "callForDoctor": "استدعاء الطبيب", "yourQueueNumber": "رقمك في الدور", "currentServing": "الدور الحالي" -} \ No newline at end of file +} diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index c3ec0ad..e27be83 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -406,11 +406,8 @@ "brand": "Brand", "power": "Power", "diameter": "Diameter", - "remarks": "Remarks", "activeMedications": "Active Medications", "expDate": "Active Exp Date :", - "route": "Route", - "frequency": "Frequency", "dailyQuantity": "Daily Quantity :", "addReminder": "Add Reminder", "cancelReminder": "Cancel Reminder", @@ -689,11 +686,7 @@ "bikini": "Bikini", "totalMinutes": "Total Minutes", "feedback": "Feedback", - "send": "أرسل", - "status": "الحالة", "likeToHear": "We would love to hear the feedback, concerns on healthcare services and eServices experience. Please use the below form", - "subject": "الموضوع", - "message": "رسالة", "emptySubject": "Please enter the subject", "emptyMessage": "Please enter message", "selectAttachment": "Select Attachment", @@ -864,7 +857,7 @@ "endDate": "End Date", "hmgHospitals": "HMG Hospitals", "hmcMedicalClinic": "HMC Medical Centers", - "applyFilter": "AppLy Filter", + "applyFilter": "Apply Filter", "facilityAndLocation": "Facility and Location", "regionAndLocation": "Region And Locations", "clearAllFilters": "Clear all filters", @@ -874,8 +867,658 @@ "continueString": "Continue", "laserClinic": "Laser Clinic", "covid_info" :"Dr. Sulaiman Al Habib hospitals are conducting a test for the emerging corona virus and issuing travel certificates 24/7 in a short time and with high accuracy. Those wishing to benefit from this service can visit one of Dr. Sulaiman Al Habib branches to conduct a corona test within few minutes, and obtain the result within several hours. Corona Virus Covid 19 testing service with PCR technology to detect the virus according to the highest international standards and with the latest high-precision RT-PCR devices (American GeneXpert and others), That is approved by the Food and Drug Authority as well as by the Saudi Center for Infectious Diseases Prevention.", + "appointmentDetails": "Appointment Details", + "checkingDoctorAvailability": "Checking doctor availability...", + "cancellingAppointmentPleaseWait": "Cancelling Appointment, Please Wait...", + "appointmentCancelledSuccessfully": "Appointment Cancelled Successfully", + "notConfirmed": "Not Confirmed", + "appointmentStatus": "Appointment Status", + "doctorWillCallYou": "The doctor will call you once the appointment time approaches.", + "getDirections": "Get Directions", + "notifyMeBeforeAppointment": "Notify me before the appointment", + "fetchingLabResults": "Fetching Lab Results...", + "fetchingRadiologyResults": "Fetching Radiology Results...", + "fetchingAppointmentPrescriptions": "Fetching Appointment Prescriptions...", + "noPrescriptionsForAppointment": "You don't have any prescriptions for this appointment.", + "amountBeforeTax": "Amount before tax", + "rebookAppointment": "Re-book Appointment", + "fetchingDoctorSchedulePleaseWait": "Fetching Doctor Schedule, Please Wait...", + "pickADate": "Pick a Date", + "confirmingAppointmentPleaseWait": "Confirming Appointment, Please Wait...", + "appointmentConfirmedSuccessfully": "Appointment Confirmed Successfully", + "appointmentPayment": "Appointment Payment", + "checkingPaymentStatusPleaseWait": "Checking payment status, Please wait...", + "paymentFailedPleaseTryAgain": "Payment Failed! Please try again.", + "appointmentCheckIn": "Appointment check in", + "insuranceExpiredOrInactive": "Insurance expired or inactive", + "totalAmountToPay": "Total amount to pay", + "vat15": "VAT 15%", + "general": "General", + "liveCare": "LiveCare", + "recentVisits": "Recent Visits", + "searchByClinic": "Search By Clinic", + "tapToSelectClinic": "Tap to select clinic", + "searchByDoctor": "Search By Doctor", + "tapToSelect": "Tap to select", + "searchByRegion": "Search By Region", + "centralRegion": "Central Region", + "immediateConsultation": "Immediate Consultation", + "scheduledConsultation": "Scheduled Consultation", + "pharmaLiveCare": "Pharma LiveCare", + "notSureHelpMeChooseClinic": "Not sure? help me choose a clinic!", + "mentionYourSymptomsAndFindDoctors": "Mention your symptoms and find the list of doctors accordingly", + "immediateService": "Immediate service", + "noNeedToWaitGetMedicalConsultation": "No need to wait, you will get medical consultation immediately via video call", + "noVisitRequired": "No visit required", + "doctorWillContact": "Doctor will contact", + "specialisedDoctorWillContactYou": "A specialised doctor will contact you and will be able to view your medical history", + "freeMedicineDelivery": "Free medicine delivery", + "offersFreeMedicineDelivery": "Offers free medicine delivery for the LiveCare appointment", + "dentalChiefComplaints": "Dental Chief Complaints", + "viewAvailableAppointments": "View available appointments", + "doctorProfile": "Doctor Profile", + "waitingAppointment": "Waiting Appointment", + "hospitalInformation": "Hospital Information", + "fetchingAppointmentShare": "Fetching Appointment Share...", + "bookingYourAppointment": "Booking your appointment...", + "selectLiveCareClinic": "Select LiveCare Clinic", + "checkingForExistingDentalPlan": "Checking for an existing dental plan, Please wait...", + "dentalTreatmentPlan": "Dental treatment plan", + "youHaveExistingTreatmentPlan": "You have an existing treatment plan: ", + "mins": "Mins", + "totalTimeRequired": "Total time required", + "wouldYouLikeToContinue": "Would you like to continue it?", + "chooseDoctor": "Choose Doctor", + "viewNearestAppos": "View nearest available appointments", + "noDoctorFound": "No Doctor found for selected criteria...", + "yesPleasImInAHurry": "Yes please, I am in a hurry", + "fetchingFeesPleaseWait": "Fetching fees, Please wait...", + "noThanksPhysicalVisit": "No, Thanks. I would like a physical visit", + "offline": "Offline", + "videoCall": "Video Call", + "liveVideoCallWithHMGDoctors": "Live Video Call with HMG Doctors", + "audioCall": "Audio Call", + "phoneCall": "Phone Call", + "livePhoneCallWithHMGDoctors": "Live Phone Call with HMG Doctors", + "reviewLiveCareRequest": "Review LiveCare Request", + "selectedLiveCareType": "Selected LiveCare Type", + "selectLiveCareCallType": "Select LiveCare call type", + "confirmingLiveCareRequest": "Confirming LiveCare request, Please wait...", + "unknownErrorOccurred": "Unknown error occurred...", + "liveCarePermissionsMessage": "LiveCare requires Camera, Microphone, Location & Notifications permissions to enable virtual consultation between patient & doctor, Please allow these to proceed.", + "liveCarePayment": "LiveCare Payment", + "mada": "Mada", + "visaOrMastercard": "Visa or Mastercard", + "tamara": "Tamara", + "fetchingApplePayDetails": "Fetching Apple Pay details, Please wait...", + "liveCarePendingRequest": "LiveCare Pending Request", + "callLiveCareSupport": "Call LiveCare Support", + "whatIsWaitingAppointment": "What is Waiting Appointment?", + "waitingAppointmentsFeature": "The waiting appointments feature allows you to book an appointment while you are inside the hospital building, and in case there is no available slot in the doctor's schedule.", + "appointmentWithDoctorConfirmed": "The appointment with the doctor is confirmed, but the time of entry is uncertain.", + "paymentWithinTenMinutes": "Note: You must have to pay within 10 minutes of booking, otherwise your appointment will be cancelled automatically", + "liveLocation": "Live Location", + "verifyYourLocationAtHospital": "Verify your location to be at hospital to check in", + "error": "Error", + "ensureWithinHospitalLocation": "Please ensure you're within the hospital location to perform online check-in.", + "nfcNearFieldCommunication": "NFC (Near Field Communication)", + "scanPhoneViaNFC": "Scan your phone via NFC board to check in", + "qrCode": "QR Code", + "scanQRCodeToCheckIn": "Scan QR code with your camera to check in", + "processingCheckIn": "Processing Check-In...", + "bookingWaitingAppointment": "Booking Waiting Appointment, Please wait...", + "enterValidIDorIqama": "Please enter a valid national ID or file number", + "selectAppointment": "Select Appointment", + "rebookSameDoctor": "Rebook with same doctor", + "queueing": "Queueing", + "inQueue": "In Queue", + "yourTurn": "Your Turn", + "halaFirstName": "Hala {firstName}!!!", + "thankYouForPatience": "Thank you for your patience, here is your queue number.", + "servingNow": "Serving Now", + "callForVitalSigns": "Call for vital signs", + "callForDoctor": "Call for Doctor", + "thingsToAskDoctor": "Things to ask your doctor today", + "improveOverallHealth": "What can I do to improve my overall health?", + "routineScreenings": "Are there any routine screenings I should get?", + "whatIsThisMedicationFor": "What is this medication for?", + "sideEffectsToKnow": "Are there any side effects I should know about?", + "whenFollowUp": "When should I come back for a follow-up?", + "goToHomepage": "Go to homepage", + "appointmentsList": "Appointments List", + "allAppt": "All Appt.", + "upcoming": "Upcoming", + "completed": "Completed", + "noAppointmentsYet": "You don't have any appointments yet.", + "viewProfile": "View Profile", + "choosePreferredHospitalForService": "Choose your preferred hospital for the service", + "noHospitalsFound": "No hospitals Found", + "cancelOrderConfirmation": "Are you sure you want to cancel this order?", + "orderCancelledSuccessfully": "Order has been cancelled successfully", + "requestID": "Request ID:", + "noCMCOrdersYet": "You don't have any CMC orders yet.", + "cmcOrders": "CMC Orders", + "summary": "Summary", + "selectedService": "Selected Service", + "requestSubmittedSuccessfully": "Your request has been successfully submitted.", + "hereIsYourRequestNumber": "Here is your request #: ", + "pleaseSelectHospitalToContinue": "Please select a hospital to continue", + "confirmSubmitRequest": "Are you sure you want to submit this request?", + "pendingOrderWait": "You have a pending order. Please wait for it to be processed.", + "noServicesAvailable": "No services available", + "selectAService": "Select a Service", + "comprehensiveCheckup": "Comprehensive Checkup", + "viewNearestHMGLocations": "View your nearest HMG locations", + "provideFeedbackOnServices": "Provide your feedback on our services", + "liveChatWithHMG": "Live chat option with HMG", + "send": "Send", + "status": "Status", + "sendingFeedback": "Sending Feedback...", + "selectFeedbackType": "Select Feedback Type", + "loadingAppointmentsList": "Loading appointments list...", + "noAppointmentsForFeedback": "You do not have any appointments to submit a feedback.", + "selectedAppointment": "Selected Appointment:", + "subject": "Subject", + "enterSubjectHere": "Enter subject here", + "message": "Message", + "enterMessageHere": "Enter message here", + "filesSelected": "{count} file(s) selected", + "otherDetails": "Other Details", + "medicalReport": "Medical Report", + "medicalReportNumber": "Medical Report {number}", + "patientIsInsured": "Patient is Insured", + "insuranceDocument": "Insurance Document", + "selectBranch": "Select Branch", + "patientInformation": "Patient information", + "patientLocation": "Where the patient located", + "identificationNumber": "Identification Number", + "enterIdentificationNumber": "Enter Identification Number*", + "patientName": "Patient Name*", + "referralRequesterInformation": "Referral requester information", + "enterReferralRequesterName": "Enter Referral Requester Name*", + "requesterName": "Requester Name", + "relationship": "Relationship", + "selectRelation": "Select Relation", + "otherName": "Other Name", + "otherNameHint": "Other Name*", + "requesterNameRequired": "Referral requester name is required", + "selectRelationshipRequired": "Please select a relationship", + "otherRelationshipNameRequired": "Other relationship name is required", + "identificationNumberRequired": "Identification number is required", + "patientNameRequired": "Patient name is required", + "enterPatientPhoneRequired": "Please Enter patient phone number", + "selectPatientCityRequired": "Please select patient city", + "medicalReportRequired": "At least one medical report is required", + "selectBranchRequired": "Please select a branch", + "insuranceDocumentRequired": "Insurance document is required for insured patients", + "searchResult": "Search Result", + "referralNo": "Referral No {number}", + "eReferral": "E Referral", + "referralCreatedSuccessfully": "Your Referral has been created Successfully.", + "hereIsYourReferralNumber": "Here is your Referral #: ", + "searchEReferral": "Search E-Referral", + "enterRequiredInfoToSearch": "Please enter the required information to search for an e-referral", + "selectPickupDirection": "Select Pickup Direction", + "selectDirection": "Select Direction", + "toHospital": "To Hospital", + "fromHospital": "From Hospital", + "selectWay": "Select Way", + "oneWay": "One Way", + "twoWay": "Two Way", + "selectPickupDetails": "Select Pickup Details", + "pleaseSelectDetailsOfPickup": " Please select the details of pickup", + "selectDetails": "Select Details", + "work": "Work", + "pick": "Pick", + "insideTheHome": "Inside the home", + "haveAnyAppointment": "Have any appointment", + "amountPaidAtHospital": "Amount will be paid at the hospital", + "submitRequest": "Submit Request", + "enterPickupLocationManually": "Enter Pickup Location Manually", + "enterPickupLocation": "Enter Pickup Location", + "trackingDetails": "Tracking Details", + "cancelRequest": "Cancel Request", + "shareLocationWhatsapp": "Share Your Live Location on Whatsapp", + "pleaseWaitForCall": "Please wait for the call", + "toHospitalLower": "to hospital", + "contact": "Contact", + "failed": "Failed", + "confirmationCall": "Confirmation Call", + "pickupFromHome": "Pickup Up from Home", + "onTheWayToHospital": " On The Way To Hospital", + "arrivedAtHospital": "Arrived at Hospital", + "orderCancel": "Order Cancel", + "emergencyCheckIn": "Emergency Check-In", + "erOnlineCheckInDescription": "This service lets patients register their ER appointment prior to arrival.", + "erOnlineCheckInSuccess": "Your ER Online Check-In has been successfully done. Please proceed to the waiting area.", + "erOnlineCheckInError": "Unexpected error occurred during check-in. Please contact support.", + "fetchingHospitalsList": "Fetching hospitals list...", + "fetchingPaymentInformation": "Fetching payment information...", + "erVisitDetails": "ER Visit Details", + "erClinic": "ER Clinic", + "vatWithAmount": "VAT 15% ({amount})", + "erAppointmentBookedSuccess": "Your appointment has been booked successfully. Please perform Check-In once you arrive at the hospital.", + "underProcessing": "Under processing", + "canceledByPatient": "Cancelled by patient", + "rapidResponseTeam": "Rapid Response Team", + "allFacilities": "All Facilities", + "selectLocation": "Select Location", + "pleaseSelectTheLocation": "Please select the location", + "viewLocationGoogleMaps": "View Location on Google Maps", + "callAmbulance": "Call Ambulance", + "requestAmbulanceInEmergency": "Request an ambulance in emergency from home or hospital", + "confirmation": "Confirmation", + "areYouSureYouWantToCallAmbulance": "Are you sure you want to call an ambulance?", + "getDetailsOfNearestBranch": "Get the details of nearest branch including directions", + "areYouSureYouWantToCallRRT": "Are you sure you want to call Rapid Response Team (RRT)?", + "priorERCheckInToSkipLine": "Prior ER Check-In to skip the line & payment at the reception.", + "areYouSureYouWantToMakeERCheckIn": "Are you sure you want to make ER Check-In?", + "checkingYourERAppointmentStatus": "Checking your ER Appointment status...", + "transportOptions": "Transport Options", + "selectHospitalForAdvancePayment": "Please select the hospital you want to make an advance payment for.", + "recharge": "Recharge", + "activityLevel": "Activity Level", + "selectActivityLevel": "Select Activity Level", + "caloriesPerDay": "Calories Per Day", + "dietType": "Diet Type", + "selectDietType": "Select Diet Type", + "bodyFrameSize": "Body Frame Size", + "selectBodyFrameSize": "Select Body Frame Size", + "averageCycleLength": "Average Cycle Length (Usually 28 days)", + "averageLutealPhase": "Average Luteal Phase Length(Usually 14 days)", + "convert": "Convert", + "calculate": "Calculate", + "healthCalculators": "Health Calculators", + "healthConverters": "Health Converters", + "generalHealth": "General Health", + "relatedToBMICalories": "Related To BMI, calories, body fat, etc to stay updated with your health.", + "selectCalculator": "Select Calculator", + "womensHealth": "Women's Health", + "relatedToPeriodsOvulation": "Related To periods, ovulation, pregnancy, and other topics.", + "bloodSugar": "Blood Sugar", + "trackYourGlucoseLevels": "Track your glucose levels, understand trends, and get personalized insights for better health.", + "bloodCholesterol": "Blood Cholesterol", + "monitorCholesterolLevels": "Monitor cholesterol levels, assess heart health risks, and take proactive steps for well-being.", + "triglyceridesFatBlood": "Triglycerides Fat Blood", + "understandTriglyceridesImpact": "Understand triglycerides' impact on heart health with personalized insights and expert recommendations.", + "bmiCalculator": "BMI\nCalculator", + "caloriesCalculator": "Calories\nCalculator", + "bmrCalculator": "BMR\nCalculator", + "idealBodyWeight": "Ideal Body\nWeight", + "bodyFatCalculator": "Body Fat\nCalculator", + "carbsProteinFat": "Carbs\nProtein & Fat", + "ovulationPeriod": "Ovulation\nPeriod", + "deliveryDueDate": "Delivery\nDue Date", + "low": "Low", + "preDiabetic": "Pre-diabetic", + "high": "High", + "elevated": "Elevated", + "recorded": "Recorded", + "noRecordsYet": "No records yet", + "lastRecord": "Last Record", + "addBloodSugar": "Add Blood Sugar", + "addBloodPressure": "Add Blood Pressure", + "addWeight": "Add Weight", + "bloodSugarDataSavedSuccessfully": "Blood Sugar Data saved successfully", + "bloodPressureDataSavedSuccessfully": "Blood Pressure Data saved successfully", + "weightDataSavedSuccessfully": "Weight Data saved successfully", + "pleaseWait": "Please wait", + "selectUnit": "Select Unit", + "selectMeasureTime": "Select Measure Time", + "selectArm": "Select Arm", + "enterBloodSugar": "Enter Blood Sugar", + "enterSystolicValue": "Enter Systolic Value", + "enterDiastolicValue": "Enter Diastolic Value", + "enterWeight": "Enter Weight", + "selectDuration": "Select Duration", + "systolic": "Systolic", + "diastolic": "Diastolic", + "sendReportByEmail": "Send Report by Email", + "enterYourEmailToReceiveReport": "Enter your email address to receive the report", + "addNewRecord": "Add new Record", + "healthTrackers": "Health Trackers", + "monitorBloodPressureLevels": "Monitor your blood pressure levels, track systolic and diastolic readings, and maintain a healthy heart.", + "trackWeightProgress": "Track your weight progress, set goals, and maintain a healthy body mass for overall wellness.", + "bookAppointment": "Book\nAppointment", + "completeCheckup": "Complete Checkup", + "indoorNavigation": "Indoor Navigation", + "eReferralServices": "E-Referral Services", + "dailyWaterMonitor": "Daily Water Monitor", + "fetchingYourWaterIntakeDetails": "Fetching your water intake details.", + "healthCalculatorsServices": "Health\nCalculators", + "healthConvertersServices": "Health\nConverters", + "smartWatchesServices": "Smart\nWatches", + "exploreServices": "Explore Services", + "medicalAndCareServices": "Medical & Care Services", + "hmgServices": "HMG Services", + "personalServices": "Personal Services", + "habibWallet": "Habib Wallet", + "loginToViewWalletBalance": "Login to view your wallet balance", + "loginToViewMedicalFile": "Login to view your medical file", + "addMember": "Add Member", + "addFamilyMember": "Add Family Member", + "pleaseFillBelowFieldToAddNewFamilyMember": "Please fill the below field to add a new family member to your profile", + "healthTools": "Health Tools", + "supportServices": "Support Services", + "virtualTour": "Virtual Tour", + "carParking": "Car Parking", + "latestNews": "Latest News", + "hmgContact": "HMG Contact", + "durationCannotExceed90": "Duration can not exceed 90 mins", + "unexpectedError": "Unexpected Error Occurred", + "gettingAmbulanceTransportOption": "Getting Ambulance Transport Option", + "fetchingAppointment": "Fetching Appointment", + "doYouWantToCancelTheRequest": "Do you want to cancel the request", + "cancellingRequest": "Cancelling request", + "fetchingTermsAndConditions": "Fetching Terms And Conditions", + "selectLocationPrescriptionDelivery": "Please select the location for prescription delivery", + "noRadiologyOrders": "No Radiology Orders Found", + "ageIsRequired": "Age is required", + "invalidAge": "Invalid age", + "ageMustBeBetween11And120": "Age must be between 11 and 120", + "heightIsRequired": "Height is required", + "invalidHeight": "Invalid height", + "weightIsRequired": "Weight is required", + "invalidWeight": "Invalid weight", + "timeToDrinkWater": "Time to Drink Water! 💧", + "stayHydratedDrinkWater": "Stay hydrated! Drink {amount}ml of water.", + "visitPharmacyOnline": "Visit Pharmacy Online", + "howAreYouFeelingToday": "How are you feeling today?", + "checkYourSymptomsWithScale": "Check your symptoms with this scale", + "checkYourSymptoms": "Check your symptoms", + "noUpcomingAppointmentPleaseBook": "You do not have any upcoming appointment. Please book an appointment", + "youHaveEROnlineCheckInRequest": "You have ER Online Check-In Request", + "quickLinks": "Quick Links", + "viewMedicalFileLandingPage": "View medical file", + "immediateLiveCareRequest": "Immediate LiveCare Request", + "yourTurnIsAfterPatients": "Your turn is after {count} patients.", + "dontHaveHHCOrders": "You don't have any Home Health Care orders yet.", + "hhcOrders": "HHC Orders", + "requestedServices": "Requested Services", + "selectServices": "Select Services", + "selectedServices": "Selected Services", + "createNewRequest": "Create new request", + "youHaveNoPendingRequests": "You have no pending requests.", + "noInsuranceDataFound": "No insurance data found...", + "noInsuranceUpdateRequest": "No insurance update requests found.", + "policyNumberInsurancePage": "Policy: {number}", + "insuranceExpired": "Insurance Expired", + "insuranceActive": "Insurance Active", + "patientCardID": "Patient Card ID: {id}", + "noInsuranceApprovals": "You don't have any insurance approvals yet.", + "noInsuranceWithHMG": "You don't have insurance registered with HMG.", + "referenceRange": "Reference Range", + "downloadReport": "Download report", + "generatingReport": "Generating report, Please wait...", + "noLabResults": "You don't have any lab results yet.", + "labResultDetails": "Lab Result Details", + "resultOf": "Result of", + "whatIsThisResult": "What is this result?", + "lastTested": "Last Tested", + "byVisit": "By Visit", + "byTest": "By Test", + "results": "results", + "viewResults": "View Results", + "rebook": "Rebook", + "noOphthalmologyAppointments": "No Ophthalmology appointments found...", + "noVitalSignsRecordedYet": "No vital signs recorded yet", + "appointmentsAndVisits": "Appointments & visits", + "labAndRadiology": "Lab & Radiology", + "activeMedicationsAndPrescriptions": "Active Medications & Prescriptions", + "allPrescriptions": "All Prescriptions", + "allMedications": "All Medications", + "youDontHaveAnyPrescriptionsYet": "You don't have any prescriptions yet.", + "youDontHaveAnyCompletedVisitsYet": "You don't have any completed visits yet", + "others": "Others", + "allergyInfo": "Allergy Info", + "vaccineInfo": "Vaccine Info", + "updateInsuranceInfo": "Update Insurance", + "myInvoicesList": "My Invoices List", + "ancillaryOrdersList": "Ancillary Orders List", + "youDontHaveAnySickLeavesYet": "You don't have any sick leaves yet.", + "medicalReports": "Medical Reports", + "sickLeaveReport": "Sick Leave Report", + "weightTracker": "Weight Tracker", + "askYourDoctor": "Ask Your Doctor", + "internetPairing": "Internet Pairing", + "requested": "Requested", + "youDontHaveAnyMedicalReportsYet": "You don't have any medical reports yet.", + "requestMedicalReport": "Request medical report", + "youDoNotHaveAnyAppointmentsToRequestMedicalReport": "You do not have any appointments to request a medical report.", + "areYouSureYouWantToRequestMedicalReport": "Are you sure you want to request a medical report for this appointment?", + "yourMedicalReportRequestSubmittedSuccessfully": "Your medical report request has been successfully submitted.", + "monthlyHealthSummaryReportDisclaimer": "This monthly health summary report reflects the health indicators and analysis results of the latest visits. Please note that this will be sent automatically from the system and it's not considered as a official report so no medical decision should be taken based on it", + "updatingMonthlyReportStatus": "Updating Monthly Report Status...", + "monthlyReportStatusUpdatedSuccessfully": "Monthly Report Status Updated Successfully", + "whoCanViewMyMedicalFile": "Who can view my medical file?", + "acceptedYourRequestToBeYourFamilyMember": "{status} your request to be your family member", + "canViewYourFile": "can view your file", + "hasARequestPendingToBeYourFamilyMember": "has a request {status} to be your family member", + "wantsToAddYouAsTheirFamilyMember": "wants to add you as their family member", + "rejectedYourRequestToBeYourFamilyMember": "{status} your request to be your family member", + "rejectedYourFamilyMemberRequest": "{status} your family member request", + "notAvailable": "N/A", + "selectAProfile": "Please select a profile", + "switchFamilyFile": "Switch from the below list of medical file", + "medicalFiles": "Medical Files", + "addANewFamilyMember": "Add a new family member", + "viewInvoiceDetails": "View invoice details", + "outPatient": "OutPatient", + "invoiceDetails": "Invoice Details", + "sendingEmailPleaseWait": "Sending email, Please wait...", + "emailSentSuccessfullyMessage": "Email sent successfully.", + "discount": "Discount", + "paid": "Paid", + "fetchingInvoiceDetails": "Fetching invoice details, Please wait...", + "scanQRCode": "Scan QR code", + "parkingSlotDetails": "Parking Slot Details", + "slotNumber": "Slot: {code}", + "basement": "Basement: {description}", + "parkingDate": "Date: {date}", + "parkedSince": "Parked Since: {time}", + "resetDirection": "Reset Direction", + "noPrescriptionOrdersYet": "You don't have any prescription orders yet.", + "fetchingPrescriptionPDFPleaseWait": "Fetching prescription PDF, Please wait...", + "ratingValue": "Rating: {rating}", + "downloadPrescription": "Download Prescription", + "fetchingPrescriptionDetails": "Fetching prescription details...", + "switchBackFamilyFile": "Switch Back To Family File", + "profileAndSettings": "Profile & Settings", + "quickActions": "Quick Actions", + "notificationsSettings": "Notifications Settings", + "touchIDFaceIDServices": "Touch ID / Face ID Services", + "personalInformation": "Personal Information", + "updateEmailAddress": "Update Email Address", + "helpAndSupport": "Help & Support", + "permissionsProfile": "Permissions", + "privacyPolicy": "Privacy Policy", + "deactivateAccount": "Deactivate account", + "ageYearsOld": "{age} {yearsOld}", + "youDontHaveRadiologyOrders": "You don't have any radiology results yet.", + "radiologyResult": "Radiology Result", + "viewRadiologyImage": "View Radiology Image", + "rateClinic": "Rate Clinic", + "back": "Back", + "rateDoctor": "Rate Doctor", + "howWasYourLastVisitWithDoctor": "How was your last visit with doctor?", + "dateOfBirthSymptoms": "What is your Date of Birth?", + "genderSymptoms": "What is your gender?", + "heightSymptoms": "How tall are you?", + "weightSymptoms": "What is your weight?", + "femaleGender": "Female", + "previous": "Previous", + "selectedOrgans": "Selected Organs", + "noOrgansSelected": "No organs selected yet", + "organSelector": "Organ Selector", + "noPredictionsAvailable": "No Predictions available", + "areYouSureYouWantToRestartOrganSelection": "Are you sure you want to restart the organ selection?", + "possibleConditions": "Possible Conditions", + "pleaseSelectAtLeastOneRiskBeforeProceeding": "Please select at least one risk before proceeding", + "aboveYouSeeCommonRiskFactors": "Above you see the most common risk factors. Although /diagnosis may return questions about risk factors, ", + "readMore": "Read more", + "riskFactors": "Risk Factors", + "noRiskFactorsFound": "No risk factors found", + "basedOnYourSelectedSymptomsNoRiskFactors": "Based on your selected symptoms, no additional risk factors were identified.", + "messageNotification": "Message", + "attachedImage": "Attached Image", + "failedToLoadImage": "Failed to load image", + "typeNotification": "Type", + "pleaseSelectAtLeastOneOptionBeforeProceeding": "Please select at least one option before proceeding", + "suggestions": "Suggestions", + "pleaseGoBackAndSelectOrgansFirst": "Please go back and select organs first", + "symptomsSelector": "Symptoms Selector", + "possibleSymptomsRelatedTo": "Possible symptoms related to", + "suggestionAIListDescription": "This is a list of symptoms suggested by our AI, based on the information gathered so far during the interview", + "analyzing": "Analyzing...", + "seekMedicalAdvice": "Seek Medical Advice", + "monitorDescription": "No need to seek medical advice. Just keep healthy routine.", + "seekMedicalAdviceDescription": "Not emergency but better to monitor the symptoms.", + "emergencyDescription": "Need to consult doctor as soon as possible before getting too late.", + "colorScience": "Color Science", + "noNeedToVisitDoctor": "No need to visit doctor", + "commonSymptom": "Common Symptom", + "bookAppointment": "Book Appointment", + "notApplicable": "Not Applicable", + "emergencyTriage": "Emergency", + "emergencyEvidenceDetected": "Emergency evidence detected. Please seek medical attention.", + "noQuestionItemsAvailable": "No question items available", + "pleaseAnswerAllQuestionsBeforeProceeding": "Please answer all questions before proceeding", + "triage": "Triage", + "areYouSureYouWantToExitProgress": "Are you sure you want to exit? Your progress will be lost.", + "noQuestionAvailable": "No question available", + "possibleSymptom": "Possible symptom: ", + "symptomsCheckerFindingScore": "- Symptoms checker finding score", + "notSet": "Not set", + "years": "Years", + "symptomsChecker": "Symptoms Checker", + "helloIsYourInformationUpToDate": "Hello {name}, Is your information up to date?", + "noEditAll": "No, Edit all", + "yesItIs": "Yes, It is", + "age": "Age", + "youDontHaveAnyAncillaryOrdersYet": "You don't have any ancillary orders yet.", + "invoiceWithNumber": "Invoice: {invoiceNo}", + "queued": "Queued", + "checkInReady": "Check-in Ready", + "checkIn": "Check In", + "viewDetails": "View Details", + "selectPaymentMethod": "Select Payment Method", + "processingPaymentPleaseWait": "Processing payment, Please wait...", + "finalizingPaymentPleaseWait": "Finalizing payment, Please wait...", + "generatingInvoicePleaseWait": "Generating invoice, Please wait...", + "hereIsYourInvoiceNumber": "Here is your invoice #: ", + "paymentCompletedSuccessfully": "Payment Completed Successfully", + "failedToInitializeApplePay": "Failed to initialize Apple Pay. Please try again.", + "cash": "Cash", + "approved": "Approved", + "approvalRejectedPleaseVisitReceptionist": "Approval Rejected - Please visit receptionist", + "sentForApproval": "Sent For Approval", + "ancillaryOrderDetails": "Ancillary Order Details", + "noProceduresAvailableForSelectedOrder": "No Procedures available for the selected order.", + "procedures": "Procedures", + "totalAmount": "Total Amount", + "covered": "Covered", + "vatPercent": "VAT (15%)", + "proceedToPayment": "Proceed to Payment", + "supportedSmartWatches": "Supported Smart Watches", + "pleaseMakeSureSamsungWatchConnected": "Please make sure that your Samsung Watch is connected to your Phone, is actively synced & updated.", + "beforeSyncingDataFollowInstructions": "Before syncing data, please make sure that you have followed the instructions properly.", + "viewWatchInstructions": "View watch instructions", + "healthConnectAppNotInstalled": "Seems like you do not have Health Connect App installed. Please install it from the Play Store to sync your health data.", + "setTimerOfReminder": "Set the timer of reminder", + "youHaveAppointmentWithDr": "You have appointment with Dr. ", + "hours": "Hours", + "secs": "Secs", + "noAllergiesDataFound": "No allergies data found...", + "heartRateDescription": "Your heart rate indicates how many times your heart beats per minute", + "bloodOxygenDescription": "Blood oxygen level indicates how much oxygen your red blood cells are carrying", + "stepsDescription": "Number of steps taken throughout the day", + "caloriesDescription": "Calories burned during physical activity", + "distanceDescription": "Distance covered throughout the day", + "overview": "Overview", + "details": "Details", + "healthy": "Healthy", + "warning": "Warning", + "vitalSignDetails": "Vital Sign Details", + "resultOf": "Result of {date}", + "resultOfNoDate": "Result of --", + "referenceRangeBetween": "Reference range: {low} – {high} {unit}", + "referenceRangeMin": "Reference range: ≥ {low} {unit}", + "referenceRangeMax": "Reference range: ≤ {high} {unit}", + "noHistoryAvailable": "No history available", + "bmiDescription": "BMI is a measurement based on height and weight that estimates body fat.", + "heightDescription": "Height is measured in centimeters and is used to calculate BMI and dosage recommendations.", + "weightDescription": "Weight helps track overall health, nutrition, and changes over time.", + "bloodPressureDescription": "Blood pressure reflects the force of blood against artery walls. It is shown as systolic/diastolic.", + "temperatureDescription": "Body temperature reflects how hot your body is and may change with infection or inflammation.", + "heartRateDescriptionVital": "Heart rate refers to the number of heart beats per minute.", + "respiratoryRateDescription": "Respiratory rate is the number of breaths taken per minute.", + "bmiAdvice": "Maintain a balanced diet and regular activity. If your BMI is high or low, consider consulting your doctor.", + "heightAdvice": "No action is needed unless your measurement looks incorrect. Update it during your next visit.", + "weightAdvice": "Monitor weight changes. Sudden gain or loss may require medical advice.", + "bloodPressureAdvice": "Keep tracking your blood pressure. High or low readings should be discussed with your doctor.", + "temperatureAdvice": "If you have a persistent fever or symptoms, contact your healthcare provider.", + "heartRateAdvice": "Track your heart rate trends. If you feel dizziness or chest pain, seek medical care.", + "respiratoryRateAdvice": "If you notice shortness of breath or abnormal breathing, seek medical advice.", + "whatShouldIDoNext": "What should I do next?", + "customizeDrinkCup": "Customize your drink cup", + "tipsToStayHydrated": "Tips to stay hydrated", + "drinkBeforeYouFeelThirsty": "Drink before you feel thirsty", + "keepRefillableBottleNextToYou": "Keep a refillable bottle next to you", + "trackYourDailyIntakeToStayMotivated": "Track your daily intake to stay motivated", + "chooseSparklingWaterInsteadOfSoda": "Choose sparkling water instead of soda", + "switchCup": "Switch Cup", + "plainWater": "Plain Water", + "yourGoal": "Your Goal", + "remaining": "Remaining", + "hydrationStatus": "Hydration Status", + "areYouSureYouWantToCancelAllWaterReminders": "Are you sure you want to cancel all water reminders?", + "remindersSet": "Reminders Set!", + "dailyWaterRemindersScheduledAt": "Daily water reminders scheduled at:", + "waterConsumption": "Water Consumption", + "selectActivityLevel": "Select Activity Level", + "selectNumberOfReminders": "Select Number of Reminders", + "h2oSettings": "H20 Settings", + "settingsSavedSuccessfully": "Settings saved successfully", + "yourName": "Your Name", + "ageYears": "Age (11-120) yrs", + "numberOfRemindersInADay": "Number of reminders in a day", + "medications": "Medications", + "remarks": "Remarks: ", + "someRemarksAboutPrescription": "some remarks about the prescription will be here", + "notifyMeBeforeConsumptionTime": "Notify me before the consumption time", + "noMedicationsToday": "No medications today", + "route": "Route", + "frequency": "Frequency", + "reminders": "Reminders", + "reminderAddedToCalendar": "Reminder added to calendar ✅", + "errorWhileSettingCalendar": "Error while setting calendar: {error}", + "instructions": "Instructions", + "requests": "Requests", + "thisWeek": "This Week", + "lastMonth": "Last Month", + "lastSixMonths": "Last 6 Months", + "selectTime": "Select Time", + "pleaseWaitYouWillBeCalledForVitalSigns": "Please wait! you will be called for vital signs", + "pleaseVisitRoomForVitalSigns": "Please visit Room {roomNumber} for vital signs", + "pleaseVisitRoomToTheDoctor": "Please visit Room {roomNumber} to the Doctor", + "erOnlineCheckInRequest": "ER Online Check-In Request", + "indoor": "Indoor", + "navigation": "Navigation", + "health": "Health", + "calculators": "Calculators", + "converters": "Converters", + "guide": "Guide", + "liveCareServiceDesc": "Get medical advice with a specialist doctor Via a video call", + "bloodGroup": "Blood: {bloodType}", + "medicalServices": "Medical Services", + "insuranceAndPayments": "Insurance & Payments", + "trackerAndOthers": "Tracker & Others", + "bmi": "BMI", + "yesPleaseINeedHelp": "Yes, Please I need help", + "noThanksIKnowTheClinic": "No, Thanks. I Know the clinic", + "unableToSendOTP": "Unable to send Verification OTP" "callForVitalSign": "Call for vital signs", "callForDoctor": "Call for Doctor", "yourQueueNumber": "Your Queue Number", "currentServing" : "Current Serving" -} \ No newline at end of file +} diff --git a/convert_json.dart b/convert_json.dart index 08f344d..af5c594 100644 --- a/convert_json.dart +++ b/convert_json.dart @@ -1,73 +1,73 @@ -import 'dart:convert'; -import 'dart:io'; - -void main() async { - final file = File('assets/json/body_symptoms_data.json'); - final content = await file.readAsString(); - - print('File size: ${content.length} characters'); - - // Split into two parts - final parts = content.split('export const SymptomsData = ['); - if (parts.length != 2) { - print('ERROR: Could not split file properly'); - exit(1); - } - - print('Split into ${parts.length} parts'); - - // Process BodySymptomsData - var bodyPart = parts[0] - .replaceAll('export const BodySymptomsData = ', '') - .trim() - .replaceAll(RegExp(r';$'), ''); - - print('Parsing body symptoms...'); - Map bodySymptomsData; - try { - bodySymptomsData = json.decode(bodyPart); - print('✅ Body symptoms parsed: ${bodySymptomsData.length} body parts'); - } catch (e) { - print('❌ Error parsing body symptoms: $e'); - exit(1); - } - - // Process SymptomsData - print('Processing symptoms data...'); - var symptomsPart = parts[1] - .trim() - .replaceAll(RegExp(r'\];$'), '') - .replaceAllMapped(RegExp(r'\n(\s*)id:'), (m) => '\n${m.group(1)}"id":') - .replaceAllMapped(RegExp(r'\n(\s*)type:'), (m) => '\n${m.group(1)}"type":') - .replaceAllMapped(RegExp(r'\n(\s*)name:'), (m) => '\n${m.group(1)}"name":') - .replaceAllMapped(RegExp(r'\n(\s*)common_name:'), (m) => '\n${m.group(1)}"common_name":'); - - print('Parsing symptoms...'); - List symptomsData; - try { - symptomsData = json.decode('[$symptomsPart]'); - print('✅ Symptoms parsed: ${symptomsData.length} symptoms'); - } catch (e) { - print('❌ Error parsing symptoms: $e'); - print('First 1000 chars:'); - print('[$symptomsPart]'.substring(0, 1000)); - exit(1); - } - - // Create final JSON - print('Creating final JSON structure...'); - final jsonStructure = { - 'bodySymptoms': bodySymptomsData, - 'symptoms': symptomsData, - }; - - // Write to file - print('Writing to file...'); - final encoder = JsonEncoder.withIndent(' '); - await file.writeAsString(encoder.convert(jsonStructure)); - - print('\n✅ SUCCESS! File converted to proper JSON'); - print('✅ Body parts: ${bodySymptomsData.length}'); - print('✅ Symptoms: ${symptomsData.length}'); -} - +// import 'dart:convert'; +// import 'dart:io'; +// +// void main() async { +// final file = File('assets/json/body_symptoms_data.json'); +// final content = await file.readAsString(); +// +// print('File size: ${content.length} characters'); +// +// // Split into two parts +// final parts = content.split('export const SymptomsData = ['); +// if (parts.length != 2) { +// print('ERROR: Could not split file properly'); +// exit(1); +// } +// +// print('Split into ${parts.length} parts'); +// +// // Process BodySymptomsData +// var bodyPart = parts[0] +// .replaceAll('export const BodySymptomsData = ', '') +// .trim() +// .replaceAll(RegExp(r';$'), ''); +// +// print('Parsing body symptoms...'); +// Map bodySymptomsData; +// try { +// bodySymptomsData = json.decode(bodyPart); +// print('✅ Body symptoms parsed: ${bodySymptomsData.length} body parts'); +// } catch (e) { +// print('❌ Error parsing body symptoms: $e'); +// exit(1); +// } +// +// // Process SymptomsData +// print('Processing symptoms data...'); +// var symptomsPart = parts[1] +// .trim() +// .replaceAll(RegExp(r'\];$'), '') +// .replaceAllMapped(RegExp(r'\n(\s*)id:'), (m) => '\n${m.group(1)}"id":') +// .replaceAllMapped(RegExp(r'\n(\s*)type:'), (m) => '\n${m.group(1)}"type":') +// .replaceAllMapped(RegExp(r'\n(\s*)name:'), (m) => '\n${m.group(1)}"name":') +// .replaceAllMapped(RegExp(r'\n(\s*)common_name:'), (m) => '\n${m.group(1)}"common_name":'); +// +// print('Parsing symptoms...'); +// List symptomsData; +// try { +// symptomsData = json.decode('[$symptomsPart]'); +// print('✅ Symptoms parsed: ${symptomsData.length} symptoms'); +// } catch (e) { +// print('❌ Error parsing symptoms: $e'); +// print('First 1000 chars:'); +// print('[$symptomsPart]'.substring(0, 1000)); +// exit(1); +// } +// +// // Create final JSON +// print('Creating final JSON structure...'); +// final jsonStructure = { +// 'bodySymptoms': bodySymptomsData, +// 'symptoms': symptomsData, +// }; +// +// // Write to file +// print('Writing to file...'); +// final encoder = JsonEncoder.withIndent(' '); +// await file.writeAsString(encoder.convert(jsonStructure)); +// +// print('\n✅ SUCCESS! File converted to proper JSON'); +// print('✅ Body parts: ${bodySymptomsData.length}'); +// print('✅ Symptoms: ${symptomsData.length}'); +// } +// diff --git a/ios/Podfile b/ios/Podfile index 9249e54..4c8bed1 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -54,6 +54,8 @@ post_install do |installer| 'PERMISSION_EVENTS_FULL_ACCESS=1', ## dart: PermissionGroup.reminders 'PERMISSION_REMINDERS=1', + ## dart: PermissionGroup.notification + 'PERMISSION_NOTIFICATIONS=1', ] build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' build_configuration.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0' diff --git a/ios/Runner/Penguin/PenguinNavigator.swift b/ios/Runner/Penguin/PenguinNavigator.swift index 31cf626..5b9934b 100644 --- a/ios/Runner/Penguin/PenguinNavigator.swift +++ b/ios/Runner/Penguin/PenguinNavigator.swift @@ -14,7 +14,7 @@ class PenguinNavigator { } func navigateToPOI( referenceId:String,completion: @escaping (Bool, String?) -> Void) { - PenNavUIManager.shared.getToken(clientID: config.clientID, clientKey: config.clientKey, showProgress: true) { [weak self] token, error in + PenNavUIManager.shared.getToken(clientID: config.clientID, clientKey: config.clientKey, showProgress: false) { [weak self] token, error in if let error = error { let errorMessage = "Token error while getting the for Navigate to method" diff --git a/ios/Runner/Penguin/PenguinView.swift b/ios/Runner/Penguin/PenguinView.swift index d5303e2..508fb74 100644 --- a/ios/Runner/Penguin/PenguinView.swift +++ b/ios/Runner/Penguin/PenguinView.swift @@ -312,6 +312,8 @@ class PenguinView: NSObject, FlutterPlatformView, PIEventsDelegate, PenNavInitia print("====== after eventsDelegate onPenNavSuccess =========") + + PenNavUIManager.shared.navigate(to: "108") @@ -385,21 +387,21 @@ class PenguinView: NSObject, FlutterPlatformView, PIEventsDelegate, PenNavInitia - self?.handleNavigation(clinicID: clinicID, token: token) { success, errorMessage in - - if success { - - print("Navigation successful") - - } else { - - print("Navigation failed: \(errorMessage ?? "Unknown error")") - - } - - - - } +// self?.handleNavigation(clinicID: clinicID, token: token) { success, errorMessage in +// +// if success { +// +// print("Navigation successful") +// +// } else { +// +// print("Navigation failed: \(errorMessage ?? "Unknown error")") +// +// } +// +// +// +// } diff --git a/lib/core/api/api_client.dart b/lib/core/api/api_client.dart index f366329..3eb8fa2 100644 --- a/lib/core/api/api_client.dart +++ b/lib/core/api/api_client.dart @@ -19,7 +19,7 @@ abstract class ApiClient { Future post( String endPoint, { - required dynamic body, + required Map body, required Function(dynamic response, int statusCode, {int? messageStatus, String? errorMessage}) onSuccess, required Function(String error, int statusCode, {int? messageStatus, Failure? failureType}) onFailure, bool isAllowAny, @@ -182,13 +182,14 @@ class ApiClientImp implements ApiClient { } // body['TokenID'] = "@dm!n"; - // body['PatientID'] = 1018977; + // body['PatientID'] = 4769038; // body['PatientTypeID'] = 1; - // // body['PatientOutSA'] = 0; // body['SessionID'] = "45786230487560q"; } + // body['IsNewFlutterApp'] = true; + body.removeWhere((key, value) => value == null); } @@ -206,10 +207,10 @@ class ApiClientImp implements ApiClient { // Handle body encoding based on isBodyPlainText flag final dynamic requestBody = isBodyPlainText ? body : json.encode(body); + debugPrint("uri: ${Uri.parse(url.trim())}"); + debugPrint("body: ${json.encode(body)}", wrapWidth: 2048); final response = await http.post(Uri.parse(url.trim()), body: requestBody, headers: headers); final int statusCode = response.statusCode; - log("uri: ${Uri.parse(url.trim())}"); - log("body: ${json.encode(body)}"); // log("response.body: ${response.body}"); if (statusCode < 200 || statusCode >= 400) { onFailure('Error While Fetching data', statusCode, failureType: StatusCodeFailure("Error While Fetching data")); diff --git a/lib/core/api_consts.dart b/lib/core/api_consts.dart index 0febdbe..bec908b 100644 --- a/lib/core/api_consts.dart +++ b/lib/core/api_consts.dart @@ -151,6 +151,7 @@ var GET_FINDUS_REQUEST = 'Services/Lists.svc/REST/Get_HMG_Locations'; ///LiveChat var GET_LIVECHAT_REQUEST = 'Services/Patients.svc/REST/GetPatientICProjects'; +var GET_LIVECHAT_REQUEST_ID = 'Services/Patients.svc/REST/Patient_ICChatRequest_Insert'; ///babyInformation var GET_BABYINFORMATION_REQUEST = 'Services/Community.svc/REST/GetBabyByUserID'; @@ -207,7 +208,7 @@ var GET_APPOINTMENT_DETAILS_BY_NO = 'Services/MobileNotifications.svc/REST/GetAp var NEW_RATE_APPOINTMENT_URL = "Services/Doctors.svc/REST/AppointmentsRating_InsertAppointmentRate"; var NEW_RATE_DOCTOR_URL = "Services/Doctors.svc/REST/DoctorsRating_InsertDoctorRate"; -var GET_QR_PARKING = 'Services/SWP.svc/REST/GetQRParkingByID'; +//var GET_QR_PARKING = 'Services/SWP.svc/REST/GetQRParkingByID'; //URL to get clinic list var GET_CLINICS_LIST_URL = "Services/lists.svc/REST/GetClinicCentralized"; @@ -398,6 +399,9 @@ var GET_COVID_DRIVETHRU_PROCEDURES_LIST = 'Services/Doctors.svc/REST/COVID19_Get var GET_PATIENT_LAST_RECORD = 'Services/Patients.svc/REST/Med_GetPatientLastRecord'; var INSERT_PATIENT_HEALTH_DATA = 'Services/Patients.svc/REST/Med_InsertTransactions'; +///Push Notifications +var GET_ALL_NOTIFICATIONS = 'Services/MobileNotifications.svc/REST/PushNotification_GetAllNotifications'; + ///My Trackers var GET_DIABETIC_RESULT_AVERAGE = 'Services/Patients.svc/REST/Patient_GetDiabeticResultAverage'; var GET_DIABTEC_RESULT = 'Services/Patients.svc/REST/Patient_GetDiabtecResults'; @@ -420,7 +424,6 @@ var GET_QUESTION_TYPES = 'Services/OUTPs.svc/REST/getQuestionsTypes'; var UPDATE_DIABETIC_RESULT = 'Services/Patients.svc/REST/Patient_UpdateDiabeticResult'; -var SEND_AVERAGE_BLOOD_SUGAR_REPORT = 'Services/Notifications.svc/REST/SendAverageBloodSugarReport'; var DEACTIVATE_DIABETIC_STATUS = 'services/Patients.svc/REST/Patient_DeactivateDiabeticStatus'; var DEACTIVATE_BLOOD_PRESSURES_STATUS = 'services/Patients.svc/REST/Patient_DeactivateBloodPressureStatus'; @@ -672,6 +675,8 @@ const FAMILY_FILES = 'Services/Authentication.svc/REST/GetAllSharedRecordsByStat var GET_PRESCRIPTION_INSTRUCTIONS_PDF = 'Services/ChatBot_Service.svc/REST/Chatbot_SendMedicationInstructionByWhatsApp'; +const DASHBOARD = 'Services/Patients.svc/REST/PatientDashboard'; + class ApiConsts { static const maxSmallScreen = 660; @@ -697,6 +702,8 @@ class ApiConsts { static String QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + static String CHAT_URL = "https://chat.hmg.com/Index.aspx?RequestedId="; + // static String GET_TAMARA_INSTALLMENTS_URL = "https://epharmacy.hmg.com/tamara/Home/getinstallments"; // var payFortEnvironment = FortEnvironment.test; @@ -714,6 +721,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://mdlaboratories.com/tamaralive/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/Index.aspx?RequestedId="; break; case AppEnvironmentTypeEnum.dev: baseUrl = "https://uat.hmgwebservices.com/"; @@ -725,6 +733,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/uat/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId"; break; case AppEnvironmentTypeEnum.uat: baseUrl = "https://uat.hmgwebservices.com/"; @@ -736,6 +745,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/uat/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId"; break; case AppEnvironmentTypeEnum.preProd: baseUrl = "https://webservices.hmg.com/"; @@ -747,6 +757,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId"; break; case AppEnvironmentTypeEnum.qa: baseUrl = "https://uat.hmgwebservices.com/"; @@ -758,6 +769,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/uat/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId"; break; case AppEnvironmentTypeEnum.staging: baseUrl = "https://uat.hmgwebservices.com/"; @@ -769,6 +781,7 @@ class ApiConsts { GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; rcBaseUrl = 'https://rc.hmg.com/uat/'; QLINE_URL = "https://ms.hmg.com/nscapi/api/PatientCall/PatientInQueue_Detail"; + CHAT_URL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId"; break; } } @@ -799,6 +812,11 @@ class ApiConsts { static final String getAllSharedRecordsByStatus = 'Services/Authentication.svc/REST/GetAllSharedRecordsByStatus'; static final String removeFileFromFamilyMembers = 'Services/Authentication.svc/REST/ActiveDeactive_PatientFile'; static final String acceptAndRejectFamilyFile = 'Services/Authentication.svc/REST/Update_FileStatus'; + static final String getActivePrescriptionsDetails = 'Services/Patients.svc/Rest/GetActivePrescriptionReportByPatientID'; + static final String getTermsConditions = 'Services/Patients.svc/Rest/GetUserTermsAndConditions'; + static final String getMonthlyReports = 'Services/Patients.svc/Rest/UpdatePateintHealthSummaryReport'; + static final String updatePatientEmail = 'Services/Patients.svc/Rest/UpdatePateintEmail'; + static final String getQrParkingDetails = 'Services/SWP.svc/REST/GetQRParkingByID'; // Ancillary Order Apis static final String getOnlineAncillaryOrderList = 'Services/Doctors.svc/REST/GetOnlineAncillaryOrderList'; @@ -825,12 +843,13 @@ class ApiConsts { static final String updateHHCOrder = 'api/hhc/update'; static final String addHHCOrder = 'api/HHC/add'; - // SYMPTOMS CHECKER + // SYMPTOMS CHECKER API + static final String symptomsUserLogin = '$symptomsCheckerApi/user_login'; static final String getBodySymptomsByName = '$symptomsCheckerApi/GetBodySymptomsByName'; static final String getRiskFactors = '$symptomsCheckerApi/GetRiskFactors'; static final String getSuggestions = '$symptomsCheckerApi/GetSuggestion'; - static final String diagnosis = '$symptomsCheckerApi/diagnosis'; - static final String explain = '$symptomsCheckerApi/explain'; + static final String diagnosis = '$symptomsCheckerApi/GetDiagnosis'; + static final String explain = '$symptomsCheckerApi/ExplainDiagnosisResult'; //E-REFERRAL SERVICES static final getAllRelationshipTypes = "Services/Patients.svc/REST/GetAllRelationshipTypes"; @@ -848,6 +867,41 @@ class ApiConsts { static String h2oUpdateUserDetail = "Services/H2ORemainder.svc/REST/H2O_UpdateUserDetails_New"; static String h2oUndoUserActivity = "Services/H2ORemainder.svc/REST/H2o_UndoUserActivity"; + // HEALTH TRACKERS + // Blood Sugar (Diabetic) + static String getDiabeticResultAverage = 'Services/Patients.svc/REST/Patient_GetDiabeticResultAverage'; + static String getDiabeticResult = 'Services/Patients.svc/REST/Patient_GetDiabtecResults'; + static String addDiabeticResult = 'Services/Patients.svc/REST/Patient_AddDiabtecResult'; + static String updateDiabeticResult = 'Services/Patients.svc/REST/Patient_UpdateDiabtecResult'; + static String deactivateDiabeticStatus = 'Services/Patients.svc/REST/Patient_DeactivateDiabeticStatus'; + static String sendAverageBloodSugarReport = 'Services/Notifications.svc/REST/SendAverageBloodSugarReport'; + + // Blood Pressure + static String getBloodPressureResultAverage = 'Services/Patients.svc/REST/Patient_GetBloodPressureResultAverage'; + static String getBloodPressureResult = 'Services/Patients.svc/REST/Patient_GetBloodPressureResult'; + static String addBloodPressureResult = 'Services/Patients.svc/REST/Patient_AddBloodPressureResult'; + static String updateBloodPressureResult = 'Services/Patients.svc/REST/Patient_UpdateBloodPressureResult'; + static String deactivateBloodPressureStatus = 'Services/Patients.svc/REST/Patient_DeactivateBloodPressureStatus'; + static String sendAverageBloodPressureReport = 'Services/Notifications.svc/REST/SendAverageBloodPressureReport'; + + // Weight Measurement + static String getWeightMeasurementResultAverage = 'Services/Patients.svc/REST/Patient_GetWeightMeasurementResultAverage'; + static String getWeightMeasurementResult = 'Services/Patients.svc/REST/Patient_GetWeightMeasurementResult'; + static String addWeightMeasurementResult = 'Services/Patients.svc/REST/Patient_AddWeightMeasurementResult'; + static String updateWeightMeasurementResult = 'Services/Patients.svc/REST/Patient_UpdateWeightMeasurementResult'; + static String deactivateWeightMeasurementStatus = 'Services/Patients.svc/REST/Patient_DeactivateWeightMeasurementStatus'; + static String sendAverageBodyWeightReport = 'Services/Notifications.svc/REST/SendAverageBodyWeightReport'; + + //Blood Donation + static String bloodGroupUpdate = "Services/PatientVarification.svc/REST/BloodDonation_RegisterBloodType"; + static String userAgreementForBloodGroupUpdate = "Services/PatientVarification.svc/REST/AddUserAgreementForBloodDonation"; + static String getProjectsHaveBDClinics = "Services/OUTPs.svc/REST/BD_getProjectsHaveBDClinics"; + static String getClinicsBDFreeSlots = "Services/OUTPs.svc/REST/BD_GetFreeSlots"; + + + static String getPatientBloodGroup = "services/PatientVarification.svc/REST/BloodDonation_GetBloodGroupDetails"; + static String getPatientBloodAgreement = "Services/PatientVarification.svc/REST/CheckUserAgreementForBloodDonation"; + // ************ static values for Api **************** static final double appVersionID = 50.3; static final int appChannelId = 3; diff --git a/lib/core/app_assets.dart b/lib/core/app_assets.dart index a581e78..5b8d2ed 100644 --- a/lib/core/app_assets.dart +++ b/lib/core/app_assets.dart @@ -4,6 +4,7 @@ class AppAssets { static const String hmg = '$svgBasePath/hmg.svg'; static const String arrow_back = '$svgBasePath/arrow-back.svg'; + static const String arrow_back_new = '$svgBasePath/arrow-back_new.svg'; static const String arrow_forward = '$svgBasePath/arrow_forward.svg'; static const String externalLink = '$svgBasePath/external_link.svg'; static const String calendar = '$svgBasePath/calendar.svg'; @@ -25,6 +26,7 @@ class AppAssets { static const String download = '$svgBasePath/download.svg'; static const String language = '$svgBasePath/language.svg'; static const String location = '$svgBasePath/location.svg'; + static const String locationFill = '$svgBasePath/location_fill.svg'; static const String pin_location = '$svgBasePath/pin_location.svg'; static const String whatsapp = '$svgBasePath/whatsapp.svg'; static const String card_user = '$svgBasePath/card_user.svg'; @@ -183,6 +185,7 @@ class AppAssets { static const String bulb_icon = '$svgBasePath/bulb_icon.svg'; static const String select_city_icon = '$svgBasePath/select_city_icon.svg'; static const String blood_donation_icon = '$svgBasePath/blood_donation_icon.svg'; + static const String my_child_vaccine_icon = '$svgBasePath/my_child_vaccine.svg'; static const String virtual_tour_icon = '$svgBasePath/virtual_tour_icon.svg'; static const String car_parking_icon = '$svgBasePath/car_parking_icon.svg'; static const String latest_news_icon = '$svgBasePath/latest_news_icon.svg'; @@ -218,20 +221,32 @@ class AppAssets { static const String activity = '$svgBasePath/activity.svg'; static const String age = '$svgBasePath/age_icon.svg'; static const String gender = '$svgBasePath/gender_icon.svg'; + static const String genderInputIcon = '$svgBasePath/genderInputIcon.svg'; + static const String bloodType = '$svgBasePath/blood_type.svg'; static const String trade_down_yellow = '$svgBasePath/trade_down_yellow.svg'; static const String trade_down_red = '$svgBasePath/trade_down_red.svg'; static const String pharmacy_icon = '$svgBasePath/phramacy_icon.svg'; + static const String forward_top_nav_icon = '$svgBasePath/forward_top_nav_icon.svg'; + static const String back_top_nav_icon = '$svgBasePath/back_top_nav_icon.svg'; + //bottom navigation// static const String homeBottom = '$svgBasePath/home_bottom.svg'; + static const String homeBottomFill = '$svgBasePath/home_bottom_fill.svg'; static const String bookAppoBottom = '$svgBasePath/book_appo_bottom.svg'; static const String myFilesBottom = '$svgBasePath/my_files_bottom.svg'; + static const String myFilesBottomFill = '$svgBasePath/my_files_bottom_fill.svg'; static const String toDoBottom = '$svgBasePath/todo_bottom.svg'; static const String servicesBottom = '$svgBasePath/services_bottom.svg'; + static const String servicesBottomFill = '$svgBasePath/services_bottom_fill.svg'; static const String closeBottomNav = '$svgBasePath/close_bottom_nav.svg'; + static const String close_bottom_nav_new = '$svgBasePath/close_bottom_nav_new.svg'; + static const String close_bottom_nav_trans = '$svgBasePath/close_bottom_nav_trans.svg'; static const String feedback = '$svgBasePath/feedback.svg'; + static const String feedbackFill = '$svgBasePath/feedback_fill.svg'; static const String news = '$svgBasePath/news.svg'; + static const String newsFill = '$svgBasePath/news_fill.svg'; static const String heart = '$svgBasePath/heart.svg'; static const String alertSquare = '$svgBasePath/alert-square.svg'; static const String arrowRight = '$svgBasePath/arrow-right.svg'; @@ -248,6 +263,8 @@ class AppAssets { static const String homeBorderedIcon = '$svgBasePath/home_bordered.svg'; static const String symptomCheckerIcon = '$svgBasePath/symptom_checker_icon.svg'; static const String symptomCheckerBottomIcon = '$svgBasePath/symptom_bottom_icon.svg'; + static const String symptomCheckerBottomFillIcon = '$svgBasePath/symptom_bottom_icon_fill.svg'; + static const String coloredDotsIcon = '$svgBasePath/colored_dots_icon.svg'; // Water Monitor static const String waterBottle = '$svgBasePath/water_bottle.svg'; @@ -268,16 +285,21 @@ class AppAssets { static const String yellowArrowDownIcon = '$svgBasePath/yellow_arrow_down_icon.svg'; static const String greenTickIcon = '$svgBasePath/green_tick_icon.svg'; - // PNGS - - static const String bloodSugar = '$svgBasePath/bloodsugar.svg'; static const String bloodCholestrol = '$svgBasePath/bloodcholestrol.svg'; static const String triglycerides = '$svgBasePath/triglycerides.svg'; static const String bulb = '$svgBasePath/bulb.svg'; static const String switchBtn = '$svgBasePath/switch.svg'; + //Health Trackers + static const String bloodPressureIcon = '$svgBasePath/blood_pressure_icon.svg'; + static const String bloodSugarOnlyIcon = '$svgBasePath/blood_sugar_only_icon.svg'; + static const String weightIcon = '$svgBasePath/weight_icon.svg'; + static const String normalStatusGreenIcon = '$svgBasePath/normal_status_green_icon.svg'; + static const String sendEmailIcon = '$svgBasePath/send_email_icon.svg'; + static const String lowIndicatorIcon = '$svgBasePath/low_indicator_icon.svg'; + // Health Calculators static const String ovulationAccordion = '$svgBasePath/approximate_ovulation_accordion.svg'; static const String nextPeriodAccordion = '$svgBasePath/next_period_accordion.svg'; static const String fertileAccordion = '$svgBasePath/fertile_window_accordion.svg'; @@ -286,9 +308,7 @@ class AppAssets { static const String covid19icon = '$svgBasePath/covid_19.svg'; - //vital sign - static const String heartRate = '$svgBasePath/heart_rate.svg'; static const String respRate = '$svgBasePath/resp_rate.svg'; static const String weightVital = '$svgBasePath/weight_2.svg'; @@ -297,7 +317,11 @@ class AppAssets { static const String bloodPressure = '$svgBasePath/blood_pressure.svg'; static const String temperature = '$svgBasePath/temperature.svg'; + static const String arLangIcon = '$svgBasePath/ar_lang_icon.svg'; + static const String enLangIcon = '$svgBasePath/en_lang_icon.svg'; + static const String doctorResponseIcon = '$svgBasePath/doctor_response_icon.svg'; + static const String changeLanguageHomePageIcon = '$svgBasePath/change_language_home_page.svg'; // PNGS // static const String hmgLogo = '$pngBasePath/hmg_logo.png'; @@ -325,8 +349,6 @@ class AppAssets { static const String fullBodyFront = '$pngBasePath/full_body_front.png'; static const String fullBodyBack = '$pngBasePath/full_body_back.png'; static const String bmiFullBody = '$pngBasePath/bmi_image_1.png'; - - } class AppAnimations { @@ -347,6 +369,4 @@ class AppAnimations { static const String ambulance = '$lottieBasePath/ambulance.json'; static const String ambulanceAlert = '$lottieBasePath/ambulance_alert.json'; static const String rrtAmbulance = '$lottieBasePath/rrt_ambulance.json'; - - } diff --git a/lib/core/dependencies.dart b/lib/core/dependencies.dart index d14d78d..fb2c64d 100644 --- a/lib/core/dependencies.dart +++ b/lib/core/dependencies.dart @@ -4,12 +4,16 @@ import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/api/api_client.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/location_util.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_repo.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart'; import 'package:hmg_patient_app_new/features/authentication/authentication_repo.dart'; import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_repo.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_repo.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/active_prescriptions_view_model.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/models/active_prescriptions_response_model.dart'; import 'package:hmg_patient_app_new/features/common/common_repo.dart'; import 'package:hmg_patient_app_new/features/contact_us/contact_us_repo.dart'; import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart'; @@ -18,6 +22,7 @@ import 'package:hmg_patient_app_new/features/emergency_services/emergency_servic import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_repo.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_repo.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_repo.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_repo.dart'; @@ -32,17 +37,21 @@ import 'package:hmg_patient_app_new/features/medical_file/medical_file_repo.dart import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart'; import 'package:hmg_patient_app_new/features/monthly_report/monthly_report_repo.dart'; import 'package:hmg_patient_app_new/features/monthly_report/monthly_report_view_model.dart'; +import 'package:hmg_patient_app_new/features/monthly_reports/monthly_reports_repo.dart'; import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_repo.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_repo.dart'; import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_view_model.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_repo.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_view_model.dart'; import 'package:hmg_patient_app_new/features/payfort/payfort_repo.dart'; import 'package:hmg_patient_app_new/features/payfort/payfort_view_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_repo.dart'; import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart'; import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_repo.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_repo.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart'; import 'package:hmg_patient_app_new/features/smartwatch_health_data/health_provider.dart'; @@ -52,6 +61,7 @@ import 'package:hmg_patient_app_new/features/todo_section/todo_section_repo.dart import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_repo.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart'; import 'package:hmg_patient_app_new/services/analytics/analytics_service.dart'; import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; @@ -66,8 +76,14 @@ import 'package:local_auth/local_auth.dart'; import 'package:logger/web.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../features/monthly_reports/monthly_reports_repo.dart'; +import '../features/qr_parking/qr_parking_view_model.dart'; import '../presentation/health_calculators_and_converts/health_calculator_view_model.dart'; +import '../features/active_prescriptions/active_prescriptions_repo.dart'; +import '../features/monthly_reports/terms_conditions_repo.dart'; +import '../features/monthly_reports/terms_conditions_view_model.dart'; + GetIt getIt = GetIt.instance; class AppDependencies { @@ -143,7 +159,16 @@ class AppDependencies { getIt.registerLazySingleton(() => BloodDonationRepoImp(loggerService: getIt(), apiClient: getIt())); getIt.registerLazySingleton(() => WaterMonitorRepoImp(loggerService: getIt(), apiClient: getIt())); getIt.registerLazySingleton(() => MyInvoicesRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => HealthTrackersRepoImp(loggerService: getIt(), apiClient: getIt())); getIt.registerLazySingleton(() => MonthlyReportRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => ActivePrescriptionsRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => TermsConditionsRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerFactory(() => TermsConditionsViewModel(termsConditionsRepo: getIt(), errorHandlerService: getIt(), + ),); + getIt.registerLazySingleton(() => MonthlyReportsRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => QrParkingRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => NotificationsRepoImp(loggerService: getIt(), apiClient: getIt())); + getIt.registerLazySingleton(() => AskDoctorRepoImp(loggerService: getIt(), apiClient: getIt())); // ViewModels // Global/shared VMs → LazySingleton @@ -154,26 +179,20 @@ class AppDependencies { () => RadiologyViewModel(radiologyRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt()), ); - getIt.registerLazySingleton( - () => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); + getIt.registerLazySingleton(() => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); getIt.registerLazySingleton(() => InsuranceViewModel(insuranceRepo: getIt(), errorHandlerService: getIt())); - getIt.registerLazySingleton( - () => MyAppointmentsViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); + getIt.registerLazySingleton(() => MyAppointmentsViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); - getIt.registerLazySingleton( - () => AppointmentRatingViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); + getIt.registerLazySingleton(() => AppointmentRatingViewModel(myAppointmentsRepo: getIt(), errorHandlerService: getIt(), appState: getIt())); getIt.registerLazySingleton( () => PayfortViewModel(payfortRepo: getIt(), errorHandlerService: getIt()), ); getIt.registerLazySingleton( - () => HabibWalletViewModel( - habibWalletRepo: getIt(), - errorHandlerService: getIt() - ), + () => HabibWalletViewModel(habibWalletRepo: getIt(), errorHandlerService: getIt()), ); getIt.registerLazySingleton( @@ -185,12 +204,7 @@ class AppDependencies { getIt.registerLazySingleton( () => BookAppointmentsViewModel( - bookAppointmentsRepo: getIt(), - errorHandlerService: getIt(), - navigationService: getIt(), - myAppointmentsViewModel: getIt(), - locationUtils: getIt(), - dialogService: getIt()), + bookAppointmentsRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt(), myAppointmentsViewModel: getIt(), locationUtils: getIt(), dialogService: getIt()), ); getIt.registerLazySingleton( @@ -204,13 +218,7 @@ class AppDependencies { getIt.registerLazySingleton( () => AuthenticationViewModel( - authenticationRepo: getIt(), - cacheService: getIt(), - navigationService: getIt(), - dialogService: getIt(), - appState: getIt(), - errorHandlerService: getIt(), - localAuthService: getIt()), + authenticationRepo: getIt(), cacheService: getIt(), navigationService: getIt(), dialogService: getIt(), appState: getIt(), errorHandlerService: getIt(), localAuthService: getIt()), ); getIt.registerLazySingleton(() => ProfileSettingsViewModel()); @@ -271,15 +279,37 @@ class AppDependencies { navigationService: getIt(), dialogService: getIt(), appState: getIt(), + navServices: getIt(), ), ); getIt.registerLazySingleton(() => HealthProvider()); - getIt.registerLazySingleton(() => WaterMonitorViewModel(waterMonitorRepo: getIt())); + getIt.registerLazySingleton(() => WaterMonitorViewModel(waterMonitorRepo: getIt(), errorHandlerService: getIt())); + //commenting this because its already define there was on run time error because of this. getIt.registerLazySingleton(() => MyInvoicesViewModel(myInvoicesRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); getIt.registerLazySingleton(() => MonthlyReportViewModel(errorHandlerService: getIt(), monthlyReportRepo: getIt())); + + getIt.registerLazySingleton(() => NotificationsViewModel(notificationsRepo: getIt(), errorHandlerService: getIt())); + + getIt.registerLazySingleton(() => HealthTrackersViewModel(healthTrackersRepo: getIt(), errorHandlerService: getIt())); + getIt.registerLazySingleton( + () => ActivePrescriptionsViewModel( + errorHandlerService: getIt(), + activePrescriptionsRepo: getIt() + ), + ); + getIt.registerFactory( + () => QrParkingViewModel( + qrParkingRepo: getIt(), + errorHandlerService: getIt(), + cacheService: getIt(), + ), + ); + + getIt.registerLazySingleton(() => AskDoctorViewModel(askDoctorRepo: getIt(), errorHandlerService: getIt())); + } } diff --git a/lib/core/enums.dart b/lib/core/enums.dart index 8fd4818..6613702 100644 --- a/lib/core/enums.dart +++ b/lib/core/enums.dart @@ -16,7 +16,7 @@ enum CountryEnum { saudiArabia, unitedArabEmirates } enum CalenderEnum { gregorian, hijri } -enum SelectionTypeEnum { dropdown, calendar, search } +enum SelectionTypeEnum { dropdown, calendar, search, time } enum GenderTypeEnum { male, female } @@ -38,7 +38,19 @@ enum HealthCalConEnum { calculator, converter } enum HealthCalculatorEnum { general, women } -enum HealthCalculatorsTypeEnum { bmi, calories, bmr, idealBodyWeight, bodyFat, crabsProteinFat, ovulation, deliveryDueDate, bloodSugar, bloodCholesterol, triglycerides } +enum HealthCalculatorsTypeEnum { + bmi, + calories, + bmr, + idealBodyWeight, + bodyFat, + crabsProteinFat, + ovulation, + deliveryDueDate, + bloodSugar, + bloodCholesterol, + triglycerides +} extension HealthCalculatorExtenshion on HealthCalculatorsTypeEnum { String get displayName { @@ -297,3 +309,152 @@ extension ServiceTypeEnumExt on ServiceTypeEnum { // SymptomsChecker enum PossibleConditionsSeverityEnum { seekMedicalAdvice, monitorOnly, emergency } + +enum HealthTrackerTypeEnum { bloodSugar, bloodPressure, weightTracker } + +// Severity Enum +enum SeverityEnum { mild, moderate, severe } + +extension SeverityEnumExtension on SeverityEnum { + int get toInt { + switch (this) { + case SeverityEnum.mild: + return 0; + case SeverityEnum.moderate: + return 1; + case SeverityEnum.severe: + return 2; + } + } + + String get displayName { + AppState appState = getIt.get(); + bool isArabic = appState.getLanguageID() == 1 ? true : false; + switch (this) { + case SeverityEnum.mild: + return isArabic ? 'خفيف' : 'Mild'; + case SeverityEnum.moderate: + return isArabic ? 'متوسط' : 'Moderate'; + case SeverityEnum.severe: + return isArabic ? 'شديد' : 'Severe'; + } + } + + static SeverityEnum? fromInt(int value) { + switch (value) { + case 0: + return SeverityEnum.mild; + case 1: + return SeverityEnum.moderate; + case 2: + return SeverityEnum.severe; + default: + return null; + } + } +} + +// Triage Level Enum +enum TriageLevelEnum { emergencyAmbulance, emergency, consultation24, consultation, selfCare } + +extension TriageLevelEnumExtension on TriageLevelEnum { + int get toInt { + switch (this) { + case TriageLevelEnum.emergencyAmbulance: + return 0; + case TriageLevelEnum.emergency: + return 1; + case TriageLevelEnum.consultation24: + return 2; + case TriageLevelEnum.consultation: + return 3; + case TriageLevelEnum.selfCare: + return 4; + } + } + + String get displayName { + AppState appState = getIt.get(); + bool isArabic = appState.getLanguageID() == 1 ? true : false; + switch (this) { + case TriageLevelEnum.emergencyAmbulance: + return isArabic ? 'طوارئ - إسعاف' : 'Emergency - Ambulance'; + case TriageLevelEnum.emergency: + return isArabic ? 'طوارئ' : 'Emergency'; + case TriageLevelEnum.consultation24: + return isArabic ? 'استشارة خلال 24 ساعة' : 'Consultation within 24 hours'; + case TriageLevelEnum.consultation: + return isArabic ? 'استشارة' : 'Consultation'; + case TriageLevelEnum.selfCare: + return isArabic ? 'رعاية ذاتية' : 'Self Care'; + } + } + + static TriageLevelEnum? fromInt(int value) { + switch (value) { + case 0: + return TriageLevelEnum.emergencyAmbulance; + case 1: + return TriageLevelEnum.emergency; + case 2: + return TriageLevelEnum.consultation24; + case 3: + return TriageLevelEnum.consultation; + case 4: + return TriageLevelEnum.selfCare; + default: + return null; + } + } +} + +// Question Type Enum +enum QuestionTypeEnum { single, groupSingle, groupMultiple, duration } + +extension QuestionTypeEnumExtension on QuestionTypeEnum { + int get toInt { + switch (this) { + case QuestionTypeEnum.single: + return 0; + case QuestionTypeEnum.groupSingle: + return 1; + case QuestionTypeEnum.groupMultiple: + return 2; + case QuestionTypeEnum.duration: + return 3; + } + } + + String get displayName { + AppState appState = getIt.get(); + bool isArabic = appState.getLanguageID() == 1 ? true : false; + switch (this) { + case QuestionTypeEnum.single: + return isArabic ? 'سؤال واحد' : 'Single'; + case QuestionTypeEnum.groupSingle: + return isArabic ? 'مجموعة - اختيار واحد' : 'Group Single'; + case QuestionTypeEnum.groupMultiple: + return isArabic ? 'مجموعة - اختيار متعدد' : 'Group Multiple'; + case QuestionTypeEnum.duration: + return isArabic ? 'المدة' : 'Duration'; + } + } + + static QuestionTypeEnum? fromInt(int value) { + switch (value) { + case 0: + return QuestionTypeEnum.single; + case 1: + return QuestionTypeEnum.groupSingle; + case 2: + return QuestionTypeEnum.groupMultiple; + case 3: + return QuestionTypeEnum.duration; + default: + return null; + } + } +} + + + diff --git a/lib/core/location_util.dart b/lib/core/location_util.dart index 9dcdbb5..cf26d24 100644 --- a/lib/core/location_util.dart +++ b/lib/core/location_util.dart @@ -104,7 +104,7 @@ class LocationUtils { title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!), navigationService.navigatorKey.currentContext!, child: Utils.getWarningWidget( - loadingText: "Please grant location permission from app settings to see better results".needTranslation, + loadingText: "Please grant location permission from app settings to see better results", isShowActionButtons: true, onCancelTap: () { navigationService.pop(); @@ -265,7 +265,7 @@ class LocationUtils { title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!), navigationService.navigatorKey.currentContext!, child: Utils.getWarningWidget( - loadingText: "Please grant location permission from app settings to see better results".needTranslation, + loadingText: "Please grant location permission from app settings to see better results", isShowActionButtons: true, onCancelTap: () { navigationService.pop(); diff --git a/lib/core/utils/calendar_utils.dart b/lib/core/utils/calendar_utils.dart new file mode 100644 index 0000000..8b21111 --- /dev/null +++ b/lib/core/utils/calendar_utils.dart @@ -0,0 +1,316 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui'; + +import 'package:device_calendar/device_calendar.dart'; +import 'package:flutter/widgets.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_reminder_view.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; +import 'package:hmg_patient_app_new/services/permission_service.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:jiffy/jiffy.dart'; +import 'package:manage_calendar_events/manage_calendar_events.dart' as ios; +import 'package:permission_handler/permission_handler.dart'; +import 'package:timezone/data/latest.dart' as tzl; + +final DeviceCalendarPlugin deviceCalendarPlugin = DeviceCalendarPlugin(); +final ios.CalendarPlugin _myPlugin = ios.CalendarPlugin(); + +class CalendarUtils { + static Completer? _completer; + + dynamic get writableCalendars => calendars.firstWhere((c) => !c.isReadOnly!); + dynamic calendars; + + CalendarUtils._(this.calendars); + + // static Future getInstance() async { + // if (_completer == null) { + // _completer = Completer(); + // print(_completer!.isCompleted); + // try { + // final dynamic calendarsResult; + // if (Platform.isIOS) { + // calendarsResult = await _myPlugin.getCalendars(); + // if (!_completer!.isCompleted) { + // _completer?.complete(CalendarUtils._(await calendarsResult!)); + // } + // } else { + // calendarsResult = await deviceCalendarPlugin.retrieveCalendars(); + // if (!_completer!.isCompleted) { + // _completer?.complete(CalendarUtils._(await calendarsResult.data!)); + // } + // } + // } on Exception catch (e) { + // if (!_completer!.isCompleted) { + // _completer!.completeError(e); + // } + // } + // } + // return _completer!.future; + // } + + static Future getInstance() async { + tzl.initializeTimeZones(); + if (_completer != null) { + return _completer!.future; + } + _completer = Completer(); + try { + final dynamic calendarsResult; + if (Platform.isIOS) { + calendarsResult = await _myPlugin.getCalendars(); + _completer!.complete(CalendarUtils._(calendarsResult)); + } else { + calendarsResult = await deviceCalendarPlugin.retrieveCalendars(); + _completer!.complete(CalendarUtils._(calendarsResult.data)); + } + } catch (e) { + _completer!.completeError(e); + } + + return _completer!.future; + } + + Future createOrUpdateEvents({List? scheduleList, String? title, String? description, List? scheduleDateTime, List? daysOfWeek}) async { + tzl.initializeTimeZones(); + List events = []; + Location _currentLocation; + if (DateTime.now().timeZoneName == "+04") + _currentLocation = getLocation('Asia/Dubai'); + else + _currentLocation = getLocation('Asia/Riyadh'); + + scheduleDateTime!.forEach((element) { + RecurrenceRule recurrenceRule = RecurrenceRule( + // RecurrenceFrequency.Daily, + // daysOfWeek: daysOfWeek, + // endDate: element, + until: element, frequency: Frequency.daily, + ); + //added byAamir Tz Time + Event event = Event(writableCalendars!.id, + recurrenceRule: recurrenceRule, + start: TZDateTime.from(element, _currentLocation), + end: TZDateTime.from(element.add(Duration(minutes: 30)), _currentLocation), + title: title, + description: description); + events.add(event); + }); + + events.forEach((element) { + deviceCalendarPlugin.createOrUpdateEvent(element); + }); + } + + Future createOrUpdateEvent({required String title, required String description, required String location, DateTime? scheduleDateTime, String? eventId}) async { + RecurrenceRule recurrenceRule = RecurrenceRule( + // RecurrenceFrequency.Daily, + // daysOfWeek: daysOfWeek, + // endDate: scheduleDateTime, + until: scheduleDateTime, frequency: Frequency.daily, + ); + + Location _currentLocation; + // if (DateTime.now().timeZoneName == "+04") + // _currentLocation = getLocation('Asia/Dubai'); + // else + _currentLocation = getLocation('Asia/Riyadh'); + + TZDateTime scheduleDateTimeUTZ = TZDateTime.from(scheduleDateTime!, _currentLocation); + + print("writableCalendars-name: " + writableCalendars.name); + print("writableCalendars-Id: " + writableCalendars.id); + print("writableCalendarsToString: " + writableCalendars.toString()); + print("writableCalendarsToString: " + writableCalendars!.id!); + Event event = Event( + writableCalendars!.id, + start: scheduleDateTimeUTZ, + end: scheduleDateTimeUTZ.add(Duration(minutes: 30)), + title: title, + description: description, + ); + + ios.CalendarEvent iosCalEvent = + ios.CalendarEvent(location: location, startDate: scheduleDateTimeUTZ, endDate: scheduleDateTimeUTZ.add(Duration(minutes: 30)), title: title, description: description, isAllDay: false); + + if (Platform.isAndroid) { + Result result = await deviceCalendarPlugin.hasPermissions(); + print(result); + await deviceCalendarPlugin.createOrUpdateEvent(event).catchError((e) { + print("catchError " + e.toString()); + }).whenComplete(() { + print("whenComplete Calender ID " + eventId!); + }); + } else { + await _myPlugin.createEvent(calendarId: writableCalendars.id!, event: iosCalEvent).catchError((e) { + print("catchError " + e.toString()); + }).whenComplete(() { + print("whenComplete Calender ID iOS " + eventId!); + }); + } + } + + deleteEvent(String _calendarId, String _eventId) async { + if (Platform.isIOS) { + await _myPlugin.deleteEvent(calendarId: _calendarId, eventId: _eventId); + } else { + await deviceCalendarPlugin.deleteEvent(_calendarId, _eventId); + } + } + + Future retrieveEvents( + String calendarId, + RetrieveEventsParams retrieveEventsParams, + ) async { + if (Platform.isIOS) { + return await _myPlugin.getEvents(calendarId: calendarId); + } else { + return await deviceCalendarPlugin.retrieveEvents(calendarId, retrieveEventsParams); + } + } + + Future createCalendar( + String calendarName, { + Color? calendarColor, + String? localAccountName, + }) async { + return await deviceCalendarPlugin.createCalendar(calendarName, calendarColor: calendarColor, localAccountName: localAccountName); + } +} + +Future> requestPermissions() async { + var permissionResults = [Permission.calendarFullAccess].request(); + return permissionResults; +} + +showReminderBottomSheet(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted, + {required Function() onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool isMultiAllowed = false}) async { + if (Platform.isAndroid) { + if (await PermissionService.isCalendarPermissionEnabled()) { + _showReminderBottomSheet(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted, + onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed); + } else { + // Utils.showPermissionConsentDialog(context, TranslationBase.of(context).calendarPermission, () async { + // if (await Permission.calendarFullAccess.request().isGranted) { + // _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted, + // onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed); + // } + // }); + } + } else { + if (await Permission.calendarWriteOnly.request().isGranted) { + if (await Permission.calendarFullAccess.request().isGranted) { + _showReminderBottomSheet(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted, + onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed); + } + } + } +} + +Future _showReminderBottomSheet(BuildContext providedContext, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted, + {required Function onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool? isMultiAllowed}) async { + showCommonBottomSheetWithoutHeight(providedContext, title: "Set the timer of reminder", child: PrescriptionReminderView( + setReminder: (int value) async { + if (!isMultiAllowed!) { + if (onMultiDateSuccess == null) { + CalendarUtils calendarUtils = await CalendarUtils.getInstance(); + await calendarUtils.createOrUpdateEvent( + title: title ?? "You have appointment with Dr. $doctorName", + description: description ?? "At $appoDateFormatted $appoTimeFormatted", + scheduleDateTime: dateTime, + eventId: eventId, + location: ''); + onSuccess(); + } + } else { + onMultiDateSuccess!(value); + } + }, + ), callBackFunc: () {}, isFullScreen: false); +} + +setCalender(BuildContext context, + {required String eventId, required int selectedMinutes, int? frequencyNumber, required int days, required String orderDate, required String itemDescriptionN, required String route}) async { + DateTime actualDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 8, 0); + frequencyNumber ??= 2; //Some time frequency number is null so by default will be 2 + + int remainingDays = days - (Jiffy.parseFromDateTime(DateTime.now()).diff(Jiffy.parseFromDateTime(DateUtil.convertStringToDate(orderDate)), unit: Unit.day) as int); + if (remainingDays.isNegative) { + getIt.get().showErrorBottomSheet(message: "Prescription date has been already passed you can not add a reminder for this prescription."); + return; + } + CalendarUtils calendarUtils = await CalendarUtils.getInstance(); + + try { + for (int i = 0; i < remainingDays; i++) { + //event for number of days. + for (int j = 0; j < frequencyNumber; j++) { + // event for number of times per day. + if (j != 0) { + actualDate.add(new Duration(hours: 8)); // 8 hours addition for daily dose. + } + //Time subtraction from actual reminder time. like before 30, or 1 hour. + + actualDate = Jiffy.parseFromDateTime(actualDate).subtract(minutes: selectedMinutes).dateTime; + + calendarUtils.createOrUpdateEvent( + title: "$itemDescriptionN} Prescription Reminder", + description: "$itemDescriptionN $frequencyNumber $route ", + scheduleDateTime: actualDate, + eventId: eventId + (i.toString() + j.toString()), + location: '', //event id with varitions + ); + print("Creating event #$j for day $i → $actualDate"); + actualDate = DateTime(actualDate.year, actualDate.month, actualDate.day, 8, 0); + } + actualDate = Jiffy.parseFromDateTime(actualDate).add(days: 1).dateTime; + } + } catch (ex) { + getIt.get().showErrorBottomSheet(message: "catch:$ex"); + } +} + +Future checkAndRemove(hasReminder, {bool delete = false, String itemDescriptionN = ""}) async { + final ios.CalendarPlugin _myPlugin = ios.CalendarPlugin(); + CalendarUtils calendarUtils = await CalendarUtils.getInstance(); + DateTime startEventsDate = Jiffy.parseFromDateTime(DateTime.now()).subtract(days: 30).dateTime; + DateTime endEventsDate = Jiffy.parseFromDateTime(DateTime.now()).add(days: 120).dateTime; + RetrieveEventsParams params = RetrieveEventsParams(startDate: startEventsDate, endDate: endEventsDate); + + if (calendarUtils.calendars != null) { + if (Platform.isAndroid) { + await processEvents(calendarUtils.calendars, calendarUtils, params, delete, itemDescriptionN, hasReminder); + } else { + List? iosCalendars = await _myPlugin.getCalendars(); + if (iosCalendars != null) { + await processEvents(iosCalendars.map((cal) => Calendar(id: cal.id, name: cal.name, accountName: cal.accountName)).toList(), calendarUtils, params, delete, itemDescriptionN, hasReminder); + } + } + } +} + +Future processEvents(List calendars, calendarUtils, params, delete, String itemDescriptionN, hasReminder) async { + for (var calendar in calendars) { + Result> events = await calendarUtils.retrieveEvents(calendar.id!, params); + for (var event in events.data!) { + if (event.title!.contains(itemDescriptionN)) { + if (delete) { + await calendarUtils.deleteEvent(calendar, event); + // AppToast.showSuccessToast(message: TranslationBase.of(context).reminderCancelSuccess); + hasReminder = false; + } else { + hasReminder = false; + // setState(() { + // hasReminder = true; + // }); + } + } + } + } +} diff --git a/lib/core/utils/calender_utils_new.dart b/lib/core/utils/calender_utils_new.dart index c411fe6..6696551 100644 --- a/lib/core/utils/calender_utils_new.dart +++ b/lib/core/utils/calender_utils_new.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:device_calendar_plus/device_calendar_plus.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:jiffy/jiffy.dart' show Jiffy; +import 'package:manage_calendar_events/manage_calendar_events.dart' hide Calendar; class CalenderUtilsNew { final DeviceCalendar calender = DeviceCalendar.instance; diff --git a/lib/core/utils/size_utils.dart b/lib/core/utils/size_utils.dart index 4fdc09c..d04ad70 100644 --- a/lib/core/utils/size_utils.dart +++ b/lib/core/utils/size_utils.dart @@ -4,19 +4,20 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; // These are the Viewport values of your Figma Design. // These are used in the code as a reference to create your UI Responsively. -const num figmaDesignWidth = 375; // iPhone X / 12 base width -const num figmaDesignHeight = 812; // iPhone X / 12 base height +const num figmaDesignWidth = 430; // iPhone X / 12 base width, 375 +const num figmaDesignHeight = 927; // iPhone X / 12 base height 812 +const num figmaDesignWidthTF = 375; +const num figmaDesignHeightTF = 812; extension ConstrainedResponsive on num { /// Width with max cap for tablets - double get wCapped => isTablet ? math.min( w, this * 1.3) : w; + double get wCapped => isTablet ? math.min(w, this * 1.3) : w; /// Height with max cap for tablets double get hCapped => isTablet ? math.min(h, this * 1.3) : h; } - extension ResponsiveExtension on num { double get _screenWidth => SizeUtils.width; @@ -52,9 +53,9 @@ extension ResponsiveExtension on num { double get w { double baseScale = (this * _screenWidth) / figmaDesignWidth; - if (_isFoldable) { + if (_isFoldable|| isTablet ) { // For foldables, use more conservative width scaling - double scale = _screenWidth / figmaDesignWidth; + double scale = _screenWidth / figmaDesignWidthTF; scale = scale.clamp(0.8, 1.4); return this * scale; } @@ -66,9 +67,9 @@ extension ResponsiveExtension on num { double get h { double baseScale = (this * _screenHeight) / figmaDesignHeight; - if (_isFoldable) { + if (_isFoldable || isTablet ) { // For foldables, use height-based scaling but with constraints - double scale = (_screenHeight / figmaDesignHeight).clamp(0.8, 1.4); + double scale = (_screenHeight / figmaDesignHeightTF).clamp(0.8, 1.4); return this * scale; } @@ -81,7 +82,7 @@ extension ResponsiveExtension on num { if (_isFoldable || isTablet) { // Use the same logic as enhanced width for foldables - double scale = _screenWidth / figmaDesignWidth; + double scale = _screenWidth / figmaDesignWidthTF; scale = scale.clamp(0.8, 1.4); return this * scale; } diff --git a/lib/core/utils/utils.dart b/lib/core/utils/utils.dart index 03ff6b5..10d3767 100644 --- a/lib/core/utils/utils.dart +++ b/lib/core/utils/utils.dart @@ -43,7 +43,7 @@ class Utils { { "Desciption": "Sahafa Hospital", "DesciptionN": "مستشفى الصحافة", - "ID": 1, + "ID": 1, // Campus ID "LegalName": "Sahafa Hospital", "LegalNameN": "مستشفى الصحافة", "Name": "Sahafa Hospital", @@ -55,19 +55,20 @@ class Utils { "IsActive": true, "IsHmg": true, "IsVidaPlus": false, - "Latitude": "24.8113774", - "Longitude": "46.6239813", + "Latitude": "24.8111548", + "Longitude": "46.6217912", "MainProjectID": 130, "ProjectOutSA": false, - "UsingInDoctorApp": false + "UsingInDoctorApp": false, + "IsHMC": false },{ - "Desciption": "Jeddah Hospital", - "DesciptionN": "مستشفى الصحافة", - "ID": 3, - "LegalName": "Jeddah Hospital", - "LegalNameN": "مستشفى الصحافة", - "Name": "Jeddah Hospital", - "NameN": "مستشفى الصحافة", + "Desciption": "Jeddah Fayhaa Hospital", + "DesciptionN": "مستشفى جدة الفيحاء", + "ID": 3, // Campus ID + "LegalName": "Jeddah Fayhaa Hospital", + "LegalNameN": "مستشفى جدة الفيحاء", + "Name": "Jeddah Fayhaa Hospital", + "NameN": "مستشفى جدة الفيحاء", "PhoneNumber": "+966115222222", "SetupID": "013311", "DistanceInKilometers": 0, @@ -75,11 +76,12 @@ class Utils { "IsActive": true, "IsHmg": true, "IsVidaPlus": false, - "Latitude": "24.8113774", - "Longitude": "46.6239813", + "Latitude": "21.5086703", + "Longitude": "39.2121855", "MainProjectID": 130, "ProjectOutSA": false, - "UsingInDoctorApp": false + "UsingInDoctorApp": false, + "IsHMC": false } ]; @@ -262,16 +264,6 @@ class Utils { return await prefs.remove(key); } - static void showLoading({bool isNeedBinding = true}) { - if (isNeedBinding) { - WidgetsBinding.instance.addPostFrameCallback((_) { - showLoadingDialog(); - }); - } else { - showLoadingDialog(); - } - } - static void showLoadingDialog() { _isLoadingVisible = true; showDialog( @@ -288,18 +280,6 @@ class Utils { ); } - static void hideLoading() { - try { - if (_isLoadingVisible) { - _isLoadingVisible = false; - Navigator.of(navigationService.navigatorKey.currentContext!).pop(); - } - _isLoadingVisible = false; - } catch (e) { - log("errr: ${e.toString()}"); - } - } - static List uniqueBy(List list, K Function(T) keySelector) { final seenKeys = {}; return list.where((item) => seenKeys.add(keySelector(item))).toList(); @@ -387,7 +367,7 @@ class Utils { crossAxisAlignment: CrossAxisAlignment.center, children: [ Lottie.asset(AppAnimations.loadingAnimation, - repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), + repeat: true, reverse: false, frameRate: FrameRate(60), width: 80.h, height: 80.h, fit: BoxFit.fill), SizedBox(height: 8.h), (loadingText ?? LocaleKeys.loadingText.tr()).toText16(color: AppColors.blackColor, isCenter: true), SizedBox(height: 8.h), @@ -834,11 +814,13 @@ class Utils { child: Utils.buildSvgWithAssets(icon: AppAssets.saudi_riyal_icon, width: iconSize.h, height: iconSize.h, iconColor: iconColor), ), TextSpan( - text: NumberFormat.currency(locale: 'en_US', symbol: " ", decimalDigits: 0).format(habibWalletAmount), + // text: NumberFormat.currency(locale: 'en_US', symbol: " ", decimalDigits: 0).format(habibWalletAmount), + text: " ${habibWalletAmount.toStringAsFixed(2)}", style: TextStyle( color: textColor, fontSize: fontSize ?? 32.f, letterSpacing: letterSpacing ?? -4, + fontFamily: "Poppins", fontWeight: fontWeight ?? FontWeight.w600, height: 1), ), @@ -979,11 +961,11 @@ class Utils { static String getCardButtonText(int currentQueueStatus, String roomNumber) { switch (currentQueueStatus) { case 0: - return "Please wait! you will be called for vital signs".needTranslation; + return LocaleKeys.pleaseWaitYouWillBeCalledForVitalSigns.tr(); case 1: - return "Please visit Room $roomNumber for vital signs".needTranslation; + return LocaleKeys.pleaseVisitRoomForVitalSigns.tr(namedArgs: {'roomNumber': roomNumber.toString()}); case 2: - return "Please visit Room $roomNumber to the Doctor".needTranslation; + return LocaleKeys.pleaseVisitRoomToTheDoctor.tr(namedArgs: {'roomNumber': roomNumber.toString()}); } return ""; } diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 309dde1..30b0f7e 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -62,6 +62,31 @@ extension EmailValidator on String { decorationColor: color ?? AppColors.blackColor), ); + Widget toText9( + {Color? color, + FontWeight? weight, + bool isBold = false, + bool isUnderLine = false, + bool isCenter = false, + int? maxlines, + FontStyle? fontStyle, + TextOverflow? textOverflow, + double letterSpacing = 0}) => + Text( + this, + textAlign: isCenter ? TextAlign.center : null, + maxLines: maxlines, + overflow: textOverflow, + style: TextStyle( + fontSize: 9.f, + fontStyle: fontStyle ?? FontStyle.normal, + fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal), + color: color ?? AppColors.blackColor, + letterSpacing: letterSpacing, + decoration: isUnderLine ? TextDecoration.underline : null, + decorationColor: color ?? AppColors.blackColor), + ); + Widget toText11( {Color? color, FontWeight? weight, @@ -92,6 +117,7 @@ extension EmailValidator on String { FontWeight? fontWeight, bool isCenter = false, double? height, + double? letterSpacing, int maxLine = 0}) => Text( this, @@ -101,7 +127,7 @@ extension EmailValidator on String { fontSize: 12.f, fontWeight: fontWeight ?? (isBold ? FontWeight.bold : FontWeight.normal), color: color ?? AppColors.blackColor, - letterSpacing: 0, + letterSpacing: letterSpacing ?? 0, height: height, decorationColor: isUnderLine ? AppColors.blackColor : null, decoration: isUnderLine ? TextDecoration.underline : null, diff --git a/lib/features/active_prescriptions/active_prescriptions_repo.dart b/lib/features/active_prescriptions/active_prescriptions_repo.dart new file mode 100644 index 0000000..437f364 --- /dev/null +++ b/lib/features/active_prescriptions/active_prescriptions_repo.dart @@ -0,0 +1,65 @@ + + +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/models/active_prescriptions_response_model.dart'; +import '../../core/api/api_client.dart'; +import '../../core/api_consts.dart'; +import '../../core/common_models/generic_api_model.dart'; +import '../../core/exceptions/api_failure.dart'; +import '../../services/logger_service.dart'; + +abstract class ActivePrescriptionsRepo { + + Future>>> getActivePrescriptionsDetails(); + +} + +class ActivePrescriptionsRepoImp implements ActivePrescriptionsRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + ActivePrescriptionsRepoImp({required this.loggerService, required this.apiClient}); + + @override + + Future>>> getActivePrescriptionsDetails() async + { + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getActivePrescriptionsDetails, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + var list = response['List_ActiveGetPrescriptionReportByPatientID']; + var res = list + .map( + (item) => ActivePrescriptionsResponseModel.fromJson(item)) + .toList(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + // data: response, + data: res + ); + return apiResponse; + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + +} \ No newline at end of file diff --git a/lib/features/active_prescriptions/active_prescriptions_view_model.dart b/lib/features/active_prescriptions/active_prescriptions_view_model.dart new file mode 100644 index 0000000..e4da04d --- /dev/null +++ b/lib/features/active_prescriptions/active_prescriptions_view_model.dart @@ -0,0 +1,101 @@ + +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/models/active_prescriptions_response_model.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/active_prescriptions_repo.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; + +class ActivePrescriptionsViewModel extends ChangeNotifier { + late ActivePrescriptionsRepo activePrescriptionsRepo; + late ErrorHandlerService errorHandlerService; + List activePrescriptionsDetailsList = []; + + ActivePrescriptionsViewModel({ + required this.activePrescriptionsRepo, + required this.errorHandlerService, + }); + + Future getActiveMedications({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + final result = + await activePrescriptionsRepo.getActivePrescriptionsDetails(); + result.fold( + (failure) async => + await errorHandlerService.handleError(failure: failure), + (apiResponse) { + if (apiResponse.messageStatus == 1) { + activePrescriptionsDetailsList = apiResponse.data ?? []; + notifyListeners(); + if (onSuccess != null) onSuccess(apiResponse.data); + } + }, + ); + } + + DateTime parseDate(String? date) { + if (date == null) return DateTime.now(); + final regex = RegExp(r"\/Date\((\d+)([+-]\d+)?\)\/"); + final match = regex.firstMatch(date); + if (match != null) { + final millis = int.parse(match.group(1)!); + return DateTime.fromMillisecondsSinceEpoch(millis); + } + return DateTime.tryParse(date) ?? DateTime.now(); + } + + List generateMedicationDays(ActivePrescriptionsResponseModel med) { + final start = parseDate(med.startDate); + final duration = med.days ?? 0; + if (duration <= 0) return []; + final f = (med.frequency ?? "").toLowerCase().trim(); + int intervalDays = 1; + + if (f.contains("every six hours") || + f.contains("every 6 hours") || + f.contains("every four hours") || + f.contains("every 4 hours") || + f.contains("every eight hours") || + f.contains("every 8 hours") || + f.contains("every 12 hours") || + f.contains("every twelve hours") || + f.contains("every 24 hours") || + f.contains("3 times a day") || + f.contains("once a day")) { + intervalDays = 1; + } + else if (f.contains("once a week")) { + intervalDays = 7; + } + else if (f.contains("every 3 days")) { + intervalDays = 3; + } + else if (f.contains("every other day")) { + intervalDays = 2; + } + + List result = []; + for (int offset = 0; offset < duration; offset += intervalDays) { + result.add(start.add(Duration(days: offset))); + } + + return result; + } + + bool sameYMD(DateTime a, DateTime b) => + a.year == b.year && a.month == b.month && a.day == b.day; + + List getMedsForSelectedDay( + DateTime selectedDate) { + final clean = DateTime(selectedDate.year, selectedDate.month, selectedDate.day); + + return activePrescriptionsDetailsList.where((med) { + final days = generateMedicationDays(med); + return days.any((d) => sameYMD(d, clean)); + }).toList(); + } +} + + + + diff --git a/lib/features/active_prescriptions/models/active_prescriptions_response_model.dart b/lib/features/active_prescriptions/models/active_prescriptions_response_model.dart new file mode 100644 index 0000000..dc859a9 --- /dev/null +++ b/lib/features/active_prescriptions/models/active_prescriptions_response_model.dart @@ -0,0 +1,78 @@ + +class ActivePrescriptionsResponseModel { + String? itemId; + String? itemDescription; + String? route; + String? frequency; + int? frequencyNumber; + int? doseDailyQuantity; + int? days; + String? startDate; + String? endDate; + String? orderDate; + String? productImageString; + bool isReminderOn; + List selectedDoseTimes = []; + + ActivePrescriptionsResponseModel({ + this.itemId, + this.itemDescription, + this.route, + this.frequency, + this.frequencyNumber, + this.doseDailyQuantity, + this.days, + this.startDate, + this.endDate, + this.orderDate, + this.productImageString, + this.isReminderOn = false, + List? selectedDoseTimes, + }) { + this.selectedDoseTimes = selectedDoseTimes ?? []; + } + + /// ========== JSON FROM ========== + factory ActivePrescriptionsResponseModel.fromJson(Map json) { + return ActivePrescriptionsResponseModel( + itemId: json["ItemID"]?.toString() ?? "", + itemDescription: json["ItemDescription"] ?? "", + route: json["Route"] ?? "", + frequency: json["Frequency"] ?? "", + frequencyNumber: json["FrequencyNumber"], + doseDailyQuantity: json["DoseDailyQuantity"] ?? 1, + days: json["Days"] ?? 0, + startDate: json["StartDate"] ?? "", + endDate: json["EndDate"] ?? "", + orderDate: json["OrderDate"] ?? "", + productImageString: json["ProductImageString"] ?? "", + isReminderOn: json["IsReminderOn"] == true, + selectedDoseTimes: + (json["SelectedDoseTimes"] as List?) + ?.map((e) => e?.toString()) + .toList() ?? + [], + ); + } + + + + /// ========== JSON TO ========== + Map toJson() { + return { + "ItemID": itemId, + "ItemDescription": itemDescription, + "Route": route, + "Frequency": frequency, + "FrequencyNumber": frequencyNumber, + "DoseDailyQuantity": doseDailyQuantity, + "Days": days, + "StartDate": startDate, + "EndDate": endDate, + "OrderDate": orderDate, + "ProductImageString": productImageString, + "IsReminderOn": isReminderOn, + "SelectedDoseTimes": selectedDoseTimes, + }; + } +} diff --git a/lib/features/ask_doctor/ask_doctor_repo.dart b/lib/features/ask_doctor/ask_doctor_repo.dart new file mode 100644 index 0000000..4e4a400 --- /dev/null +++ b/lib/features/ask_doctor/ask_doctor_repo.dart @@ -0,0 +1,128 @@ +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/core/api/api_client.dart'; +import 'package:hmg_patient_app_new/core/api_consts.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; +import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/ask_doctor_appointments_list.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/doctor_response_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/ask_doctor_request_type_response_model.dart'; +import 'package:hmg_patient_app_new/services/logger_service.dart'; + +abstract class AskDoctorRepo { + Future>>> getAskDoctorAppointmentsList(); + + Future>>> getDoctorResponse({ + required String fromDate, + }); +} + +class AskDoctorRepoImp implements AskDoctorRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + AskDoctorRepoImp({ + required this.loggerService, + required this.apiClient, + }); + + @override + Future>>> getAskDoctorAppointmentsList() async { + Map mapDevice = { + "Top": 25, + "beforeDays": 15, + "exludType": 4, + }; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + IS_ALLOW_ASK_DOCTOR, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final list = response['PatientDoctorAppointmentResultList']; + + final clinicsList = list.map((item) => AskDoctorAppointmentHistoryList.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: clinicsList, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> getDoctorResponse({ + required String fromDate, + }) async { + Map mapDevice = { + "isDentalAllowedBackend": false, + "from": fromDate, + }; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + GET_DOCTOR_RESPONSE, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final list = response['List_DoctorResponse']; + + if (list == null || list.isEmpty) { + // Return empty list if no responses + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: [], + ); + return; + } + + final doctorResponsesList = list + .map((item) => DoctorResponseModel.fromJson(item as Map)) + .toList() + .cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: doctorResponsesList, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + loggerService.logError("AskDoctorRepo.getDoctorResponse error: $e"); + return Left(UnknownFailure(e.toString())); + } + } +} diff --git a/lib/features/ask_doctor/ask_doctor_view_model.dart b/lib/features/ask_doctor/ask_doctor_view_model.dart new file mode 100644 index 0000000..2b9600e --- /dev/null +++ b/lib/features/ask_doctor/ask_doctor_view_model.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_repo.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/ask_doctor_appointments_list.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/doctor_response_model.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; + +class AskDoctorViewModel extends ChangeNotifier { + final AskDoctorRepo askDoctorRepo; + final ErrorHandlerService errorHandlerService; + + AskDoctorViewModel({ + required this.askDoctorRepo, + required this.errorHandlerService, + }); + + bool isAskDoctorAppointmentsLoading = false; + bool isDoctorResponsesLoading = false; + + List askDoctorAppointmentsList = []; + List doctorResponsesList = []; + + /// Initialize the view model + void initAskDoctorViewModel() { + askDoctorAppointmentsList.clear(); + doctorResponsesList.clear(); + isAskDoctorAppointmentsLoading = true; + getAskDoctorAppointmentsList(); + notifyListeners(); + } + + Future getAskDoctorAppointmentsList({Function(dynamic)? onSuccess, Function(String)? onError}) async { + final result = await askDoctorRepo.getAskDoctorAppointmentsList(); + + result.fold( + (failure) async => await errorHandlerService.handleError(failure: failure), + (apiResponse) { + if (apiResponse.messageStatus == 2) { + // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); + } else if (apiResponse.messageStatus == 1) { + askDoctorAppointmentsList = apiResponse.data!; + isAskDoctorAppointmentsLoading = false; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } + + /// Get doctor responses from a specific date + Future getDoctorResponses({ + String? fromDate, + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + isDoctorResponsesLoading = true; + notifyListeners(); + + // If no date provided, use current date minus 30 days + final dateToUse = "${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day} ${DateTime.now().hour}:${DateTime.now().minute}:00"; + + final result = await askDoctorRepo.getDoctorResponse(fromDate: dateToUse); + + result.fold( + (failure) async { + isDoctorResponsesLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isDoctorResponsesLoading = false; + + if (apiResponse.messageStatus == 2) { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? "Unknown error"); + } + } else if (apiResponse.messageStatus == 1) { + doctorResponsesList = apiResponse.data ?? []; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } +} diff --git a/lib/features/ask_doctor/models/ask_doctor_appointments_list.dart b/lib/features/ask_doctor/models/ask_doctor_appointments_list.dart new file mode 100644 index 0000000..7f40d71 --- /dev/null +++ b/lib/features/ask_doctor/models/ask_doctor_appointments_list.dart @@ -0,0 +1,200 @@ +class AskDoctorAppointmentHistoryList { + String? setupID; + int? projectID; + int? appointmentNo; + String? appointmentDate; + bool? appointmentType; + String? bookDate; + bool? patientType; + int? patientID; + int? clinicID; + int? doctorID; + String? endDate; + String? startTime; + String? endTime; + bool? status; + bool? visitType; + bool? isReminderActivated; + int? companyID; + String? bookedOn; + String? confirmedOn; + String? arrivedOn; + String? editedOn; + int? appointmentDays; + int? isActive; + int? actualDoctorRate; + String? clinicName; + String? date; + num? decimalDoctorRate; + String? doctorCases; + String? doctorImageURL; + String? doctorInfo; + String? doctorName; + num? doctorRate; + num? doctorStarsRate; + String? doctorTitle; + int? gender; + String? genderDescription; + bool? isActiveDoctorProfile; + bool? isAppointmentAllowed; + bool? isDoctorAllowVedioCall; + bool? isLiveCareClinic; + String? nationalityFlagURL; + String? nationalityID; + String? nationalityName; + int? noOfPatientsRate; + String? projectName; + String? qR; + List? speciality; + + AskDoctorAppointmentHistoryList( + {this.setupID, + this.projectID, + this.appointmentNo, + this.appointmentDate, + this.appointmentType, + this.bookDate, + this.patientType, + this.patientID, + this.clinicID, + this.doctorID, + this.endDate, + this.startTime, + this.endTime, + this.status, + this.visitType, + this.isReminderActivated, + this.companyID, + this.bookedOn, + this.confirmedOn, + this.arrivedOn, + this.editedOn, + this.appointmentDays, + this.isActive, + this.actualDoctorRate, + this.clinicName, + this.date, + this.decimalDoctorRate, + this.doctorCases, + this.doctorImageURL, + this.doctorInfo, + this.doctorName, + this.doctorRate, + this.doctorStarsRate, + this.doctorTitle, + this.gender, + this.genderDescription, + this.isActiveDoctorProfile, + this.isAppointmentAllowed, + this.isDoctorAllowVedioCall, + this.isLiveCareClinic, + this.nationalityFlagURL, + this.nationalityID, + this.nationalityName, + this.noOfPatientsRate, + this.projectName, + this.qR, + this.speciality}); + + AskDoctorAppointmentHistoryList.fromJson(Map json) { + setupID = json['SetupID']; + projectID = json['ProjectID']; + appointmentNo = json['AppointmentNo']; + appointmentDate = json['AppointmentDate']; + appointmentType = json['AppointmentType']; + bookDate = json['BookDate']; + patientType = json['PatientType']; + patientID = json['PatientID']; + clinicID = json['ClinicID']; + doctorID = json['DoctorID']; + endDate = json['EndDate']; + startTime = json['StartTime']; + endTime = json['EndTime']; + status = json['Status']; + visitType = json['VisitType']; + isReminderActivated = json['IsReminderActivated']; + companyID = json['CompanyID']; + bookedOn = json['BookedOn']; + confirmedOn = json['ConfirmedOn']; + arrivedOn = json['ArrivedOn']; + editedOn = json['EditedOn']; + appointmentDays = json['AppointmentDays']; + isActive = json['IsActive']; + actualDoctorRate = json['ActualDoctorRate']; + clinicName = json['ClinicName']; + date = json['Date']; + decimalDoctorRate = json['DecimalDoctorRate']; + doctorCases = json['DoctorCases']; + doctorImageURL = json['DoctorImageURL']; + doctorInfo = json['DoctorInfo']; + doctorName = json['DoctorName']; + doctorRate = json['DoctorRate']; + doctorStarsRate = json['DoctorStarsRate']; + doctorTitle = json['DoctorTitle']; + gender = json['Gender']; + genderDescription = json['GenderDescription']; + isActiveDoctorProfile = json['IsActiveDoctorProfile']; + isAppointmentAllowed = json['IsAppointmentAllowed']; + isDoctorAllowVedioCall = json['IsDoctorAllowVedioCall']; + isLiveCareClinic = json['IsLiveCareClinic']; + nationalityFlagURL = json['NationalityFlagURL']; + nationalityID = json['NationalityID']; + nationalityName = json['NationalityName']; + noOfPatientsRate = json['NoOfPatientsRate']; + projectName = json['ProjectName']; + qR = json['QR']; + speciality = json['Speciality'].cast(); + } + + Map toJson() { + final Map data = new Map(); + data['SetupID'] = this.setupID; + data['ProjectID'] = this.projectID; + data['AppointmentNo'] = this.appointmentNo; + data['AppointmentDate'] = this.appointmentDate; + data['AppointmentType'] = this.appointmentType; + data['BookDate'] = this.bookDate; + data['PatientType'] = this.patientType; + data['PatientID'] = this.patientID; + data['ClinicID'] = this.clinicID; + data['DoctorID'] = this.doctorID; + data['EndDate'] = this.endDate; + data['StartTime'] = this.startTime; + data['EndTime'] = this.endTime; + data['Status'] = this.status; + data['VisitType'] = this.visitType; + data['IsReminderActivated'] = this.isReminderActivated; + data['CompanyID'] = this.companyID; + data['BookedOn'] = this.bookedOn; + data['ConfirmedOn'] = this.confirmedOn; + data['ArrivedOn'] = this.arrivedOn; + data['EditedOn'] = this.editedOn; + data['AppointmentDays'] = this.appointmentDays; + data['IsActive'] = this.isActive; + data['ActualDoctorRate'] = this.actualDoctorRate; + data['ClinicName'] = this.clinicName; + data['Date'] = this.date; + data['DecimalDoctorRate'] = this.decimalDoctorRate; + data['DoctorCases'] = this.doctorCases; + data['DoctorImageURL'] = this.doctorImageURL; + data['DoctorInfo'] = this.doctorInfo; + data['DoctorName'] = this.doctorName; + data['DoctorRate'] = this.doctorRate; + data['DoctorStarsRate'] = this.doctorStarsRate; + data['DoctorTitle'] = this.doctorTitle; + data['Gender'] = this.gender; + data['GenderDescription'] = this.genderDescription; + data['IsActiveDoctorProfile'] = this.isActiveDoctorProfile; + data['IsAppointmentAllowed'] = this.isAppointmentAllowed; + data['IsDoctorAllowVedioCall'] = this.isDoctorAllowVedioCall; + data['IsLiveCareClinic'] = this.isLiveCareClinic; + data['NationalityFlagURL'] = this.nationalityFlagURL; + data['NationalityID'] = this.nationalityID; + data['NationalityName'] = this.nationalityName; + data['NoOfPatientsRate'] = this.noOfPatientsRate; + data['ProjectName'] = this.projectName; + data['QR'] = this.qR; + data['Speciality'] = this.speciality; + return data; + } +} diff --git a/lib/features/ask_doctor/models/doctor_response_model.dart b/lib/features/ask_doctor/models/doctor_response_model.dart new file mode 100644 index 0000000..b44ee0a --- /dev/null +++ b/lib/features/ask_doctor/models/doctor_response_model.dart @@ -0,0 +1,180 @@ +class DoctorResponseModel { + int? projectID; + int? transactionNo; + int? patientID; + int? doctorID; + int? requestType; + String? requestTypeDescription; + dynamic requestTypeDescriptionN; + int? status; + String? remarks; + String? createdOn; + int? readStatus; + String? doctorResponse; + dynamic clinicID; + dynamic clinicName; + int? createdBy; + String? doctorName; + dynamic infoStatusDescription; + bool? isDoctorRespond; + bool? isPatientRead; + dynamic memberName; + dynamic memberNameN; + dynamic patientDateofBirth; + dynamic patientGender; + dynamic patientMobileNumber; + dynamic patientName; + dynamic patientNameN; + dynamic projectName; + dynamic statusDescription; + List? transactions; + + DoctorResponseModel( + {this.projectID, + this.transactionNo, + this.patientID, + this.doctorID, + this.requestType, + this.requestTypeDescription, + this.requestTypeDescriptionN, + this.status, + this.remarks, + this.createdOn, + this.readStatus, + this.doctorResponse, + this.clinicID, + this.clinicName, + this.createdBy, + this.doctorName, + this.infoStatusDescription, + this.isDoctorRespond, + this.isPatientRead, + this.memberName, + this.memberNameN, + this.patientDateofBirth, + this.patientGender, + this.patientMobileNumber, + this.patientName, + this.patientNameN, + this.projectName, + this.statusDescription, + this.transactions}); + + DoctorResponseModel.fromJson(Map json) { + projectID = json['ProjectID']; + transactionNo = json['TransactionNo']; + patientID = json['PatientID']; + doctorID = json['DoctorID']; + requestType = json['RequestType']; + requestTypeDescription = json['RequestTypeDescription']; + requestTypeDescriptionN = json['RequestTypeDescriptionN']; + status = json['Status']; + remarks = json['Remarks']; + createdOn = json['CreatedOn']; + readStatus = json['ReadStatus']; + doctorResponse = json['DoctorResponse']; + clinicID = json['ClinicID']; + clinicName = json['ClinicName']; + createdBy = json['CreatedBy']; + doctorName = json['DoctorName']; + infoStatusDescription = json['InfoStatusDescription']; + isDoctorRespond = json['IsDoctorRespond']; + isPatientRead = json['IsPatientRead']; + memberName = json['MemberName']; + memberNameN = json['MemberNameN']; + patientDateofBirth = json['PatientDateofBirth']; + patientGender = json['PatientGender']; + patientMobileNumber = json['PatientMobileNumber']; + patientName = json['PatientName']; + patientNameN = json['PatientNameN']; + projectName = json['ProjectName']; + statusDescription = json['StatusDescription']; + if (json['Transactions'] != null) { + transactions = []; + json['Transactions'].forEach((v) { + transactions!.add(new Transactions.fromJson(v)); + }); + } + } + + Map toJson() { + final Map data = new Map(); + data['ProjectID'] = this.projectID; + data['TransactionNo'] = this.transactionNo; + data['PatientID'] = this.patientID; + data['DoctorID'] = this.doctorID; + data['RequestType'] = this.requestType; + data['RequestTypeDescription'] = this.requestTypeDescription; + data['RequestTypeDescriptionN'] = this.requestTypeDescriptionN; + data['Status'] = this.status; + data['Remarks'] = this.remarks; + data['CreatedOn'] = this.createdOn; + data['ReadStatus'] = this.readStatus; + data['DoctorResponse'] = this.doctorResponse; + data['ClinicID'] = this.clinicID; + data['ClinicName'] = this.clinicName; + data['CreatedBy'] = this.createdBy; + data['DoctorName'] = this.doctorName; + data['InfoStatusDescription'] = this.infoStatusDescription; + data['IsDoctorRespond'] = this.isDoctorRespond; + data['IsPatientRead'] = this.isPatientRead; + data['MemberName'] = this.memberName; + data['MemberNameN'] = this.memberNameN; + data['PatientDateofBirth'] = this.patientDateofBirth; + data['PatientGender'] = this.patientGender; + data['PatientMobileNumber'] = this.patientMobileNumber; + data['PatientName'] = this.patientName; + data['PatientNameN'] = this.patientNameN; + data['ProjectName'] = this.projectName; + data['StatusDescription'] = this.statusDescription; + if (this.transactions != null) { + data['Transactions'] = this.transactions!.map((v) => v.toJson()).toList(); + } + return data; + } +} + +class Transactions { + int? lineItemNo; + String? doctorResponse; + int? infoEnteredBy; + String? infoEnteredOn; + String? createdOn; + int? infoStatus; + String? infoStatusDescription; + dynamic infoStatusDescriptionN; + + Transactions( + {this.lineItemNo, + this.doctorResponse, + this.infoEnteredBy, + this.infoEnteredOn, + this.createdOn, + this.infoStatus, + this.infoStatusDescription, + this.infoStatusDescriptionN}); + + Transactions.fromJson(Map json) { + lineItemNo = json['LineItemNo']; + doctorResponse = json['DoctorResponse']; + infoEnteredBy = json['InfoEnteredBy']; + infoEnteredOn = json['InfoEnteredOn']; + createdOn = json['CreatedOn']; + infoStatus = json['InfoStatus']; + infoStatusDescription = json['InfoStatusDescription']; + infoStatusDescriptionN = json['InfoStatusDescriptionN']; + } + + Map toJson() { + final Map data = new Map(); + data['LineItemNo'] = this.lineItemNo; + data['DoctorResponse'] = this.doctorResponse; + data['InfoEnteredBy'] = this.infoEnteredBy; + data['InfoEnteredOn'] = this.infoEnteredOn; + data['CreatedOn'] = this.createdOn; + data['InfoStatus'] = this.infoStatus; + data['InfoStatusDescription'] = this.infoStatusDescription; + data['InfoStatusDescriptionN'] = this.infoStatusDescriptionN; + return data; + } +} diff --git a/lib/features/authentication/authentication_view_model.dart b/lib/features/authentication/authentication_view_model.dart index b393772..c49554f 100644 --- a/lib/features/authentication/authentication_view_model.dart +++ b/lib/features/authentication/authentication_view_model.dart @@ -246,7 +246,6 @@ class AuthenticationViewModel extends ChangeNotifier { } Future _handleNewImeiRegistration() async { - await selectDeviceImei(onSuccess: (dynamic respData) async { try { if (respData != null) { @@ -433,6 +432,15 @@ class AuthenticationViewModel extends ChangeNotifier { } else { // TODO: Handle isSMSSent false // navigateToOTPScreen(otpTypeEnum: otpTypeEnum, phoneNumber: phoneNumber); + if (isFormFamilyFile) { + LoaderBottomSheet.hideLoader(); + await _dialogService.showCommonBottomSheetWithoutH( + message: LocaleKeys.unableToSendOTP.tr(), + label: LocaleKeys.notice.tr(), + onOkPressed: () { + _navigationService.pop(); + }); + } } } }, @@ -461,6 +469,12 @@ class AuthenticationViewModel extends ChangeNotifier { bool isForRegister = (_appState.getUserRegistrationPayload.healthId != null || _appState.getUserRegistrationPayload.patientOutSa == true || _appState.getUserRegistrationPayload.patientOutSa == 1); MyAppointmentsViewModel myAppointmentsVM = getIt(); + if (isSwitchUser && _appState.getSuperUserID == null) { + nationalIdController.text = responseID.toString(); + } else if (isSwitchUser && _appState.getSuperUserID != null) { + nationalIdController.text = _appState.getSuperUserID.toString(); + } + final request = RequestUtils.getCommonRequestWelcome( phoneNumber: phoneNumberController.text, otpTypeEnum: otpTypeEnum, @@ -566,7 +580,7 @@ class AuthenticationViewModel extends ChangeNotifier { MedicalFileViewModel medicalVm = getIt(); if (!_appState.getIsChildLoggedIn) { await medicalVm.getFamilyFiles(status: 0); - await medicalVm.getAllPendingRecordsByResponseId(); + // await medicalVm.getAllPendingRecordsByResponseId(); _navigationService.replaceAllRoutesAndNavigateToLanding(); } } else { @@ -591,7 +605,7 @@ class AuthenticationViewModel extends ChangeNotifier { } // _appState.setUserBloodGroup = (activation.patientBlodType ?? ""); _appState.setAppAuthToken = activation.authenticationTokenId; - myAppointmentsVM.getActiveAppointmentsCount(); + // myAppointmentsVM.getActiveAppointmentsCount(); final request = RequestUtils.getAuthanticatedCommonRequest().toJson(); bool isUserAgreedBefore = await checkIfUserAgreedBefore(request: request); @@ -605,7 +619,7 @@ class AuthenticationViewModel extends ChangeNotifier { MedicalFileViewModel medicalVm = getIt(); insertPatientIMEIData(loginTypeEnum.toInt); medicalVm.getFamilyFiles(status: 0); //TODO: Remove status: 1 by Aamir Need to Discuss With Sultan - medicalVm.getAllPendingRecordsByResponseId(); + // medicalVm.getAllPendingRecordsByResponseId(); } await clearDefaultInputValues(); if (isUserAgreedBefore) { @@ -761,14 +775,14 @@ class AuthenticationViewModel extends ChangeNotifier { phoneNumberController.text = (_appState.getAuthenticatedUser()!.mobileNumber!.startsWith("0") ? _appState.getAuthenticatedUser()!.mobileNumber!.replaceFirst("0", "") : _appState.getAuthenticatedUser()!.mobileNumber)!; - nationalIdController.text = _appState.getAuthenticatedUser()!.nationalityId!; + nationalIdController.text = _appState.getAuthenticatedUser()!.patientIdentificationNo!; onSuccess(); } else if ((loginTypeEnum == LoginTypeEnum.sms || loginTypeEnum == LoginTypeEnum.whatsapp && _appState.getSelectDeviceByImeiRespModelElement == null) && _appState.getAuthenticatedUser() != null) { phoneNumberController.text = (_appState.getAuthenticatedUser()!.mobileNumber!.startsWith("0") ? _appState.getAuthenticatedUser()!.mobileNumber!.replaceFirst("0", "") : _appState.getAuthenticatedUser()!.mobileNumber)!; - nationalIdController.text = _appState.getAuthenticatedUser()!.nationalityId!; + nationalIdController.text = _appState.getAuthenticatedUser()!.patientIdentificationNo!; onSuccess(); } } @@ -1073,4 +1087,30 @@ class AuthenticationViewModel extends ChangeNotifier { return null; } } + + Future logout() async { + try { + // Clear user data from AppState + _appState.setAuthenticatedUser(null); + _appState.setAuthenticatedUser(null, isFamily: true); + _appState.setIsAuthenticated = false; + _appState.setAppAuthToken = ""; + _appState.setUserBloodGroup = ""; + _appState.setSuperUserID = null; + _appState.setIsChildLoggedIn = false; + _appState.setFamilyFileTokenID = ""; + _appState.setSelectDeviceByImeiRespModelElement(null); + _appState.setNHICUserData = CheckUserStatusResponseNHIC(); + _appState.setUserRegistrationPayload = RegistrationDataModelPayload(); + // Clear privilege lists + _appState.setPrivilegeModelList([]); + _appState.setVidaPlusProjectList([]); + _appState.setHMCProjectList([]); + _appState.setProjectsDetailList([]); + await clearDefaultInputValues(); + _navigationService.pushAndReplace(AppRoutes.landingScreen); + } catch (e) { + _navigationService.pushAndReplace(AppRoutes.landingScreen); + } + } } diff --git a/lib/features/authentication/widgets/otp_verification_screen.dart b/lib/features/authentication/widgets/otp_verification_screen.dart index e33222c..7ddccda 100644 --- a/lib/features/authentication/widgets/otp_verification_screen.dart +++ b/lib/features/authentication/widgets/otp_verification_screen.dart @@ -545,20 +545,20 @@ class _OTPVerificationScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 10.h), - LocaleKeys.otpVerification.tr().toText24(isBold: true), + LocaleKeys.otpVerification.tr(context: context).toText24(isBold: true), SizedBox(height: 20.h), Wrap( spacing: 2.h, runSpacing: 2.h, children: [ - LocaleKeys.weHaveSendOTP.tr().toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), + LocaleKeys.weHaveSendOTP.tr(context: context).toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), _getMaskedPhoneNumber().toText15(color: AppColors.inputLabelTextColor, isBold: true), - LocaleKeys.via.tr().toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), + LocaleKeys.via.tr(context: context).toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), (widget.isFormFamilyFile ? LoginTypeEnum.sms.displayName : authVM.loginTypeEnum.displayName) .toText15(color: AppColors.inputLabelTextColor, isBold: true, letterSpacing: -0.4), appState.getUserRegistrationPayload.isRegister != null && appState.getUserRegistrationPayload.isRegister == true - ? LocaleKeys.forRegistrationVerification.tr().toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4) - : LocaleKeys.forLoginVerification.tr().toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), + ? LocaleKeys.forRegistrationVerification.tr(context: context).toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4) + : LocaleKeys.forLoginVerification.tr(context: context).toText15(color: AppColors.inputLabelTextColor, letterSpacing: -0.4), ], ), @@ -590,7 +590,7 @@ class _OTPVerificationScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - LocaleKeys.didntReceiveIt.tr().toText16(color: AppColors.inputLabelTextColor), + LocaleKeys.didntReceiveIt.tr(context: context).toText16(color: AppColors.inputLabelTextColor), SizedBox(width: 5.h), if (_resendTime > 0) Builder( @@ -599,7 +599,7 @@ class _OTPVerificationScreenState extends State { final seconds = (_resendTime % 60).toString().padLeft(2, '0'); return Row( children: [ - LocaleKeys.resendIn.tr().toText16(color: AppColors.inputLabelTextColor), + LocaleKeys.resendIn.tr(context: context).toText16(color: AppColors.inputLabelTextColor), SizedBox(width: 2.h), ' ($minutes:$seconds). '.toText16(color: AppColors.inputLabelTextColor) ], @@ -609,7 +609,7 @@ class _OTPVerificationScreenState extends State { else GestureDetector( onTap: _resendOtp, - child: LocaleKeys.resendOTP.tr().toText16(color: AppColors.primaryRedColor), + child: LocaleKeys.resendOTP.tr(context: context).toText16(color: AppColors.primaryRedColor), ), ], ), diff --git a/lib/features/blood_donation/blood_donation_repo.dart b/lib/features/blood_donation/blood_donation_repo.dart index dce0975..c709b03 100644 --- a/lib/features/blood_donation/blood_donation_repo.dart +++ b/lib/features/blood_donation/blood_donation_repo.dart @@ -3,14 +3,28 @@ import 'package:hmg_patient_app_new/core/api/api_client.dart'; import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_response_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/models/cities_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; abstract class BloodDonationRepo { Future>>> getAllCities(); + Future>>> getProjectList(); + + Future>>> getBloodDonationProjectsList(); + Future>> getPatientBloodGroupDetails(); + + Future>> updateBloodGroup({required Map request}); + + Future>> getFreeBloodDonationSlots({required Map request}); + + Future>> addUserAgreementForBloodDonation({required Map request}); + + Future>> getUserAgreementForBloodDonation(); } class BloodDonationRepoImp implements BloodDonationRepo { @@ -64,7 +78,7 @@ class BloodDonationRepoImp implements BloodDonationRepo { GenericApiModel? apiResponse; Failure? failure; await apiClient.post( - GET_BLOOD_REQUEST, + ApiConsts.getPatientBloodGroup, body: mapDevice, isAllowAny: true, onFailure: (error, statusCode, {messageStatus, failureType}) { @@ -93,4 +107,218 @@ class BloodDonationRepoImp implements BloodDonationRepo { return Left(UnknownFailure(e.toString())); } } -} \ No newline at end of file + + @override + Future>>> getProjectList() async { + Map request = {}; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + GET_PROJECT_LIST, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final list = response['ListProject']; + + final appointmentsList = list.map((item) => HospitalsModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: appointmentsList, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> getBloodDonationProjectsList() async { + Map request = {}; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getProjectsHaveBDClinics, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final listData = (response['BD_getProjectsHaveBDClinics'] as List); + final list = listData.map((item) => BdGetProjectsHaveBdClinic.fromJson(item as Map)).toList(); + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: list, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> updateBloodGroup({required Map request}) async { + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.bloodGroupUpdate, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // final list = response['ListProject']; + + // final appointmentsList = list.map((item) => HospitalsModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> getFreeBloodDonationSlots({required Map request}) async { + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getClinicsBDFreeSlots, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // final list = response['ListProject']; + + // final appointmentsList = list.map((item) => HospitalsModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> addUserAgreementForBloodDonation({required Map request}) async { + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.userAgreementForBloodGroupUpdate, + body: request, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // final list = response['ListProject']; + + // final appointmentsList = list.map((item) => HospitalsModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> getUserAgreementForBloodDonation() async { + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + ApiConsts.getPatientBloodAgreement, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } +} diff --git a/lib/features/blood_donation/blood_donation_view_model.dart b/lib/features/blood_donation/blood_donation_view_model.dart index b8f0e9c..8ad5bde 100644 --- a/lib/features/blood_donation/blood_donation_view_model.dart +++ b/lib/features/blood_donation/blood_donation_view_model.dart @@ -1,15 +1,26 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/utils/doctor_response_mapper.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_repo.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_list_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_response_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/models/cities_model.dart'; +import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/facility_selection.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/doctor_list_api_response.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; class BloodDonationViewModel extends ChangeNotifier { final DialogService dialogService; @@ -17,8 +28,21 @@ class BloodDonationViewModel extends ChangeNotifier { ErrorHandlerService errorHandlerService; final NavigationService navigationService; final AppState appState; + bool isTermsAccepted = false; + BdGetProjectsHaveBdClinic? selectedHospital; + CitiesModel? selectedCity; + BloodGroupListModel? selectedBloodGroup; + int _selectedHospitalIndex = 0; + int _selectedBloodTypeIndex = 0; + GenderTypeEnum? selectedGender; + String? selectedBloodType; + final NavigationService navServices; + + List hospitalList = []; List citiesList = []; + List_BloodGroupDetailsModel patientBloodGroupDetailsModel = List_BloodGroupDetailsModel(); + List bloodGroupList = [ BloodGroupListModel("O+", 0), BloodGroupListModel("O-", 1), @@ -30,35 +54,34 @@ class BloodDonationViewModel extends ChangeNotifier { BloodGroupListModel("B-", 7), ]; - List genderList = [ - BloodGroupListModel(LocaleKeys.malE.tr(), 1), - BloodGroupListModel("Female".needTranslation.tr(), 2), - ]; - - late CitiesModel selectedCity; - late BloodGroupListModel selectedBloodGroup; - int _selectedHospitalIndex = 0; - int _selectedBloodTypeIndex = 0; - String selectedBloodType = ''; - - List_BloodGroupDetailsModel patientBloodGroupDetailsModel = List_BloodGroupDetailsModel(); - - BloodDonationViewModel({required this.bloodDonationRepo, required this.errorHandlerService, required this.navigationService, required this.dialogService, required this.appState}); + BloodDonationViewModel({ + required this.bloodDonationRepo, + required this.errorHandlerService, + required this.navigationService, + required this.dialogService, + required this.appState, + required this.navServices, + }); setSelectedCity(CitiesModel city) { selectedCity = city; notifyListeners(); } + void onGenderChange(String? status) { + selectedGender = GenderTypeExtension.fromType(status)!; + notifyListeners(); + } + setSelectedBloodGroup(BloodGroupListModel bloodGroup) { selectedBloodGroup = bloodGroup; - selectedBloodType = selectedBloodGroup.name; + selectedBloodType = selectedBloodGroup!.name; notifyListeners(); } Future getRegionSelectedClinics({Function(dynamic)? onSuccess, Function(String)? onError}) async { citiesList.clear(); - selectedCity = CitiesModel(); + selectedCity = null; notifyListeners(); final result = await bloodDonationRepo.getAllCities(); @@ -71,6 +94,7 @@ class BloodDonationViewModel extends ChangeNotifier { onError!(apiResponse.errorMessage ?? 'An unexpected error occurred'); } else if (apiResponse.messageStatus == 1) { citiesList = apiResponse.data!; + citiesList.sort((a, b) => a.description!.compareTo(b.description!)); notifyListeners(); if (onSuccess != null) { onSuccess(apiResponse); @@ -100,7 +124,7 @@ class BloodDonationViewModel extends ChangeNotifier { citiesModel.descriptionN = citiesList[_selectedHospitalIndex].descriptionN; selectedCity = citiesModel; selectedBloodType = patientBloodGroupDetailsModel.bloodGroup!; - _selectedBloodTypeIndex = getBloodIndex(selectedBloodType); + _selectedBloodTypeIndex = getBloodIndex(selectedBloodType ?? ''); notifyListeners(); if (onSuccess != null) { @@ -113,11 +137,11 @@ class BloodDonationViewModel extends ChangeNotifier { int getSelectedCityID() { int cityID = 1; - citiesList.forEach((element) { + for (var element in citiesList) { if (element.description == patientBloodGroupDetailsModel.city) { cityID = element.iD!; } - }); + } return cityID; } @@ -144,4 +168,119 @@ class BloodDonationViewModel extends ChangeNotifier { return 0; } } + + void onTermAccepted() { + isTermsAccepted = !isTermsAccepted; + notifyListeners(); + } + + bool isUserAuthanticated() { + print("the app state is ${appState.isAuthenticated}"); + if (!appState.isAuthenticated) { + return false; + } else { + return true; + } + } + + Future fetchHospitalsList() async { + // hospitalList.clear(); + notifyListeners(); + final result = await bloodDonationRepo.getBloodDonationProjectsList(); + + result.fold( + (failure) async => await errorHandlerService.handleError(failure: failure), + (apiResponse) async { + if (apiResponse.messageStatus == 2) { + } else if (apiResponse.messageStatus == 1) { + hospitalList = apiResponse.data!; + hospitalList.sort((a, b) => a.projectName!.compareTo(b.projectName!)); + notifyListeners(); + } + }, + ); + } + + Future getFreeBloodDonationSlots({required Map request}) async { + final result = await bloodDonationRepo.getFreeBloodDonationSlots(request: request); + + result.fold( + (failure) async => await errorHandlerService.handleError(failure: failure), + (apiResponse) async { + if (apiResponse.messageStatus == 2) { + } else if (apiResponse.messageStatus == 1) { + // TODO: Handle free slots data + print(apiResponse.data['BD_FreeSlots']); + notifyListeners(); + } + }, + ); + } + + bool isLocationEnabled() { + return appState.userLong != 0.0 && appState.userLong != 0.0; + } + + setSelectedHospital(BdGetProjectsHaveBdClinic hospital) { + selectedHospital = hospital; + notifyListeners(); + } + + Future validateSelections() async { + if (selectedCity == null) { + await dialogService.showErrorBottomSheet( + message: "Please choose city", + ); + return false; + } + + if (selectedGender == null) { + await dialogService.showErrorBottomSheet( + message: "Please choose Gender", + ); + return false; + } + + if (selectedBloodType == null) { + await dialogService.showErrorBottomSheet( + message: "Please choose Blood Group", + ); + return false; + } + + if (!isTermsAccepted) { + await dialogService.showErrorBottomSheet( + message: "Please accept Terms and Conditions to continue", + ); + return false; + } + return true; + } + + Future updateBloodGroup() async { + LoaderBottomSheet.showLoader(); + Map payload = {"City": selectedCity?.description, "cityCode": selectedCity?.iD, "Gender": selectedGender?.value, "isDentalAllowedBackend": false}; + await bloodDonationRepo.updateBloodGroup(request: payload); + await addUserAgreementForBloodDonation(); + LoaderBottomSheet.hideLoader(); + dialogService.showSuccessBottomSheetWithoutH(message: "Blood Group Updated Successfully", onOkPressed: () {}); + } + + Future addUserAgreementForBloodDonation() async { + Map payload = {"IsAgreed": true}; + await bloodDonationRepo.addUserAgreementForBloodDonation(request: payload); + } + + Future getUserAgreementForBloodDonation() async { + await bloodDonationRepo.getUserAgreementForBloodDonation(); + } + + Future fetchAllData() async { + LoaderBottomSheet.showLoader(loadingText: "Fetching Data..."); + await getRegionSelectedClinics(); + if (isUserAuthanticated()) { + // await getPatientBloodGroupDetails(); + } + LoaderBottomSheet.hideLoader(); + } } diff --git a/lib/features/blood_donation/models/blood_group_hospitals_model.dart b/lib/features/blood_donation/models/blood_group_hospitals_model.dart new file mode 100644 index 0000000..10b4e67 --- /dev/null +++ b/lib/features/blood_donation/models/blood_group_hospitals_model.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; + +class BdProjectsHaveBdClinicsModel { + List? bdGetProjectsHaveBdClinics; + + BdProjectsHaveBdClinicsModel({ + this.bdGetProjectsHaveBdClinics, + }); + + factory BdProjectsHaveBdClinicsModel.fromRawJson(String str) => BdProjectsHaveBdClinicsModel.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory BdProjectsHaveBdClinicsModel.fromJson(Map json) => BdProjectsHaveBdClinicsModel( + bdGetProjectsHaveBdClinics: json["BD_getProjectsHaveBDClinics"] == null ? [] : List.from(json["BD_getProjectsHaveBDClinics"]!.map((x) => BdGetProjectsHaveBdClinic.fromJson(x))), + ); + + Map toJson() => { + "BD_getProjectsHaveBDClinics": bdGetProjectsHaveBdClinics == null ? [] : List.from(bdGetProjectsHaveBdClinics!.map((x) => x.toJson())), + }; +} + +class BdGetProjectsHaveBdClinic { + int? rowId; + int? id; + int? projectId; + int? numberOfRooms; + bool? isActive; + int? createdBy; + String? createdOn; + dynamic editedBy; + dynamic editedOn; + String? projectName; + dynamic projectNameN; + + BdGetProjectsHaveBdClinic({ + this.rowId, + this.id, + this.projectId, + this.numberOfRooms, + this.isActive, + this.createdBy, + this.createdOn, + this.editedBy, + this.editedOn, + this.projectName, + this.projectNameN, + }); + + factory BdGetProjectsHaveBdClinic.fromRawJson(String str) => BdGetProjectsHaveBdClinic.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory BdGetProjectsHaveBdClinic.fromJson(Map json) => BdGetProjectsHaveBdClinic( + rowId: json["RowID"], + id: json["ID"], + projectId: json["ProjectID"], + numberOfRooms: json["NumberOfRooms"], + isActive: json["IsActive"], + createdBy: json["CreatedBy"], + createdOn: json["CreatedOn"], + editedBy: json["EditedBy"], + editedOn: json["EditedON"], + projectName: json["ProjectName"], + projectNameN: json["ProjectNameN"], + ); + + Map toJson() => { + "RowID": rowId, + "ID": id, + "ProjectID": projectId, + "NumberOfRooms": numberOfRooms, + "IsActive": isActive, + "CreatedBy": createdBy, + "CreatedOn": createdOn, + "EditedBy": editedBy, + "EditedON": editedOn, + "ProjectName": projectName, + "ProjectNameN": projectNameN, + }; +} diff --git a/lib/features/blood_donation/widgets/hospital_selection.dart b/lib/features/blood_donation/widgets/hospital_selection.dart new file mode 100644 index 0000000..9889410 --- /dev/null +++ b/lib/features/blood_donation/widgets/hospital_selection.dart @@ -0,0 +1,82 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors; +import 'package:provider/provider.dart'; + +class HospitalBottomSheetBodySelection extends StatelessWidget { + final Function(BdGetProjectsHaveBdClinic userSelection) onUserHospitalSelection; + final bool isHideTitle; + + const HospitalBottomSheetBodySelection({super.key, required this.onUserHospitalSelection(BdGetProjectsHaveBdClinic userSelection), this.isHideTitle = false}); + + @override + Widget build(BuildContext context) { + final bloodDonationVm = Provider.of(context, listen: false); + AppState appState = getIt.get(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if(!isHideTitle) LocaleKeys.selectHospital.tr(context: context).toText16(weight: FontWeight.w500, color: AppColors.greyTextColor), + SizedBox(height: 16.h), + SizedBox( + height: MediaQuery.sizeOf(context).height * .4, + child: ListView.separated( + itemBuilder: (_, index) { + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8.h, + children: [ + hospitalName(bloodDonationVm.hospitalList[index]).onPress(() { + onUserHospitalSelection(bloodDonationVm.hospitalList[index]); + Navigator.of(context).pop(); + }) + ], + ), + ), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.blackColor, width: 40.h, height: 40.h, fit: BoxFit.contain), + ), + ], + ).paddingSymmetrical(16.h, 16.h), + ).onPress(() { + bloodDonationVm.setSelectedHospital(bloodDonationVm.hospitalList[index]); + Navigator.of(context).pop(); + }); + }, + separatorBuilder: (_, __) => SizedBox(height: 16.h), + itemCount: bloodDonationVm.hospitalList.length), + ) + ], + ); + } + + Widget hospitalName(dynamic hospital) => Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.hmg).paddingOnly(right: 10), + Expanded( + child: Text(hospital.projectName ?? "", style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16, color: AppColors.blackColor)), + ) + ], + ); +} diff --git a/lib/features/book_appointments/book_appointments_repo.dart b/lib/features/book_appointments/book_appointments_repo.dart index cfd473e..cab79ad 100644 --- a/lib/features/book_appointments/book_appointments_repo.dart +++ b/lib/features/book_appointments/book_appointments_repo.dart @@ -30,6 +30,8 @@ abstract class BookAppointmentsRepo { Future>> getDoctorProfile(int clinicID, int projectID, int doctorId, {Function(dynamic)? onSuccess, Function(String)? onError}); + Future>> getDoctorRatingDetails(int doctorId, {Function(dynamic)? onSuccess, Function(String)? onError}); + Future>> getDoctorFreeSlots(int clinicID, int projectID, int doctorId, bool isBookingForLiveCare, {bool continueDentalPlan = false, Function(dynamic)? onSuccess, Function(String)? onError}); @@ -298,6 +300,52 @@ class BookAppointmentsRepoImp implements BookAppointmentsRepo { } } + @override + Future>> getDoctorRatingDetails(int doctorId, {Function(dynamic)? onSuccess, Function(String)? onError}) async { + Map mapDevice = { + "DoctorID": doctorId, + "PatientID": 0, + "License": true, + "IsRegistered": true, + "isDentalAllowedBackend": false, + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + GET_DOCTOR_RATING_DETAILS, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + if (onError != null) { + onError(error); + } + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: response, + ); + if (onSuccess != null) { + onSuccess(response); + } + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + //TODO: Implement the logic for Dental & laser clinics @override Future>> getDoctorFreeSlots(int clinicID, int projectID, int doctorId, bool isBookingForLiveCare, diff --git a/lib/features/book_appointments/book_appointments_view_model.dart b/lib/features/book_appointments/book_appointments_view_model.dart index cbed940..34858b4 100644 --- a/lib/features/book_appointments/book_appointments_view_model.dart +++ b/lib/features/book_appointments/book_appointments_view_model.dart @@ -17,6 +17,7 @@ import 'package:hmg_patient_app_new/features/book_appointments/models/free_slot. import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/appointment_nearest_gate_response_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/dental_chief_complaints_response_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctor_profile_response_model.dart'; +import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctor_rating_details_response_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_clinic_list_response_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_patient_dental_plan_response_model.dart'; @@ -49,9 +50,13 @@ class BookAppointmentsViewModel extends ChangeNotifier { bool isLiveCareSchedule = false; bool isGetDocForHealthCal = false; + bool showSortFilterButtons = false; int? calculationID = 0; bool isSortByClinic = true; + // Accordion expansion state + int? expandedGroupIndex; + int initialSlotDuration = 0; bool isNearestAppointmentSelected = false; @@ -88,6 +93,9 @@ class BookAppointmentsViewModel extends ChangeNotifier { late DoctorsProfileResponseModel doctorsProfileResponseModel; + bool isDoctorRatingDetailsLoading = false; + List doctorDetailsList = []; + List slotsList = []; List docFreeSlots = []; List dayEvents = []; @@ -157,13 +165,65 @@ class BookAppointmentsViewModel extends ChangeNotifier { bool isBodyPartsLoading = false; int duration = 0; - setIsSortByClinic(bool value) { isSortByClinic = value; doctorsListGrouped = isSortByClinic ? doctorsListByClinic : doctorsListByHospital; notifyListeners(); } + // Toggle accordion expansion + void toggleGroupExpansion(int index) { + if (expandedGroupIndex == index) { + expandedGroupIndex = null; + } else { + expandedGroupIndex = index; + } + notifyListeners(); + } + + // Reset accordion expansion + void resetGroupExpansion() { + expandedGroupIndex = null; + notifyListeners(); + } + + // Sort filtered doctor list by clinic or hospital + void sortFilteredDoctorList(bool sortByClinic) { + isSortByClinic = sortByClinic; + if (sortByClinic) { + // Sort by clinic name + filteredDoctorList.sort((a, b) { + final clinicA = (a.clinicName ?? 'Unknown').toLowerCase(); + final clinicB = (b.clinicName ?? 'Unknown').toLowerCase(); + return clinicA.compareTo(clinicB); + }); + } else { + // Sort by hospital/project name + filteredDoctorList.sort((a, b) { + final hospitalA = (a.projectName ?? 'Unknown').toLowerCase(); + final hospitalB = (b.projectName ?? 'Unknown').toLowerCase(); + return hospitalA.compareTo(hospitalB); + }); + } + notifyListeners(); + } + + // Group filtered doctors list for accordion display + List> getGroupedFilteredDoctorsList() { + final clinicMap = >{}; + final hospitalMap = >{}; + + for (var doctor in filteredDoctorList) { + final clinicKey = (doctor.clinicName ?? 'Unknown').trim(); + clinicMap.putIfAbsent(clinicKey, () => []).add(doctor); + + final hospitalKey = (doctor.projectName ?? 'Unknown').trim(); + hospitalMap.putIfAbsent(hospitalKey, () => []).add(doctor); + } + + return isSortByClinic ? clinicMap.values.toList() : hospitalMap.values.toList(); + } + // Group doctors by clinic and hospital void _groupDoctorsList() { final clinicMap = >{}; @@ -200,8 +260,10 @@ class BookAppointmentsViewModel extends ChangeNotifier { void filterClinics(String? query) { if (query!.isEmpty) { _filteredClinicsList = List.from(clinicsList); + showSortFilterButtons = false; } else { _filteredClinicsList = clinicsList.where((clinic) => clinic.clinicDescription?.toLowerCase().contains(query!.toLowerCase()) ?? false).toList(); + showSortFilterButtons = query.length >= 3; } notifyListeners(); } @@ -213,6 +275,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { isDoctorProfileLoading = true; isLiveCareSchedule = false; currentlySelectedHospitalFromRegionFlow = null; + expandedGroupIndex = null; // Reset accordion state clinicsList.clear(); doctorsList.clear(); liveCareClinicsList.clear(); @@ -230,9 +293,24 @@ class BookAppointmentsViewModel extends ChangeNotifier { this.isNearestAppointmentSelected = isNearestAppointmentSelected; if (isNearestAppointmentSelected) { - doctorsList.sort((a, b) => DateUtil.convertStringToDate(a.nearestFreeSlot!).compareTo(DateUtil.convertStringToDate(b.nearestFreeSlot!))); + for (var group in doctorsListGrouped) { + group.sort((a, b) { + var aSlot = a.nearestFreeSlot; + var bSlot = b.nearestFreeSlot; + if (aSlot == null || bSlot == null) return 0; + return DateUtil.convertStringToDate(aSlot).compareTo(DateUtil.convertStringToDate(bSlot)); + }); + } } else { - doctorsList.sort((a, b) => b.decimalDoctorRate!.compareTo(a.decimalDoctorRate!)); + for (var group in doctorsListGrouped) { + group.sort((a, b) { + var aSlot = a.decimalDoctorRate; + var bSlot = b.decimalDoctorRate; + if (aSlot == null || bSlot == null) return 0; + return bSlot.compareTo(aSlot); + }); + } + // doctorsList.sort((a, b) => b.decimalDoctorRate!.compareTo(a.decimalDoctorRate!)); } notifyListeners(); @@ -266,6 +344,14 @@ class BookAppointmentsViewModel extends ChangeNotifier { notifyListeners(); } + setIsLiveCareDoctorsListLoading(bool value) { + if (value) { + liveCareDoctorsList.clear(); + } + isDoctorsListLoading = value; + notifyListeners(); + } + setIsClinicsListLoading(bool value) { if (value) { clinicsList.clear(); @@ -393,13 +479,13 @@ class BookAppointmentsViewModel extends ChangeNotifier { } Future getLiveCareDoctorsList({Function(dynamic)? onSuccess, Function(String)? onError}) async { - doctorsList.clear(); + liveCareDoctorsList.clear(); + notifyListeners(); final result = await bookAppointmentsRepo.getLiveCareDoctorsList(selectedLiveCareClinic.serviceID!, _appState.getAuthenticatedUser()!.age!, _appState.getAuthenticatedUser()!.gender!, onError: onError); - result.fold( (failure) async { - onError!("No doctors found for the search criteria".needTranslation); + onError!(LocaleKeys.noDoctorFound.tr()); }, (apiResponse) { if (apiResponse.messageStatus == 2) { @@ -427,7 +513,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { result.fold( (failure) async { isDoctorsListLoading = false; - if (onError != null) onError("No doctors found for the search criteria".needTranslation); + if (onError != null) onError(LocaleKeys.noDoctorFound.tr()); notifyListeners(); }, @@ -459,7 +545,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { result.fold( (failure) async { isDoctorsListLoading = false; - if (onError != null) onError("No doctors found for the search criteria".needTranslation); + if (onError != null) onError(LocaleKeys.noDoctorFound.tr()); notifyListeners(); }, @@ -495,7 +581,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { result.fold( (failure) async { - onError?.call("No doctors found for the search criteria".needTranslation); + onError?.call(LocaleKeys.noDoctorFound.tr()); }, (apiResponse) async { if (apiResponse.messageStatus == 2) { @@ -540,6 +626,46 @@ class BookAppointmentsViewModel extends ChangeNotifier { ); } + Future getDoctorRatingDetails({Function(dynamic)? onSuccess, Function(String)? onError}) async { + isDoctorRatingDetailsLoading = true; + doctorDetailsList.clear(); + notifyListeners(); + + final result = await bookAppointmentsRepo.getDoctorRatingDetails(selectedDoctor.doctorID ?? 0, onSuccess: onSuccess, onError: onError); + + result.fold( + (failure) async { + if (onError != null) { + onError("Failed to load doctor rating details"); + } + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + if (onError != null) { + onError(apiResponse.errorMessage ?? "Unknown error occurred"); + } + isDoctorRatingDetailsLoading = false; + } else if (apiResponse.messageStatus == 1) { + try { + apiResponse.data['DoctorRatingDetailsList'].forEach((v) { + doctorDetailsList.add(DoctorRateDetails.fromJson(v)); + }); + isDoctorRatingDetailsLoading = false; + // doctorRatingDetails = DoctorRateDetails.fromJson(apiResponse.data); + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse.data); + } + } catch (e) { + if (onError != null) { + onError("Failed to parse rating details: ${e.toString()}"); + } + } + } + }, + ); + } + Future getDoctorFreeSlots({bool isBookingForLiveCare = false, Function(dynamic)? onSuccess, Function(String)? onError}) async { docFreeSlots.clear(); DateTime date; @@ -710,7 +836,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { ); showCommonBottomSheet(navigationService.navigatorKey.currentContext!, - child: Utils.getLoadingWidget(loadingText: "Cancelling your previous appointment....".needTranslation), + child: Utils.getLoadingWidget(loadingText: LocaleKeys.cancellingAppointmentPleaseWait.tr()), callBackFunc: (str) {}, title: "", height: ResponsiveExtension.screenHeight * 0.3, @@ -720,7 +846,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { await cancelAppointment(patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel).then((val) async { navigationService.pop(); Future.delayed(Duration(milliseconds: 50)).then((value) async {}); - LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: "Booking your appointment...".needTranslation); + LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: LocaleKeys.bookingYourAppointment.tr()); await insertSpecificAppointment( onError: (err) {}, onSuccess: (apiResp) async { @@ -806,7 +932,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { ); showCommonBottomSheet(navigationService.navigatorKey.currentContext!, - child: Utils.getLoadingWidget(loadingText: "Cancelling your previous appointment....".needTranslation), + child: Utils.getLoadingWidget(loadingText: LocaleKeys.cancellingAppointmentPleaseWait.tr()), callBackFunc: (str) {}, title: "", height: ResponsiveExtension.screenHeight * 0.3, @@ -816,7 +942,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { await cancelAppointment(patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel).then((val) async { navigationService.pop(); Future.delayed(Duration(milliseconds: 50)).then((value) async {}); - LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: "Booking your appointment...".needTranslation); + LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: LocaleKeys.bookingYourAppointment.tr()); await insertSpecificAppointment( onError: (err) {}, onSuccess: (apiResp) async { @@ -1130,7 +1256,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { result.fold( (failure) async { - onError!("No doctors found for the search criteria...".needTranslation); + onError!(LocaleKeys.noDoctorFound.tr()); }, (apiResponse) { if (apiResponse.messageStatus == 2) { @@ -1217,18 +1343,18 @@ class BookAppointmentsViewModel extends ChangeNotifier { notifyListeners(); } else { - if (this.duration == 90) { - dialogService.showErrorBottomSheet( - message: "Duration can not exceed 90 min".needTranslation, - ); - return; - } + // if (this.duration == 90) { + // dialogService.showErrorBottomSheet( + // message: "Duration can not exceed 90 min".needTranslation, + // ); + // return; + // } selectedBodyPartList.add(part); var duration = getDuration(); if (duration > 90) { selectedBodyPartList.remove(part); dialogService.showErrorBottomSheet( - message: "Duration Exceeds 90 min".needTranslation, + message: LocaleKeys.durationCannotExceed90.tr(), ); return; } @@ -1262,7 +1388,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { result.fold( (failure) async { - onError!("Invalid verification point scanned.".needTranslation); + onError!("Invalid verification point scanned."); }, (apiResponse) { // if (apiResponse.data['returnValue'] == 0) { @@ -1336,7 +1462,7 @@ class BookAppointmentsViewModel extends ChangeNotifier { ); } else if (apiResponse.messageStatus == 1) { if (apiResponse.data == null || apiResponse.data!.isEmpty) { - onError!("Unexpected Error Occurred".needTranslation); + onError!(LocaleKeys.unexpectedError.tr()); return; } notifyListeners(); diff --git a/lib/features/book_appointments/models/resp_models/doctor_rating_details_response_model.dart b/lib/features/book_appointments/models/resp_models/doctor_rating_details_response_model.dart new file mode 100644 index 0000000..5866885 --- /dev/null +++ b/lib/features/book_appointments/models/resp_models/doctor_rating_details_response_model.dart @@ -0,0 +1,36 @@ +class DoctorRateDetails { + dynamic doctorID; + dynamic projectID; + dynamic clinicID; + dynamic rate; + dynamic patientNumber; + dynamic ratio; + + DoctorRateDetails( + {this.doctorID, + this.projectID, + this.clinicID, + this.rate, + this.patientNumber, + this.ratio}); + + DoctorRateDetails.fromJson(Map json) { + doctorID = json['DoctorID']; + projectID = json['ProjectID']; + clinicID = json['ClinicID']; + rate = json['Rate']; + patientNumber = json['PatientNumber']; + ratio = json['Ratio']; + } + + Map toJson() { + final Map data = new Map(); + data['DoctorID'] = this.doctorID; + data['ProjectID'] = this.projectID; + data['ClinicID'] = this.clinicID; + data['Rate'] = this.rate; + data['PatientNumber'] = this.patientNumber; + data['Ratio'] = this.ratio; + return data; + } +} diff --git a/lib/features/contact_us/contact_us_repo.dart b/lib/features/contact_us/contact_us_repo.dart index 3e96f91..5b9057b 100644 --- a/lib/features/contact_us/contact_us_repo.dart +++ b/lib/features/contact_us/contact_us_repo.dart @@ -14,6 +14,8 @@ abstract class ContactUsRepo { Future>>> getLiveChatProjectsList(); + Future>> getChatRequestID({required String name, required String mobileNo, required String workGroup}); + Future>> insertCOCItem({required RequestInsertCOCItem requestInsertCOCItem, PatientAppointmentHistoryResponseModel? patientSelectedAppointment}); } @@ -97,6 +99,45 @@ class ContactUsRepoImp implements ContactUsRepo { } } + @override + Future>> getChatRequestID({required String name, required String mobileNo, required String workGroup}) async { + Map body = {}; + body['Name'] = name; + body['MobileNo'] = mobileNo; + body['WorkGroup'] = workGroup; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + GET_LIVECHAT_REQUEST_ID, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final requestId = response['RequestId'] as String; + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: requestId, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + @override Future>> insertCOCItem({required RequestInsertCOCItem requestInsertCOCItem, PatientAppointmentHistoryResponseModel? patientSelectedAppointment}) async { final Map body = requestInsertCOCItem.toJson(); diff --git a/lib/features/contact_us/contact_us_view_model.dart b/lib/features/contact_us/contact_us_view_model.dart index 1185700..1029802 100644 --- a/lib/features/contact_us/contact_us_view_model.dart +++ b/lib/features/contact_us/contact_us_view_model.dart @@ -29,6 +29,8 @@ class ContactUsViewModel extends ChangeNotifier { int selectedLiveChatProjectIndex = -1; + String? chatRequestID; + List feedbackAttachmentList = []; PatientAppointmentHistoryResponseModel? patientFeedbackSelectedAppointment; @@ -153,6 +155,32 @@ class ContactUsViewModel extends ChangeNotifier { ); } + Future getChatRequestID({required String name, required String mobileNo, required String workGroup, Function(dynamic)? onSuccess, Function(String)? onError}) async { + final result = await contactUsRepo.getChatRequestID(name: name, mobileNo: mobileNo, workGroup: workGroup); + + result.fold( + (failure) async { + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } else if (apiResponse.messageStatus == 1) { + chatRequestID = apiResponse.data; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } + Future insertCOCItem({required String subject, required String message, Function(dynamic)? onSuccess, Function(String)? onError}) async { RequestInsertCOCItem requestInsertCOCItem = RequestInsertCOCItem(); requestInsertCOCItem.attachment = feedbackAttachmentList.isNotEmpty ? feedbackAttachmentList.first : ""; diff --git a/lib/features/emergency_services/emergency_services_view_model.dart b/lib/features/emergency_services/emergency_services_view_model.dart index 400eb04..ec21179 100644 --- a/lib/features/emergency_services/emergency_services_view_model.dart +++ b/lib/features/emergency_services/emergency_services_view_model.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart' as GMSMapServices; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -32,6 +33,7 @@ import 'package:hmg_patient_app_new/features/my_appointments/models/facility_sel import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_repo.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/RRT/rrt_request_type_select.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/RRT/terms_and_condition.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/call_ambulance_page.dart'; @@ -152,7 +154,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { print("the app state is ${appState.isAuthenticated}"); if (!appState.isAuthenticated) { dialogService.showErrorBottomSheet( - message: "You Need To Login First To Continue".needTranslation, + message: LocaleKeys.loginToUseService.tr(), onOkPressed: () { navServices.pop(); getIt().onLoginPressed(); @@ -196,7 +198,6 @@ class EmergencyServicesViewModel extends ChangeNotifier { } void filterErList(String query) { - print("the query is $query"); if (query.isEmpty) { nearestERFilteredList = nearestERList; } else { @@ -277,7 +278,6 @@ class EmergencyServicesViewModel extends ChangeNotifier { flushData(); selectedFacility = FacilitySelection.ALL; - print("the app state is ${appState.isAuthenticated}"); if (appState.isAuthenticated) { locationUtils!.getLocation( isShowConfirmDialog: true, @@ -289,7 +289,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { }); } else { dialogService.showErrorBottomSheet( - message: "You Need To Login First To Continue".needTranslation, + message: LocaleKeys.loginToUseService.tr(), onOkPressed: () { navServices.pop(); navServices.pushAndReplace(AppRoutes.loginScreen); @@ -311,7 +311,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { void updateBottomSheetState(BottomSheetType sheetType) { if (sheetType == BottomSheetType.EXPANDED && selectedHospital == null) { - dialogService.showErrorBottomSheet(message: "Kindly Select Hospital".needTranslation); + dialogService.showErrorBottomSheet(message: LocaleKeys.selectHospital.tr()); return; } bottomSheetType = sheetType; @@ -481,21 +481,18 @@ class EmergencyServicesViewModel extends ChangeNotifier { Future getTransportationOption() async { //handle the cache if the data is present then dont fetch it in the authenticated lifecycle - - print("the app state is ${appState.isAuthenticated}"); if (appState.isAuthenticated == false) { dialogService.showErrorBottomSheet( - message: "You Need To Login First To Continue".needTranslation, + message: LocaleKeys.loginToUseService.tr(), onOkPressed: () { navServices.pop(); - print("inside the ok button"); getIt().onLoginPressed(); }); return; } int? id = appState.getAuthenticatedUser()?.patientId; - LoaderBottomSheet.showLoader(loadingText: "Getting Ambulance Transport Option".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.gettingAmbulanceTransportOption.tr()); notifyListeners(); var response = await emergencyServicesRepo.getTransportationMethods(id: id); @@ -514,7 +511,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { Future getTransportationMethods() async { int? id = appState.getAuthenticatedUser()?.patientId; - LoaderBottomSheet.showLoader(loadingText: "Getting Ambulance Transport Option".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.gettingAmbulanceTransportOption.tr()); notifyListeners(); var response = await emergencyServicesRepo.getTransportationMethods(id: id); @@ -703,7 +700,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { } Future getAppointments() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Appointment".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingAppointment.tr()); var result = await appointmentRepo.getPatientAppointments(isActiveAppointment: true, isArrivedAppointments: false); LoaderBottomSheet.hideLoader(); @@ -860,10 +857,10 @@ class EmergencyServicesViewModel extends ChangeNotifier { Future cancelOrder(AmbulanceRequestOrdersModel? order, {bool shouldPop = false}) async { dialogService.showCommonBottomSheetWithoutH( - message: "Do you want to cancel the request".needTranslation, + message: LocaleKeys.doYouWantToCancelTheRequest.tr(), onOkPressed: () async { navServices.pop(); - LoaderBottomSheet.showLoader(loadingText: "Cancelling request".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.cancellingRequest.tr()); var response = await emergencyServicesRepo.cancelOrder(order?.iD, appState.getAuthenticatedUser()?.patientId ?? 0); LoaderBottomSheet.hideLoader(); response.fold((failure) => errorHandlerService.handleError(failure: failure), (success) { @@ -968,10 +965,10 @@ class EmergencyServicesViewModel extends ChangeNotifier { FutureOr cancelRRTOrder(int? orderID, {bool shouldPop = false}) async { dialogService.showCommonBottomSheetWithoutH( - message: "Do you want to cancel the request".needTranslation, + message: LocaleKeys.doYouWantToCancelTheRequest.tr(), onOkPressed: () async { navServices.pop(); - LoaderBottomSheet.showLoader(loadingText: "Cancelling request".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.cancellingRequest.tr()); var response = await emergencyServicesRepo.cancelRRTOrder(orderID); LoaderBottomSheet.hideLoader(); response.fold((failure) => errorHandlerService.handleError(failure: failure), (success) { @@ -1001,11 +998,10 @@ class EmergencyServicesViewModel extends ChangeNotifier { } void openRRT() { - print("the app state is ${appState.isAuthenticated}"); if (appState.isAuthenticated) { if (agreedToTermsAndCondition == false) { dialogService.showErrorBottomSheet( - message: "You Need To Agree To Terms And Conditions".needTranslation, + message: LocaleKeys.pleaseAcceptTermsConditions.tr(), onOkPressed: () { if (navServices.context == null) return; showCommonBottomSheetWithoutHeight( @@ -1042,9 +1038,9 @@ class EmergencyServicesViewModel extends ChangeNotifier { bool result = await navServices.push( CustomPageRoute( page: MapUtilityScreen( - confirmButtonString: "Submit Request".needTranslation, - titleString: "Select Location".needTranslation, - subTitleString: "Please select the location".needTranslation, + confirmButtonString: LocaleKeys.submitRequest.tr(), + titleString: LocaleKeys.selectLocation.tr(), + subTitleString: LocaleKeys.pleaseSelectTheLocation.tr(), isGmsAvailable: appState.isGMSAvailable, ), direction: AxisDirection.down), @@ -1059,7 +1055,7 @@ class EmergencyServicesViewModel extends ChangeNotifier { }); } else { dialogService.showErrorBottomSheet( - message: "You Need To Login First To Continue".needTranslation, + message: LocaleKeys.loginToUseService.tr(), onOkPressed: () { navServices.pop(); getIt().onLoginPressed(); @@ -1072,12 +1068,11 @@ class EmergencyServicesViewModel extends ChangeNotifier { } FutureOr getTermsAndConditions() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Terms And Conditions".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingTermsAndConditions.tr()); var response = await emergencyServicesRepo.getTermsAndCondition(); LoaderBottomSheet.hideLoader(); response.fold((failure) => errorHandlerService.handleError(failure: failure), (success) { termsAndConditions = success.data; - print("the response terms are $termsAndConditions"); notifyListeners(); navServices.push( CustomPageRoute(page: TermsAndCondition(termsAndCondition: success.data ?? ""), direction: AxisDirection.down), diff --git a/lib/features/health_trackers/health_trackers_repo.dart b/lib/features/health_trackers/health_trackers_repo.dart new file mode 100644 index 0000000..2a64fc4 --- /dev/null +++ b/lib/features/health_trackers/health_trackers_repo.dart @@ -0,0 +1,873 @@ +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/core/api/api_client.dart'; +import 'package:hmg_patient_app_new/core/api_consts.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; +import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; +import 'package:hmg_patient_app_new/services/logger_service.dart'; + +/// Progress types to request different ranges from the progress API. +enum ProgressType { today, week, month } + +abstract class HealthTrackersRepo { + // ==================== BLOOD SUGAR (DIABETIC) ==================== + /// Get blood sugar result averages (week, month, year). + Future>> getDiabeticResultAverage(); + + /// Get blood sugar results (week, month, year). + Future>> getDiabeticResults(); + + /// Add new blood sugar result. + Future>> addDiabeticResult({ + required String bloodSugarDateChart, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + }); + + /// Update existing blood sugar result. + Future>> updateDiabeticResult({ + required DateTime month, + required DateTime hour, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + required int lineItemNo, + }); + + /// Deactivate blood sugar record. + Future>> deactivateDiabeticStatus({ + required int lineItemNo, + }); + + /// Send blood sugar report by email. + Future>> sendBloodSugarReportByEmail({ + required String email, + }); + + // ==================== BLOOD PRESSURE ==================== + /// Get blood pressure result averages (week, month, year). + Future>> getBloodPressureResultAverage(); + + /// Get blood pressure results (week, month, year). + Future>> getBloodPressureResults(); + + /// Add new blood pressure result. + Future>> addBloodPressureResult({ + required String bloodPressureDate, + required String diastolicPressure, + required String systolicePressure, + required int measuredArm, + }); + + /// Update existing blood pressure result. + Future>> updateBloodPressureResult({ + required String bloodPressureDate, + required String diastolicPressure, + required String systolicePressure, + required int measuredArm, + required int lineItemNo, + }); + + /// Deactivate blood pressure record. + Future>> deactivateBloodPressureStatus({ + required int lineItemNo, + }); + + /// Send blood pressure report by email. + Future>> sendBloodPressureReportByEmail({ + required String email, + }); + + // ==================== WEIGHT MEASUREMENT ==================== + /// Get weight measurement result averages (week, month, year). + Future>> getWeightMeasurementResultAverage(); + + /// Get weight measurement results (week, month, year). + Future>> getWeightMeasurementResults(); + + /// Add new weight measurement result. + Future>> addWeightMeasurementResult({ + required String weightDate, + required String weightMeasured, + required int weightUnit, + }); + + /// Update existing weight measurement result. + Future>> updateWeightMeasurementResult({ + required int lineItemNo, + required int weightUnit, + required String weightMeasured, + required String weightDate, + }); + + /// Deactivate weight measurement record. + Future>> deactivateWeightMeasurementStatus({ + required int lineItemNo, + }); + + /// Send weight report by email. + Future>> sendWeightReportByEmail({ + required String email, + }); +} + +class HealthTrackersRepoImp implements HealthTrackersRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + HealthTrackersRepoImp({required this.loggerService, required this.apiClient}); + + // ==================== BLOOD SUGAR (DIABETIC) METHODS ==================== + + @override + Future>> getDiabeticResultAverage() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getDiabeticResultAverage, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract average lists + extracted = { + 'monthAverageList': response['List_MonthDiabtectResultAverage'] ?? [], + 'weekAverageList': response['List_WeekDiabtectResultAverage'] ?? [], + 'yearAverageList': response['List_YearDiabtecResultAverage'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getDiabeticResults() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getDiabeticResult, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract patient result lists + extracted = { + 'monthResultList': response['List_MonthDiabtecPatientResult'] ?? [], + 'weekResultList': response['List_WeekDiabtecPatientResult'] ?? [], + 'yearResultList': response['List_YearDiabtecPatientResult'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> addDiabeticResult({ + required String bloodSugarDateChart, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'BloodSugerDateChart': bloodSugarDateChart, + 'BloodSugerResult': bloodSugarResult, + 'DiabtecUnit': diabeticUnit, + 'MeasuredTime': measuredTime + 1, // Add 1 as per old service + }; + + await apiClient.post( + ApiConsts.addDiabeticResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> updateDiabeticResult({ + required DateTime month, + required DateTime hour, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + required int lineItemNo, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + // Format: 'YYYY-MM-DD HH:MM:SS' as per old service + String formattedDate = '${month.year}-${month.month}-${month.day} ${hour.hour}:${hour.minute}:00'; + + Map body = { + 'BloodSugerDateChart': formattedDate, + 'BloodSugerResult': bloodSugarResult, + 'DiabtecUnit': diabeticUnit, + 'MeasuredTime': measuredTime + 1, // Add 1 as per old service + 'LineItemNo': lineItemNo, + }; + + await apiClient.post( + ApiConsts.updateDiabeticResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> deactivateDiabeticStatus({ + required int lineItemNo, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'LineItemNo': lineItemNo, + }; + + await apiClient.post( + ApiConsts.deactivateDiabeticStatus, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> sendBloodSugarReportByEmail({ + required String email, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'To': email, + }; + + await apiClient.post( + ApiConsts.sendAverageBloodSugarReport, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + // ==================== BLOOD PRESSURE METHODS ==================== + + @override + Future>> getBloodPressureResultAverage() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getBloodPressureResultAverage, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract all three list types + extracted = { + 'monthList': response['List_MonthBloodPressureResultAverage'] ?? [], + 'weekList': response['List_WeekBloodPressureResultAverage'] ?? [], + 'yearList': response['List_YearBloodPressureResultAverage'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getBloodPressureResults() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getBloodPressureResult, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract all three list types + extracted = { + 'weekList': response['List_WeekBloodPressureResult'] ?? [], + 'monthList': response['List_MonthBloodPressureResult'] ?? [], + 'yearList': response['List_YearBloodPressureResult'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> addBloodPressureResult({ + required String bloodPressureDate, + required String diastolicPressure, + required String systolicePressure, + required int measuredArm, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'BloodPressureDate': bloodPressureDate, + 'DiastolicPressure': diastolicPressure, + 'SystolicePressure': systolicePressure, + 'MeasuredArm': measuredArm, + }; + + await apiClient.post( + ApiConsts.addBloodPressureResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> updateBloodPressureResult({ + required String bloodPressureDate, + required String diastolicPressure, + required String systolicePressure, + required int measuredArm, + required int lineItemNo, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'BloodPressureDate': bloodPressureDate, + 'DiastolicPressure': diastolicPressure, + 'SystolicePressure': systolicePressure, + 'MeasuredArm': measuredArm, + 'LineItemNo': lineItemNo, + }; + + await apiClient.post( + ApiConsts.updateBloodPressureResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> deactivateBloodPressureStatus({ + required int lineItemNo, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'LineItemNo': lineItemNo, + }; + + await apiClient.post( + ApiConsts.deactivateBloodPressureStatus, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> sendBloodPressureReportByEmail({ + required String email, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'To': email, + }; + + await apiClient.post( + ApiConsts.sendAverageBloodPressureReport, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + // ==================== WEIGHT MEASUREMENT METHODS ==================== + + @override + Future>> getWeightMeasurementResultAverage() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getWeightMeasurementResultAverage, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract average lists + extracted = { + 'monthAverageList': response['List_MonthWeightMeasurementResultAverage'] ?? [], + 'weekAverageList': response['List_WeekWeightMeasurementResultAverage'] ?? [], + 'yearAverageList': response['List_YearWeightMeasurementResultAverage'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getWeightMeasurementResults() async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getWeightMeasurementResult, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + dynamic extracted; + if (response is Map) { + // Extract result lists + extracted = { + 'weekResultList': response['List_WeekWeightMeasurementResult'] ?? [], + 'monthResultList': response['List_MonthWeightMeasurementResult'] ?? [], + 'yearResultList': response['List_YearWeightMeasurementResult'] ?? [], + }; + } else { + extracted = response; + } + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: extracted, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> addWeightMeasurementResult({ + required String weightDate, + required String weightMeasured, + required int weightUnit, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'WeightDate': weightDate, + 'WeightMeasured': weightMeasured, + 'weightUnit': weightUnit, + }; + + await apiClient.post( + ApiConsts.addWeightMeasurementResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> updateWeightMeasurementResult({ + required int lineItemNo, + required int weightUnit, + required String weightMeasured, + required String weightDate, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'LineItemNo': lineItemNo, + 'weightUnit': '$weightUnit', // Convert to string as per old service + 'WeightMeasured': weightMeasured, + 'WeightDate': weightDate, + }; + + await apiClient.post( + ApiConsts.updateWeightMeasurementResult, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> deactivateWeightMeasurementStatus({required int lineItemNo}) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'LineItemNo': lineItemNo, + }; + + await apiClient.post( + ApiConsts.deactivateWeightMeasurementStatus, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> sendWeightReportByEmail({ + required String email, + }) async { + try { + GenericApiModel? apiResponse; + Failure? failure; + + Map body = { + 'To': email, + }; + + await apiClient.post( + ApiConsts.sendAverageBodyWeightReport, + body: body, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } +} diff --git a/lib/features/health_trackers/health_trackers_view_model.dart b/lib/features/health_trackers/health_trackers_view_model.dart new file mode 100644 index 0000000..ab54f59 --- /dev/null +++ b/lib/features/health_trackers/health_trackers_view_model.dart @@ -0,0 +1,1121 @@ +import 'dart:developer'; + +import 'package:flutter/cupertino.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_repo.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/blood_pressure_result.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/month_blood_pressure_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/week_blood_pressure_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_pressure/year_blood_pressure_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/diabetic_patient_result.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/month_diabetic_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/month_weight_measurement_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/week_weight_measurement_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/weight_measurement_result.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/year_weight_measurement_result_average.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; + +class HealthTrackersViewModel extends ChangeNotifier { + HealthTrackersRepo healthTrackersRepo; + ErrorHandlerService errorHandlerService; + + HealthTrackersViewModel({required this.healthTrackersRepo, required this.errorHandlerService}); + + // ==================== STATE MANAGEMENT ==================== + bool isLoading = false; + String? _errorMessage; + + String? get errorMessage => _errorMessage; + + List get durationFilters => ["Week", "Month", "Year"]; + + String _selectedDuration = "Week"; + bool _isGraphView = true; + + String get selectedDurationFilter => _selectedDuration; + + bool get isGraphView => _isGraphView; + + final List bloodSugarUnit = ['mg/dlt', 'mol/L']; + + String _selectedBloodSugarUnit = 'mg/dlt'; + + String get selectedBloodSugarUnit => _selectedBloodSugarUnit; + + String _selectedBloodSugarMeasureTime = ''; + + String get selectedBloodSugarMeasureTime => _selectedBloodSugarMeasureTime; + + final List bloodSugarMeasureTimeEnList = [ + 'Before Breakfast', + 'After Breakfast', + 'Before Lunch', + 'After Lunch', + 'Before Dinner', + 'After Dinner', + 'Before Sleep', + 'After Sleep', + 'Fasting', + 'Other', + ]; + final List bloodSugarMeasureTimeArList = [ + "قبل الإفطار", + "بعد الإفطار", + "قبل الغداء", + "بعد الغداء", + "قبل العشاء", + "بعد العشاء", + "قبل النوم", + "بعد النوم", + "صائم", + "آخر", + ]; + + // Setters with notification + void setBloodSugarMeasureTime(String duration) async { + _selectedBloodSugarMeasureTime = duration; + notifyListeners(); + } + + // Setters with notification + void setFilterDuration(String duration) async { + _selectedDuration = duration; + notifyListeners(); + } + + // Setters with notification + void setGraphView(bool value) { + _isGraphView = value; + notifyListeners(); + } + + void setBloodSugarUnit(String unit) { + _selectedBloodSugarUnit = unit; + notifyListeners(); + } + + // ==================== WEIGHT FORM FIELDS ==================== + final List weightUnits = ['kg', 'lb']; + String _selectedWeightUnit = 'kg'; + + String get selectedWeightUnit => _selectedWeightUnit; + + void setWeightUnit(String unit) { + _selectedWeightUnit = unit; + notifyListeners(); + } + + // ==================== BLOOD PRESSURE FORM FIELDS ==================== + final List measuredArmList = ['Left Arm', 'Right Arm']; + String _selectedMeasuredArm = ''; + + String get selectedMeasuredArm => _selectedMeasuredArm; + + void setMeasuredArm(String arm) { + _selectedMeasuredArm = arm; + notifyListeners(); + } + + // Text Controllers + TextEditingController weightController = TextEditingController(); + TextEditingController bloodSugarController = TextEditingController(); + TextEditingController systolicController = TextEditingController(); + TextEditingController diastolicController = TextEditingController(); + + // Get current progress list based on selected duration + // dynamic get currentProgressData { + // switch (_selectedDuration) { + // case 'Daily': + // return _todayProgressList; + // case 'Weekly': + // return _weekProgressList; + // case 'Monthly': + // return _monthProgressList; + // default: + // return _todayProgressList; + // } + // } + + // ==================== WEIGHT TRACKING DATA ==================== + final List _monthWeightMeasurementResultAverage = []; + final List _weekWeightMeasurementResultAverage = []; + final List _yearWeightMeasurementResultAverage = []; + + final List _monthWeightMeasurementResult = []; + final List _weekWeightMeasurementResult = []; + final List _yearWeightMeasurementResult = []; + + // Getters for weight data + List get monthWeightMeasurementResultAverage => _monthWeightMeasurementResultAverage; + + List get weekWeightMeasurementResultAverage => _weekWeightMeasurementResultAverage; + + List get yearWeightMeasurementResultAverage => _yearWeightMeasurementResultAverage; + + List get monthWeightMeasurementResult => _monthWeightMeasurementResult; + + List get weekWeightMeasurementResult => _weekWeightMeasurementResult; + + List get yearWeightMeasurementResult => _yearWeightMeasurementResult; + + // ==================== BLOOD PRESSURE TRACKING DATA ==================== + final List _monthBloodPressureResultAverage = []; + final List _weekBloodPressureResultAverage = []; + final List _yearBloodPressureResultAverage = []; + + final List _monthBloodPressureResult = []; + final List _weekBloodPressureResult = []; + final List _yearBloodPressureResult = []; + + // Getters for blood pressure data + List get monthBloodPressureResultAverage => _monthBloodPressureResultAverage; + + List get weekBloodPressureResultAverage => _weekBloodPressureResultAverage; + + List get yearBloodPressureResultAverage => _yearBloodPressureResultAverage; + + List get monthBloodPressureResult => _monthBloodPressureResult; + + List get weekBloodPressureResult => _weekBloodPressureResult; + + List get yearBloodPressureResult => _yearBloodPressureResult; + + // ==================== BLOOD SUGAR (DIABETIC) TRACKING DATA ==================== + final List _monthDiabeticResultAverage = []; + final List _weekDiabeticResultAverage = []; + final List _yearDiabeticResultAverage = []; + + final List _monthDiabeticPatientResult = []; + final List _weekDiabeticPatientResult = []; + final List _yearDiabeticPatientResult = []; + + // Getters for blood sugar data + List get monthDiabeticResultAverage => _monthDiabeticResultAverage; + + List get weekDiabeticResultAverage => _weekDiabeticResultAverage; + + List get yearDiabeticResultAverage => _yearDiabeticResultAverage; + + List get monthDiabeticPatientResult => _monthDiabeticPatientResult; + + List get weekDiabeticPatientResult => _weekDiabeticPatientResult; + + List get yearDiabeticPatientResult => _yearDiabeticPatientResult; + + // ==================== WEIGHT TRACKING METHODS ==================== + + /// Fetch weight averages and results + Future getWeight() async { + isLoading = true; + notifyListeners(); + + try { + // Fetch weight averages + final averageResult = await healthTrackersRepo.getWeightMeasurementResultAverage(); + + averageResult.fold( + // (failure) => errorHandlerService.handleError(failure: failure), + (failure) => {}, + (apiModel) { + final data = apiModel.data; + if (data is Map) { + // Clear existing data + _monthWeightMeasurementResultAverage.clear(); + _weekWeightMeasurementResultAverage.clear(); + _yearWeightMeasurementResultAverage.clear(); + + // Parse month averages + if (data['monthAverageList'] != null) { + for (var item in (data['monthAverageList'] as List)) { + _monthWeightMeasurementResultAverage.add( + MonthWeightMeasurementResultAverage.fromJson(item), + ); + } + } + + // Parse week averages + if (data['weekAverageList'] != null) { + for (var item in (data['weekAverageList'] as List)) { + _weekWeightMeasurementResultAverage.add( + WeekWeightMeasurementResultAverage.fromJson(item), + ); + } + } + + // Parse year averages + if (data['yearAverageList'] != null) { + for (var item in (data['yearAverageList'] as List)) { + _yearWeightMeasurementResultAverage.add( + YearWeightMeasurementResultAverage.fromJson(item), + ); + } + } + } + }, + ); + + // Fetch weight results + final resultsResponse = await healthTrackersRepo.getWeightMeasurementResults(); + + resultsResponse.fold( + // (failure) => errorHandlerService.handleError(failure: failure), + (failure) => {}, + (apiModel) { + final data = apiModel.data; + if (data is Map) { + // Clear existing data + _monthWeightMeasurementResult.clear(); + _weekWeightMeasurementResult.clear(); + _yearWeightMeasurementResult.clear(); + + // Parse week results + if (data['weekResultList'] != null) { + for (var item in (data['weekResultList'] as List)) { + _weekWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item)); + } + } + + // Parse month results + if (data['monthResultList'] != null) { + for (var item in (data['monthResultList'] as List)) { + _monthWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item)); + } + } + + // Parse year results + if (data['yearResultList'] != null) { + for (var item in (data['yearResultList'] as List)) { + _yearWeightMeasurementResult.add(WeightMeasurementResult.fromJson(item)); + } + } + } + }, + ); + } catch (e) { + log('Error in getWeight: $e'); + } finally { + isLoading = false; + notifyListeners(); + } + } + + /// Add new weight result + Future addWeightResult({ + required String weightDate, + required String weightMeasured, + required int weightUnit, + }) async { + try { + final result = await healthTrackersRepo.addWeightMeasurementResult( + weightDate: weightDate, + weightMeasured: weightMeasured, + weightUnit: weightUnit, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful add + await getWeight(); + }, + ); + + return success; + } catch (e) { + log('Error in addWeightResult: $e'); + return false; + } + } + + /// Update existing weight result + Future updateWeightResult({ + required int lineItemNo, + required int weightUnit, + required String weightMeasured, + required String weightDate, + }) async { + try { + final result = await healthTrackersRepo.updateWeightMeasurementResult( + lineItemNo: lineItemNo, + weightUnit: weightUnit, + weightMeasured: weightMeasured, + weightDate: weightDate, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful update + await getWeight(); + }, + ); + + return success; + } catch (e) { + log('Error in updateWeightResult: $e'); + return false; + } + } + + /// Delete weight result + Future deleteWeightResult({ + required int lineItemNo, + }) async { + try { + final result = await healthTrackersRepo.deactivateWeightMeasurementStatus( + lineItemNo: lineItemNo, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful delete + await getWeight(); + }, + ); + + return success; + } catch (e) { + return false; + } + } + + /// Send weight report by email + Future sendWeightReportByEmail({ + required String email, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + try { + final result = await healthTrackersRepo.sendWeightReportByEmail( + email: email, + ); + + bool success = false; + + result.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + if (onFailure != null) onFailure("Failed to send report by email"); + }, + (apiModel) { + success = true; + if (onSuccess != null) onSuccess(); + }, + ); + + notifyListeners(); + + return success; + } catch (e) { + log('Error in sendWeightReportByEmail: $e'); + + if (onFailure != null) onFailure("An error occurred"); + return false; + } + } + + // ==================== BLOOD PRESSURE TRACKING METHODS ==================== + + /// Fetch blood pressure averages and results + Future getBloodPressure() async { + isLoading = true; + notifyListeners(); + + try { + // Fetch blood pressure averages + final averageResult = await healthTrackersRepo.getBloodPressureResultAverage(); + + averageResult.fold( + // (failure) => errorHandlerService.handleError(failure: failure), + (failure) => {}, + (apiModel) { + final data = apiModel.data; + + if (data is Map) { + // Clear existing data + _monthBloodPressureResultAverage.clear(); + _weekBloodPressureResultAverage.clear(); + _yearBloodPressureResultAverage.clear(); + + // Parse month averages + if (data['monthList'] != null) { + for (var item in (data['monthList'] as List)) { + _monthBloodPressureResultAverage.add( + MonthBloodPressureResultAverage.fromJson(item), + ); + } + } + + // Parse week averages + if (data['weekList'] != null) { + for (var item in (data['weekList'] as List)) { + _weekBloodPressureResultAverage.add( + WeekBloodPressureResultAverage.fromJson(item), + ); + } + } + + // Parse year averages + if (data['yearList'] != null) { + for (var item in (data['yearList'] as List)) { + _yearBloodPressureResultAverage.add( + YearBloodPressureResultAverage.fromJson(item), + ); + } + } + } + }, + ); + + // Fetch blood pressure results + final resultsResponse = await healthTrackersRepo.getBloodPressureResults(); + + resultsResponse.fold( + // (failure) => errorHandlerService.handleError(failure: failure), + (failure) => {}, + (apiModel) { + final data = apiModel.data; + if (data is Map) { + // Clear existing data + _monthBloodPressureResult.clear(); + _weekBloodPressureResult.clear(); + _yearBloodPressureResult.clear(); + + // Parse week results + if (data['weekList'] != null) { + for (var item in (data['weekList'] as List)) { + _weekBloodPressureResult.add(BloodPressureResult.fromJson(item)); + } + } + + // Parse month results + if (data['monthList'] != null) { + for (var item in (data['monthList'] as List)) { + _monthBloodPressureResult.add(BloodPressureResult.fromJson(item)); + } + } + + // Parse year results + if (data['yearList'] != null) { + for (var item in (data['yearList'] as List)) { + _yearBloodPressureResult.add(BloodPressureResult.fromJson(item)); + } + } + } + }, + ); + } catch (e) { + log('Error in getBloodPressure: $e'); + } finally { + isLoading = false; + notifyListeners(); + } + } + + /// Add or Update blood pressure result + Future addOrUpdateBloodPressureResult({ + required String bloodPressureDate, + required String diastolicPressure, + required String systolicePressure, + required int measuredArm, + int? lineItemNo, + bool isUpdate = false, + }) async { + try { + final result = isUpdate + ? await healthTrackersRepo.updateBloodPressureResult( + bloodPressureDate: bloodPressureDate, + diastolicPressure: diastolicPressure, + systolicePressure: systolicePressure, + measuredArm: measuredArm, + lineItemNo: lineItemNo!, + ) + : await healthTrackersRepo.addBloodPressureResult( + bloodPressureDate: bloodPressureDate, + diastolicPressure: diastolicPressure, + systolicePressure: systolicePressure, + measuredArm: measuredArm, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful add/update + await getBloodPressure(); + }, + ); + + return success; + } catch (e) { + log('Error in addOrUpdateBloodPressureResult: $e'); + return false; + } + } + + /// Delete blood pressure result + Future deleteBloodPressureResult({ + required int lineItemNo, + }) async { + try { + final result = await healthTrackersRepo.deactivateBloodPressureStatus( + lineItemNo: lineItemNo, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful delete + await getBloodPressure(); + }, + ); + + return success; + } catch (e) { + log('Error in deleteBloodPressureResult: $e'); + return false; + } + } + + /// Send blood pressure report by email + Future sendBloodPressureReportByEmail({ + required String email, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + try { + final result = await healthTrackersRepo.sendBloodPressureReportByEmail( + email: email, + ); + + bool success = false; + + result.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + if (onFailure != null) onFailure("Failed to send report by email"); + }, + (apiModel) { + success = true; + if (onSuccess != null) onSuccess(); + }, + ); + + notifyListeners(); + + return success; + } catch (e) { + log('Error in sendBloodPressureReportByEmail: $e'); + + if (onFailure != null) onFailure("An error occurred"); + return false; + } + } + + // ==================== BLOOD SUGAR (DIABETIC) TRACKING METHODS ==================== + + /// Fetch blood sugar averages and results + Future getBloodSugar() async { + isLoading = true; + notifyListeners(); + + try { + // Fetch blood sugar averages + final averageResult = await healthTrackersRepo.getDiabeticResultAverage(); + + averageResult.fold( + (failure) {}, + (apiModel) { + final data = apiModel.data; + if (data is Map) { + // Clear existing data + _monthDiabeticResultAverage.clear(); + _weekDiabeticResultAverage.clear(); + _yearDiabeticResultAverage.clear(); + + // Parse month averages + if (data['monthAverageList'] != null) { + for (var item in (data['monthAverageList'] as List)) { + _monthDiabeticResultAverage.add( + MonthDiabeticResultAverage.fromJson(item), + ); + } + } + + // Parse week averages + if (data['weekAverageList'] != null) { + for (var item in (data['weekAverageList'] as List)) { + _weekDiabeticResultAverage.add( + WeekDiabeticResultAverage.fromJson(item), + ); + } + } + + // Parse year averages + if (data['yearAverageList'] != null) { + for (var item in (data['yearAverageList'] as List)) { + _yearDiabeticResultAverage.add( + YearDiabeticResultAverage.fromJson(item), + ); + } + } + } + }, + ); + + // Fetch blood sugar results + final resultsResponse = await healthTrackersRepo.getDiabeticResults(); + + resultsResponse.fold( + // (failure) => errorHandlerService.handleError(failure: failure), + (failure) {}, + (apiModel) { + final data = apiModel.data; + if (data is Map) { + // Clear existing data + _monthDiabeticPatientResult.clear(); + _weekDiabeticPatientResult.clear(); + _yearDiabeticPatientResult.clear(); + + // Parse week results + if (data['weekResultList'] != null) { + for (var item in (data['weekResultList'] as List)) { + _weekDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item)); + } + } + + // Parse month results + if (data['monthResultList'] != null) { + for (var item in (data['monthResultList'] as List)) { + _monthDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item)); + } + } + + // Parse year results + if (data['yearResultList'] != null) { + for (var item in (data['yearResultList'] as List)) { + _yearDiabeticPatientResult.add(DiabeticPatientResult.fromJson(item)); + } + } + } + }, + ); + } catch (e) { + log('Error in getBloodSugar: $e'); + } finally { + isLoading = false; + notifyListeners(); + } + } + + /// Add new blood sugar result + Future addBloodSugarResult({ + required String bloodSugarDateChart, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + }) async { + try { + final result = await healthTrackersRepo.addDiabeticResult( + bloodSugarDateChart: bloodSugarDateChart, + bloodSugarResult: bloodSugarResult, + diabeticUnit: diabeticUnit, + measuredTime: measuredTime, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful add + await getBloodSugar(); + }, + ); + + return success; + } catch (e) { + log('Error in addBloodSugarResult: $e'); + return false; + } + } + + /// Update existing blood sugar result + Future updateBloodSugarResult({ + required DateTime month, + required DateTime hour, + required String bloodSugarResult, + required String diabeticUnit, + required int measuredTime, + required int lineItemNo, + }) async { + try { + final result = await healthTrackersRepo.updateDiabeticResult( + month: month, + hour: hour, + bloodSugarResult: bloodSugarResult, + diabeticUnit: diabeticUnit, + measuredTime: measuredTime, + lineItemNo: lineItemNo, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful update + await getBloodSugar(); + }, + ); + + return success; + } catch (e) { + log('Error in updateBloodSugarResult: $e'); + return false; + } + } + + /// Delete blood sugar result + Future deleteBloodSugarResult({ + required int lineItemNo, + }) async { + try { + final result = await healthTrackersRepo.deactivateDiabeticStatus( + lineItemNo: lineItemNo, + ); + + bool success = false; + + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) async { + success = true; + // Refresh data after successful delete + await getBloodSugar(); + }, + ); + + return success; + } catch (e) { + log('Error in deleteBloodSugarResult: $e'); + return false; + } + } + + /// Send blood sugar report by email + Future sendBloodSugarReportByEmail({ + required String email, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + try { + final result = await healthTrackersRepo.sendBloodSugarReportByEmail( + email: email, + ); + + bool success = false; + + result.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + if (onFailure != null) onFailure("Failed to send report by email"); + }, + (apiModel) { + success = true; + if (onSuccess != null) onSuccess(); + }, + ); + + notifyListeners(); + + return success; + } catch (e) { + log('Error in sendBloodSugarReportByEmail: $e'); + if (onFailure != null) onFailure("An error occurred"); + return false; + } + } + + // Validation method + String? _validateBloodSugarEntry(String dateTime) { + // Validate blood sugar value + if (bloodSugarController.text.trim().isEmpty) { + return "Please enter blood sugar value"; + } + + final bloodSugarValue = double.tryParse(bloodSugarController.text.trim()); + if (bloodSugarValue == null) { + return "Please enter a valid number"; + } + + if (bloodSugarValue <= 0) { + return "Blood sugar value must be greater than 0"; + } + + // Validate reasonable range (typical ranges) + if (bloodSugarValue > 1000) { + return "Blood sugar value seems too high. Please check and enter again"; + } + + // Validate date time + if (dateTime.trim().isEmpty) { + return "Please select date and time"; + } + + // Validate measure time + if (_selectedBloodSugarMeasureTime.isEmpty) { + return "Please select when the measurement was taken"; + } + + return null; // No errors + } + + // Save blood sugar entry with validation + Future saveBloodSugarEntry({ + required String dateTime, + required String measureTime, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + // Validate + final validationError = _validateBloodSugarEntry(dateTime); + if (validationError != null) { + _errorMessage = validationError; + if (onFailure != null) onFailure(validationError); + return; + } + + // Clear previous error and show loading + _errorMessage = null; + isLoading = true; + notifyListeners(); + + try { + // Get measure time index (0-based, but API expects 1-based) + final measureTimeIndex = bloodSugarMeasureTimeEnList.indexOf(measureTime); + + // Call API + final success = await addBloodSugarResult( + bloodSugarDateChart: dateTime, + bloodSugarResult: bloodSugarController.text.trim(), + diabeticUnit: _selectedBloodSugarUnit, + measuredTime: measureTimeIndex >= 0 ? measureTimeIndex : 0, + ); + + isLoading = false; + + if (success) { + // Clear form after successful save + bloodSugarController.clear(); + _selectedBloodSugarMeasureTime = ''; + notifyListeners(); + if (onSuccess != null) onSuccess(); + } else { + _errorMessage = "Failed to save blood sugar entry. Please try again"; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } catch (e) { + log('Error in saveBloodSugarEntry: $e'); + _errorMessage = "An error occurred. Please try again"; + isLoading = false; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } + + // ==================== WEIGHT ENTRY METHODS ==================== + + // Validate weight entry before saving + String? _validateWeightEntry(String dateTime) { + // Validate weight value + final weightValue = weightController.text.trim(); + if (weightValue.isEmpty) { + return "Please enter weight value"; + } + + // Check if it's a valid number + final parsedValue = double.tryParse(weightValue); + if (parsedValue == null || parsedValue <= 0) { + return "Please enter a valid weight value"; + } + + // Validate date time + if (dateTime.trim().isEmpty) { + return "Please select date and time"; + } + + return null; // No errors + } + + // Save weight entry with validation + Future saveWeightEntry({ + required String dateTime, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + // Validate + final validationError = _validateWeightEntry(dateTime); + if (validationError != null) { + _errorMessage = validationError; + if (onFailure != null) onFailure(validationError); + return; + } + + // Clear previous error and show loading + _errorMessage = null; + isLoading = true; + notifyListeners(); + + try { + // Get weight unit index (0 = kg, 1 = lb) + final weightUnitIndex = weightUnits.indexOf(_selectedWeightUnit); + + // Call API + final success = await addWeightResult( + weightDate: dateTime, + weightMeasured: weightController.text.trim(), + weightUnit: weightUnitIndex >= 0 ? weightUnitIndex : 0, + ); + + isLoading = false; + + if (success) { + // Clear form after successful save + weightController.clear(); + notifyListeners(); + if (onSuccess != null) onSuccess(); + } else { + _errorMessage = "Failed to save weight entry. Please try again"; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } catch (e) { + log('Error in saveWeightEntry: $e'); + _errorMessage = "An error occurred. Please try again"; + isLoading = false; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } + + // ==================== BLOOD PRESSURE ENTRY METHODS ==================== + + // Validate blood pressure entry before saving + String? _validateBloodPressureEntry(String dateTime) { + // Validate systolic value + final systolicValue = systolicController.text.trim(); + if (systolicValue.isEmpty) { + return "Please enter systolic value"; + } + final parsedSystolic = int.tryParse(systolicValue); + if (parsedSystolic == null || parsedSystolic <= 0) { + return "Please enter a valid systolic value"; + } + + // Validate diastolic value + final diastolicValue = diastolicController.text.trim(); + if (diastolicValue.isEmpty) { + return "Please enter diastolic value"; + } + final parsedDiastolic = int.tryParse(diastolicValue); + if (parsedDiastolic == null || parsedDiastolic <= 0) { + return "Please enter a valid diastolic value"; + } + + // Validate arm selection + if (_selectedMeasuredArm.isEmpty) { + return "Please select measured arm"; + } + + // Validate date time + if (dateTime.trim().isEmpty) { + return "Please select date and time"; + } + + return null; // No errors + } + + // Save blood pressure entry with validation + Future saveBloodPressureEntry({ + required String dateTime, + Function()? onSuccess, + Function(String error)? onFailure, + }) async { + // Validate + final validationError = _validateBloodPressureEntry(dateTime); + if (validationError != null) { + _errorMessage = validationError; + if (onFailure != null) onFailure(validationError); + return; + } + + // Clear previous error and show loading + _errorMessage = null; + isLoading = true; + notifyListeners(); + + try { + // Get measured arm index (0 = Left Arm, 1 = Right Arm) + final measuredArmIndex = measuredArmList.indexOf(_selectedMeasuredArm); + + // Call API + final success = await addOrUpdateBloodPressureResult( + bloodPressureDate: dateTime, + systolicePressure: systolicController.text.trim(), + diastolicPressure: diastolicController.text.trim(), + measuredArm: measuredArmIndex >= 0 ? measuredArmIndex : 0, + isUpdate: false, + ); + + isLoading = false; + + if (success) { + // Clear form after successful save + systolicController.clear(); + diastolicController.clear(); + _selectedMeasuredArm = ''; + notifyListeners(); + if (onSuccess != null) onSuccess(); + } else { + _errorMessage = "Failed to save blood pressure entry. Please try again"; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } catch (e) { + log('Error in saveBloodPressureEntry: $e'); + _errorMessage = "An error occurred. Please try again"; + isLoading = false; + notifyListeners(); + if (onFailure != null) onFailure(_errorMessage!); + } + } + + @override + void dispose() { + bloodSugarController.dispose(); + weightController.dispose(); + systolicController.dispose(); + diastolicController.dispose(); + super.dispose(); + } +} diff --git a/lib/features/health_trackers/models/blood_pressure/blood_pressure_result.dart b/lib/features/health_trackers/models/blood_pressure/blood_pressure_result.dart new file mode 100644 index 0000000..f024d8e --- /dev/null +++ b/lib/features/health_trackers/models/blood_pressure/blood_pressure_result.dart @@ -0,0 +1,87 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class BloodPressureResult { + int? patientID; + int? lineItemNo; + DateTime? bloodPressureDate; + int? measuredArm; + int? systolicePressure; + int? diastolicPressure; + dynamic remark; + bool? isActive; + int? chartYear; + String? chartMonth; + dynamic yearSystolicePressureAverageResult; + dynamic monthSystolicePressureResult; + dynamic weekSystolicePressureResult; + int? yearDiastolicPressureAverageResult; + dynamic monthDiastolicPressureResult; + dynamic weekDiastolicPressureResult; + String? measuredArmDesc; + dynamic weekDesc; + + BloodPressureResult( + {this.patientID, + this.lineItemNo, + this.bloodPressureDate, + this.measuredArm, + this.systolicePressure, + this.diastolicPressure, + this.remark, + this.isActive, + this.chartYear, + this.chartMonth, + this.yearSystolicePressureAverageResult, + this.monthSystolicePressureResult, + this.weekSystolicePressureResult, + this.yearDiastolicPressureAverageResult, + this.monthDiastolicPressureResult, + this.weekDiastolicPressureResult, + this.measuredArmDesc, + this.weekDesc}); + + BloodPressureResult.fromJson(Map json) { + patientID = json['PatientID']; + lineItemNo = json['LineItemNo']; + bloodPressureDate = DateUtil.convertStringToDate(json['BloodPressureDate']); + measuredArm = json['MeasuredArm']; + systolicePressure = json['SystolicePressure']; + diastolicPressure = json['DiastolicPressure']; + remark = json['Remark']; + isActive = json['IsActive']; + chartYear = json['ChartYear']; + chartMonth = json['ChartMonth']; + yearSystolicePressureAverageResult = json['YearSystolicePressureAverageResult']; + monthSystolicePressureResult = json['MonthSystolicePressureResult']; + weekSystolicePressureResult = json['WeekSystolicePressureResult']; + yearDiastolicPressureAverageResult = json['YearDiastolicPressureAverageResult']; + monthDiastolicPressureResult = json['MonthDiastolicPressureResult']; + weekDiastolicPressureResult = json['WeekDiastolicPressureResult']; + measuredArmDesc = json['MeasuredArmDesc']; + weekDesc = json['WeekDesc']; + } + + Map toJson() { + final Map data = {}; + data['PatientID'] = patientID; + data['LineItemNo'] = lineItemNo; + data['BloodPressureDate'] = bloodPressureDate; + data['MeasuredArm'] = measuredArm; + data['SystolicePressure'] = systolicePressure; + data['DiastolicPressure'] = diastolicPressure; + data['Remark'] = remark; + data['IsActive'] = isActive; + data['ChartYear'] = chartYear; + data['ChartMonth'] = chartMonth; + data['YearSystolicePressureAverageResult'] = yearSystolicePressureAverageResult; + data['MonthSystolicePressureResult'] = monthSystolicePressureResult; + data['WeekSystolicePressureResult'] = weekSystolicePressureResult; + data['YearDiastolicPressureAverageResult'] = yearDiastolicPressureAverageResult; + data['MonthDiastolicPressureResult'] = monthDiastolicPressureResult; + data['WeekDiastolicPressureResult'] = weekDiastolicPressureResult; + data['MeasuredArmDesc'] = measuredArmDesc; + data['WeekDesc'] = weekDesc; + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_pressure/month_blood_pressure_result_average.dart b/lib/features/health_trackers/models/blood_pressure/month_blood_pressure_result_average.dart new file mode 100644 index 0000000..3975805 --- /dev/null +++ b/lib/features/health_trackers/models/blood_pressure/month_blood_pressure_result_average.dart @@ -0,0 +1,58 @@ +class MonthBloodPressureResultAverage { + dynamic weekfourSystolicePressureAverageResult; + dynamic weekfourDiastolicPressureAverageResult; + dynamic weekthreeSystolicePressureAverageResult; + dynamic weekthreeDiastolicPressureAverageResult; + dynamic weektwoSystolicePressureAverageResult; + dynamic weektwoDiastolicPressureAverageResult; + dynamic weekoneSystolicePressureAverageResult; + dynamic weekoneDiastolicPressureAverageResult; + String? weekDesc; + int? weekDiastolicPressureAverageResult; + int? weekSystolicePressureAverageResult; + + MonthBloodPressureResultAverage({ + this.weekfourSystolicePressureAverageResult, + this.weekfourDiastolicPressureAverageResult, + this.weekthreeSystolicePressureAverageResult, + this.weekthreeDiastolicPressureAverageResult, + this.weektwoSystolicePressureAverageResult, + this.weektwoDiastolicPressureAverageResult, + this.weekoneSystolicePressureAverageResult, + this.weekoneDiastolicPressureAverageResult, + this.weekDesc, + this.weekDiastolicPressureAverageResult, + this.weekSystolicePressureAverageResult, + }); + + MonthBloodPressureResultAverage.fromJson(Map json) { + weekfourSystolicePressureAverageResult = json['weekfourSystolicePressureAverageResult']; + weekfourDiastolicPressureAverageResult = json['weekfourDiastolicPressureAverageResult']; + weekthreeSystolicePressureAverageResult = json['weekthreeSystolicePressureAverageResult']; + weekthreeDiastolicPressureAverageResult = json['weekthreeDiastolicPressureAverageResult']; + weektwoSystolicePressureAverageResult = json['weektwoSystolicePressureAverageResult']; + weektwoDiastolicPressureAverageResult = json['weektwoDiastolicPressureAverageResult']; + weekoneSystolicePressureAverageResult = json['weekoneSystolicePressureAverageResult']; + weekoneDiastolicPressureAverageResult = json['weekoneDiastolicPressureAverageResult']; + weekDesc = json['WeekDesc']; + weekDiastolicPressureAverageResult = json['WeekDiastolicPressureAverageResult']; + weekSystolicePressureAverageResult = json['WeekSystolicePressureAverageResult']; + } + + Map toJson() { + final Map data = {}; + data['weekfourSystolicePressureAverageResult'] = weekfourSystolicePressureAverageResult; + data['weekfourDiastolicPressureAverageResult'] = weekfourDiastolicPressureAverageResult; + data['weekthreeSystolicePressureAverageResult'] = weekthreeSystolicePressureAverageResult; + data['weekthreeDiastolicPressureAverageResult'] = weekthreeDiastolicPressureAverageResult; + data['weektwoSystolicePressureAverageResult'] = weektwoSystolicePressureAverageResult; + data['weektwoDiastolicPressureAverageResult'] = weektwoDiastolicPressureAverageResult; + data['weekoneSystolicePressureAverageResult'] = weekoneSystolicePressureAverageResult; + data['weekoneDiastolicPressureAverageResult'] = weekoneDiastolicPressureAverageResult; + data['WeekDesc'] = weekDesc; + data['WeekDiastolicPressureAverageResult'] = weekDiastolicPressureAverageResult; + data['WeekSystolicePressureAverageResult'] = weekSystolicePressureAverageResult; + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_pressure/week_blood_pressure_result_average.dart b/lib/features/health_trackers/models/blood_pressure/week_blood_pressure_result_average.dart new file mode 100644 index 0000000..381d514 --- /dev/null +++ b/lib/features/health_trackers/models/blood_pressure/week_blood_pressure_result_average.dart @@ -0,0 +1,24 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class WeekBloodPressureResultAverage { + int? dailySystolicePressureAverageResult; + int? dailyDiastolicPressureAverageResult; + DateTime? bloodPressureDate; + + WeekBloodPressureResultAverage({this.dailySystolicePressureAverageResult, this.dailyDiastolicPressureAverageResult, this.bloodPressureDate}); + + WeekBloodPressureResultAverage.fromJson(Map json) { + dailySystolicePressureAverageResult = json['DailySystolicePressureAverageResult']; + dailyDiastolicPressureAverageResult = json['DailyDiastolicPressureAverageResult']; + bloodPressureDate = DateUtil.convertStringToDate(json['BloodPressureDate']); + } + + Map toJson() { + final Map data = {}; + data['DailySystolicePressureAverageResult'] = dailySystolicePressureAverageResult; + data['DailyDiastolicPressureAverageResult'] = dailyDiastolicPressureAverageResult; + data['BloodPressureDate'] = bloodPressureDate; + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_pressure/year_blood_pressure_result_average.dart b/lib/features/health_trackers/models/blood_pressure/year_blood_pressure_result_average.dart new file mode 100644 index 0000000..6f34246 --- /dev/null +++ b/lib/features/health_trackers/models/blood_pressure/year_blood_pressure_result_average.dart @@ -0,0 +1,37 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class YearBloodPressureResultAverage { + int? monthSystolicePressureAverageResult; + int? monthDiastolicPressureAverageResult; + dynamic monthNumber; + String? monthName; + String? yearName; + DateTime? date; + + YearBloodPressureResultAverage({ + this.monthSystolicePressureAverageResult, + this.monthDiastolicPressureAverageResult, + this.monthNumber, + this.monthName, + this.yearName, + }); + + YearBloodPressureResultAverage.fromJson(Map json) { + monthSystolicePressureAverageResult = json['monthSystolicePressureAverageResult']; + monthDiastolicPressureAverageResult = json['monthDiastolicPressureAverageResult']; + monthNumber = json['monthNumber']; + monthName = json['monthName']; + yearName = json['yearName']; + date = DateUtil.getMonthDateTime(monthName!, yearName); + } + + Map toJson() { + final Map data = {}; + data['monthSystolicePressureAverageResult'] = monthSystolicePressureAverageResult; + data['monthDiastolicPressureAverageResult'] = monthDiastolicPressureAverageResult; + data['monthNumber'] = monthNumber; + data['monthName'] = monthName; + data['yearName'] = yearName; + return data; + } +} diff --git a/lib/features/health_trackers/models/blood_sugar/diabetic_patient_result.dart b/lib/features/health_trackers/models/blood_sugar/diabetic_patient_result.dart new file mode 100644 index 0000000..066df3c --- /dev/null +++ b/lib/features/health_trackers/models/blood_sugar/diabetic_patient_result.dart @@ -0,0 +1,99 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class DiabeticPatientResult { + String? chartMonth; + var chartYear; + DateTime? dateChart; + var description; + var descriptionN; + int? diabtecAvarage; + bool? isActive; + int? lineItemNo; + var listMonth; + var listWeek; + int? measured; + String? measuredDesc; + var monthAverageResult; + int? patientID; + var remark; + var resultDesc; + dynamic resultValue; + String? unit; + var weekAverageResult; + String? weekDesc; + var yearAverageResult; + + DiabeticPatientResult( + {this.chartMonth, + this.chartYear, + this.dateChart, + this.description, + this.descriptionN, + this.diabtecAvarage, + this.isActive, + this.lineItemNo, + this.listMonth, + this.listWeek, + this.measured, + this.measuredDesc, + this.monthAverageResult, + this.patientID, + this.remark, + this.resultDesc, + this.resultValue, + this.unit, + this.weekAverageResult, + this.weekDesc, + this.yearAverageResult}); + + DiabeticPatientResult.fromJson(Map json) { + chartMonth = json['ChartMonth']; + chartYear = json['ChartYear']; + dateChart = DateUtil.convertStringToDate(json['DateChart']); + description = json['Description']; + descriptionN = json['DescriptionN']; + diabtecAvarage = json['DiabtecAvarage']; + isActive = json['IsActive']; + lineItemNo = json['LineItemNo']; + listMonth = json['List_Month']; + listWeek = json['List_Week']; + measured = json['Measured']; + measuredDesc = json['MeasuredDesc']; + monthAverageResult = json['MonthAverageResult']; + patientID = json['PatientID']; + remark = json['Remark']; + resultDesc = json['ResultDesc']; + resultValue = json['ResultValue']; + unit = json['Unit']; + weekAverageResult = json['WeekAverageResult']; + weekDesc = json['WeekDesc']; + yearAverageResult = json['YearAverageResult']; + } + + Map toJson() { + final Map data = {}; + data['ChartMonth'] = chartMonth; + data['ChartYear'] = chartYear; + data['DateChart'] = DateUtil.convertDateToString(dateChart!); + data['Description'] = description; + data['DescriptionN'] = descriptionN; + data['DiabtecAvarage'] = diabtecAvarage; + data['IsActive'] = isActive; + data['LineItemNo'] = lineItemNo; + data['List_Month'] = listMonth; + data['List_Week'] = listWeek; + data['Measured'] = measured; + data['MeasuredDesc'] = measuredDesc; + data['MonthAverageResult'] = monthAverageResult; + data['PatientID'] = patientID; + data['Remark'] = remark; + data['ResultDesc'] = resultDesc; + data['ResultValue'] = resultValue; + data['Unit'] = unit; + data['WeekAverageResult'] = weekAverageResult; + data['WeekDesc'] = weekDesc; + data['YearAverageResult'] = yearAverageResult; + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_sugar/month_diabetic_result_average.dart b/lib/features/health_trackers/models/blood_sugar/month_diabetic_result_average.dart new file mode 100644 index 0000000..77b06f1 --- /dev/null +++ b/lib/features/health_trackers/models/blood_sugar/month_diabetic_result_average.dart @@ -0,0 +1,37 @@ +class MonthDiabeticResultAverage { + var weekfourAverageResult; + var weekthreeAverageResult; + var weektwoAverageResult; + var weekoneAverageResult; + dynamic weekAverageResult; + String? weekDesc; + + MonthDiabeticResultAverage( + {this.weekfourAverageResult, + this.weekthreeAverageResult, + this.weektwoAverageResult, + this.weekoneAverageResult, + this.weekAverageResult, + this.weekDesc}); + + MonthDiabeticResultAverage.fromJson(Map json) { + weekfourAverageResult = json['weekfourAverageResult']; + weekthreeAverageResult = json['weekthreeAverageResult']; + weektwoAverageResult = json['weektwoAverageResult']; + weekoneAverageResult = json['weekoneAverageResult']; + weekAverageResult = json['WeekAverageResult']; + weekDesc = json['WeekDesc']; + } + + Map toJson() { + final Map data = {}; + data['weekfourAverageResult'] = weekfourAverageResult; + data['weekthreeAverageResult'] = weekthreeAverageResult; + data['weektwoAverageResult'] = weektwoAverageResult; + data['weekoneAverageResult'] = weekoneAverageResult; + data['WeekAverageResult'] = weekAverageResult; + data['WeekDesc'] = weekDesc; + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart b/lib/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart new file mode 100644 index 0000000..3b35fe7 --- /dev/null +++ b/lib/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart @@ -0,0 +1,21 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class WeekDiabeticResultAverage { + dynamic dailyAverageResult; + DateTime? dateChart; + + WeekDiabeticResultAverage({this.dailyAverageResult, this.dateChart}); + + WeekDiabeticResultAverage.fromJson(Map json) { + dailyAverageResult = json['DailyAverageResult']; + dateChart = DateUtil.convertStringToDate(json['DateChart']); + } + + Map toJson() { + final Map data = {}; + data['DailyAverageResult'] = dailyAverageResult; + data['DateChart'] = DateUtil.convertDateToString(dateChart!); + return data; + } +} + diff --git a/lib/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart b/lib/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart new file mode 100644 index 0000000..fb34056 --- /dev/null +++ b/lib/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart @@ -0,0 +1,35 @@ +import 'dart:developer'; + +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class YearDiabeticResultAverage { + dynamic monthAverageResult; + var monthNumber; + String? monthName; + String? yearName; + DateTime? date; + + YearDiabeticResultAverage({this.monthAverageResult, this.monthNumber, this.monthName, this.yearName}); + + YearDiabeticResultAverage.fromJson(Map json) { + try { + monthAverageResult = json['monthAverageResult']; + monthNumber = json['monthNumber']; + monthName = json['monthName']; + yearName = json['yearName']; + date = DateUtil.getMonthDateTime(monthName!, yearName); + } catch (e) { + log(e.toString()); + } + } + + Map toJson() { + final Map data = {}; + data['monthAverageResult'] = monthAverageResult; + data['monthNumber'] = monthNumber; + data['monthName'] = monthName; + data['yearName'] = yearName; + return data; + } +} + diff --git a/lib/features/health_trackers/models/weight/month_weight_measurement_result_average.dart b/lib/features/health_trackers/models/weight/month_weight_measurement_result_average.dart new file mode 100644 index 0000000..f95470c --- /dev/null +++ b/lib/features/health_trackers/models/weight/month_weight_measurement_result_average.dart @@ -0,0 +1,37 @@ +class MonthWeightMeasurementResultAverage { + dynamic weekfourAverageResult; + dynamic weekthreeAverageResult; + dynamic weektwoAverageResult; + dynamic weekoneAverageResult; + dynamic weekAverageResult; + String? weekDesc; + + MonthWeightMeasurementResultAverage( + {this.weekfourAverageResult, + this.weekthreeAverageResult, + this.weektwoAverageResult, + this.weekoneAverageResult, + this.weekAverageResult, + this.weekDesc}); + + MonthWeightMeasurementResultAverage.fromJson(Map json) { + weekfourAverageResult = json['weekfourAverageResult']; + weekthreeAverageResult = json['weekthreeAverageResult']; + weektwoAverageResult = json['weektwoAverageResult']; + weekoneAverageResult = json['weekoneAverageResult']; + weekAverageResult = json['WeekAverageResult']; + weekDesc = json['WeekDesc']; + } + + Map toJson() { + final Map data = {}; + data['weekfourAverageResult'] = weekfourAverageResult; + data['weekthreeAverageResult'] = weekthreeAverageResult; + data['weektwoAverageResult'] = weektwoAverageResult; + data['weekoneAverageResult'] = weekoneAverageResult; + data['WeekAverageResult'] = weekAverageResult; + data['WeekDesc'] = weekDesc; + return data; + } +} + diff --git a/lib/features/health_trackers/models/weight/week_weight_measurement_result_average.dart b/lib/features/health_trackers/models/weight/week_weight_measurement_result_average.dart new file mode 100644 index 0000000..ad53325 --- /dev/null +++ b/lib/features/health_trackers/models/weight/week_weight_measurement_result_average.dart @@ -0,0 +1,21 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class WeekWeightMeasurementResultAverage { + dynamic dailyAverageResult; + DateTime? weightDate; + + WeekWeightMeasurementResultAverage({this.dailyAverageResult, this.weightDate}); + + WeekWeightMeasurementResultAverage.fromJson(Map json) { + dailyAverageResult = json['DailyAverageResult']; + weightDate = DateUtil.convertStringToDate(json['WeightDate']); + } + + Map toJson() { + final Map data = {}; + data['DailyAverageResult'] = dailyAverageResult; + data['WeightDate'] = weightDate; + return data; + } +} + diff --git a/lib/features/health_trackers/models/weight/weight_measurement_result.dart b/lib/features/health_trackers/models/weight/weight_measurement_result.dart new file mode 100644 index 0000000..896d33f --- /dev/null +++ b/lib/features/health_trackers/models/weight/weight_measurement_result.dart @@ -0,0 +1,77 @@ +import 'dart:developer'; + +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class WeightMeasurementResult { + int? patientID; + int? lineItemNo; + int? weightMeasured; + DateTime? weightDate; + dynamic remark; + bool? isActive; + int? measured; + dynamic unit; + int? chartYear; + dynamic chartMonth; + double? yearAverageResult; + dynamic monthAverageResult; + dynamic weekAverageResult; + dynamic weekDesc; + + WeightMeasurementResult( + {this.patientID, + this.lineItemNo, + this.weightMeasured, + this.weightDate, + this.remark, + this.isActive, + this.measured, + this.unit, + this.chartYear, + this.chartMonth, + this.yearAverageResult, + this.monthAverageResult, + this.weekAverageResult, + this.weekDesc}); + + WeightMeasurementResult.fromJson(Map json) { + try { + patientID = json['PatientID']; + lineItemNo = json['LineItemNo']; + weightMeasured = json['WeightMeasured']; + weightDate = DateUtil.convertStringToDate(json['WeightDate']); + remark = json['Remark']; + isActive = json['IsActive']; + measured = json['Measured']; + unit = json['Unit']; + chartYear = json['ChartYear']; + chartMonth = json['ChartMonth']; + // Convert to double safely since API may return int + yearAverageResult = json['YearAverageResult'] != null ? (json['YearAverageResult'] as num).toDouble() : null; + monthAverageResult = json['MonthAverageResult']; + weekAverageResult = json['WeekAverageResult']; + weekDesc = json['WeekDesc']; + } catch (e) { + log(e.toString()); + } + } + + Map toJson() { + final Map data = {}; + data['PatientID'] = patientID; + data['LineItemNo'] = lineItemNo; + data['WeightMeasured'] = weightMeasured; + data['WeightDate'] = weightDate; + data['Remark'] = remark; + data['IsActive'] = isActive; + data['Measured'] = measured; + data['Unit'] = unit; + data['ChartYear'] = chartYear; + data['ChartMonth'] = chartMonth; + data['YearAverageResult'] = yearAverageResult; + data['MonthAverageResult'] = monthAverageResult; + data['WeekAverageResult'] = weekAverageResult; + data['WeekDesc'] = weekDesc; + return data; + } +} diff --git a/lib/features/health_trackers/models/weight/year_weight_measurement_result_average.dart b/lib/features/health_trackers/models/weight/year_weight_measurement_result_average.dart new file mode 100644 index 0000000..7dc4b24 --- /dev/null +++ b/lib/features/health_trackers/models/weight/year_weight_measurement_result_average.dart @@ -0,0 +1,29 @@ +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; + +class YearWeightMeasurementResultAverage { + dynamic monthAverageResult; + int? monthNumber; + String? monthName; + String? yearName; + DateTime? date; + + YearWeightMeasurementResultAverage({this.monthAverageResult, this.monthNumber, this.monthName, this.yearName}); + + YearWeightMeasurementResultAverage.fromJson(Map json) { + monthAverageResult = json['monthAverageResult']; + monthNumber = json['monthNumber']; + monthName = json['monthName']; + yearName = json['yearName']; + date = DateUtil.getMonthDateTime(monthName!, yearName); + } + + Map toJson() { + final Map data = {}; + data['monthAverageResult'] = monthAverageResult; + data['monthNumber'] = monthNumber; + data['monthName'] = monthName; + data['yearName'] = yearName; + return data; + } +} + diff --git a/lib/features/hmg_services/hmg_services_repo.dart b/lib/features/hmg_services/hmg_services_repo.dart index 85e6018..e4b9a03 100644 --- a/lib/features/hmg_services/hmg_services_repo.dart +++ b/lib/features/hmg_services/hmg_services_repo.dart @@ -940,7 +940,16 @@ class HmgServicesRepoImp implements HmgServicesRepo { for (var vitalSignJson in vitalSignsList) { if (vitalSignJson is Map) { - vitalSignList.add(VitalSignResModel.fromJson(vitalSignJson)); + final vitalSign = VitalSignResModel.fromJson(vitalSignJson); + + // Only add records where BOTH height AND weight are greater than 0 + final hasValidWeight = _isValidValue(vitalSign.weightKg); + final hasValidHeight = _isValidValue(vitalSign.heightCm); + + // Only add if both height and weight are valid (> 0) + if (hasValidWeight && hasValidHeight) { + vitalSignList.add(vitalSign); + } } } } @@ -967,5 +976,22 @@ class HmgServicesRepoImp implements HmgServicesRepo { } } + /// Helper method to check if a value is valid (greater than 0) + bool _isValidValue(dynamic value) { + if (value == null) return false; + + if (value is num) { + return value > 0; + } + + if (value is String) { + if (value.trim().isEmpty) return false; + final parsed = double.tryParse(value); + return parsed != null && parsed > 0; + } + + return false; + } + } diff --git a/lib/features/hmg_services/hmg_services_view_model.dart b/lib/features/hmg_services/hmg_services_view_model.dart index c55a11c..daddbff 100644 --- a/lib/features/hmg_services/hmg_services_view_model.dart +++ b/lib/features/hmg_services/hmg_services_view_model.dart @@ -40,6 +40,8 @@ class HmgServicesViewModel extends ChangeNotifier { bool isHospitalListLoading = false; bool isVitalSignLoading = false; + bool hasVitalSignDataLoaded = false; + // HHC specific loading states bool isHhcOrdersLoading = false; bool isHhcServicesLoading = false; @@ -878,6 +880,7 @@ class HmgServicesViewModel extends ChangeNotifier { Function(dynamic)? onSuccess, Function(String)? onError, }) async { + if (hasVitalSignDataLoaded) return; isVitalSignLoading = true; notifyListeners(); @@ -896,6 +899,7 @@ class HmgServicesViewModel extends ChangeNotifier { isVitalSignLoading = false; if (apiResponse.messageStatus == 1) { vitalSignList = apiResponse.data ?? []; + hasVitalSignDataLoaded = true; notifyListeners(); if (onSuccess != null) { onSuccess(apiResponse); diff --git a/lib/features/hmg_services/models/ui_models/hmg_services_component_model.dart b/lib/features/hmg_services/models/ui_models/hmg_services_component_model.dart index 7a92198..ebc9511 100644 --- a/lib/features/hmg_services/models/ui_models/hmg_services_component_model.dart +++ b/lib/features/hmg_services/models/ui_models/hmg_services_component_model.dart @@ -8,8 +8,10 @@ class HmgServicesComponentModel { Color? iconColor; bool isLogin; bool isLocked; + Color textColor; Color bgColor; String? route; + bool isExternalLink; Function? onTap; HmgServicesComponentModel( @@ -23,6 +25,8 @@ class HmgServicesComponentModel { this.bgColor = Colors.white, this.iconColor = Colors.white, this.route, - this.onTap + this.onTap, + this.textColor = Colors.black, + this.isExternalLink = false, }); } diff --git a/lib/features/hospital/hospital_selection_view_model.dart b/lib/features/hospital/hospital_selection_view_model.dart index dd9531f..c0cab2a 100644 --- a/lib/features/hospital/hospital_selection_view_model.dart +++ b/lib/features/hospital/hospital_selection_view_model.dart @@ -1,5 +1,7 @@ import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/location_util.dart'; import 'package:hmg_patient_app_new/core/utils/penguin_method_channel.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/features/hospital/AppPermission.dart'; @@ -17,20 +19,32 @@ class HospitalSelectionBottomSheetViewModel extends ChangeNotifier { int hmgCount = 0; TextEditingController searchController = TextEditingController(); final AppState appState; + LocationUtils locationUtils = getIt.get(); HospitalSelectionBottomSheetViewModel(this.appState) { - Utils.navigationProjectsList.forEach((element) { - HospitalsModel model = HospitalsModel.fromJson(element); - if (model.isHMC == true) { - hmcHospitalList.add(model); - } else { - hmgHospitalList.add(model); - } - listOfData.add(model); + locationUtils.getCurrentLocation(onSuccess: (value) { + Utils.navigationProjectsList.forEach((element) { + HospitalsModel model = HospitalsModel.fromJson(element); + + double dist = Utils.distance(value.latitude, value.longitude, double.parse(model.latitude!), double.parse(model.longitude!)).ceilToDouble(); + print(dist); + model.distanceInKilometers = dist; + + if (model.isHMC == true) { + hmcHospitalList.add(model); + } else { + hmgHospitalList.add(model); + } + listOfData.add(model); + }); + hmgCount = hmgHospitalList.length; + hmcCount = hmcHospitalList.length; + + listOfData.sort((a, b) => a.distanceInKilometers.compareTo(b.distanceInKilometers)); + hmgHospitalList.sort((a, b) => a.distanceInKilometers.compareTo(b.distanceInKilometers)); + + getDisplayList(); }); - hmgCount = hmgHospitalList.length; - hmcCount = hmcHospitalList.length; - getDisplayList(); } getDisplayList() { @@ -79,13 +93,14 @@ class HospitalSelectionBottomSheetViewModel extends ChangeNotifier { } - void openPenguin(HospitalsModel hospital) { - initPenguinSDK(hospital.iD); + void openPenguin(HospitalsModel hospital, {String clinicID = ""}) { + initPenguinSDK(hospital.iD, clinicID: clinicID); } - initPenguinSDK(int projectID) async { + initPenguinSDK(int projectID, {String clinicID = ""}) async { NavigationClinicDetails data = NavigationClinicDetails(); data.projectId = projectID.toString(); + data.clinicId = clinicID; final bool permited = await AppPermission.askPenguinPermissions(); if (!permited) { Map statuses = await [ diff --git a/lib/features/immediate_livecare/immediate_livecare_view_model.dart b/lib/features/immediate_livecare/immediate_livecare_view_model.dart index 1baa81b..ffa0b00 100644 --- a/lib/features/immediate_livecare/immediate_livecare_view_model.dart +++ b/lib/features/immediate_livecare/immediate_livecare_view_model.dart @@ -45,9 +45,7 @@ class ImmediateLiveCareViewModel extends ChangeNotifier { initImmediateLiveCare() { _appState = getIt(); immediateLiveCareClinicsList = []; - patientLiveCareHistoryList = []; isImmediateLiveCareClinicsLoading = true; - patientHasPendingLiveCareRequest = false; liveCareSelectedCallType = 0; // 1- Video, 2- Audio, 3- Phone immediateLiveCareSelectedClinic = GetLiveCareClinicListResponseModel(); liveCareImmediateAppointmentFeesList = LiveCareImmediateAppointmentFeesList(); @@ -136,6 +134,10 @@ class ImmediateLiveCareViewModel extends ChangeNotifier { } Future getPatientLiveCareHistory({Function(dynamic)? onSuccess, Function(String)? onError}) async { + patientLiveCareHistoryList = []; + patientHasPendingLiveCareRequest = false; + notifyListeners(); + final result = await immediateLiveCareRepo.getPatientLiveCareHistory(); result.fold( diff --git a/lib/features/medical_file/medical_file_repo.dart b/lib/features/medical_file/medical_file_repo.dart index 2f5cae6..09856ca 100644 --- a/lib/features/medical_file/medical_file_repo.dart +++ b/lib/features/medical_file/medical_file_repo.dart @@ -293,14 +293,13 @@ class MedicalFileRepoImp implements MedicalFileRepo { Failure? failure; await apiClient.post( ApiConsts.getAllSharedRecordsByStatus, - body: {if (status != null) "Status": status, "PatientID": patientID}, + body: {if (status != null) "Status": status, "PatientID": patientID.toString()}, onFailure: (error, statusCode, {messageStatus, failureType}) { failure = failureType; }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) { try { - final list = response['GetAllSharedRecordsByStatusList']; - + final list = response['GetAllSharedRecordsByStatusList'] ?? []; final familyLists = list.map((item) => FamilyFileResponseModelLists.fromJson(item as Map)).toList().cast(); @@ -336,7 +335,7 @@ class MedicalFileRepoImp implements MedicalFileRepo { }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) { try { - final list = response['GetAllPendingRecordsList']; + final list = response['GetAllPendingRecordsList'] ?? []; final familyLists = list.map((item) => FamilyFileResponseModelLists.fromJson(item as Map)).toList().cast(); apiResponse = GenericApiModel>( diff --git a/lib/features/medical_file/medical_file_view_model.dart b/lib/features/medical_file/medical_file_view_model.dart index d67e5de..b26a87a 100644 --- a/lib/features/medical_file/medical_file_view_model.dart +++ b/lib/features/medical_file/medical_file_view_model.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; import 'package:hmg_patient_app_new/core/utils/request_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; @@ -40,6 +41,7 @@ class MedicalFileViewModel extends ChangeNotifier { List patientSickLeavesViewList = []; bool isSickLeavesSortByClinic = true; + bool isSickLeavesDataNeedsReloading = true; List patientAllergiesList = []; @@ -162,15 +164,15 @@ class MedicalFileViewModel extends ChangeNotifier { } setIsPatientSickLeaveListLoading(bool val) { - if (val) { + if (val && isSickLeavesDataNeedsReloading) { patientSickLeaveList.clear(); patientSickLeavesByClinic.clear(); patientSickLeavesByHospital.clear(); patientSickLeavesViewList.clear(); patientSickLeavePDFBase64 = ""; isSickLeavesSortByClinic = true; + isPatientSickLeaveListLoading = val; } - isPatientSickLeaveListLoading = val; notifyListeners(); } @@ -266,6 +268,10 @@ class MedicalFileViewModel extends ChangeNotifier { } Future getPatientSickLeaveList({Function(dynamic)? onSuccess, Function(String)? onError}) async { + if (!isSickLeavesDataNeedsReloading) { + return; + } + patientSickLeaveList.clear(); final result = await medicalFileRepo.getPatientSickLeavesList(); @@ -308,6 +314,7 @@ class MedicalFileViewModel extends ChangeNotifier { } } patientSickLeavesViewList = patientSickLeavesByClinic; + isSickLeavesDataNeedsReloading = false; notifyListeners(); if (onSuccess != null) { @@ -576,9 +583,18 @@ class MedicalFileViewModel extends ChangeNotifier { await RequestUtils.getAddFamilyRequest(nationalIDorFile: authVM.nationalIdController.text, mobileNo: authVM.phoneNumberController.text, countryCode: authVM.selectedCountrySignup.countryCode); final resultEither = await medicalFileRepo.addFamilyFile(request: request.toJson()); - resultEither.fold((failure) async => await errorHandlerService.handleError(failure: failure), (apiResponse) async { + resultEither.fold( + (failure) async => await errorHandlerService.handleError( + failure: failure, + onUnHandledFailure: (failure) { + LoaderBottomSheet.hideLoader(); + _dialogService.showErrorBottomSheet( + message: failure.message!, + onOkPressed: () { + navigationService.pop(); + }); + }), (apiResponse) async { if (apiResponse.messageStatus == 2) { - print("======="); LoaderBottomSheet.hideLoader(); _dialogService.showErrorBottomSheet( message: apiResponse.errorMessage!, diff --git a/lib/features/monthly_reports/monthly_reports_repo.dart b/lib/features/monthly_reports/monthly_reports_repo.dart new file mode 100644 index 0000000..4ace6ec --- /dev/null +++ b/lib/features/monthly_reports/monthly_reports_repo.dart @@ -0,0 +1,96 @@ +import 'package:dartz/dartz.dart'; +import '../../core/api/api_client.dart'; +import '../../core/api_consts.dart'; +import '../../core/common_models/generic_api_model.dart'; +import '../../core/exceptions/api_failure.dart'; +import '../../services/logger_service.dart'; + +abstract class MonthlyReportsRepo { + Future>> saveMonthlyReport({ + String? email, + }); +} + +class MonthlyReportsRepoImp implements MonthlyReportsRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + MonthlyReportsRepoImp({ + required this.loggerService, + required this.apiClient, + }); + + @override + Future>> saveMonthlyReport({ + String? email, + }) async { + try { + Failure? failure; + + GenericApiModel? reportApiResponse; + + await apiClient.post( + ApiConsts.getMonthlyReports, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + reportApiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (reportApiResponse == null) return Left(ServerFailure("Unknown error")); + + if ((reportApiResponse!.messageStatus ?? 0) != 1) { + return Right(reportApiResponse!); + } + + GenericApiModel? emailApiResponse; + + final Map emailRequest = {}; + + if (email != null && email.trim().isNotEmpty) { + emailRequest["Email"] = email.trim(); + } + + await apiClient.post( + ApiConsts.updatePatientEmail, + body: emailRequest, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + emailApiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (emailApiResponse == null) return Left(ServerFailure("Unknown error")); + + return Right(emailApiResponse!); + } catch (e) { + loggerService.logError("MonthlyReportsRepo.saveMonthlyReport error: $e"); + return Left(UnknownFailure(e.toString())); + } + } +} diff --git a/lib/features/monthly_reports/monthly_reports_view_model.dart b/lib/features/monthly_reports/monthly_reports_view_model.dart new file mode 100644 index 0000000..4fd82da --- /dev/null +++ b/lib/features/monthly_reports/monthly_reports_view_model.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; +import 'monthly_reports_repo.dart'; +class MonthlyReportsViewModel extends ChangeNotifier { + final MonthlyReportsRepo monthlyReportsRepo; + final ErrorHandlerService errorHandlerService; + + bool isLoading = false; + + MonthlyReportsViewModel({ + required this.monthlyReportsRepo, + required this.errorHandlerService, + }); + + Future saveMonthlyReport({String? email}) async { + isLoading = true; + notifyListeners(); + + final result = await monthlyReportsRepo.saveMonthlyReport(email: email); + + final success = result.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + return false; + }, + (apiResponse) => (apiResponse.messageStatus ?? 0) == 1, + ); + + isLoading = false; + notifyListeners(); + return success; + } +} diff --git a/lib/features/monthly_reports/terms_conditions_repo.dart b/lib/features/monthly_reports/terms_conditions_repo.dart new file mode 100644 index 0000000..a5d3f95 --- /dev/null +++ b/lib/features/monthly_reports/terms_conditions_repo.dart @@ -0,0 +1,60 @@ +import 'package:dartz/dartz.dart'; +import '../../core/api/api_client.dart'; +import '../../core/api_consts.dart'; +import '../../core/exceptions/api_failure.dart'; +import '../../services/logger_service.dart'; + +abstract class TermsConditionsRepo { + Future> getTermsConditions(); +} + +class TermsConditionsRepoImp implements TermsConditionsRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + TermsConditionsRepoImp({ + required this.loggerService, + required this.apiClient, + }); + + @override + Future> getTermsConditions() async { + Failure? failure; + String? html; + + try { + await apiClient.post( + ApiConsts.getTermsConditions, + body: {}, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType ?? ServerFailure(error.toString()); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + + final content = response['UserAgreementContent']; + + if (content is String && content.isNotEmpty) { + html = content; + } else { + failure = DataParsingFailure( + 'UserAgreementContent is null or not String'); + } + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + } catch (e) { + failure = UnknownFailure(e.toString()); + } + + if (failure != null) return Left(failure!); + if (html == null || html!.isEmpty) { + return Left(ServerFailure('No terms and conditions returned')); + } + + return Right(html!); + } +} + diff --git a/lib/features/monthly_reports/terms_conditions_view_model.dart b/lib/features/monthly_reports/terms_conditions_view_model.dart new file mode 100644 index 0000000..bd70b87 --- /dev/null +++ b/lib/features/monthly_reports/terms_conditions_view_model.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/features/monthly_reports/terms_conditions_repo.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; + +class TermsConditionsViewModel extends ChangeNotifier { + final TermsConditionsRepo termsConditionsRepo; + final ErrorHandlerService errorHandlerService; + + String? termsConditionsHtml; + bool isLoading = false; + + TermsConditionsViewModel({ + required this.termsConditionsRepo, + required this.errorHandlerService, + }); + + Future getTermsConditions({ + Function()? onSuccess, + Function(String)? onError, + }) async { + isLoading = true; + notifyListeners(); + + final result = await termsConditionsRepo.getTermsConditions(); + + result.fold( + (failure) async { + await errorHandlerService.handleError(failure: failure); + isLoading = false; + notifyListeners(); + if (onError != null) { + onError(failure.message ?? 'Something went wrong'); + } + }, + (html) { + termsConditionsHtml = html; + isLoading = false; + notifyListeners(); + if (onSuccess != null) onSuccess(); + }, + ); + } +} + + diff --git a/lib/features/my_appointments/my_appointments_view_model.dart b/lib/features/my_appointments/my_appointments_view_model.dart index 9bd48ec..f287803 100644 --- a/lib/features/my_appointments/my_appointments_view_model.dart +++ b/lib/features/my_appointments/my_appointments_view_model.dart @@ -220,6 +220,7 @@ class MyAppointmentsViewModel extends ChangeNotifier { } Future getPatientAppointments(bool isActiveAppointment, bool isArrivedAppointments, {Function(dynamic)? onSuccess, Function(String)? onError}) async { + isPatientHasQueueAppointment = false; if (!isAppointmentDataToBeLoaded) return; filteredAppointmentList.clear(); @@ -281,9 +282,9 @@ class MyAppointmentsViewModel extends ChangeNotifier { } } - print('Upcoming Appointments: ${patientUpcomingAppointmentsHistoryList.length}'); - print('Arrived Appointments: ${patientArrivedAppointmentsHistoryList.length}'); - print('All Appointments: ${patientAppointmentsHistoryList.length}'); + debugPrint('Upcoming Appointments: ${patientUpcomingAppointmentsHistoryList.length}'); + debugPrint('Arrived Appointments: ${patientArrivedAppointmentsHistoryList.length}'); + debugPrint('All Appointments: ${patientAppointmentsHistoryList.length}'); getFiltersForSelectedAppointmentList(filteredAppointmentList); notifyListeners(); } @@ -726,6 +727,8 @@ class MyAppointmentsViewModel extends ChangeNotifier { } Future getPatientAppointmentQueueDetails({Function(dynamic)? onSuccess, Function(String)? onError}) async { + //TODO: Discuss With Haroon, Is the User Has no data it return No Element Bad State; + isPatientHasQueueAppointment = false; isAppointmentQueueDetailsLoading = true; notifyListeners(); final result = await myAppointmentsRepo.getPatientAppointmentQueueDetails( diff --git a/lib/features/my_appointments/utils/appointment_type.dart b/lib/features/my_appointments/utils/appointment_type.dart index abc23dc..ae3c751 100644 --- a/lib/features/my_appointments/utils/appointment_type.dart +++ b/lib/features/my_appointments/utils/appointment_type.dart @@ -69,7 +69,7 @@ class AppointmentType { case 10: return AppColors.successColor; case 15: - return AppColors.greyColor; + return AppColors.greyTextColor; case 20: return AppColors.infoColor; case 50: @@ -84,7 +84,7 @@ class AppointmentType { static String getNextActionText(nextAction) { switch (nextAction) { case 0: - return "No Action".needTranslation; + return LocaleKeys.upcomingNoAction.tr(); case 10: return LocaleKeys.confirm.tr(); case 15: @@ -96,7 +96,7 @@ class AppointmentType { case 90: return LocaleKeys.checkinOption.tr(); default: - return "No Action".needTranslation; + return LocaleKeys.upcomingNoAction.tr(); } } diff --git a/lib/features/notifications/models/resp_models/notification_response_model.dart b/lib/features/notifications/models/resp_models/notification_response_model.dart new file mode 100644 index 0000000..034e19c --- /dev/null +++ b/lib/features/notifications/models/resp_models/notification_response_model.dart @@ -0,0 +1,96 @@ +class NotificationResponseModel { + int? id; + int? recordId; + int? patientID; + bool? projectOutSA; + String? deviceType; + String? deviceToken; + String? message; + String? messageType; + String? messageTypeData; + String? videoURL; + bool? isQueue; + String? isQueueOn; + String? createdOn; + dynamic createdBy; + String? notificationType; + bool? isSent; + String? isSentOn; + bool? isRead; + dynamic isReadOn; + int? channelID; + int? projectID; + + NotificationResponseModel( + {this.id, + this.recordId, + this.patientID, + this.projectOutSA, + this.deviceType, + this.deviceToken, + this.message, + this.messageType, + this.messageTypeData, + this.videoURL, + this.isQueue, + this.isQueueOn, + this.createdOn, + this.createdBy, + this.notificationType, + this.isSent, + this.isSentOn, + this.isRead, + this.isReadOn, + this.channelID, + this.projectID}); + + NotificationResponseModel.fromJson(Map json) { + id = json['Id']; + recordId = json['RecordId']; + patientID = json['PatientID']; + projectOutSA = json['ProjectOutSA']; + deviceType = json['DeviceType']; + deviceToken = json['DeviceToken']; + message = json['Message']; + messageType = json['MessageType']; + messageTypeData = json['MessageTypeData']; + videoURL = json['VideoURL']; + isQueue = json['IsQueue']; + isQueueOn = json['IsQueueOn']; + createdOn = json['CreatedOn']; + createdBy = json['CreatedBy']; + notificationType = json['NotificationType']; + isSent = json['IsSent']; + isSentOn = json['IsSentOn']; + isRead = json['IsRead']; + isReadOn = json['IsReadOn']; + channelID = json['ChannelID']; + projectID = json['ProjectID']; + } + + Map toJson() { + final Map data = new Map(); + data['Id'] = this.id; + data['RecordId'] = this.recordId; + data['PatientID'] = this.patientID; + data['ProjectOutSA'] = this.projectOutSA; + data['DeviceType'] = this.deviceType; + data['DeviceToken'] = this.deviceToken; + data['Message'] = this.message; + data['MessageType'] = this.messageType; + data['MessageTypeData'] = this.messageTypeData; + data['VideoURL'] = this.videoURL; + data['IsQueue'] = this.isQueue; + data['IsQueueOn'] = this.isQueueOn; + data['CreatedOn'] = this.createdOn; + data['CreatedBy'] = this.createdBy; + data['NotificationType'] = this.notificationType; + data['IsSent'] = this.isSent; + data['IsSentOn'] = this.isSentOn; + data['IsRead'] = this.isRead; + data['IsReadOn'] = this.isReadOn; + data['ChannelID'] = this.channelID; + data['ProjectID'] = this.projectID; + return data; + } +} diff --git a/lib/features/notifications/notifications_repo.dart b/lib/features/notifications/notifications_repo.dart new file mode 100644 index 0000000..853a979 --- /dev/null +++ b/lib/features/notifications/notifications_repo.dart @@ -0,0 +1,78 @@ +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/core/api/api_client.dart'; +import 'package:hmg_patient_app_new/core/api_consts.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; +import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; +import 'package:hmg_patient_app_new/features/notifications/models/resp_models/notification_response_model.dart'; +import 'package:hmg_patient_app_new/services/logger_service.dart'; + +abstract class NotificationsRepo { + Future>>> getAllNotifications({ + required int notificationStatusID, + required int pagingSize, + required int currentPage, + }); +} + +class NotificationsRepoImp implements NotificationsRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + NotificationsRepoImp({required this.loggerService, required this.apiClient}); + + @override + Future>>> getAllNotifications({ + required int notificationStatusID, + required int pagingSize, + required int currentPage, + }) async { + Map mapDevice = { + "NotificationStatusID": notificationStatusID, + "pagingSize": pagingSize, + "currentPage": currentPage, + }; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + await apiClient.post( + GET_ALL_NOTIFICATIONS, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final list = response['List_GetAllNotificationsFromPool']; + if (list == null || list.isEmpty) { + // Return empty list if no notifications + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: [], + ); + return; + } + + final notifications = list.map((item) => NotificationResponseModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: notifications, + ); + } catch (e) { + failure = DataParsingFailure(e.toString()); + } + }, + ); + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } +} diff --git a/lib/features/notifications/notifications_view_model.dart b/lib/features/notifications/notifications_view_model.dart new file mode 100644 index 0000000..e15e267 --- /dev/null +++ b/lib/features/notifications/notifications_view_model.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/features/notifications/models/resp_models/notification_response_model.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_repo.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; + +class NotificationsViewModel extends ChangeNotifier { + bool isNotificationsLoading = false; + bool hasMoreNotifications = true; + + NotificationsRepo notificationsRepo; + ErrorHandlerService errorHandlerService; + + List notificationsList = []; + + int currentPage = 0; + int pagingSize = 14; + int notificationStatusID = 2; // Default to status 2 (e.g., unread) + + NotificationsViewModel({ + required this.notificationsRepo, + required this.errorHandlerService, + }); + + initNotificationsViewModel({int? statusID}) { + notificationsList.clear(); + currentPage = 0; + hasMoreNotifications = true; + isNotificationsLoading = true; + // if (statusID != null) { + // notificationStatusID = statusID; + // } + // getAllNotifications(); + notifyListeners(); + } + + setNotificationStatusID(int statusID) { + notificationStatusID = statusID; + notificationsList.clear(); + currentPage = 0; + hasMoreNotifications = true; + notifyListeners(); + } + + Future getAllNotifications({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + isNotificationsLoading = true; + notifyListeners(); + + final result = await notificationsRepo.getAllNotifications( + notificationStatusID: notificationStatusID, + pagingSize: pagingSize, + currentPage: currentPage, + ); + + result.fold( + (failure) async { + isNotificationsLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isNotificationsLoading = false; + if (apiResponse.messageStatus == 2) { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? "Unknown error"); + } + } else if (apiResponse.messageStatus == 1) { + final newNotifications = apiResponse.data ?? []; + + if (newNotifications.isEmpty || newNotifications.length < pagingSize) { + hasMoreNotifications = false; + } + + notificationsList.addAll(newNotifications); + currentPage++; + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } + + Future refreshNotifications({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + notificationsList.clear(); + currentPage = 0; + hasMoreNotifications = true; + await getAllNotifications(onSuccess: onSuccess, onError: onError); + } + + Future loadMoreNotifications({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + await getAllNotifications(onSuccess: onSuccess, onError: onError); + } + + @override + void dispose() { + super.dispose(); + } +} diff --git a/lib/features/prescriptions/prescriptions_view_model.dart b/lib/features/prescriptions/prescriptions_view_model.dart index ff86406..a7cd42f 100644 --- a/lib/features/prescriptions/prescriptions_view_model.dart +++ b/lib/features/prescriptions/prescriptions_view_model.dart @@ -47,20 +47,24 @@ class PrescriptionsViewModel extends ChangeNotifier { late GeocodeResponse locationGeocodeResponse; bool isPrescriptionsDeliveryOrdersLoading = false; + + bool isPrescriptionsDataNeedsReloading = true; List prescriptionsOrderList = []; PrescriptionsViewModel({required this.prescriptionsRepo, required this.errorHandlerService, required this.navServices}); initPrescriptionsViewModel() { - patientPrescriptionOrders.clear(); - patientPrescriptionOrdersByClinic.clear(); - patientPrescriptionOrdersByHospital.clear(); - patientPrescriptionOrdersViewList.clear(); - prescriptionsOrderList.clear(); - isPrescriptionsOrdersLoading = true; + if (isPrescriptionsDataNeedsReloading) { + patientPrescriptionOrders.clear(); + patientPrescriptionOrdersByClinic.clear(); + patientPrescriptionOrdersByHospital.clear(); + patientPrescriptionOrdersViewList.clear(); + prescriptionsOrderList.clear(); + isPrescriptionsOrdersLoading = true; + getPatientPrescriptionOrders(); + } isSortByClinic = true; isPrescriptionsDeliveryOrdersLoading = true; - getPatientPrescriptionOrders(); notifyListeners(); } @@ -98,6 +102,10 @@ class PrescriptionsViewModel extends ChangeNotifier { } Future getPatientPrescriptionOrders({Function(dynamic)? onSuccess, Function(String)? onError}) async { + if (!isPrescriptionsDataNeedsReloading) { + return; + } + final result = await prescriptionsRepo.getPatientPrescriptionOrders(patientId: "1231755"); result.fold( @@ -131,6 +139,7 @@ class PrescriptionsViewModel extends ChangeNotifier { } } patientPrescriptionOrdersViewList = patientPrescriptionOrdersByClinic; + isPrescriptionsDataNeedsReloading = false; notifyListeners(); if (onSuccess != null) { onSuccess(apiResponse); @@ -245,8 +254,8 @@ class PrescriptionsViewModel extends ChangeNotifier { CustomPageRoute( page: MapUtilityScreen( confirmButtonString: LocaleKeys.next.tr(), - titleString: "Select Location".needTranslation, - subTitleString: "Please select the location for prescription delivery".needTranslation, + titleString: LocaleKeys.selectLocation.tr(), + subTitleString: LocaleKeys.selectLocationPrescriptionDelivery.tr(), isGmsAvailable: getIt.get().isGMSAvailable, ), direction: AxisDirection.down), diff --git a/lib/features/qr_parking/models/qr_parking_response_model.dart b/lib/features/qr_parking/models/qr_parking_response_model.dart new file mode 100644 index 0000000..2e90da1 --- /dev/null +++ b/lib/features/qr_parking/models/qr_parking_response_model.dart @@ -0,0 +1,183 @@ + + +class QrParkingResponseModel { + dynamic totalRecords; + dynamic nRowID; + int? qRParkingID; + String? description; + String? descriptionN; + dynamic qRCompare; + dynamic qRValue; + String? imagePath; + bool? isActive; + int? parkingID; + int? branchID; + int? companyID; + int? buildingID; + int? rowID; + int? gateID; + int? floorID; + dynamic imagePath1; + int? createdBy; + String? createdOn; + dynamic editedBy; + dynamic editedOn; + String? parkingDescription; + String? parkingDescriptionN; + String? gateDescription; + String? gateDescriptionN; + String? branchDescription; + String? branchDescriptionN; + String? companyDescription; + String? companyDescriptionN; + String? rowDescription; + String? rowDescriptionN; + String? floorDescription; + String? floorDescriptionN; + String? buildingDescription; + String? buildingDescriptionN; + String? qRParkingCode; + String? parkingCode; + double? latitude; + double? longitude; + String? qRImageStr; + + QrParkingResponseModel({ + this.totalRecords, + this.nRowID, + this.qRParkingID, + this.description, + this.descriptionN, + this.qRCompare, + this.qRValue, + this.imagePath, + this.isActive, + this.parkingID, + this.branchID, + this.companyID, + this.buildingID, + this.rowID, + this.gateID, + this.floorID, + this.imagePath1, + this.createdBy, + this.createdOn, + this.editedBy, + this.editedOn, + this.parkingDescription, + this.parkingDescriptionN, + this.gateDescription, + this.gateDescriptionN, + this.branchDescription, + this.branchDescriptionN, + this.companyDescription, + this.companyDescriptionN, + this.rowDescription, + this.rowDescriptionN, + this.floorDescription, + this.floorDescriptionN, + this.buildingDescription, + this.buildingDescriptionN, + this.qRParkingCode, + this.parkingCode, + this.latitude, + this.longitude, + this.qRImageStr, + }); + + QrParkingResponseModel.fromJson(Map json) { + totalRecords = json['TotalRecords']; + nRowID = json['nRowID']; + qRParkingID = json['QRParkingID']; + description = json['Description']; + descriptionN = json['DescriptionN']; + qRCompare = json['QRCompare']; + qRValue = json['QRValue']; + imagePath = json['ImagePath']; + isActive = json['IsActive']; + parkingID = json['ParkingID']; + branchID = json['BranchID']; + companyID = json['CompanyID']; + buildingID = json['BuildingID']; + rowID = json['RowID']; + gateID = json['GateID']; + floorID = json['FloorID']; + imagePath1 = json['ImagePath1']; + createdBy = json['CreatedBy']; + createdOn = json['CreatedOn']; + editedBy = json['EditedBy']; + editedOn = json['EditedOn']; + parkingDescription = json['ParkingDescription']; + parkingDescriptionN = json['ParkingDescriptionN']; + gateDescription = json['GateDescription']; + gateDescriptionN = json['GateDescriptionN']; + branchDescription = json['BranchDescription']; + branchDescriptionN = json['BranchDescriptionN']; + companyDescription = json['CompanyDescription']; + companyDescriptionN = json['CompanyDescriptionN']; + rowDescription = json['RowDescription']; + rowDescriptionN = json['RowDescriptionN']; + floorDescription = json['FloorDescription']; + floorDescriptionN = json['FloorDescriptionN']; + buildingDescription = json['BuildingDescription']; + buildingDescriptionN = json['BuildingDescriptionN']; + qRParkingCode = json['QRParkingCode']; + parkingCode = json['ParkingCode']; + latitude = _toDouble(json['Latitude']); + longitude = _toDouble(json['Longitude']); + qRImageStr = json['QRImageStr']; + } + + Map toJson() { + final Map data = {}; + data['TotalRecords'] = totalRecords; + data['nRowID'] = nRowID; + data['QRParkingID'] = qRParkingID; + data['Description'] = description; + data['DescriptionN'] = descriptionN; + data['QRCompare'] = qRCompare; + data['QRValue'] = qRValue; + data['ImagePath'] = imagePath; + data['IsActive'] = isActive; + data['ParkingID'] = parkingID; + data['BranchID'] = branchID; + data['CompanyID'] = companyID; + data['BuildingID'] = buildingID; + data['RowID'] = rowID; + data['GateID'] = gateID; + data['FloorID'] = floorID; + data['ImagePath1'] = imagePath1; + data['CreatedBy'] = createdBy; + data['CreatedOn'] = createdOn; + data['EditedBy'] = editedBy; + data['EditedOn'] = editedOn; + data['ParkingDescription'] = parkingDescription; + data['ParkingDescriptionN'] = parkingDescriptionN; + data['GateDescription'] = gateDescription; + data['GateDescriptionN'] = gateDescriptionN; + data['BranchDescription'] = branchDescription; + data['BranchDescriptionN'] = branchDescriptionN; + data['CompanyDescription'] = companyDescription; + data['CompanyDescriptionN'] = companyDescriptionN; + data['RowDescription'] = rowDescription; + data['RowDescriptionN'] = rowDescriptionN; + data['FloorDescription'] = floorDescription; + data['FloorDescriptionN'] = floorDescriptionN; + data['BuildingDescription'] = buildingDescription; + data['BuildingDescriptionN'] = buildingDescriptionN; + data['QRParkingCode'] = qRParkingCode; + data['ParkingCode'] = parkingCode; + data['Latitude'] = latitude; + data['Longitude'] = longitude; + data['QRImageStr'] = qRImageStr; + return data; + } + + static double? _toDouble(dynamic v) { + if (v == null) return null; + if (v is double) return v; + if (v is int) return v.toDouble(); + return double.tryParse(v.toString()); + } +} + diff --git a/lib/features/qr_parking/qr_parking_repo.dart b/lib/features/qr_parking/qr_parking_repo.dart new file mode 100644 index 0000000..1ec905f --- /dev/null +++ b/lib/features/qr_parking/qr_parking_repo.dart @@ -0,0 +1,74 @@ + + +import 'package:dartz/dartz.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/models/qr_parking_response_model.dart'; +import '../../core/api/api_client.dart'; +import '../../core/api_consts.dart'; +import '../../core/common_models/generic_api_model.dart'; +import '../../core/exceptions/api_failure.dart'; +import '../../services/logger_service.dart'; + + +abstract class QrParkingRepo { + Future>>> + getQrParking({ + required int qrParkingId, + }); +} + +class QrParkingRepoImp implements QrParkingRepo { + final ApiClient apiClient; + final LoggerService loggerService; + + QrParkingRepoImp({ + required this.loggerService, + required this.apiClient, + }); + + @override + Future>>> + getQrParking({required int qrParkingId}) async { + try { + GenericApiModel>? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getQrParkingDetails, // GetQRParkingByID + body: {'QRParkingID': qrParkingId}, + onFailure: (error, statusCode, + {messageStatus, failureType}) { + failure = failureType ?? + StatusCodeFailure("$error ($statusCode)"); + }, + onSuccess: (response, statusCode, + {messageStatus, errorMessage}) { + final list = + (response['List_SWP_QRParkingModel'] as List?) ?? []; + + final res = list + .map((e) => QrParkingResponseModel.fromJson( + Map.from(e), + )) + .toList(); + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: res, + ); + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) { + return Left(ServerFailure("Unknown error")); + } + + return Right(apiResponse!); + } catch (e) { + return Left(UnknownFailure(e.toString())); + } + } +} + diff --git a/lib/features/qr_parking/qr_parking_view_model.dart b/lib/features/qr_parking/qr_parking_view_model.dart new file mode 100644 index 0000000..b0b688f --- /dev/null +++ b/lib/features/qr_parking/qr_parking_view_model.dart @@ -0,0 +1,144 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:barcode_scan2/barcode_scan2.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_repo.dart'; + +import '../../services/cache_service.dart'; +import '../../services/error_handler_service.dart'; +import 'models/qr_parking_response_model.dart'; + + +class QrParkingViewModel extends ChangeNotifier { + final QrParkingRepo qrParkingRepo; + final ErrorHandlerService errorHandlerService; + final CacheService cacheService; + String IS_GO_TO_PARKING = 'IS_GO_TO_PARKING'; + + bool isLoading = false; + String? error; + + bool isSavePark = false; + QrParkingResponseModel? qrParkingModel; + List qrParkingList = []; + + QrParkingViewModel({ + required this.qrParkingRepo, + required this.errorHandlerService, + required this.cacheService, + }); + + + Future scanAndGetParking() async { + try { + error = null; + isLoading = true; + notifyListeners(); + + final result = await BarcodeScanner.scan(); + + if (result.type != ResultType.Barcode) { + isLoading = false; + notifyListeners(); + return null; + } + + final raw = result.rawContent.trim(); + if (raw.isEmpty) { + error = "Invalid QR Code"; + isLoading = false; + notifyListeners(); + return null; + } + + final qrParkingId = _extractQrParkingId(raw); + if (qrParkingId == null) { + error = "Invalid QR Code"; + isLoading = false; + notifyListeners(); + return null; + } + + final apiResult = + await qrParkingRepo.getQrParking(qrParkingId: qrParkingId); + + final model = apiResult.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + error = failure.toString(); + return null; + }, + (apiResponse) { + qrParkingList = apiResponse.data ?? []; + if (qrParkingList.isNotEmpty) { + return qrParkingList.first; + } + error = "Invalid Qr Code"; + return null; + }, + ); + + if (model != null) { + qrParkingModel = model; + isSavePark = true; + + await cacheService.saveObject( + key: IS_GO_TO_PARKING, + value: model.toJson(), + ); + } + + isLoading = false; + notifyListeners(); + return model; + } catch (e) { + error = "Scan error"; + isLoading = false; + notifyListeners(); + return null; + } + } + + /// Load saved parking + Future getIsSaveParking() async { + isLoading = true; + notifyListeners(); + + final parking = + await cacheService.getObject(key: IS_GO_TO_PARKING); + + if (parking != null) { + isSavePark = true; + qrParkingModel = QrParkingResponseModel.fromJson( + Map.from(parking), + ); + } else { + isSavePark = false; + qrParkingModel = null; + } + + isLoading = false; + notifyListeners(); + } + + /// Reset parking + Future clearParking() async { + await cacheService.remove(key: IS_GO_TO_PARKING); + isSavePark = false; + qrParkingModel = null; + notifyListeners(); + } + + int? _extractQrParkingId(String raw) { + try { + if (raw.startsWith("{")) { + final data = jsonDecode(raw); + return int.tryParse(data['QRParkingID'].toString()); + } + return int.tryParse(raw); + } catch (_) { + return null; + } + } +} + + diff --git a/lib/features/radiology/radiology_view_model.dart b/lib/features/radiology/radiology_view_model.dart index 986945e..c8150c1 100644 --- a/lib/features/radiology/radiology_view_model.dart +++ b/lib/features/radiology/radiology_view_model.dart @@ -1,7 +1,9 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_repo.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/radiology/radiology_result_page.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; @@ -97,7 +99,7 @@ class RadiologyViewModel extends ChangeNotifier { ); } else { if (onError != null) { - onError("No Radiology Orders Found".needTranslation); + onError(LocaleKeys.noRadiologyOrders.tr()); } } } @@ -110,7 +112,8 @@ class RadiologyViewModel extends ChangeNotifier { final result = await radiologyRepo.getRadiologyImage(patientRadiologyResponseModel: patientRadiologyResponseModel); result.fold( - (failure) async => await errorHandlerService.handleError(failure: failure), + // (failure) async => await errorHandlerService.handleError(failure: failure), + (failure) async {}, (apiResponse) { if (apiResponse.messageStatus == 2) { // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); diff --git a/lib/features/smartwatch_health_data/health_provider.dart b/lib/features/smartwatch_health_data/health_provider.dart index fc9dacc..0acb25b 100644 --- a/lib/features/smartwatch_health_data/health_provider.dart +++ b/lib/features/smartwatch_health_data/health_provider.dart @@ -10,6 +10,15 @@ class HealthProvider with ChangeNotifier { String selectedTimeRange = '7D'; int selectedTabIndex = 0; + String selectedWatchType = 'apple'; + String selectedWatchURL = 'assets/images/png/smartwatches/apple-watch-5.jpg'; + + setSelectedWatchType(String type, String imageURL) { + selectedWatchType = type; + selectedWatchURL = imageURL; + notifyListeners(); + } + void onTabChanged(int index) { selectedTabIndex = index; notifyListeners(); diff --git a/lib/features/symptoms_checker/data/organ_mapping_data.dart b/lib/features/symptoms_checker/data/organ_mapping_data.dart index 6b50b25..c338a94 100644 --- a/lib/features/symptoms_checker/data/organ_mapping_data.dart +++ b/lib/features/symptoms_checker/data/organ_mapping_data.dart @@ -8,28 +8,36 @@ class OrganData { OrganModel( id: 'head', name: 'whole_head', + nameAr: 'الرأس_كامل', description: 'Head', + descriptionAr: 'الرأس', bodyView: BodyView.front, position: OrganPosition(x: 0.50, y: 0.03), ), OrganModel( id: 'left_eye', name: 'eyes', + nameAr: 'العيون', description: 'Left Eye', + descriptionAr: 'العين اليسرى', bodyView: BodyView.front, position: OrganPosition(x: 0.43, y: 0.07), ), OrganModel( id: 'right_eye', name: 'eyes', + nameAr: 'العيون', description: 'Right Eye', + descriptionAr: 'العين اليمنى', bodyView: BodyView.front, position: OrganPosition(x: 0.57, y: 0.07), ), OrganModel( id: 'nose_mouth', name: 'oral_cavity', + nameAr: 'تجويف_الفم', description: 'Nose/Mouth', + descriptionAr: 'الأنف/الفم', bodyView: BodyView.front, position: OrganPosition(x: 0.50, y: 0.09), ), @@ -38,7 +46,9 @@ class OrganData { OrganModel( id: 'throat', name: 'neck_or_throat', + nameAr: 'الرقبة_أو_الحلق', description: 'Throat', + descriptionAr: 'الحلق', bodyView: BodyView.front, position: OrganPosition(x: 0.50, y: 0.15), ), @@ -47,14 +57,18 @@ class OrganData { OrganModel( id: 'left_shoulder', name: 'upper_arm', + nameAr: 'الذراع_العلوي', description: 'Left Shoulder', + descriptionAr: 'الكتف الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.22, y: 0.22), ), OrganModel( id: 'right_shoulder', name: 'upper_arm', + nameAr: 'الذراع_العلوي', description: 'Right Shoulder', + descriptionAr: 'الكتف الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.8, y: 0.22), ), @@ -63,21 +77,27 @@ class OrganData { OrganModel( id: 'left_chest', name: 'chest', + nameAr: 'الصدر', description: 'Left Chest', + descriptionAr: 'الصدر الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.38, y: 0.22), ), OrganModel( id: 'center_chest', name: 'chest', + nameAr: 'الصدر', description: 'Center Chest', + descriptionAr: 'وسط الصدر', bodyView: BodyView.front, position: OrganPosition(x: 0.52, y: 0.25), ), OrganModel( id: 'right_chest', name: 'chest', + nameAr: 'الصدر', description: 'Right Chest', + descriptionAr: 'الصدر الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.65, y: 0.22), ), @@ -86,14 +106,18 @@ class OrganData { OrganModel( id: 'left_ribs', name: 'chest', + nameAr: 'الصدر', description: 'Left Ribs', + descriptionAr: 'الأضلاع اليسرى', bodyView: BodyView.front, position: OrganPosition(x: 0.38, y: 0.35), ), OrganModel( id: 'right_ribs', name: 'chest', + nameAr: 'الصدر', description: 'Right Ribs', + descriptionAr: 'الأضلاع اليمنى', bodyView: BodyView.front, position: OrganPosition(x: 0.64, y: 0.35), ), @@ -102,21 +126,27 @@ class OrganData { OrganModel( id: 'upper_abdomen', name: 'upper_abdomen', + nameAr: 'البطن_العلوي', description: 'Upper Abdomen', + descriptionAr: 'أعلى البطن', bodyView: BodyView.front, position: OrganPosition(x: 0.51, y: 0.31), ), OrganModel( id: 'navel', name: 'mid_abdomen', + nameAr: 'البطن_الأوسط', description: 'Navel', + descriptionAr: 'السرة', bodyView: BodyView.front, position: OrganPosition(x: 0.51, y: 0.38), ), OrganModel( id: 'lower_abdomen', name: 'lower_abdomen', + nameAr: 'البطن_السفلي', description: 'Lower Abdomen', + descriptionAr: 'أسفل البطن', bodyView: BodyView.front, position: OrganPosition(x: 0.51, y: 0.44), ), @@ -125,14 +155,18 @@ class OrganData { OrganModel( id: 'left_groin', name: 'sexual_organs', + nameAr: 'الأعضاء_التناسلية', description: 'Left Groin', + descriptionAr: 'الفخذ الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.42, y: 0.49), ), OrganModel( id: 'right_groin', name: 'sexual_organs', + nameAr: 'الأعضاء_التناسلية', description: 'Right Groin', + descriptionAr: 'الفخذ الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.59, y: 0.49), ), @@ -142,21 +176,27 @@ class OrganData { OrganModel( id: 'left_elbow', name: 'elbow', + nameAr: 'الكوع', description: 'Left Elbow', + descriptionAr: 'الكوع الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.21, y: 0.35), ), OrganModel( id: 'left_forearm', name: 'forearm', + nameAr: 'الساعد', description: 'Left Forearm', + descriptionAr: 'الساعد الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.19, y: 0.43), ), OrganModel( id: 'left_wrist', name: 'hand', + nameAr: 'اليد', description: 'Left Wrist', + descriptionAr: 'المعصم الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.14, y: 0.5), ), @@ -166,21 +206,27 @@ class OrganData { OrganModel( id: 'right_elbow', name: 'elbow', + nameAr: 'الكوع', description: 'Right Elbow', + descriptionAr: 'الكوع الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.79, y: 0.35), ), OrganModel( id: 'right_forearm', name: 'forearm', + nameAr: 'الساعد', description: 'Right Forearm', + descriptionAr: 'الساعد الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.81, y: 0.43), ), OrganModel( id: 'right_wrist', name: 'hand', + nameAr: 'اليد', description: 'Right Wrist', + descriptionAr: 'المعصم الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.85, y: 0.5), ), @@ -189,28 +235,36 @@ class OrganData { OrganModel( id: 'left_thigh', name: 'thigh', + nameAr: 'الفخذ', description: 'Left Thigh', + descriptionAr: 'الفخذ الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.4, y: 0.60), ), OrganModel( id: 'left_knee', name: 'knee', + nameAr: 'الركبة', description: 'Left Knee', + descriptionAr: 'الركبة اليسرى', bodyView: BodyView.front, position: OrganPosition(x: 0.4, y: 0.72), ), OrganModel( id: 'left_shin', name: 'lower_leg', + nameAr: 'الساق_السفلي', description: 'Left Shin', + descriptionAr: 'الساق اليسرى', bodyView: BodyView.front, position: OrganPosition(x: 0.41, y: 0.82), ), OrganModel( id: 'left_ankle', name: 'foot', + nameAr: 'القدم', description: 'Left Ankle', + descriptionAr: 'الكاحل الأيسر', bodyView: BodyView.front, position: OrganPosition(x: 0.43, y: 0.91), ), @@ -219,28 +273,36 @@ class OrganData { OrganModel( id: 'right_thigh', name: 'thigh', + nameAr: 'الفخذ', description: 'Right Thigh', + descriptionAr: 'الفخذ الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.65, y: 0.60), ), OrganModel( id: 'right_knee', name: 'knee', + nameAr: 'الركبة', description: 'Right Knee', + descriptionAr: 'الركبة اليمنى', bodyView: BodyView.front, position: OrganPosition(x: 0.6, y: 0.72), ), OrganModel( id: 'right_shin', name: 'lower_leg', + nameAr: 'الساق_السفلي', description: 'Right Shin', + descriptionAr: 'الساق اليمنى', bodyView: BodyView.front, position: OrganPosition(x: 0.57, y: 0.82), ), OrganModel( id: 'right_ankle', name: 'foot', + nameAr: 'القدم', description: 'Right Ankle', + descriptionAr: 'الكاحل الأيمن', bodyView: BodyView.front, position: OrganPosition(x: 0.57, y: 0.91), ), @@ -252,14 +314,18 @@ class OrganData { OrganModel( id: 'back_of_head', name: 'whole_head', + nameAr: 'الرأس_كامل', description: 'Back of Head', + descriptionAr: 'مؤخرة الرأس', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.04), ), OrganModel( id: 'neck_back', name: 'nape_of_neck', + nameAr: 'مؤخرة_الرقبة', description: 'Neck', + descriptionAr: 'الرقبة', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.14), ), @@ -268,14 +334,18 @@ class OrganData { OrganModel( id: 'left_shoulder_back', name: 'upper_arm', + nameAr: 'الذراع_العلوي', description: 'Left Shoulder', + descriptionAr: 'الكتف الأيسر', bodyView: BodyView.back, position: OrganPosition(x: 0.33, y: 0.19), ), OrganModel( id: 'right_shoulder_back', name: 'upper_arm', + nameAr: 'الذراع_العلوي', description: 'Right Shoulder', + descriptionAr: 'الكتف الأيمن', bodyView: BodyView.back, position: OrganPosition(x: 0.67, y: 0.19), ), @@ -284,21 +354,27 @@ class OrganData { OrganModel( id: 'upper_spine', name: 'back', + nameAr: 'الظهر', description: 'Upper Spine', + descriptionAr: 'العمود الفقري العلوي', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.23), ), OrganModel( id: 'left_upper_back', name: 'back', + nameAr: 'الظهر', description: 'Left Upper Back', + descriptionAr: 'أعلى الظهر الأيسر', bodyView: BodyView.back, position: OrganPosition(x: 0.38, y: 0.28), ), OrganModel( id: 'right_upper_back', name: 'back', + nameAr: 'الظهر', description: 'Right Upper Back', + descriptionAr: 'أعلى الظهر الأيمن', bodyView: BodyView.back, position: OrganPosition(x: 0.62, y: 0.28), ), @@ -307,21 +383,27 @@ class OrganData { OrganModel( id: 'mid_spine', name: 'back', + nameAr: 'الظهر', description: 'Mid Spine', + descriptionAr: 'العمود الفقري الأوسط', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.35), ), OrganModel( id: 'left_mid_back', name: 'back', + nameAr: 'الظهر', description: 'Left Mid Back', + descriptionAr: 'وسط الظهر الأيسر', bodyView: BodyView.back, position: OrganPosition(x: 0.38, y: 0.35), ), OrganModel( id: 'right_mid_back', name: 'back', + nameAr: 'الظهر', description: 'Right Mid Back', + descriptionAr: 'وسط الظهر الأيمن', bodyView: BodyView.back, position: OrganPosition(x: 0.62, y: 0.35), ), @@ -330,21 +412,27 @@ class OrganData { OrganModel( id: 'lower_spine', name: 'lower_back', + nameAr: 'أسفل_الظهر', description: 'Lower Back', + descriptionAr: 'أسفل الظهر', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.43), ), OrganModel( id: 'left_lower_back', name: 'lower_back', + nameAr: 'أسفل_الظهر', description: 'Left Lower Back', + descriptionAr: 'أسفل الظهر الأيسر', bodyView: BodyView.back, position: OrganPosition(x: 0.40, y: 0.43), ), OrganModel( id: 'right_lower_back', name: 'lower_back', + nameAr: 'أسفل_الظهر', description: 'Right Lower Back', + descriptionAr: 'أسفل الظهر الأيمن', bodyView: BodyView.back, position: OrganPosition(x: 0.60, y: 0.43), ), @@ -353,21 +441,27 @@ class OrganData { OrganModel( id: 'sacrum', name: 'lower_back', + nameAr: 'أسفل_الظهر', description: 'Sacrum', + descriptionAr: 'العجز', bodyView: BodyView.back, position: OrganPosition(x: 0.50, y: 0.52), ), OrganModel( id: 'left_glute', name: 'buttocks', + nameAr: 'الأرداف', description: 'Left Glute', + descriptionAr: 'الأرداف اليسرى', bodyView: BodyView.back, position: OrganPosition(x: 0.45, y: 0.56), ), OrganModel( id: 'right_glute', name: 'buttocks', + nameAr: 'الأرداف', description: 'Right Glute', + descriptionAr: 'الأرداف اليمنى', bodyView: BodyView.back, position: OrganPosition(x: 0.55, y: 0.56), ), @@ -376,28 +470,36 @@ class OrganData { OrganModel( id: 'left_hamstring', name: 'thigh', + nameAr: 'الفخذ', description: 'Left Hamstring', + descriptionAr: 'عضلة الفخذ الخلفية اليسرى', bodyView: BodyView.back, position: OrganPosition(x: 0.43, y: 0.65), ), OrganModel( id: 'right_hamstring', name: 'thigh', + nameAr: 'الفخذ', description: 'Right Hamstring', + descriptionAr: 'عضلة الفخذ الخلفية اليمنى', bodyView: BodyView.back, position: OrganPosition(x: 0.57, y: 0.65), ), OrganModel( id: 'left_calf', name: 'lower_leg', + nameAr: 'الساق_السفلي', description: 'Left Calf', + descriptionAr: 'ربلة الساق اليسرى', bodyView: BodyView.back, position: OrganPosition(x: 0.43, y: 0.79), ), OrganModel( id: 'right_calf', name: 'lower_leg', + nameAr: 'الساق_السفلي', description: 'Right Calf', + descriptionAr: 'ربلة الساق اليمنى', bodyView: BodyView.back, position: OrganPosition(x: 0.57, y: 0.79), ), diff --git a/lib/features/symptoms_checker/models/conditions_model.dart b/lib/features/symptoms_checker/models/conditions_model.dart index 774d8c3..af66c21 100644 --- a/lib/features/symptoms_checker/models/conditions_model.dart +++ b/lib/features/symptoms_checker/models/conditions_model.dart @@ -1,97 +1,97 @@ -import 'package:flutter/material.dart'; -import 'package:hmg_patient_app_new/core/enums.dart'; - -class ConditionsModel { - final IconData icon; - final String title; - final int percentage; - final String tagText; - final String clinic; - final List symptoms; - final String description; - final String? monitorNote; - final String? appointmentLabel; - final PossibleConditionsSeverityEnum possibleConditionsSeverityEnum; - - ConditionsModel({ - required this.icon, - required this.title, - required this.percentage, - required this.tagText, - required this.clinic, - required this.symptoms, - required this.description, - required this.possibleConditionsSeverityEnum, - this.monitorNote, - this.appointmentLabel, - }); -} - -List dummyConditions = [ - ConditionsModel( - icon: Icons.psychology_alt, - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, - title: "Migraine", - percentage: 87, - tagText: "Seek Medical Advice", - clinic: "Internal Medicine Clinic", - symptoms: ["Headache", "Nausea", "Sensitivity to light"], - description: "A migraine is a type of headache that can cause severe throbbing pain, usually on one side of the head.", - appointmentLabel: "Book Appointment", - ), - ConditionsModel( - icon: Icons.deblur, - title: "Tension Headache", - percentage: 37, - tagText: "Monitor", - monitorNote: "No need to visit doctor", - clinic: "GP Clinic", - symptoms: ["Mild head pressure", "Scalp tenderness"], - description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.monitorOnly, - ), - ConditionsModel( - icon: Icons.medication_liquid, - title: "Meningitis", - percentage: 28, - tagText: "Emergency", - clinic: "Neurology Clinic", - symptoms: ["Mild head pressure", "Scalp tenderness"], - description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", - appointmentLabel: "Book Appointment", - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.emergency, - ), - ConditionsModel( - icon: Icons.psychology_alt, - title: "Migraine", - percentage: 87, - tagText: "Seek Medical Advice", - clinic: "Internal Medicine Clinic", - symptoms: ["Headache", "Nausea", "Sensitivity to light"], - description: "A migraine is a type of headache that can cause severe throbbing pain, usually on one side of the head.", - appointmentLabel: "Book Appointment", - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, - ), - ConditionsModel( - icon: Icons.deblur, - title: "Tension Headache", - percentage: 37, - tagText: "Monitor", - monitorNote: "No need to visit doctor", - clinic: "GP Clinic", - symptoms: ["Mild head pressure", "Scalp tenderness"], - description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.monitorOnly, - ), - ConditionsModel( - icon: Icons.medication_liquid, - title: "Meningitis", - percentage: 28, - tagText: "Emergency", - clinic: "Neurology Clinic", - symptoms: ["Mild head pressure", "Scalp tenderness"], - description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", - appointmentLabel: "Book Appointment", - possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.emergency, - ), -]; +// import 'package:flutter/material.dart'; +// import 'package:hmg_patient_app_new/core/enums.dart'; +// +// class ConditionsModel { +// final IconData icon; +// final String title; +// final int percentage; +// final String tagText; +// final String clinic; +// final List symptoms; +// final String description; +// final String? monitorNote; +// final String? appointmentLabel; +// final PossibleConditionsSeverityEnum possibleConditionsSeverityEnum; +// +// ConditionsModel({ +// required this.icon, +// required this.title, +// required this.percentage, +// required this.tagText, +// required this.clinic, +// required this.symptoms, +// required this.description, +// required this.possibleConditionsSeverityEnum, +// this.monitorNote, +// this.appointmentLabel, +// }); +// } +// +// List dummyConditions = [ +// ConditionsModel( +// icon: Icons.psychology_alt, +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, +// title: "Migraine", +// percentage: 87, +// tagText: "Seek Medical Advice", +// clinic: "Internal Medicine Clinic", +// symptoms: ["Headache", "Nausea", "Sensitivity to light"], +// description: "A migraine is a type of headache that can cause severe throbbing pain, usually on one side of the head.", +// appointmentLabel: "Book Appointment", +// ), +// ConditionsModel( +// icon: Icons.deblur, +// title: "Tension Headache", +// percentage: 37, +// tagText: "Monitor", +// monitorNote: "No need to visit doctor", +// clinic: "GP Clinic", +// symptoms: ["Mild head pressure", "Scalp tenderness"], +// description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.monitorOnly, +// ), +// ConditionsModel( +// icon: Icons.medication_liquid, +// title: "Meningitis", +// percentage: 28, +// tagText: "Emergency", +// clinic: "Neurology Clinic", +// symptoms: ["Mild head pressure", "Scalp tenderness"], +// description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", +// appointmentLabel: "Book Appointment", +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.emergency, +// ), +// ConditionsModel( +// icon: Icons.psychology_alt, +// title: "Migraine", +// percentage: 87, +// tagText: "Seek Medical Advice", +// clinic: "Internal Medicine Clinic", +// symptoms: ["Headache", "Nausea", "Sensitivity to light"], +// description: "A migraine is a type of headache that can cause severe throbbing pain, usually on one side of the head.", +// appointmentLabel: "Book Appointment", +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, +// ), +// ConditionsModel( +// icon: Icons.deblur, +// title: "Tension Headache", +// percentage: 37, +// tagText: "Monitor", +// monitorNote: "No need to visit doctor", +// clinic: "GP Clinic", +// symptoms: ["Mild head pressure", "Scalp tenderness"], +// description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.monitorOnly, +// ), +// ConditionsModel( +// icon: Icons.medication_liquid, +// title: "Meningitis", +// percentage: 28, +// tagText: "Emergency", +// clinic: "Neurology Clinic", +// symptoms: ["Mild head pressure", "Scalp tenderness"], +// description: "A tension-type headache is generally a mild to moderate pain that feels like a tight band around your head.", +// appointmentLabel: "Book Appointment", +// possibleConditionsSeverityEnum: PossibleConditionsSeverityEnum.emergency, +// ), +// ]; diff --git a/lib/features/symptoms_checker/models/organ_model.dart b/lib/features/symptoms_checker/models/organ_model.dart index fab7dff..9a871f3 100644 --- a/lib/features/symptoms_checker/models/organ_model.dart +++ b/lib/features/symptoms_checker/models/organ_model.dart @@ -3,29 +3,47 @@ import 'package:hmg_patient_app_new/core/enums.dart'; class OrganModel { final String id; final String name; + final String nameAr; final String description; + final String descriptionAr; final BodyView bodyView; final OrganPosition position; const OrganModel({ required this.id, required this.name, + required this.nameAr, required this.description, + required this.descriptionAr, required this.bodyView, required this.position, }); + /// Get localized name based on isArabic flag + String getLocalizedName(bool isArabic) { + return isArabic ? nameAr : name; + } + + /// Get localized description based on isArabic flag + String getLocalizedDescription(bool isArabic) { + return isArabic ? descriptionAr : description; + } + OrganModel copyWith({ String? id, String? name, + String? nameAr, String? description, + String? descriptionAr, BodyView? bodyView, OrganPosition? position, }) { return OrganModel( id: id ?? this.id, name: name ?? this.name, + nameAr: nameAr ?? this.nameAr, description: description ?? this.description, + descriptionAr: descriptionAr ?? this.descriptionAr, bodyView: bodyView ?? this.bodyView, position: position ?? this.position, ); diff --git a/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart b/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart index b2be4a2..9928d78 100644 --- a/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart +++ b/lib/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart @@ -22,6 +22,8 @@ class RiskAndSuggestionsItemModel { final String? type; final String? name; final String? commonName; + final String? nameAr; + final String? commonNameAr; final String? language; RiskAndSuggestionsItemModel({ @@ -29,6 +31,8 @@ class RiskAndSuggestionsItemModel { this.type, this.name, this.commonName, + this.nameAr, + this.commonNameAr, this.language, }); @@ -38,6 +42,8 @@ class RiskAndSuggestionsItemModel { type: json['type'], name: json['name'], commonName: json['common_name'], + nameAr: json['nameAr'], + commonNameAr: json['common_nameAr'], language: json['language'], ); } @@ -48,12 +54,17 @@ class RiskAndSuggestionsItemModel { 'type': type, 'name': name, 'common_name': commonName, + 'nameAr': nameAr, + 'common_nameAr': commonNameAr, 'language': language, }; } - // Helper method to get display name - String getDisplayName() { + // Helper method to get display name based on locale + String getDisplayName({bool isArabic = false}) { + if (isArabic) { + return commonNameAr ?? nameAr ?? commonName ?? name ?? ''; + } return commonName ?? name ?? ''; } } diff --git a/lib/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart b/lib/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart new file mode 100644 index 0000000..c0466c4 --- /dev/null +++ b/lib/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart @@ -0,0 +1,188 @@ +class SymptomsUserDetailsResponseModel { + final TokenDetails? tokenDetails; + final UserDetails? userDetails; + final String? sessionId; + + SymptomsUserDetailsResponseModel({ + this.tokenDetails, + this.userDetails, + this.sessionId, + }); + + factory SymptomsUserDetailsResponseModel.fromJson(Map json) { + return SymptomsUserDetailsResponseModel( + tokenDetails: json['tokenDetails'] != null ? TokenDetails.fromJson(json['tokenDetails']) : null, + userDetails: json['userDetails'] != null ? UserDetails.fromJson(json['userDetails']) : null, + sessionId: json['sessionId'], + ); + } + + Map toJson() { + return { + 'tokenDetails': tokenDetails?.toJson(), + 'userDetails': userDetails?.toJson(), + 'sessionId': sessionId, + }; + } +} + +class TokenDetails { + final String? id; + final String? authToken; + final int? expiresIn; + + TokenDetails({ + this.id, + this.authToken, + this.expiresIn, + }); + + factory TokenDetails.fromJson(Map json) { + return TokenDetails( + id: json['id'], + authToken: json['auth_token'], + expiresIn: json['expires_in'], + ); + } + + Map toJson() { + return { + 'id': id, + 'auth_token': authToken, + 'expires_in': expiresIn, + }; + } +} + +class UserDetails { + final String? fileNo; + final String? nationalId; + final String? email; + final String? dateOfBirth; + final String? dateOfBirthHijri; + final int? age; + final UserName? name; + final int? maritalStatus; + final String? maritalStatusCode; + final String? nationality; + final String? nationalityIsoCode; + final String? occupation; + final int? idType; + final int? gender; + final String? jwtToken; + final String? countryDialCode; + final String? phoneNo; + + UserDetails({ + this.fileNo, + this.nationalId, + this.email, + this.dateOfBirth, + this.dateOfBirthHijri, + this.age, + this.name, + this.maritalStatus, + this.maritalStatusCode, + this.nationality, + this.nationalityIsoCode, + this.occupation, + this.idType, + this.gender, + this.jwtToken, + this.countryDialCode, + this.phoneNo, + }); + + factory UserDetails.fromJson(Map json) { + return UserDetails( + fileNo: json['FileNo'], + nationalId: json['national_id'], + email: json['email'], + dateOfBirth: json['date_of_birth'], + dateOfBirthHijri: json['date_of_birth_hijri'], + age: json['age'], + name: json['name'] != null ? UserName.fromJson(json['name']) : null, + maritalStatus: json['marital_status'], + maritalStatusCode: json['marital_status_code'], + nationality: json['nationality'], + nationalityIsoCode: json['nationality_iso_code'], + occupation: json['occupation'], + idType: json['id_type'], + gender: json['gender'], + jwtToken: json['jwt_token'], + countryDialCode: json['country_dial_code'], + phoneNo: json['phone_no'], + ); + } + + Map toJson() { + return { + 'FileNo': fileNo, + 'national_id': nationalId, + 'email': email, + 'date_of_birth': dateOfBirth, + 'date_of_birth_hijri': dateOfBirthHijri, + 'age': age, + 'name': name?.toJson(), + 'marital_status': maritalStatus, + 'marital_status_code': maritalStatusCode, + 'nationality': nationality, + 'nationality_iso_code': nationalityIsoCode, + 'occupation': occupation, + 'id_type': idType, + 'gender': gender, + 'jwt_token': jwtToken, + 'country_dial_code': countryDialCode, + 'phone_no': phoneNo, + }; + } + + // Helper method to get full name + String getFullName(bool isArabic) { + if (name == null) return ''; + if (isArabic) { + return '${name!.firstNameAr ?? ''} ${name!.middleNameAr ?? ''} ${name!.lastNameAr ?? ''}'.trim(); + } + return '${name!.firstName ?? ''} ${name!.middleName ?? ''} ${name!.lastName ?? ''}'.trim(); + } +} + +class UserName { + final String? firstName; + final String? middleName; + final String? lastName; + final String? firstNameAr; + final String? middleNameAr; + final String? lastNameAr; + + UserName({ + this.firstName, + this.middleName, + this.lastName, + this.firstNameAr, + this.middleNameAr, + this.lastNameAr, + }); + + factory UserName.fromJson(Map json) { + return UserName( + firstName: json['first_name'], + middleName: json['middle_name'], + lastName: json['last_name'], + firstNameAr: json['first_name_ar'], + middleNameAr: json['middle_name_ar'], + lastNameAr: json['last_name_ar'], + ); + } + + Map toJson() { + return { + 'first_name': firstName, + 'middle_name': middleName, + 'last_name': lastName, + 'first_name_ar': firstNameAr, + 'middle_name_ar': middleNameAr, + 'last_name_ar': lastNameAr, + }; + } +} diff --git a/lib/features/symptoms_checker/models/resp_models/triage_response_model.dart b/lib/features/symptoms_checker/models/resp_models/triage_response_model.dart new file mode 100644 index 0000000..da0f4b6 --- /dev/null +++ b/lib/features/symptoms_checker/models/resp_models/triage_response_model.dart @@ -0,0 +1,299 @@ +import 'package:hmg_patient_app_new/core/enums.dart'; + +class TriageDataDetails { + final TriageQuestion? question; + final List? conditions; + final bool? hasEmergencyEvidence; + final bool? shouldStop; + final String? interviewToken; + final String? message; + final List? errorList; + final int? id; + final String? language; + final String? generalId; + final String? createDate; + final String? lastEditDate; + final String? createdBy; + final String? lastEditBy; + final bool? active; + final int? sortOrder; + final int? userType; + final String? userId; + + TriageDataDetails({ + this.question, + this.conditions, + this.hasEmergencyEvidence, + this.shouldStop, + this.interviewToken, + this.message, + this.errorList, + this.id, + this.language, + this.generalId, + this.createDate, + this.lastEditDate, + this.createdBy, + this.lastEditBy, + this.active, + this.sortOrder, + this.userType, + this.userId, + }); + + factory TriageDataDetails.fromJson(Map json) { + return TriageDataDetails( + question: json['question'] != null ? TriageQuestion.fromJson(json['question']) : null, + conditions: json['conditions'] != null ? (json['conditions'] as List).map((item) => TriageCondition.fromJson(item)).toList() : null, + hasEmergencyEvidence: json['has_emergency_evidence'], + shouldStop: json['should_stop'], + interviewToken: json['interview_token'], + message: json['Message'], + errorList: json['ErrorList'] != null ? List.from(json['ErrorList']) : null, + id: json['Id'], + language: json['language'], + generalId: json['generalId'], + createDate: json['CreateDate'], + lastEditDate: json['LastEditDate'], + createdBy: json['CreatedBy'], + lastEditBy: json['LastEditBy'], + active: json['Active'], + sortOrder: json['SortOrder'], + userType: json['userType'], + userId: json['userId'], + ); + } + + Map toJson() { + return { + 'question': question?.toJson(), + 'conditions': conditions?.map((item) => item.toJson()).toList(), + 'has_emergency_evidence': hasEmergencyEvidence, + 'should_stop': shouldStop, + 'interview_token': interviewToken, + 'Message': message, + 'ErrorList': errorList, + 'Id': id, + 'language': language, + 'generalId': generalId, + 'CreateDate': createDate, + 'LastEditDate': lastEditDate, + 'CreatedBy': createdBy, + 'LastEditBy': lastEditBy, + 'Active': active, + 'SortOrder': sortOrder, + 'userType': userType, + 'userId': userId, + }; + } +} + +class TriageQuestion { + final int? type; + final String? text; + final List? items; + + TriageQuestion({ + this.type, + this.text, + this.items, + }); + + factory TriageQuestion.fromJson(Map json) { + return TriageQuestion( + type: json['type'], + text: json['text'], + items: json['items'] != null ? (json['items'] as List).map((item) => TriageQuestionItem.fromJson(item)).toList() : null, + ); + } + + Map toJson() { + return { + 'type': type, + 'text': text, + 'items': items?.map((item) => item.toJson()).toList(), + }; + } +} + +class TriageQuestionItem { + final String? id; + final String? name; + final List? choices; + + TriageQuestionItem({ + this.id, + this.name, + this.choices, + }); + + factory TriageQuestionItem.fromJson(Map json) { + return TriageQuestionItem( + id: json['id'], + name: json['name'], + choices: json['choices'] != null ? (json['choices'] as List).map((item) => TriageChoice.fromJson(item)).toList() : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'choices': choices?.map((item) => item.toJson()).toList(), + }; + } +} + +class TriageChoice { + final String? id; + final String? label; + + TriageChoice({ + this.id, + this.label, + }); + + factory TriageChoice.fromJson(Map json) { + return TriageChoice( + id: json['id'], + label: json['label'], + ); + } + + Map toJson() { + return { + 'id': id, + 'label': label, + }; + } +} + +class TriageCondition { + final String? id; + final String? name; + final String? commonName; + final String? nameAr; + final String? commonNameAr; + final double? probability; + final ConditionDetails? conditionDetails; + + TriageCondition({ + this.id, + this.name, + this.commonName, + this.nameAr, + this.commonNameAr, + this.probability, + this.conditionDetails, + }); + + factory TriageCondition.fromJson(Map json) { + return TriageCondition( + id: json['id'], + name: json['name'], + commonName: json['common_name'], + nameAr: json['nameAr'], + commonNameAr: json['common_nameAr'], + probability: json['probability']?.toDouble(), + conditionDetails: json['condition_details'] != null ? ConditionDetails.fromJson(json['condition_details']) : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'common_name': commonName, + 'nameAr': nameAr, + 'common_nameAr': commonNameAr, + 'probability': probability, + 'condition_details': conditionDetails?.toJson(), + }; + } + + /// Get display name based on locale + String getDisplayName({bool isArabic = false}) { + if (isArabic) { + return commonNameAr ?? nameAr ?? commonName ?? name ?? ''; + } + return commonName ?? name ?? ''; + } + + /// Get probability as percentage + String getProbabilityPercentage() { + if (probability == null) return '0%'; + return '${(probability! * 100).toStringAsFixed(1)}%'; + } +} + +class ConditionDetails { + final String? icd10Code; + final ConditionCategory? category; + final SeverityEnum? severity; + final TriageLevelEnum? triageLevel; + final String? hint; + final bool? hasPatientEducation; + final String? prevalence; + final String? acuteness; + + ConditionDetails({ + this.icd10Code, + this.category, + this.severity, + this.triageLevel, + this.hint, + this.hasPatientEducation, + this.prevalence, + this.acuteness, + }); + + factory ConditionDetails.fromJson(Map json) { + return ConditionDetails( + icd10Code: json['icd10_code'], + category: json['category'] != null ? ConditionCategory.fromJson(json['category']) : null, + severity: json['severity'] != null ? SeverityEnumExtension.fromInt(json['severity']) : null, + triageLevel: json['triage_level'] != null ? TriageLevelEnumExtension.fromInt(json['triage_level']) : null, + hint: json['hint'], + hasPatientEducation: json['has_patient_education'], + prevalence: json['prevalence'], + acuteness: json['acuteness'], + ); + } + + Map toJson() { + return { + 'icd10_code': icd10Code, + 'category': category?.toJson(), + 'severity': severity?.toInt, + 'triage_level': triageLevel?.toInt, + 'hint': hint, + 'has_patient_education': hasPatientEducation, + 'prevalence': prevalence, + 'acuteness': acuteness, + }; + } +} + +class ConditionCategory { + final String? id; + final String? name; + + ConditionCategory({ + this.id, + this.name, + }); + + factory ConditionCategory.fromJson(Map json) { + return ConditionCategory( + id: json['id'], + name: json['name'], + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + }; + } +} diff --git a/lib/features/symptoms_checker/symptoms_checker_repo.dart b/lib/features/symptoms_checker/symptoms_checker_repo.dart index 954d414..c0214e1 100644 --- a/lib/features/symptoms_checker/symptoms_checker_repo.dart +++ b/lib/features/symptoms_checker/symptoms_checker_repo.dart @@ -1,5 +1,4 @@ import 'dart:convert'; -import 'dart:developer'; import 'package:dartz/dartz.dart'; import 'package:hmg_patient_app_new/core/api/api_client.dart'; @@ -8,25 +7,48 @@ import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; abstract class SymptomsCheckerRepo { + Future>> getUserDetails({ + required String userName, + required String password, + }); + Future>> getBodySymptomsByName({ required List organNames, + required String userSessionToken, + required int gender, }); Future>> getRiskFactors({ required int age, - required String sex, + required int gender, required List evidenceIds, required String language, + required String userSessionToken, + required String sessionId, }); Future>> getSuggestions({ required int age, - required String sex, + required int gender, + required List evidenceIds, + required String language, + required String userSessionToken, + required String sessionId, + }); + + Future>> getDiagnosisForTriage({ + required int age, + required int gender, required List evidenceIds, + List>? triageEvidence, required String language, + required String userSessionToken, + required String sessionId, }); } @@ -37,11 +59,71 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { SymptomsCheckerRepoImp({required this.apiClient, required this.loggerService}); @override - Future>> getBodySymptomsByName({required List organNames}) async { - log("GetBodySymptomsByName Request URL: ${ApiConsts.getBodySymptomsByName}"); - log("GetBodySymptomsByName Request Body: ${jsonEncode(organNames)}"); + Future>> getUserDetails({ + required String userName, + required String password, + }) async { + Map body = {"userName": userName, "password": password}; + + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.symptomsUserLogin, + body: body, + isExternal: true, + isAllowAny: true, + isBodyPlainText: false, + onFailure: (error, statusCode, {messageStatus, failureType}) { + loggerService.logError("getUserDetails API Failed: $error"); + failure = failureType ?? ServerFailure(error); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // Parse response if it's a string + final Map responseData = response is String ? jsonDecode(response) : response; - Map headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}; + SymptomsUserDetailsResponseModel symptomsUserDetailsResponseModel = SymptomsUserDetailsResponseModel.fromJson(responseData); + + apiResponse = GenericApiModel( + messageStatus: messageStatus ?? 1, + statusCode: statusCode, + errorMessage: errorMessage, + data: symptomsUserDetailsResponseModel, + ); + } catch (e, stackTrace) { + loggerService.logError("Error parsing getUserDetails response: $e"); + loggerService.logError("StackTrace: $stackTrace"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e, stackTrace) { + loggerService.logError("Exception in getUserDetails: $e"); + loggerService.logError("StackTrace: $stackTrace"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getBodySymptomsByName({ + required List organNames, + required String userSessionToken, + required int gender, + }) async { + Map headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $userSessionToken', + }; + Map body = { + 'bodyPartName': organNames, + 'gender': gender, + }; try { GenericApiModel? apiResponse; @@ -50,21 +132,15 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { await apiClient.post( ApiConsts.getBodySymptomsByName, apiHeaders: headers, - body: jsonEncode(organNames), + body: body, isExternal: true, isAllowAny: true, - isBodyPlainText: true, + isBodyPlainText: false, onFailure: (error, statusCode, {messageStatus, failureType}) { - loggerService.logError("GetBodySymptomsByName API Failed: $error"); - log("GetBodySymptomsByName Failed: $error, Status: $statusCode"); failure = failureType ?? ServerFailure(error); }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) { try { - log("GetBodySymptomsByName Response Status: $statusCode"); - loggerService.logInfo("GetBodySymptomsByName API Success: $response"); - log("GetBodySymptomsByName Response: $response"); - BodySymptomResponseModel bodySymptomResponse = BodySymptomResponseModel.fromJson(response); apiResponse = GenericApiModel( @@ -76,7 +152,6 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { } catch (e, stackTrace) { loggerService.logError("Error parsing GetBodySymptomsByName response: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Parse Error: $e"); failure = DataParsingFailure(e.toString()); } }, @@ -88,7 +163,6 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { } catch (e, stackTrace) { loggerService.logError("Exception in getBodySymptomsByName: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Exception: $e"); return Left(UnknownFailure(e.toString())); } } @@ -96,17 +170,25 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { @override Future>> getRiskFactors({ required int age, - required String sex, + required int gender, required List evidenceIds, required String language, + required String userSessionToken, + required String sessionId, }) async { final Map body = { "age": { "value": age, }, - "sex": sex, + "gender": gender, "evidence": evidenceIds.map((id) => {"id": id}).toList(), "language": language, + "generalId": sessionId, + }; + + Map headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $userSessionToken', }; try { @@ -115,17 +197,16 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { await apiClient.post( ApiConsts.getRiskFactors, + apiHeaders: headers, body: body, isExternal: true, isAllowAny: true, onFailure: (error, statusCode, {messageStatus, failureType}) { - log("GetRiskFactors Failed: $error, Status: $statusCode"); + loggerService.logError("GetRiskFactors API Failed: $error"); failure = failureType ?? ServerFailure(error); }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) { try { - log("GetRiskFactors Response: $response"); - // Parse response if it's a string final Map responseData = response is String ? jsonDecode(response) : response; @@ -140,7 +221,6 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { } catch (e, stackTrace) { loggerService.logError("Error parsing GetRiskFactors response: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Parse Error: $e"); failure = DataParsingFailure(e.toString()); } }, @@ -152,7 +232,92 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { } catch (e, stackTrace) { loggerService.logError("Exception in getRiskFactors: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Exception: $e"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> getDiagnosisForTriage({ + required int age, + required int gender, + required List evidenceIds, + List>? triageEvidence, // Additional triage-specific evidence + required String language, + required String userSessionToken, + required String sessionId, + }) async { + // Build evidence list: combine initial symptoms with triage evidence + List> evidenceList = []; + + // Add initial evidence as simple IDs + for (var id in evidenceIds) { + evidenceList.add({"id": id}); + } + + // Add triage evidence with proper format (id, choice_id, source) + if (triageEvidence != null && triageEvidence.isNotEmpty) { + evidenceList.addAll(triageEvidence); + } + + final Map body = { + "age": { + "value": age, + }, + "gender": gender, + "evidence": evidenceList, + "language": language, + "suggest_method": "diagnosis", + "generalId": sessionId, + }; + + Map headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $userSessionToken', + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.diagnosis, + apiHeaders: headers, + body: body, + isExternal: true, + isAllowAny: true, + onFailure: (error, statusCode, {messageStatus, failureType}) { + loggerService.logError("getDiagnosisForTriage API Failed: $error"); + failure = failureType ?? ServerFailure(error); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + // Parse response if it's a string + final Map responseData = response is String ? jsonDecode(response) : response; + + final updatedResponseData = responseData['dataDetails']; + + TriageDataDetails riskFactorsResponse = TriageDataDetails.fromJson(updatedResponseData); + + apiResponse = GenericApiModel( + messageStatus: messageStatus ?? 1, + statusCode: statusCode, + errorMessage: errorMessage, + data: riskFactorsResponse, + ); + } catch (e, stackTrace) { + loggerService.logError("Error parsing getDiagnosisForTriage response: $e"); + loggerService.logError("StackTrace: $stackTrace"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e, stackTrace) { + loggerService.logError("Exception in getDiagnosisForTriage: $e"); + loggerService.logError("StackTrace: $stackTrace"); return Left(UnknownFailure(e.toString())); } } @@ -160,17 +325,25 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { @override Future>> getSuggestions({ required int age, - required String sex, + required int gender, required List evidenceIds, required String language, + required String userSessionToken, + required String sessionId, }) async { final Map body = { "age": { "value": age, }, - "sex": sex, + "gender": gender, "evidence": evidenceIds.map((id) => {"id": id}).toList(), "language": language, + "generalId": sessionId, + }; + + Map headers = { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $userSessionToken', }; try { @@ -179,17 +352,16 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { await apiClient.post( ApiConsts.getSuggestions, + apiHeaders: headers, body: body, isExternal: true, isAllowAny: true, onFailure: (error, statusCode, {messageStatus, failureType}) { - log("getSuggestions Failed: $error, Status: $statusCode"); + loggerService.logError("GetSuggestions API Failed: $error"); failure = failureType ?? ServerFailure(error); }, onSuccess: (response, statusCode, {messageStatus, errorMessage}) { try { - log("getSuggestions Response: $response"); - // Parse response if it's a string final Map responseData = response is String ? jsonDecode(response) : response; @@ -202,9 +374,8 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { data: riskFactorsResponse, ); } catch (e, stackTrace) { - loggerService.logError("Error parsing getSuggestions response: $e"); + loggerService.logError("Error parsing GetSuggestions response: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Parse Error: $e"); failure = DataParsingFailure(e.toString()); } }, @@ -216,7 +387,6 @@ class SymptomsCheckerRepoImp implements SymptomsCheckerRepo { } catch (e, stackTrace) { loggerService.logError("Exception in getSuggestions: $e"); loggerService.logError("StackTrace: $stackTrace"); - log("Exception: $e"); return Left(UnknownFailure(e.toString())); } } diff --git a/lib/features/symptoms_checker/symptoms_checker_view_model.dart b/lib/features/symptoms_checker/symptoms_checker_view_model.dart index da439c6..ed82451 100644 --- a/lib/features/symptoms_checker/symptoms_checker_view_model.dart +++ b/lib/features/symptoms_checker/symptoms_checker_view_model.dart @@ -1,12 +1,14 @@ import 'dart:async'; -import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/data/organ_mapping_data.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/organ_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/risk_and_suggestions_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/symptoms_user_details_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_repo.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; @@ -21,6 +23,23 @@ class SymptomsCheckerViewModel extends ChangeNotifier { required this.appState, }); + // Gender constants for both English and Arabic + static const String _maleEn = "male"; + static const String _femaleEn = "female"; + static const String _maleAr = "ذكر"; + static const String _femaleAr = "أنثى"; + + /// Convert gender string to integer (1 for male, 2 for female) + /// Handles both English and Arabic values + int _getGenderAsInt(String? gender) { + if (gender == null) return 1; // Default to male + final lowerGender = gender.toLowerCase(); + if (lowerGender == _maleEn || gender == _maleAr) { + return 1; + } + return 2; // Female or any other value + } + // State variables bool isBodyHidden = false; BodyView _currentView = BodyView.front; @@ -35,11 +54,20 @@ class SymptomsCheckerViewModel extends ChangeNotifier { bool isBodySymptomsLoading = false; bool isRiskFactorsLoading = false; bool isSuggestionsLoading = false; + bool isTriageDiagnosisLoading = false; // API data storage - using API models directly + SymptomsUserDetailsResponseModel? symptomsUserDetailsResponseModel; BodySymptomResponseModel? bodySymptomResponse; RiskAndSuggestionsResponseModel? riskFactorsResponse; RiskAndSuggestionsResponseModel? suggestionsResponse; + TriageDataDetails? triageDataDetails; + + // Triage state + int? _selectedTriageChoiceIndex; // Deprecated - keeping for backward compatibility + final Map _selectedTriageChoicesByItemId = {}; // Map of itemId -> choiceIndex for multi-item questions + final List> _triageEvidenceList = []; // Store triage evidence with proper format + int _triageQuestionCount = 0; // Track number of triage questions answered // Selected risk factors tracking final Set _selectedRiskFactorIds = {}; @@ -92,6 +120,46 @@ class SymptomsCheckerViewModel extends ChangeNotifier { String? get tooltipOrganId => _tooltipOrganId; + String get currentSessionAuthToken => symptomsUserDetailsResponseModel?.tokenDetails?.authToken ?? ""; + + String get currentSessionId => symptomsUserDetailsResponseModel?.sessionId ?? ""; + + // Triage-related getters + bool get shouldStopTriage => triageDataDetails?.shouldStop ?? false; + + bool get hasEmergencyEvidence => triageDataDetails?.hasEmergencyEvidence ?? false; + + String? get currentInterviewToken => triageDataDetails?.interviewToken; + + TriageQuestion? get currentTriageQuestion => triageDataDetails?.question; + + List? get currentConditions => triageDataDetails?.conditions; + + int? get selectedTriageChoiceIndex => _selectedTriageChoiceIndex; + + /// Get the number of triage questions answered + int get triageQuestionCount => _triageQuestionCount; + + /// Get choice index for a specific item + int? getTriageChoiceForItem(String itemId) { + return _selectedTriageChoicesByItemId[itemId]; + } + + /// Check if all items in current question have been answered + bool get areAllTriageItemsAnswered { + if (currentTriageQuestion?.items == null || currentTriageQuestion!.items!.isEmpty) { + return false; + } + + // Check if we have an answer for each item + for (var item in currentTriageQuestion!.items!) { + if (item.id != null && !_selectedTriageChoicesByItemId.containsKey(item.id)) { + return false; + } + } + return true; + } + /// Get organs for current view List get currentOrgans => OrganData.getOrgansForView(_currentView); @@ -389,8 +457,9 @@ class SymptomsCheckerViewModel extends ChangeNotifier { await getRiskFactors( age: _selectedAge!, - sex: _selectedGender!.toLowerCase(), + gender: _getGenderAsInt(_selectedGender), evidenceIds: evidenceIds, + sessionId: currentSessionId, language: appState.isArabic() ? 'ar' : 'en', onSuccess: (response) { if (onSuccess != null) { @@ -408,7 +477,8 @@ class SymptomsCheckerViewModel extends ChangeNotifier { /// Call Risk Factors API Future getRiskFactors({ required int age, - required String sex, + required int gender, + required String sessionId, required List evidenceIds, required String language, Function(RiskAndSuggestionsResponseModel)? onSuccess, @@ -419,9 +489,11 @@ class SymptomsCheckerViewModel extends ChangeNotifier { final result = await symptomsCheckerRepo.getRiskFactors( age: age, - sex: sex, + gender: gender, evidenceIds: evidenceIds, language: language, + sessionId: sessionId, + userSessionToken: currentSessionAuthToken, ); result.fold( @@ -443,6 +515,8 @@ class SymptomsCheckerViewModel extends ChangeNotifier { id: "not_applicable", commonName: "Not Applicable", name: "Not Applicable", + commonNameAr: "لا ينطبق", + nameAr: "لا ينطبق", language: appState.isArabic() ? 'ar' : 'en', type: null, ); @@ -502,6 +576,25 @@ class SymptomsCheckerViewModel extends ChangeNotifier { notifyListeners(); } + /// Get all evidence IDs (symptoms + risk factors + suggestions) for triage/diagnosis + List getAllEvidenceIds() { + List evidenceIds = []; + + // Add selected symptoms + final selectedSymptoms = getAllSelectedSymptoms(); + evidenceIds.addAll(selectedSymptoms.where((s) => s.id != null).map((s) => s.id!)); + + // Add selected risk factors (excluding "not_applicable") + final selectedRiskFactors = getAllSelectedRiskFactors(); + evidenceIds.addAll(selectedRiskFactors.where((rf) => rf.id != null && rf.id != "not_applicable").map((rf) => rf.id!)); + + // Add selected suggestions (excluding "not_applicable") + final selectedSuggestions = getAllSelectedSuggestions(); + evidenceIds.addAll(selectedSuggestions.where((s) => s.id != null && s.id != "not_applicable").map((s) => s.id!)); + + return evidenceIds; + } + /// Fetch risk factors based on selected symptoms Future fetchSuggestions({ Function()? onSuccess, @@ -538,7 +631,7 @@ class SymptomsCheckerViewModel extends ChangeNotifier { await getSuggestions( age: _selectedAge!, - sex: _selectedGender!.toLowerCase(), + gender: _getGenderAsInt(_selectedGender), evidenceIds: evidenceIds, language: appState.isArabic() ? 'ar' : 'en', onSuccess: (response) { @@ -557,7 +650,7 @@ class SymptomsCheckerViewModel extends ChangeNotifier { /// Call Suggestions API Future getSuggestions({ required int age, - required String sex, + required int gender, required List evidenceIds, required String language, Function(RiskAndSuggestionsResponseModel)? onSuccess, @@ -568,9 +661,11 @@ class SymptomsCheckerViewModel extends ChangeNotifier { final result = await symptomsCheckerRepo.getSuggestions( age: age, - sex: sex, + gender: gender, evidenceIds: evidenceIds, language: language, + sessionId: currentSessionId, + userSessionToken: currentSessionAuthToken, ); result.fold( @@ -592,6 +687,8 @@ class SymptomsCheckerViewModel extends ChangeNotifier { id: "not_applicable", commonName: "Not Applicable", name: "Not Applicable", + commonNameAr: "لا ينطبق", + nameAr: "لا ينطبق", language: appState.isArabic() ? 'ar' : 'en', type: null, ); @@ -612,15 +709,154 @@ class SymptomsCheckerViewModel extends ChangeNotifier { ); } + /// Call Diagnosis API for Triage - This is called iteratively until shouldStop is true + Future getDiagnosisForTriage({ + required int age, + required int gender, + required List evidenceIds, + List>? triageEvidence, + required String language, + Function(TriageDataDetails)? onSuccess, + Function(String)? onError, + }) async { + isTriageDiagnosisLoading = true; + notifyListeners(); + + final result = await symptomsCheckerRepo.getDiagnosisForTriage( + age: age, + gender: gender, + evidenceIds: evidenceIds, + triageEvidence: triageEvidence, + language: language, + sessionId: currentSessionId, + userSessionToken: currentSessionAuthToken, + ); + + result.fold( + (failure) async { + isTriageDiagnosisLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isTriageDiagnosisLoading = false; + if (apiResponse.messageStatus == 1 && apiResponse.data != null) { + triageDataDetails = apiResponse.data; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse.data!); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Failed to fetch diagnosis'); + } + } + }, + ); + } + + /// Convenience method to start or continue the triage process + /// This automatically uses all selected evidence (symptoms + risk factors + suggestions) + Future startOrContinueTriage({ + Function()? onSuccess, + Function(String)? onError, + }) async { + // Validate user info + if (_selectedAge == null || _selectedGender == null) { + if (onError != null) { + onError('User information is incomplete'); + } + return; + } + + // Get all evidence IDs + final evidenceIds = getAllEvidenceIds(); + + if (evidenceIds.isEmpty) { + if (onError != null) { + onError('No evidence selected'); + } + return; + } + + await getDiagnosisForTriage( + age: _selectedAge!, + gender: _getGenderAsInt(_selectedGender), + evidenceIds: evidenceIds, + language: appState.isArabic() ? 'ar' : 'en', + onSuccess: (response) { + if (onSuccess != null) { + onSuccess(); + } + }, + onError: (error) { + if (onError != null) { + onError(error); + } + }, + ); + } + + /// Select a triage choice option (for backward compatibility with single-item questions) + void selectTriageChoice(int choiceIndex) { + _selectedTriageChoiceIndex = choiceIndex; + notifyListeners(); + } + + /// Select a choice for a specific item (for multi-item questions) + void selectTriageChoiceForItem(String itemId, int choiceIndex) { + _selectedTriageChoicesByItemId[itemId] = choiceIndex; + notifyListeners(); + } + + /// Reset triage choice selection and increment question count + void resetTriageChoice() { + _selectedTriageChoiceIndex = null; + _selectedTriageChoicesByItemId.clear(); + _triageQuestionCount++; // Increment question count + notifyListeners(); + } + + /// Add triage evidence in the proper format + void addTriageEvidence(String itemId, String choiceId) { + _triageEvidenceList.add({ + "id": itemId, + "choice_id": choiceId, + "source": "triage", + }); + notifyListeners(); + } + + /// Get all triage evidence + List> getTriageEvidence() { + return List.from(_triageEvidenceList); + } + + /// Clear triage evidence + void clearTriageEvidence() { + _triageEvidenceList.clear(); + notifyListeners(); + } + void reset() { _currentView = BodyView.front; _selectedOrganIds.clear(); _selectedSymptomsByOrgan.clear(); _selectedRiskFactorIds.clear(); _selectedSuggestionsIds.clear(); + _triageEvidenceList.clear(); + _selectedTriageChoicesByItemId.clear(); + _triageQuestionCount = 0; // Reset question count bodySymptomResponse = null; riskFactorsResponse = null; suggestionsResponse = null; + triageDataDetails = null; + isTriageDiagnosisLoading = false; + _selectedTriageChoiceIndex = null; _isBottomSheetExpanded = false; _tooltipTimer?.cancel(); _tooltipOrganId = null; @@ -712,6 +948,22 @@ class SymptomsCheckerViewModel extends ChangeNotifier { bool get isUserInfoFirstPage => _userInfoCurrentPage == 0; + /// Check if current user info page has valid selection + bool get isCurrentUserInfoPageValid { + switch (_userInfoCurrentPage) { + case 0: // Gender page + return _selectedGender != null && _selectedGender!.isNotEmpty; + case 1: // Age/Birth date page + return _dateOfBirth != null || (_selectedAge != null && _selectedAge! > 0); + case 2: // Height page + return _selectedHeight > 0; + case 3: // Weight page + return _selectedWeight > 0; + default: + return false; + } + } + /// Validate and submit user info Map getUserInfoData() { return { @@ -725,6 +977,43 @@ class SymptomsCheckerViewModel extends ChangeNotifier { }; } + Future getSymptomsUserDetails({ + required String userName, + required String password, + Function()? onSuccess, + Function(String)? onError, + }) async { + isBodySymptomsLoading = true; + notifyListeners(); + final result = await symptomsCheckerRepo.getUserDetails(userName: userName, password: password); + + result.fold( + (failure) async { + isBodySymptomsLoading = false; + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + isBodySymptomsLoading = false; + if (apiResponse.messageStatus == 1 && apiResponse.data != null) { + symptomsUserDetailsResponseModel = apiResponse.data; + notifyListeners(); + if (onSuccess != null) { + onSuccess(); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Failed to fetch symptoms'); + } + } + }, + ); + } + Future getBodySymptomsByName({ required List organNames, Function(BodySymptomResponseModel)? onSuccess, @@ -735,6 +1024,8 @@ class SymptomsCheckerViewModel extends ChangeNotifier { final result = await symptomsCheckerRepo.getBodySymptomsByName( organNames: organNames, + userSessionToken: currentSessionAuthToken, + gender: _getGenderAsInt(selectedGender ?? "Male"), ); result.fold( diff --git a/lib/features/todo_section/todo_section_repo.dart b/lib/features/todo_section/todo_section_repo.dart index 008b22c..76a4438 100644 --- a/lib/features/todo_section/todo_section_repo.dart +++ b/lib/features/todo_section/todo_section_repo.dart @@ -48,6 +48,8 @@ abstract class TodoSectionRepo { }); Future> applePayInsertRequest({required dynamic applePayInsertRequest}); + + Future> getPatientDashboard(); } class TodoSectionRepoImp implements TodoSectionRepo { @@ -376,4 +378,29 @@ class TodoSectionRepoImp implements TodoSectionRepo { return Left(UnknownFailure(e.toString())); } } + + @override + Future> getPatientDashboard() async { + Map mapDevice = {}; + + try { + dynamic apiResponse; + Failure? failure; + await apiClient.post( + DASHBOARD, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + apiResponse = response; + }, + ); + if (failure != null) return Left(failure!); + return Right(apiResponse); + } catch (e) { + loggerService.logError("Unknown error in applePayInsertRequest: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } } diff --git a/lib/features/todo_section/todo_section_view_model.dart b/lib/features/todo_section/todo_section_view_model.dart index c0fb96b..0f6cc87 100644 --- a/lib/features/todo_section/todo_section_view_model.dart +++ b/lib/features/todo_section/todo_section_view_model.dart @@ -10,16 +10,23 @@ class TodoSectionViewModel extends ChangeNotifier { TodoSectionViewModel({required this.todoSectionRepo, required this.errorHandlerService}); + String? notificationsCount = "0"; + initializeTodoSectionViewModel() async { - patientAncillaryOrdersList.clear(); - isAncillaryOrdersLoading = true; - isAncillaryDetailsProceduresLoading = true; - await getPatientOnlineAncillaryOrderList(); + if (isAncillaryOrdersNeedReloading) { + patientAncillaryOrdersList.clear(); + isAncillaryOrdersLoading = true; + isAncillaryDetailsProceduresLoading = true; + notificationsCount = "0"; + getPatientOnlineAncillaryOrderList(); + } + getPatientDashboard(); } bool isAncillaryOrdersLoading = false; bool isAncillaryDetailsProceduresLoading = false; bool isProcessingPayment = false; + bool isAncillaryOrdersNeedReloading = true; List patientAncillaryOrdersList = []; List patientAncillaryOrderProceduresList = []; @@ -28,7 +35,38 @@ class TodoSectionViewModel extends ChangeNotifier { notifyListeners(); } + void setIsAncillaryOrdersNeedReloading(bool value) { + isAncillaryOrdersNeedReloading = value; + notifyListeners(); + } + + Future getPatientDashboard({Function(dynamic)? onSuccess, Function(String)? onError}) async { + final result = await todoSectionRepo.getPatientDashboard(); + + result.fold( + (failure) async { + await errorHandlerService.handleError(failure: failure); + }, + (apiResponse) { + // if (apiResponse.messageStatus == 2) { + // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); + // } else if (apiResponse.messageStatus == 1) { + notificationsCount = + apiResponse['List_PatientDashboard'][0]['UnreadPatientNotificationCount'] > 99 ? '99+' : apiResponse['List_PatientDashboard'][0]['UnreadPatientNotificationCount'].toString(); + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + // } + }, + ); + } + Future getPatientOnlineAncillaryOrderList({Function(dynamic)? onSuccess, Function(String)? onError}) async { + if (!isAncillaryOrdersNeedReloading) { + return; + } + patientAncillaryOrdersList.clear(); isAncillaryOrdersLoading = true; notifyListeners(); @@ -45,6 +83,7 @@ class TodoSectionViewModel extends ChangeNotifier { } else if (apiResponse.messageStatus == 1) { patientAncillaryOrdersList = apiResponse.data!; isAncillaryOrdersLoading = false; + isAncillaryOrdersNeedReloading = false; notifyListeners(); if (onSuccess != null) { onSuccess(apiResponse); diff --git a/lib/features/water_monitor/water_monitor_view_model.dart b/lib/features/water_monitor/water_monitor_view_model.dart index 01167fe..1ef2ef6 100644 --- a/lib/features/water_monitor/water_monitor_view_model.dart +++ b/lib/features/water_monitor/water_monitor_view_model.dart @@ -1,5 +1,6 @@ import 'dart:developer'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -14,16 +15,22 @@ import 'package:hmg_patient_app_new/features/water_monitor/models/update_user_de import 'package:hmg_patient_app_new/features/water_monitor/models/user_progress_models.dart'; import 'package:hmg_patient_app_new/features/water_monitor/models/water_cup_model.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_repo.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; import 'package:hmg_patient_app_new/services/cache_service.dart'; +import 'package:hmg_patient_app_new/services/error_handler_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/services/notification_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; class WaterMonitorViewModel extends ChangeNotifier { WaterMonitorRepo waterMonitorRepo; + ErrorHandlerService errorHandlerService; - WaterMonitorViewModel({required this.waterMonitorRepo}); + WaterMonitorViewModel({ + required this.waterMonitorRepo, + required this.errorHandlerService, + }); // Controllers final TextEditingController nameController = TextEditingController(); @@ -190,9 +197,9 @@ class WaterMonitorViewModel extends ChangeNotifier { identificationNo: identification, ); - result.fold((failure) { - log('Error fetching user progress: ${failure.message}'); - }, (apiModel) { + result.fold( + (failure) => errorHandlerService.handleError(failure: failure), + (apiModel) { log("User Progress Data ($_selectedDuration): ${apiModel.data.toString()}"); // Parse the response based on progress type @@ -300,10 +307,13 @@ class WaterMonitorViewModel extends ChangeNotifier { identificationNo: identification, ); - result.fold((failure) { - _userDetailData = null; - if (onError != null) onError(failure.message); - }, (apiModel) { + result.fold( + (failure) { + errorHandlerService.handleError(failure: failure); + _userDetailData = null; + if (onError != null) onError(failure.message); + }, + (apiModel) { _userDetailData = apiModel.data; // Populate form fields from the fetched data @@ -322,7 +332,7 @@ class WaterMonitorViewModel extends ChangeNotifier { if (_userDetailData == null) { try { - _navigationService.pushAndReplace(AppRoutes.waterMonitorSettingsScreen); + _navigationService.pushAndReplace(AppRoutes.waterMonitorSettingsPage); } catch (navErr) { log('Navigation to water monitor settings failed: $navErr'); } @@ -590,36 +600,36 @@ class WaterMonitorViewModel extends ChangeNotifier { String? validateAge() { if (ageController.text.trim().isEmpty) { - return 'Age is required'.needTranslation; + return LocaleKeys.ageIsRequired.tr(); } final age = int.tryParse(ageController.text.trim()); if (age == null) { - return 'Invalid age'.needTranslation; + return LocaleKeys.invalidAge.tr(); } if (age < 11 || age > 120) { - return 'Age must be between 11 and 120'.needTranslation; + return LocaleKeys.ageMustBeBetween11And120.tr(); } return null; } String? validateHeight() { if (heightController.text.trim().isEmpty) { - return 'Height is required'.needTranslation; + return LocaleKeys.heightIsRequired.tr(); } final height = double.tryParse(heightController.text.trim()); if (height == null || height <= 0) { - return 'Invalid height'.needTranslation; + return LocaleKeys.invalidHeight.tr(); } return null; } String? validateWeight() { if (weightController.text.trim().isEmpty) { - return 'Weight is required'.needTranslation; + return LocaleKeys.weightIsRequired.tr(); } final weight = double.tryParse(weightController.text.trim()); if (weight == null || weight <= 0) { - return 'Invalid weight'.needTranslation; + return LocaleKeys.invalidWeight.tr(); } return null; } @@ -686,6 +696,7 @@ class WaterMonitorViewModel extends ChangeNotifier { return result.fold( (failure) { + errorHandlerService.handleError(failure: failure); _validationError = failure.message; _isLoading = false; notifyListeners(); @@ -1060,14 +1071,14 @@ class WaterMonitorViewModel extends ChangeNotifier { return result.fold( (failure) { + errorHandlerService.handleError(failure: failure); log('Error inserting user activity: ${failure.message}'); _isLoading = false; notifyListeners(); return false; }, - (apiModel) { + (apiModel) async { log("Insert user activity success: ${apiModel.data.toString()}"); - // Update consumed amount and goal from the response if (apiModel.data != null && apiModel.data is List && (apiModel.data as List).isNotEmpty) { final progressData = (apiModel.data as List).first; if (progressData is Map) { @@ -1090,7 +1101,7 @@ class WaterMonitorViewModel extends ChangeNotifier { } // Refresh progress data to ensure consistency - fetchUserProgressForMonitoring(); + await fetchUserProgressForMonitoring(); } _isLoading = false; @@ -1135,12 +1146,13 @@ class WaterMonitorViewModel extends ChangeNotifier { return result.fold( (failure) { + errorHandlerService.handleError(failure: failure); log('Error undoing user activity: ${failure.message}'); _isLoading = false; notifyListeners(); return false; }, - (apiModel) { + (apiModel) async { log("Undo user activity success: ${apiModel.data.toString()}"); // Update consumed amount and goal from the response @@ -1164,8 +1176,8 @@ class WaterMonitorViewModel extends ChangeNotifier { } } } + await fetchUserProgressForMonitoring(); } - fetchUserProgressForMonitoring(); _isLoading = false; notifyListeners(); return true; @@ -1202,8 +1214,8 @@ class WaterMonitorViewModel extends ChangeNotifier { // Schedule water reminders await notificationService.scheduleWaterReminders( reminderTimes: reminderTimes, - title: 'Time to Drink Water! 💧'.needTranslation, - body: 'Stay hydrated! Drink ${selectedCupCapacityMl}ml of water.'.needTranslation, + title: LocaleKeys.timeToDrinkWater.tr(), + body: LocaleKeys.stayHydratedDrinkWater.tr(namedArgs: {'amount': selectedCupCapacityMl.toString()}), ); // Save reminder enabled state to cache @@ -1324,8 +1336,8 @@ class WaterMonitorViewModel extends ChangeNotifier { await notificationService.scheduleNotification( id: 9999, // Use a unique ID for test notifications - title: 'Time to Drink Water! 💧'.needTranslation, - body: 'Stay hydrated! Drink ${selectedCupCapacityMl}ml of water.'.needTranslation, + title: LocaleKeys.timeToDrinkWater.tr(), + body: LocaleKeys.stayHydratedDrinkWater.tr(namedArgs: {'amount': selectedCupCapacityMl.toString()}), scheduledDate: scheduledTime, payload: 'test_notification', ); diff --git a/lib/generated/locale_keys.g.dart b/lib/generated/locale_keys.g.dart index 97721a6..46bdb0f 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -693,11 +693,7 @@ abstract class LocaleKeys { static const bikini = 'bikini'; static const totalMinutes = 'totalMinutes'; static const feedback = 'feedback'; - static const send = 'send'; - static const status = 'status'; static const likeToHear = 'likeToHear'; - static const subject = 'subject'; - static const message = 'message'; static const emptySubject = 'emptySubject'; static const emptyMessage = 'emptyMessage'; static const selectAttachment = 'selectAttachment'; @@ -880,5 +876,648 @@ abstract class LocaleKeys { static const callForDoctor = 'callForDoctor'; static const yourQueueNumber = 'yourQueueNumber'; static const currentServing = 'currentServing'; + static const appointmentDetails = 'appointmentDetails'; + static const checkingDoctorAvailability = 'checkingDoctorAvailability'; + static const cancellingAppointmentPleaseWait = 'cancellingAppointmentPleaseWait'; + static const appointmentCancelledSuccessfully = 'appointmentCancelledSuccessfully'; + static const notConfirmed = 'notConfirmed'; + static const appointmentStatus = 'appointmentStatus'; + static const doctorWillCallYou = 'doctorWillCallYou'; + static const getDirections = 'getDirections'; + static const notifyMeBeforeAppointment = 'notifyMeBeforeAppointment'; + static const fetchingLabResults = 'fetchingLabResults'; + static const fetchingRadiologyResults = 'fetchingRadiologyResults'; + static const fetchingAppointmentPrescriptions = 'fetchingAppointmentPrescriptions'; + static const noPrescriptionsForAppointment = 'noPrescriptionsForAppointment'; + static const amountBeforeTax = 'amountBeforeTax'; + static const rebookAppointment = 'rebookAppointment'; + static const fetchingDoctorSchedulePleaseWait = 'fetchingDoctorSchedulePleaseWait'; + static const pickADate = 'pickADate'; + static const confirmingAppointmentPleaseWait = 'confirmingAppointmentPleaseWait'; + static const appointmentConfirmedSuccessfully = 'appointmentConfirmedSuccessfully'; + static const appointmentPayment = 'appointmentPayment'; + static const checkingPaymentStatusPleaseWait = 'checkingPaymentStatusPleaseWait'; + static const paymentFailedPleaseTryAgain = 'paymentFailedPleaseTryAgain'; + static const appointmentCheckIn = 'appointmentCheckIn'; + static const insuranceExpiredOrInactive = 'insuranceExpiredOrInactive'; + static const totalAmountToPay = 'totalAmountToPay'; + static const vat15 = 'vat15'; + static const liveCare = 'liveCare'; + static const recentVisits = 'recentVisits'; + static const searchByClinic = 'searchByClinic'; + static const tapToSelectClinic = 'tapToSelectClinic'; + static const searchByDoctor = 'searchByDoctor'; + static const tapToSelect = 'tapToSelect'; + static const searchByRegion = 'searchByRegion'; + static const centralRegion = 'centralRegion'; + static const immediateConsultation = 'immediateConsultation'; + static const scheduledConsultation = 'scheduledConsultation'; + static const pharmaLiveCare = 'pharmaLiveCare'; + static const notSureHelpMeChooseClinic = 'notSureHelpMeChooseClinic'; + static const mentionYourSymptomsAndFindDoctors = 'mentionYourSymptomsAndFindDoctors'; + static const immediateService = 'immediateService'; + static const noNeedToWaitGetMedicalConsultation = 'noNeedToWaitGetMedicalConsultation'; + static const noVisitRequired = 'noVisitRequired'; + static const doctorWillContact = 'doctorWillContact'; + static const specialisedDoctorWillContactYou = 'specialisedDoctorWillContactYou'; + static const freeMedicineDelivery = 'freeMedicineDelivery'; + static const offersFreeMedicineDelivery = 'offersFreeMedicineDelivery'; + static const dentalChiefComplaints = 'dentalChiefComplaints'; + static const viewAvailableAppointments = 'viewAvailableAppointments'; + static const doctorProfile = 'doctorProfile'; + static const waitingAppointment = 'waitingAppointment'; + static const hospitalInformation = 'hospitalInformation'; + static const fetchingAppointmentShare = 'fetchingAppointmentShare'; + static const bookingYourAppointment = 'bookingYourAppointment'; + static const selectLiveCareClinic = 'selectLiveCareClinic'; + static const checkingForExistingDentalPlan = 'checkingForExistingDentalPlan'; + static const dentalTreatmentPlan = 'dentalTreatmentPlan'; + static const youHaveExistingTreatmentPlan = 'youHaveExistingTreatmentPlan'; + static const mins = 'mins'; + static const totalTimeRequired = 'totalTimeRequired'; + static const wouldYouLikeToContinue = 'wouldYouLikeToContinue'; + static const chooseDoctor = 'chooseDoctor'; + static const viewNearestAppos = 'viewNearestAppos'; + static const noDoctorFound = 'noDoctorFound'; + static const yesPleasImInAHurry = 'yesPleasImInAHurry'; + static const fetchingFeesPleaseWait = 'fetchingFeesPleaseWait'; + static const noThanksPhysicalVisit = 'noThanksPhysicalVisit'; + static const offline = 'offline'; + static const videoCall = 'videoCall'; + static const liveVideoCallWithHMGDoctors = 'liveVideoCallWithHMGDoctors'; + static const audioCall = 'audioCall'; + static const phoneCall = 'phoneCall'; + static const livePhoneCallWithHMGDoctors = 'livePhoneCallWithHMGDoctors'; + static const reviewLiveCareRequest = 'reviewLiveCareRequest'; + static const selectedLiveCareType = 'selectedLiveCareType'; + static const selectLiveCareCallType = 'selectLiveCareCallType'; + static const confirmingLiveCareRequest = 'confirmingLiveCareRequest'; + static const unknownErrorOccurred = 'unknownErrorOccurred'; + static const liveCarePermissionsMessage = 'liveCarePermissionsMessage'; + static const liveCarePayment = 'liveCarePayment'; + static const mada = 'mada'; + static const visaOrMastercard = 'visaOrMastercard'; + static const tamara = 'tamara'; + static const fetchingApplePayDetails = 'fetchingApplePayDetails'; + static const liveCarePendingRequest = 'liveCarePendingRequest'; + static const callLiveCareSupport = 'callLiveCareSupport'; + static const whatIsWaitingAppointment = 'whatIsWaitingAppointment'; + static const waitingAppointmentsFeature = 'waitingAppointmentsFeature'; + static const appointmentWithDoctorConfirmed = 'appointmentWithDoctorConfirmed'; + static const paymentWithinTenMinutes = 'paymentWithinTenMinutes'; + static const liveLocation = 'liveLocation'; + static const verifyYourLocationAtHospital = 'verifyYourLocationAtHospital'; + static const error = 'error'; + static const ensureWithinHospitalLocation = 'ensureWithinHospitalLocation'; + static const nfcNearFieldCommunication = 'nfcNearFieldCommunication'; + static const scanPhoneViaNFC = 'scanPhoneViaNFC'; + static const qrCode = 'qrCode'; + static const scanQRCodeToCheckIn = 'scanQRCodeToCheckIn'; + static const processingCheckIn = 'processingCheckIn'; + static const bookingWaitingAppointment = 'bookingWaitingAppointment'; + static const enterValidIDorIqama = 'enterValidIDorIqama'; + static const selectAppointment = 'selectAppointment'; + static const rebookSameDoctor = 'rebookSameDoctor'; + static const queueing = 'queueing'; + static const inQueue = 'inQueue'; + static const yourTurn = 'yourTurn'; + static const halaFirstName = 'halaFirstName'; + static const thankYouForPatience = 'thankYouForPatience'; + static const servingNow = 'servingNow'; + static const callForVitalSigns = 'callForVitalSigns'; + static const callForDoctor = 'callForDoctor'; + static const thingsToAskDoctor = 'thingsToAskDoctor'; + static const improveOverallHealth = 'improveOverallHealth'; + static const routineScreenings = 'routineScreenings'; + static const whatIsThisMedicationFor = 'whatIsThisMedicationFor'; + static const sideEffectsToKnow = 'sideEffectsToKnow'; + static const whenFollowUp = 'whenFollowUp'; + static const goToHomepage = 'goToHomepage'; + static const appointmentsList = 'appointmentsList'; + static const allAppt = 'allAppt'; + static const upcoming = 'upcoming'; + static const completed = 'completed'; + static const noAppointmentsYet = 'noAppointmentsYet'; + static const viewProfile = 'viewProfile'; + static const choosePreferredHospitalForService = 'choosePreferredHospitalForService'; + static const noHospitalsFound = 'noHospitalsFound'; + static const cancelOrderConfirmation = 'cancelOrderConfirmation'; + static const orderCancelledSuccessfully = 'orderCancelledSuccessfully'; + static const requestID = 'requestID'; + static const noCMCOrdersYet = 'noCMCOrdersYet'; + static const cmcOrders = 'cmcOrders'; + static const summary = 'summary'; + static const selectedService = 'selectedService'; + static const requestSubmittedSuccessfully = 'requestSubmittedSuccessfully'; + static const hereIsYourRequestNumber = 'hereIsYourRequestNumber'; + static const pleaseSelectHospitalToContinue = 'pleaseSelectHospitalToContinue'; + static const confirmSubmitRequest = 'confirmSubmitRequest'; + static const pendingOrderWait = 'pendingOrderWait'; + static const noServicesAvailable = 'noServicesAvailable'; + static const selectAService = 'selectAService'; + static const comprehensiveCheckup = 'comprehensiveCheckup'; + static const viewNearestHMGLocations = 'viewNearestHMGLocations'; + static const provideFeedbackOnServices = 'provideFeedbackOnServices'; + static const liveChatWithHMG = 'liveChatWithHMG'; + static const send = 'send'; + static const status = 'status'; + static const sendingFeedback = 'sendingFeedback'; + static const selectFeedbackType = 'selectFeedbackType'; + static const loadingAppointmentsList = 'loadingAppointmentsList'; + static const noAppointmentsForFeedback = 'noAppointmentsForFeedback'; + static const selectedAppointment = 'selectedAppointment'; + static const subject = 'subject'; + static const enterSubjectHere = 'enterSubjectHere'; + static const message = 'message'; + static const enterMessageHere = 'enterMessageHere'; + static const filesSelected = 'filesSelected'; + static const otherDetails = 'otherDetails'; + static const medicalReport = 'medicalReport'; + static const medicalReportNumber = 'medicalReportNumber'; + static const patientIsInsured = 'patientIsInsured'; + static const insuranceDocument = 'insuranceDocument'; + static const selectBranch = 'selectBranch'; + static const patientInformation = 'patientInformation'; + static const patientLocation = 'patientLocation'; + static const identificationNumber = 'identificationNumber'; + static const enterIdentificationNumber = 'enterIdentificationNumber'; + static const patientName = 'patientName'; + static const referralRequesterInformation = 'referralRequesterInformation'; + static const enterReferralRequesterName = 'enterReferralRequesterName'; + static const requesterName = 'requesterName'; + static const relationship = 'relationship'; + static const selectRelation = 'selectRelation'; + static const otherName = 'otherName'; + static const otherNameHint = 'otherNameHint'; + static const requesterNameRequired = 'requesterNameRequired'; + static const selectRelationshipRequired = 'selectRelationshipRequired'; + static const otherRelationshipNameRequired = 'otherRelationshipNameRequired'; + static const identificationNumberRequired = 'identificationNumberRequired'; + static const patientNameRequired = 'patientNameRequired'; + static const enterPatientPhoneRequired = 'enterPatientPhoneRequired'; + static const selectPatientCityRequired = 'selectPatientCityRequired'; + static const medicalReportRequired = 'medicalReportRequired'; + static const selectBranchRequired = 'selectBranchRequired'; + static const insuranceDocumentRequired = 'insuranceDocumentRequired'; + static const searchResult = 'searchResult'; + static const referralNo = 'referralNo'; + static const eReferral = 'eReferral'; + static const referralCreatedSuccessfully = 'referralCreatedSuccessfully'; + static const hereIsYourReferralNumber = 'hereIsYourReferralNumber'; + static const searchEReferral = 'searchEReferral'; + static const enterRequiredInfoToSearch = 'enterRequiredInfoToSearch'; + static const selectPickupDirection = 'selectPickupDirection'; + static const selectDirection = 'selectDirection'; + static const toHospital = 'toHospital'; + static const fromHospital = 'fromHospital'; + static const selectWay = 'selectWay'; + static const oneWay = 'oneWay'; + static const twoWay = 'twoWay'; + static const selectPickupDetails = 'selectPickupDetails'; + static const pleaseSelectDetailsOfPickup = 'pleaseSelectDetailsOfPickup'; + static const selectDetails = 'selectDetails'; + static const work = 'work'; + static const pick = 'pick'; + static const insideTheHome = 'insideTheHome'; + static const haveAnyAppointment = 'haveAnyAppointment'; + static const amountPaidAtHospital = 'amountPaidAtHospital'; + static const submitRequest = 'submitRequest'; + static const enterPickupLocationManually = 'enterPickupLocationManually'; + static const enterPickupLocation = 'enterPickupLocation'; + static const trackingDetails = 'trackingDetails'; + static const cancelRequest = 'cancelRequest'; + static const shareLocationWhatsapp = 'shareLocationWhatsapp'; + static const pleaseWaitForCall = 'pleaseWaitForCall'; + static const toHospitalLower = 'toHospitalLower'; + static const contact = 'contact'; + static const failed = 'failed'; + static const confirmationCall = 'confirmationCall'; + static const pickupFromHome = 'pickupFromHome'; + static const onTheWayToHospital = 'onTheWayToHospital'; + static const arrivedAtHospital = 'arrivedAtHospital'; + static const orderCancel = 'orderCancel'; + static const emergencyCheckIn = 'emergencyCheckIn'; + static const erOnlineCheckInDescription = 'erOnlineCheckInDescription'; + static const erOnlineCheckInSuccess = 'erOnlineCheckInSuccess'; + static const erOnlineCheckInError = 'erOnlineCheckInError'; + static const fetchingHospitalsList = 'fetchingHospitalsList'; + static const fetchingPaymentInformation = 'fetchingPaymentInformation'; + static const erVisitDetails = 'erVisitDetails'; + static const erClinic = 'erClinic'; + static const vatWithAmount = 'vatWithAmount'; + static const erAppointmentBookedSuccess = 'erAppointmentBookedSuccess'; + static const underProcessing = 'underProcessing'; + static const canceledByPatient = 'canceledByPatient'; + static const rapidResponseTeam = 'rapidResponseTeam'; + static const allFacilities = 'allFacilities'; + static const selectLocation = 'selectLocation'; + static const pleaseSelectTheLocation = 'pleaseSelectTheLocation'; + static const viewLocationGoogleMaps = 'viewLocationGoogleMaps'; + static const callAmbulance = 'callAmbulance'; + static const requestAmbulanceInEmergency = 'requestAmbulanceInEmergency'; + static const confirmation = 'confirmation'; + static const areYouSureYouWantToCallAmbulance = 'areYouSureYouWantToCallAmbulance'; + static const getDetailsOfNearestBranch = 'getDetailsOfNearestBranch'; + static const areYouSureYouWantToCallRRT = 'areYouSureYouWantToCallRRT'; + static const priorERCheckInToSkipLine = 'priorERCheckInToSkipLine'; + static const areYouSureYouWantToMakeERCheckIn = 'areYouSureYouWantToMakeERCheckIn'; + static const checkingYourERAppointmentStatus = 'checkingYourERAppointmentStatus'; + static const transportOptions = 'transportOptions'; + static const selectHospitalForAdvancePayment = 'selectHospitalForAdvancePayment'; + static const recharge = 'recharge'; + static const activityLevel = 'activityLevel'; + static const selectActivityLevel = 'selectActivityLevel'; + static const caloriesPerDay = 'caloriesPerDay'; + static const dietType = 'dietType'; + static const selectDietType = 'selectDietType'; + static const bodyFrameSize = 'bodyFrameSize'; + static const selectBodyFrameSize = 'selectBodyFrameSize'; + static const averageCycleLength = 'averageCycleLength'; + static const averageLutealPhase = 'averageLutealPhase'; + static const convert = 'convert'; + static const calculate = 'calculate'; + static const healthCalculators = 'healthCalculators'; + static const healthConverters = 'healthConverters'; + static const generalHealth = 'generalHealth'; + static const relatedToBMICalories = 'relatedToBMICalories'; + static const selectCalculator = 'selectCalculator'; + static const womensHealth = 'womensHealth'; + static const relatedToPeriodsOvulation = 'relatedToPeriodsOvulation'; + static const bloodSugar = 'bloodSugar'; + static const trackYourGlucoseLevels = 'trackYourGlucoseLevels'; + static const bloodCholesterol = 'bloodCholesterol'; + static const monitorCholesterolLevels = 'monitorCholesterolLevels'; + static const triglyceridesFatBlood = 'triglyceridesFatBlood'; + static const understandTriglyceridesImpact = 'understandTriglyceridesImpact'; + static const bmiCalculator = 'bmiCalculator'; + static const caloriesCalculator = 'caloriesCalculator'; + static const bmrCalculator = 'bmrCalculator'; + static const idealBodyWeight = 'idealBodyWeight'; + static const bodyFatCalculator = 'bodyFatCalculator'; + static const carbsProteinFat = 'carbsProteinFat'; + static const ovulationPeriod = 'ovulationPeriod'; + static const deliveryDueDate = 'deliveryDueDate'; + static const low = 'low'; + static const preDiabetic = 'preDiabetic'; + static const high = 'high'; + static const elevated = 'elevated'; + static const recorded = 'recorded'; + static const noRecordsYet = 'noRecordsYet'; + static const lastRecord = 'lastRecord'; + static const addBloodSugar = 'addBloodSugar'; + static const addBloodPressure = 'addBloodPressure'; + static const addWeight = 'addWeight'; + static const bloodSugarDataSavedSuccessfully = 'bloodSugarDataSavedSuccessfully'; + static const bloodPressureDataSavedSuccessfully = 'bloodPressureDataSavedSuccessfully'; + static const weightDataSavedSuccessfully = 'weightDataSavedSuccessfully'; + static const pleaseWait = 'pleaseWait'; + static const selectUnit = 'selectUnit'; + static const selectMeasureTime = 'selectMeasureTime'; + static const selectArm = 'selectArm'; + static const enterBloodSugar = 'enterBloodSugar'; + static const enterSystolicValue = 'enterSystolicValue'; + static const enterDiastolicValue = 'enterDiastolicValue'; + static const enterWeight = 'enterWeight'; + static const selectDuration = 'selectDuration'; + static const systolic = 'systolic'; + static const diastolic = 'diastolic'; + static const sendReportByEmail = 'sendReportByEmail'; + static const enterYourEmailToReceiveReport = 'enterYourEmailToReceiveReport'; + static const addNewRecord = 'addNewRecord'; + static const healthTrackers = 'healthTrackers'; + static const monitorBloodPressureLevels = 'monitorBloodPressureLevels'; + static const trackWeightProgress = 'trackWeightProgress'; + static const bookAppointment = 'bookAppointment'; + static const completeCheckup = 'completeCheckup'; + static const indoorNavigation = 'indoorNavigation'; + static const eReferralServices = 'eReferralServices'; + static const dailyWaterMonitor = 'dailyWaterMonitor'; + static const fetchingYourWaterIntakeDetails = 'fetchingYourWaterIntakeDetails'; + static const healthCalculatorsServices = 'healthCalculatorsServices'; + static const healthConvertersServices = 'healthConvertersServices'; + static const smartWatchesServices = 'smartWatchesServices'; + static const exploreServices = 'exploreServices'; + static const medicalAndCareServices = 'medicalAndCareServices'; + static const hmgServices = 'hmgServices'; + static const personalServices = 'personalServices'; + static const habibWallet = 'habibWallet'; + static const loginToViewWalletBalance = 'loginToViewWalletBalance'; + static const loginToViewMedicalFile = 'loginToViewMedicalFile'; + static const addMember = 'addMember'; + static const addFamilyMember = 'addFamilyMember'; + static const pleaseFillBelowFieldToAddNewFamilyMember = 'pleaseFillBelowFieldToAddNewFamilyMember'; + static const healthTools = 'healthTools'; + static const supportServices = 'supportServices'; + static const virtualTour = 'virtualTour'; + static const carParking = 'carParking'; + static const latestNews = 'latestNews'; + static const hmgContact = 'hmgContact'; + static const durationCannotExceed90 = 'durationCannotExceed90'; + static const unexpectedError = 'unexpectedError'; + static const gettingAmbulanceTransportOption = 'gettingAmbulanceTransportOption'; + static const fetchingAppointment = 'fetchingAppointment'; + static const doYouWantToCancelTheRequest = 'doYouWantToCancelTheRequest'; + static const cancellingRequest = 'cancellingRequest'; + static const fetchingTermsAndConditions = 'fetchingTermsAndConditions'; + static const selectLocationPrescriptionDelivery = 'selectLocationPrescriptionDelivery'; + static const noRadiologyOrders = 'noRadiologyOrders'; + static const ageIsRequired = 'ageIsRequired'; + static const invalidAge = 'invalidAge'; + static const ageMustBeBetween11And120 = 'ageMustBeBetween11And120'; + static const heightIsRequired = 'heightIsRequired'; + static const invalidHeight = 'invalidHeight'; + static const weightIsRequired = 'weightIsRequired'; + static const invalidWeight = 'invalidWeight'; + static const timeToDrinkWater = 'timeToDrinkWater'; + static const stayHydratedDrinkWater = 'stayHydratedDrinkWater'; + static const visitPharmacyOnline = 'visitPharmacyOnline'; + static const howAreYouFeelingToday = 'howAreYouFeelingToday'; + static const checkYourSymptomsWithScale = 'checkYourSymptomsWithScale'; + static const checkYourSymptoms = 'checkYourSymptoms'; + static const noUpcomingAppointmentPleaseBook = 'noUpcomingAppointmentPleaseBook'; + static const youHaveEROnlineCheckInRequest = 'youHaveEROnlineCheckInRequest'; + static const quickLinks = 'quickLinks'; + static const viewMedicalFileLandingPage = 'viewMedicalFileLandingPage'; + static const immediateLiveCareRequest = 'immediateLiveCareRequest'; + static const yourTurnIsAfterPatients = 'yourTurnIsAfterPatients'; + static const dontHaveHHCOrders = 'dontHaveHHCOrders'; + static const hhcOrders = 'hhcOrders'; + static const requestedServices = 'requestedServices'; + static const selectServices = 'selectServices'; + static const selectedServices = 'selectedServices'; + static const createNewRequest = 'createNewRequest'; + static const youHaveNoPendingRequests = 'youHaveNoPendingRequests'; + static const noInsuranceDataFound = 'noInsuranceDataFound'; + static const noInsuranceUpdateRequest = 'noInsuranceUpdateRequest'; + static const policyNumberInsurancePage = 'policyNumberInsurancePage'; + static const insuranceExpired = 'insuranceExpired'; + static const insuranceActive = 'insuranceActive'; + static const patientCardID = 'patientCardID'; + static const noInsuranceApprovals = 'noInsuranceApprovals'; + static const noInsuranceWithHMG = 'noInsuranceWithHMG'; + static const referenceRange = 'referenceRange'; + static const downloadReport = 'downloadReport'; + static const generatingReport = 'generatingReport'; + static const noLabResults = 'noLabResults'; + static const labResultDetails = 'labResultDetails'; + static const resultOf = 'resultOf'; + static const whatIsThisResult = 'whatIsThisResult'; + static const lastTested = 'lastTested'; + static const byVisit = 'byVisit'; + static const byTest = 'byTest'; + static const results = 'results'; + static const viewResults = 'viewResults'; + static const rebook = 'rebook'; + static const noOphthalmologyAppointments = 'noOphthalmologyAppointments'; + static const noVitalSignsRecordedYet = 'noVitalSignsRecordedYet'; + static const appointmentsAndVisits = 'appointmentsAndVisits'; + static const labAndRadiology = 'labAndRadiology'; + static const activeMedicationsAndPrescriptions = 'activeMedicationsAndPrescriptions'; + static const allPrescriptions = 'allPrescriptions'; + static const allMedications = 'allMedications'; + static const youDontHaveAnyPrescriptionsYet = 'youDontHaveAnyPrescriptionsYet'; + static const youDontHaveAnyCompletedVisitsYet = 'youDontHaveAnyCompletedVisitsYet'; + static const others = 'others'; + static const allergyInfo = 'allergyInfo'; + static const vaccineInfo = 'vaccineInfo'; + static const updateInsuranceInfo = 'updateInsuranceInfo'; + static const myInvoicesList = 'myInvoicesList'; + static const ancillaryOrdersList = 'ancillaryOrdersList'; + static const youDontHaveAnySickLeavesYet = 'youDontHaveAnySickLeavesYet'; + static const medicalReports = 'medicalReports'; + static const sickLeaveReport = 'sickLeaveReport'; + static const weightTracker = 'weightTracker'; + static const askYourDoctor = 'askYourDoctor'; + static const internetPairing = 'internetPairing'; + static const requested = 'requested'; + static const youDontHaveAnyMedicalReportsYet = 'youDontHaveAnyMedicalReportsYet'; + static const requestMedicalReport = 'requestMedicalReport'; + static const youDoNotHaveAnyAppointmentsToRequestMedicalReport = 'youDoNotHaveAnyAppointmentsToRequestMedicalReport'; + static const areYouSureYouWantToRequestMedicalReport = 'areYouSureYouWantToRequestMedicalReport'; + static const yourMedicalReportRequestSubmittedSuccessfully = 'yourMedicalReportRequestSubmittedSuccessfully'; + static const monthlyHealthSummaryReportDisclaimer = 'monthlyHealthSummaryReportDisclaimer'; + static const updatingMonthlyReportStatus = 'updatingMonthlyReportStatus'; + static const monthlyReportStatusUpdatedSuccessfully = 'monthlyReportStatusUpdatedSuccessfully'; + static const whoCanViewMyMedicalFile = 'whoCanViewMyMedicalFile'; + static const acceptedYourRequestToBeYourFamilyMember = 'acceptedYourRequestToBeYourFamilyMember'; + static const canViewYourFile = 'canViewYourFile'; + static const hasARequestPendingToBeYourFamilyMember = 'hasARequestPendingToBeYourFamilyMember'; + static const wantsToAddYouAsTheirFamilyMember = 'wantsToAddYouAsTheirFamilyMember'; + static const rejectedYourRequestToBeYourFamilyMember = 'rejectedYourRequestToBeYourFamilyMember'; + static const rejectedYourFamilyMemberRequest = 'rejectedYourFamilyMemberRequest'; + static const notAvailable = 'notAvailable'; + static const selectAProfile = 'selectAProfile'; + static const switchFamilyFile = 'switchFamilyFile'; + static const medicalFiles = 'medicalFiles'; + static const addANewFamilyMember = 'addANewFamilyMember'; + static const viewInvoiceDetails = 'viewInvoiceDetails'; + static const outPatient = 'outPatient'; + static const invoiceDetails = 'invoiceDetails'; + static const sendingEmailPleaseWait = 'sendingEmailPleaseWait'; + static const emailSentSuccessfullyMessage = 'emailSentSuccessfullyMessage'; + static const discount = 'discount'; + static const paid = 'paid'; + static const fetchingInvoiceDetails = 'fetchingInvoiceDetails'; + static const scanQRCode = 'scanQRCode'; + static const parkingSlotDetails = 'parkingSlotDetails'; + static const slotNumber = 'slotNumber'; + static const basement = 'basement'; + static const parkingDate = 'parkingDate'; + static const parkedSince = 'parkedSince'; + static const resetDirection = 'resetDirection'; + static const noPrescriptionOrdersYet = 'noPrescriptionOrdersYet'; + static const fetchingPrescriptionPDFPleaseWait = 'fetchingPrescriptionPDFPleaseWait'; + static const ratingValue = 'ratingValue'; + static const downloadPrescription = 'downloadPrescription'; + static const fetchingPrescriptionDetails = 'fetchingPrescriptionDetails'; + static const switchBackFamilyFile = 'switchBackFamilyFile'; + static const profileAndSettings = 'profileAndSettings'; + static const quickActions = 'quickActions'; + static const notificationsSettings = 'notificationsSettings'; + static const touchIDFaceIDServices = 'touchIDFaceIDServices'; + static const personalInformation = 'personalInformation'; + static const updateEmailAddress = 'updateEmailAddress'; + static const helpAndSupport = 'helpAndSupport'; + static const permissionsProfile = 'permissionsProfile'; + static const privacyPolicy = 'privacyPolicy'; + static const deactivateAccount = 'deactivateAccount'; + static const ageYearsOld = 'ageYearsOld'; + static const youDontHaveRadiologyOrders = 'youDontHaveRadiologyOrders'; + static const radiologyResult = 'radiologyResult'; + static const viewRadiologyImage = 'viewRadiologyImage'; + static const rateClinic = 'rateClinic'; + static const back = 'back'; + static const rateDoctor = 'rateDoctor'; + static const howWasYourLastVisitWithDoctor = 'howWasYourLastVisitWithDoctor'; + static const dateOfBirthSymptoms = 'dateOfBirthSymptoms'; + static const genderSymptoms = 'genderSymptoms'; + static const heightSymptoms = 'heightSymptoms'; + static const weightSymptoms = 'weightSymptoms'; + static const femaleGender = 'femaleGender'; + static const previous = 'previous'; + static const selectedOrgans = 'selectedOrgans'; + static const noOrgansSelected = 'noOrgansSelected'; + static const organSelector = 'organSelector'; + static const noPredictionsAvailable = 'noPredictionsAvailable'; + static const areYouSureYouWantToRestartOrganSelection = 'areYouSureYouWantToRestartOrganSelection'; + static const possibleConditions = 'possibleConditions'; + static const pleaseSelectAtLeastOneRiskBeforeProceeding = 'pleaseSelectAtLeastOneRiskBeforeProceeding'; + static const aboveYouSeeCommonRiskFactors = 'aboveYouSeeCommonRiskFactors'; + static const readMore = 'readMore'; + static const riskFactors = 'riskFactors'; + static const noRiskFactorsFound = 'noRiskFactorsFound'; + static const basedOnYourSelectedSymptomsNoRiskFactors = 'basedOnYourSelectedSymptomsNoRiskFactors'; + static const messageNotification = 'messageNotification'; + static const attachedImage = 'attachedImage'; + static const failedToLoadImage = 'failedToLoadImage'; + static const typeNotification = 'typeNotification'; + static const pleaseSelectAtLeastOneOptionBeforeProceeding = 'pleaseSelectAtLeastOneOptionBeforeProceeding'; + static const suggestions = 'suggestions'; + static const pleaseGoBackAndSelectOrgansFirst = 'pleaseGoBackAndSelectOrgansFirst'; + static const symptomsSelector = 'symptomsSelector'; + static const possibleSymptomsRelatedTo = 'possibleSymptomsRelatedTo'; + static const suggestionAIListDescription = 'suggestionAIListDescription'; + static const analyzing = 'analyzing'; + static const seekMedicalAdvice = 'seekMedicalAdvice'; + static const monitorDescription = 'monitorDescription'; + static const seekMedicalAdviceDescription = 'seekMedicalAdviceDescription'; + static const emergencyDescription = 'emergencyDescription'; + static const colorScience = 'colorScience'; + static const noNeedToVisitDoctor = 'noNeedToVisitDoctor'; + static const commonSymptom = 'commonSymptom'; + static const notApplicable = 'notApplicable'; + static const emergencyTriage = 'emergencyTriage'; + static const emergencyEvidenceDetected = 'emergencyEvidenceDetected'; + static const noQuestionItemsAvailable = 'noQuestionItemsAvailable'; + static const pleaseAnswerAllQuestionsBeforeProceeding = 'pleaseAnswerAllQuestionsBeforeProceeding'; + static const triage = 'triage'; + static const areYouSureYouWantToExitProgress = 'areYouSureYouWantToExitProgress'; + static const noQuestionAvailable = 'noQuestionAvailable'; + static const possibleSymptom = 'possibleSymptom'; + static const symptomsCheckerFindingScore = 'symptomsCheckerFindingScore'; + static const notSet = 'notSet'; + static const years = 'years'; + static const symptomsChecker = 'symptomsChecker'; + static const helloIsYourInformationUpToDate = 'helloIsYourInformationUpToDate'; + static const noEditAll = 'noEditAll'; + static const yesItIs = 'yesItIs'; + static const age = 'age'; + static const youDontHaveAnyAncillaryOrdersYet = 'youDontHaveAnyAncillaryOrdersYet'; + static const invoiceWithNumber = 'invoiceWithNumber'; + static const queued = 'queued'; + static const checkInReady = 'checkInReady'; + static const checkIn = 'checkIn'; + static const viewDetails = 'viewDetails'; + static const selectPaymentMethod = 'selectPaymentMethod'; + static const processingPaymentPleaseWait = 'processingPaymentPleaseWait'; + static const finalizingPaymentPleaseWait = 'finalizingPaymentPleaseWait'; + static const generatingInvoicePleaseWait = 'generatingInvoicePleaseWait'; + static const hereIsYourInvoiceNumber = 'hereIsYourInvoiceNumber'; + static const paymentCompletedSuccessfully = 'paymentCompletedSuccessfully'; + static const failedToInitializeApplePay = 'failedToInitializeApplePay'; + static const cash = 'cash'; + static const approved = 'approved'; + static const approvalRejectedPleaseVisitReceptionist = 'approvalRejectedPleaseVisitReceptionist'; + static const sentForApproval = 'sentForApproval'; + static const ancillaryOrderDetails = 'ancillaryOrderDetails'; + static const noProceduresAvailableForSelectedOrder = 'noProceduresAvailableForSelectedOrder'; + static const procedures = 'procedures'; + static const totalAmount = 'totalAmount'; + static const covered = 'covered'; + static const vatPercent = 'vatPercent'; + static const proceedToPayment = 'proceedToPayment'; + static const supportedSmartWatches = 'supportedSmartWatches'; + static const pleaseMakeSureSamsungWatchConnected = 'pleaseMakeSureSamsungWatchConnected'; + static const beforeSyncingDataFollowInstructions = 'beforeSyncingDataFollowInstructions'; + static const viewWatchInstructions = 'viewWatchInstructions'; + static const healthConnectAppNotInstalled = 'healthConnectAppNotInstalled'; + static const setTimerOfReminder = 'setTimerOfReminder'; + static const youHaveAppointmentWithDr = 'youHaveAppointmentWithDr'; + static const hours = 'hours'; + static const secs = 'secs'; + static const noAllergiesDataFound = 'noAllergiesDataFound'; + static const heartRateDescription = 'heartRateDescription'; + static const bloodOxygenDescription = 'bloodOxygenDescription'; + static const stepsDescription = 'stepsDescription'; + static const caloriesDescription = 'caloriesDescription'; + static const distanceDescription = 'distanceDescription'; + static const overview = 'overview'; + static const details = 'details'; + static const healthy = 'healthy'; + static const warning = 'warning'; + static const vitalSignDetails = 'vitalSignDetails'; + static const resultOfNoDate = 'resultOfNoDate'; + static const referenceRangeBetween = 'referenceRangeBetween'; + static const referenceRangeMin = 'referenceRangeMin'; + static const referenceRangeMax = 'referenceRangeMax'; + static const noHistoryAvailable = 'noHistoryAvailable'; + static const bmiDescription = 'bmiDescription'; + static const heightDescription = 'heightDescription'; + static const weightDescription = 'weightDescription'; + static const bloodPressureDescription = 'bloodPressureDescription'; + static const temperatureDescription = 'temperatureDescription'; + static const heartRateDescriptionVital = 'heartRateDescriptionVital'; + static const respiratoryRateDescription = 'respiratoryRateDescription'; + static const bmiAdvice = 'bmiAdvice'; + static const heightAdvice = 'heightAdvice'; + static const weightAdvice = 'weightAdvice'; + static const bloodPressureAdvice = 'bloodPressureAdvice'; + static const temperatureAdvice = 'temperatureAdvice'; + static const heartRateAdvice = 'heartRateAdvice'; + static const respiratoryRateAdvice = 'respiratoryRateAdvice'; + static const whatShouldIDoNext = 'whatShouldIDoNext'; + static const customizeDrinkCup = 'customizeDrinkCup'; + static const tipsToStayHydrated = 'tipsToStayHydrated'; + static const drinkBeforeYouFeelThirsty = 'drinkBeforeYouFeelThirsty'; + static const keepRefillableBottleNextToYou = 'keepRefillableBottleNextToYou'; + static const trackYourDailyIntakeToStayMotivated = 'trackYourDailyIntakeToStayMotivated'; + static const chooseSparklingWaterInsteadOfSoda = 'chooseSparklingWaterInsteadOfSoda'; + static const switchCup = 'switchCup'; + static const plainWater = 'plainWater'; + static const yourGoal = 'yourGoal'; + static const remaining = 'remaining'; + static const hydrationStatus = 'hydrationStatus'; + static const areYouSureYouWantToCancelAllWaterReminders = 'areYouSureYouWantToCancelAllWaterReminders'; + static const remindersSet = 'remindersSet'; + static const dailyWaterRemindersScheduledAt = 'dailyWaterRemindersScheduledAt'; + static const waterConsumption = 'waterConsumption'; + static const selectNumberOfReminders = 'selectNumberOfReminders'; + static const h2oSettings = 'h2oSettings'; + static const settingsSavedSuccessfully = 'settingsSavedSuccessfully'; + static const yourName = 'yourName'; + static const ageYears = 'ageYears'; + static const numberOfRemindersInADay = 'numberOfRemindersInADay'; + static const medications = 'medications'; + static const someRemarksAboutPrescription = 'someRemarksAboutPrescription'; + static const notifyMeBeforeConsumptionTime = 'notifyMeBeforeConsumptionTime'; + static const noMedicationsToday = 'noMedicationsToday'; + static const reminders = 'reminders'; + static const reminderAddedToCalendar = 'reminderAddedToCalendar'; + static const errorWhileSettingCalendar = 'errorWhileSettingCalendar'; + static const instructions = 'instructions'; + static const requests = 'requests'; + static const thisWeek = 'thisWeek'; + static const lastMonth = 'lastMonth'; + static const lastSixMonths = 'lastSixMonths'; + static const selectTime = 'selectTime'; + static const pleaseWaitYouWillBeCalledForVitalSigns = 'pleaseWaitYouWillBeCalledForVitalSigns'; + static const pleaseVisitRoomForVitalSigns = 'pleaseVisitRoomForVitalSigns'; + static const pleaseVisitRoomToTheDoctor = 'pleaseVisitRoomToTheDoctor'; + static const erOnlineCheckInRequest = 'erOnlineCheckInRequest'; + static const indoor = 'indoor'; + static const navigation = 'navigation'; + static const health = 'health'; + static const calculators = 'calculators'; + static const converters = 'converters'; + static const guide = 'guide'; + static const liveCareServiceDesc = 'liveCareServiceDesc'; + static const bloodGroup = 'bloodGroup'; + static const medicalServices = 'medicalServices'; + static const insuranceAndPayments = 'insuranceAndPayments'; + static const trackerAndOthers = 'trackerAndOthers'; + static const bmi = 'bmi'; + static const yesPleaseINeedHelp = 'yesPleaseINeedHelp'; + static const noThanksIKnowTheClinic = 'noThanksIKnowTheClinic'; + static const unableToSendOTP = 'unableToSendOTP'; } diff --git a/lib/main.dart b/lib/main.dart index c141951..28c0bc5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -3,13 +3,16 @@ import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart'; import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/active_prescriptions_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart'; import 'package:hmg_patient_app_new/features/doctor_filter/doctor_filter_view_model.dart'; @@ -27,15 +30,18 @@ import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_ import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_view_model.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_view_model.dart'; import 'package:hmg_patient_app_new/features/payfort/payfort_view_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart'; import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_view_model.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart'; import 'package:hmg_patient_app_new/features/smartwatch_health_data/health_provider.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; @@ -46,6 +52,7 @@ import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; import 'core/utils/size_utils.dart'; +import 'features/monthly_reports/terms_conditions_view_model.dart'; import 'firebase_options.dart'; @pragma('vm:entry-point') @@ -177,11 +184,29 @@ void main() async { ChangeNotifierProvider( create: (_) => getIt.get(), ), + ChangeNotifierProvider( + create: (_) => getIt.get(), + ), ChangeNotifierProvider( create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), + ), + ChangeNotifierProvider( + create: (_) => getIt.get(), ) ], child: MyApp()), - ), + ), // Wrap your app ); } @@ -201,7 +226,7 @@ class MyApp extends StatelessWidget { return MaterialApp( title: 'Dr. AlHabib', builder: (context, mchild) { - return MediaQuery(data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(1.0)), child: mchild!); + return MediaQuery(data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling), child: mchild!); }, showSemanticsDebugger: false, debugShowCheckedModeBanner: false, diff --git a/lib/presentation/active_medication/active_medication_page.dart b/lib/presentation/active_medication/active_medication_page.dart new file mode 100644 index 0000000..14da5b0 --- /dev/null +++ b/lib/presentation/active_medication/active_medication_page.dart @@ -0,0 +1,1030 @@ + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:flutter/cupertino.dart'; +import '../../core/app_assets.dart'; +import '../../core/utils/calendar_utils.dart'; +import '../../features/active_prescriptions/active_prescriptions_view_model.dart'; +import '../../features/active_prescriptions/models/active_prescriptions_response_model.dart'; +import '../../generated/locale_keys.g.dart'; +import '../../theme/colors.dart'; +import '../../widgets/appbar/app_bar_widget.dart'; +import 'package:intl/intl.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import '../../widgets/buttons/custom_button.dart'; +import '../../widgets/chip/app_custom_chip_widget.dart'; // for date formatting +import 'package:provider/provider.dart'; +import '../../widgets/loader/bottomsheet_loader.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + + +class ActiveMedicationPage extends StatefulWidget { + const ActiveMedicationPage({super.key}); + + @override + State createState() => _ActiveMedicationPageState(); +} + +class _ActiveMedicationPageState extends State { + late DateTime currentDate; + late DateTime selectedDate; + List selectedDayMeds = []; + ActivePrescriptionsViewModel? activePreVM; + + + Map medReminderStatus = {}; + + String _buildMedKey(ActivePrescriptionsResponseModel med) { + return "${med.itemId}_${med.startDate}_${med.days}_${med.frequency}"; + } + + int _getDosesCount(ActivePrescriptionsResponseModel med) { + return med.frequencyNumber ?? 1; + } + + @override + void initState() { + super.initState(); + currentDate = DateTime.now(); + selectedDate = currentDate; + + WidgetsBinding.instance.addPostFrameCallback((_) async { + activePreVM = + Provider.of(context, listen: false); + LoaderBottomSheet.showLoader(); + await activePreVM!.getActiveMedications( + onSuccess: (_) async { + LoaderBottomSheet.hideLoader(); + + final todayMeds = + activePreVM!.getMedsForSelectedDay(selectedDate); + setState(() => selectedDayMeds = todayMeds); + + WidgetsBinding.instance.addPostFrameCallback((_) async { + await loadSavedReminders(); + }); + }, + onError: (_) { + LoaderBottomSheet.hideLoader(); + }, + ); + + activePreVM!.addListener(() { + if (!mounted) return; + final medsForDay = + activePreVM!.getMedsForSelectedDay(selectedDate); + setState(() => selectedDayMeds = medsForDay); + }); + }); + } + + Future loadSavedReminders() async { + final prefs = await SharedPreferences.getInstance(); + + for (final med in activePreVM!.activePrescriptionsDetailsList) { + final medKey = _buildMedKey(med); + final doses = _getDosesCount(med); + + med.selectedDoseTimes = + List.filled(doses, null, growable: false); + + for (int i = 0; i < doses; i++) { + final saved = prefs.getString("doseTime_${medKey}_$i"); + if (saved != null) { + med.selectedDoseTimes[i] = saved; + } + } + + final reminderOn = + prefs.getBool("reminderStatus_$medKey") ?? false; + med.isReminderOn = reminderOn; + medReminderStatus[medKey] = reminderOn; + } + + setState(() {}); + } + + Future saveReminderStatus(String medKey, bool value) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool("reminderStatus_$medKey", value); + } + + Future saveDoseTime( + String medKey, int doseIndex, String time) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString("doseTime_${medKey}_$doseIndex", time); + } + + List getUpcomingDays() => + List.generate(7, (index) => currentDate.add(Duration(days: index))); + + @override + Widget build(BuildContext context) { + final days = getUpcomingDays(); + return Scaffold( + backgroundColor: AppColors.scaffoldBgColor, + appBar: CustomAppBar( + onBackPressed: () => Navigator.of(context).pop(), + onLanguageChanged: (_) {}, + hideLogoAndLang: true, + ), + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(LocaleKeys.activeMedications.tr(), + style: TextStyle( + color: AppColors.textColor, + fontSize: 27.f, + fontWeight: FontWeight.w600)), + SizedBox(height: 16.h), + SizedBox( + height: 65.h, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: days.length, + itemBuilder: (context, index) { + final day = days[index]; + final label = DateFormat('E').format(day); + return Padding( + padding: const EdgeInsets.only(right: 12), + child: buildDayCard(label, day), + ); + }, + ), + ), + SizedBox(height: 20.h), + RichText( + text: TextSpan( + children: [ + TextSpan( + text: "${selectedDate.day}", + style: TextStyle( + color: AppColors.textColor, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + WidgetSpan( + child: Transform.translate( + offset: const Offset(0, -4), + child: Text( + _getSuffix(selectedDate.day), + style: const TextStyle( + fontSize: 12, + color: AppColors.textColor, + fontWeight: FontWeight.w500, + ), + ), + ), + ), + TextSpan( + text: " ${DateFormat.MMMM().format(selectedDate)}", + style: const TextStyle( + color: AppColors.textColor, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + Text(LocaleKeys.medications.tr(), + style: TextStyle( + color: AppColors.primaryRedBorderColor, + fontSize: 12.f, + fontWeight: FontWeight.w500)), + SizedBox(height: 16.h), + Expanded( + child: SingleChildScrollView( + child: selectedDayMeds.isNotEmpty + ? ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: selectedDayMeds.length, + itemBuilder: (context, index) { + final med = selectedDayMeds[index]; + final doses = _getDosesCount(med); + if (med.selectedDoseTimes.length != doses) { + final old = med.selectedDoseTimes; + med.selectedDoseTimes = + List.filled(doses, null, + growable: false); + for (int i = 0; + i < old.length && i < doses; + i++) { + med.selectedDoseTimes[i] = old[i]; + } + } + + return Container( + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + margin: EdgeInsets.all(10), + child: Column( + children: [ + _buildMedHeader(med), + Row( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + // Utils.buildSvgWithAssets( + // icon: AppAssets., + // height: 18.h, + // width: 18.h, + // iconColor: + // AppColors.lightGreyTextColor, + // ), + Icon( + Icons.info_outline, + color: AppColors + .lightGreyTextColor, + size: 18, + ), + SizedBox(width: 6.h), + Expanded( + child: RichText( + text: TextSpan( + children: [ + TextSpan( + text: LocaleKeys.remarks.tr(), + style: TextStyle( + color: + AppColors.textColor, + fontWeight: + FontWeight.w600, + fontSize: 10, + ), + ), + TextSpan( + text: + LocaleKeys.someRemarksAboutPrescription.tr(), + style: TextStyle( + color: AppColors + .lightGreyTextColor, + fontWeight: + FontWeight.normal, + fontSize: 10, + ), + ), + ], + ), + ), + ), + ], + ).paddingOnly(left: 16, right: 16), + const Divider( + color: AppColors.greyColor), + GestureDetector( + onTap: () => showDoseDialog(med), + child: Row( + children: [ + Container( + width: 40.h, + height: 40.h, + alignment: Alignment.center, + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: + BorderRadius.circular(10), + ), + child: + Utils.buildSvgWithAssets( + icon: AppAssets.bell, + height: 24.h, + width: 24.h, + iconColor: + AppColors.greyTextColor, + ), + ), + SizedBox(width: 12.h), + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + LocaleKeys.setReminder.tr(), + style: TextStyle( + fontSize: 14.f, + fontWeight: + FontWeight.w600, + color: AppColors + .textColor)), + Text( + LocaleKeys.notifyMeBeforeConsumptionTime.tr(), + style: TextStyle( + fontSize: 12.f, + color: AppColors + .textColorLight, + )), + ], + ), + ), + _buildToggle(med), + ], + ).paddingAll(16), + ), + const Divider( + color: AppColors.greyColor), + _buildButtons(), + ], + ), + ); + }, + ) + : Utils.getNoDataWidget( + context, + noDataText: + LocaleKeys.noMedicationsToday.tr(), + ), + ), + ), + ], + ).paddingAll(16), + ); + } + + // medicine card + Widget _buildMedHeader(ActivePrescriptionsResponseModel med) => + Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Container( + width: 59.h, + height: 59.h, + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration( + color: AppColors.spacerLineColor, + borderRadius: 30.r, + hasShadow: false, + ), + child: Utils.buildImgWithNetwork( + url: med.productImageString ?? "", + iconColor: Colors.transparent) + .circle(52.h)), + ), + SizedBox(width: 12.h), + Expanded( + child: Text( + med.itemDescription ?? "", + style: TextStyle( + fontSize: 16.f, + fontWeight: FontWeight.w600, + color: AppColors.textColor), + ), + ), + ]), + SizedBox(height: 12.h), + Wrap( + spacing: 4, + runSpacing: 4, + children: [ + AppCustomChipWidget( + labelText: + LocaleKeys.route.tr(namedArgs: {'route': med.route ?? ''})), + AppCustomChipWidget( + labelText: + LocaleKeys.frequency.tr(namedArgs: {'frequency': med.frequency ?? ''})), + AppCustomChipWidget( + labelText: + LocaleKeys.instruction.tr(namedArgs: {'instruction': med.doseDailyQuantity?.toString() ?? ''})), + AppCustomChipWidget( + labelText: + LocaleKeys.duration.tr(namedArgs: {'days': med.days.toString() ?? ''})), + ], + ), + ], + ), + ); + + Widget _buildButtons() => Padding( + padding: EdgeInsets.all(16), + child: Row(children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.checkAvailability.tr(), + fontSize: 13.f, + onPressed: () {}, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.errorColor, + ), + ), + SizedBox(width: 12.h), + Expanded( + child: CustomButton( + text: LocaleKeys.readInstructions.tr(), + fontSize: 13.f, + onPressed: () {})), + ]), + ); + + Widget _buildToggle(ActivePrescriptionsResponseModel med) { + final medKey = _buildMedKey(med); + final value = medReminderStatus[medKey] ?? false; + + return GestureDetector( + onTap: () async { + await showDoseDialog(med); + final hasTime = + (med.selectedDoseTimes).any((t) => t != null); + medReminderStatus[medKey] = hasTime; + await saveReminderStatus(medKey, hasTime); + + setState(() {}); + }, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 50.h, + height: 28.h, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + color: value + ? AppColors.lightGreenColor + : AppColors.greyColor.withOpacity(0.3), + ), + child: AnimatedAlign( + duration: const Duration(milliseconds: 200), + alignment: + value ? Alignment.centerRight : Alignment.centerLeft, + child: Padding( + padding: const EdgeInsets.all(3), + child: Container( + width: 22.h, + height: 22.h, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: value + ? AppColors.textGreenColor + : AppColors.greyTextColor, + ), + ), + ), + ), + ), + ); + } + + + Future showDoseDialog(ActivePrescriptionsResponseModel med) { + final doses = _getDosesCount(med); + if (med.selectedDoseTimes.length != doses) { + final old = med.selectedDoseTimes; + med.selectedDoseTimes = + List.filled(doses, null, growable: false); + for (int i = 0; i < old.length && i < doses; i++) { + med.selectedDoseTimes[i] = old[i]; + } + } + + return showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => Container( + width: double.infinity, + height: 520.h, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.bottomSheetBgColor, + customBorder: const BorderRadius.only( + topLeft: Radius.circular(24), + topRight: Radius.circular(24), + ), + hasShadow: true, + ), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + LocaleKeys.reminders.tr(), + style: TextStyle( + fontSize: 20.f, + fontWeight: FontWeight.w600, + color: AppColors.textColor, + ), + ), + GestureDetector( + onTap: () => Navigator.pop(context), + child: Utils.buildSvgWithAssets( + icon: AppAssets.close_bottom_sheet_icon, + height: 24.h, + width: 24.h, + iconColor: + AppColors.blackBgColor, + ), + ), + ], + ), + SizedBox(height: 20.h), + Expanded( + child: ListView.builder( + itemCount: doses, + itemBuilder: (context, doseIndex) { + final badgeColor = [ + AppColors.textGreenColor, + AppColors.infoColor, + AppColors.labelColorYellow, + AppColors.mainPurple + ][doseIndex % 4]; + final doseLabel = + "${doseIndex + 1}${_getSuffix(doseIndex + 1)}"; + final time = + med.selectedDoseTimes[doseIndex] ?? + "Not set yet"; + return GestureDetector( + onTap: () { + Navigator.pop(context); + showTimePickerSheet(med, doseIndex); + }, + child: Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(16), + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 16.r, + hasShadow: false, + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 14), + decoration: BoxDecoration( + color: badgeColor, + borderRadius: BorderRadius.circular(12), + ), + child: RichText( + text: TextSpan( + children: [ + TextSpan( + text: "${doseIndex + 1}", + style: TextStyle( + color: AppColors.whiteColor, + fontWeight: FontWeight.bold, + fontSize: 16.f, + ), + ), + WidgetSpan( + child: Transform.translate( + offset: const Offset(0, -4), + child: Text( + _getSuffix(doseIndex + 1), + style: TextStyle( + color: AppColors.whiteColor, + fontSize: 10.f, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + ), + ), + SizedBox(height: 8.h), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + "Set reminder for $doseLabel dose", + style: TextStyle( + color: AppColors.textColor, + fontWeight: FontWeight.bold, + fontSize: 16.f, + ), + ), + ), + Utils.buildSvgWithAssets( + icon: AppAssets.arrow_forward, + height: 24.h, + width: 24.h, + iconColor: + AppColors.textColor, + ), + ], + ), + SizedBox(height: 4.h), + Text( + time, + style: TextStyle( + fontSize: 12.f, + color: AppColors.greyTextColor, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ), + ); + } + + + void showTimePickerSheet( + ActivePrescriptionsResponseModel med, int doseIndex) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => Container( + width: double.infinity, + height: 460.h, + decoration: const BoxDecoration( + color: AppColors.bottomSheetBgColor, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(24), + topRight: Radius.circular(24), + ), + ), + child: ReminderTimerDialog( + med: med, + frequencyNumber: _getDosesCount(med), + doseIndex: doseIndex, + onTimeSelected: (String time) async { + final medKey = _buildMedKey(med); + med.selectedDoseTimes[doseIndex] = time; + await saveDoseTime(medKey, doseIndex, time); + medReminderStatus[medKey] = true; + await saveReminderStatus(medKey, true); + setState(() {}); + }, + ), + ), + ); + } + + Widget buildDayCard(String label, DateTime date) { + final isSelected = selectedDate.day == date.day && + selectedDate.month == date.month && + selectedDate.year == date.year; + return GestureDetector( + onTap: () { + final vm = + Provider.of(context, + listen: false); + setState(() { + selectedDate = date; + selectedDayMeds = vm.getMedsForSelectedDay(date); + }); + }, + child: Container( + width: 57.h, + height: 65.h, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: isSelected + ? AppColors.secondaryLightRedBorderColor + : Colors.transparent, + border: Border.all( + color: isSelected + ? AppColors.primaryRedBorderColor + : AppColors.spacerLineColor, + width: 1, + ), + ), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + date.day == currentDate.day ? "Today" : label, + style: TextStyle( + color: isSelected + ? AppColors.primaryRedBorderColor + : AppColors.greyTextColor, + fontSize: 11.f, + fontWeight: FontWeight.w500), + ), + SizedBox(height: 5.h), + Text("${date.day}", + style: TextStyle( + fontSize: 16.f, + fontWeight: FontWeight.bold, + color: isSelected + ? AppColors.primaryRedBorderColor + : AppColors.textColor)) + ]), + ), + ), + ); + } + + String _getSuffix(int day) { + if (day == 1 || day == 21 || day == 31) return "st"; + if (day == 2 || day == 22) return "nd"; + if (day == 3 || day == 23) return "rd"; + return "th"; + } + +} + + +class ReminderTimerDialog extends StatefulWidget { + final int frequencyNumber; + final int doseIndex; + final Function(String) onTimeSelected; + final ActivePrescriptionsResponseModel med; + + const ReminderTimerDialog({ + super.key, + required this.frequencyNumber, + required this.doseIndex, + required this.onTimeSelected, + required this.med, + }); + + @override + State createState() => _ReminderTimerDialogState(); +} + +class _ReminderTimerDialogState extends State { + TimeOfDay selectedTime = TimeOfDay.now(); + String? _selectedTime; + String bigTimeText = "00:00"; + bool showPicker = false; + + final List> presetTimes = [ + ["06:00 AM", "07:00 AM", "08:00 AM", "09:00 AM"], // Morning + ["12:00 PM", "01:00 PM", "02:00 PM", "03:00 PM"], // Noon + ["06:00 PM", "07:00 PM", "08:00 PM", "09:00 PM"], // Evening + ]; + + String _getSuffix(int number) { + if (number == 1 || number == 21 || number == 31) return "st"; + if (number == 2 || number == 22) return "nd"; + if (number == 3 || number == 23) return "rd"; + return "th"; + } + + @override + Widget build(BuildContext context) { + final int bucket = widget.doseIndex.clamp(0, 2); + final List times = presetTimes[bucket]; + + return Padding( + padding: const EdgeInsets.all(16), + child: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.bottomSheetBgColor, + customBorder: const BorderRadius.only( + topLeft: Radius.circular(24), + topRight: Radius.circular(24), + ), + hasShadow: true, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: "Time for ", + style: TextStyle( + fontSize: 18.f, + fontWeight: FontWeight.bold, + color: AppColors.textColor, + ), + ), + TextSpan( + text: "${widget.doseIndex + 1}", + style: TextStyle( + fontSize: 18.f, + fontWeight: FontWeight.bold, + color: AppColors.textColor, + ), + ), + WidgetSpan( + child: Transform.translate( + offset: const Offset(0, -6), + child: Text( + _getSuffix(widget.doseIndex + 1), + style: TextStyle( + fontSize: 12.f, + fontWeight: FontWeight.bold, + color: AppColors.textColor, + ), + ), + ), + ), + TextSpan( + text: " reminder", + style: TextStyle( + fontSize: 18.f, + fontWeight: FontWeight.bold, + color: AppColors.textColor, + ), + ), + ], + ), + ), + GestureDetector( + onTap: () => Navigator.pop(context), + child:Utils.buildSvgWithAssets( + icon: AppAssets.close_bottom_sheet_icon, + height: 24.h, + width: 24.h, + iconColor: + AppColors.blackBgColor, + ),), + ], + ), + SizedBox(height: 12.h), + Wrap( + spacing: 8, + runSpacing: 8, + children: times.map((t) { + bool selected = _selectedTime == t; + return AppCustomChipWidget( + labelText: t, + backgroundColor: selected + ? AppColors.lightGreenButtonColor + : AppColors.transparent, + textColor: AppColors.textColor, + shape: RoundedRectangleBorder( + side: BorderSide( + color: selected + ? AppColors.successColor + : AppColors.spacerLineColor, + width: 1.2, + ), + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 14), + onChipTap: () { + setState(() { + _selectedTime = t; + selectedTime = _parseTime(t); + bigTimeText = selectedTime.format(context).split(" ")[0]; + showPicker = false; + }); + }, + ); + }).toList(), + ), + SizedBox(height: 25.h), + GestureDetector( + onTap: () { + setState(() => showPicker = !showPicker); + }, + child: Center( + child: Column( + children: [ + Text( + bigTimeText, + style: TextStyle( + fontSize: 48.f, + fontWeight: FontWeight.bold, + color: AppColors.textColor, + ), + ), + Text( + selectedTime.period == DayPeriod.am ? "AM" : "PM", + style: TextStyle( + fontSize: 20.f, + fontWeight: FontWeight.bold, + color: AppColors.greyTextColor, + ), + ), + ], + ), + ), + ), + SizedBox(height: 15.h), + if (showPicker) + SizedBox( + height: 100.h, + child: CupertinoDatePicker( + mode: CupertinoDatePickerMode.time, + use24hFormat: false, + initialDateTime: DateTime( + 2024, + 1, + 1, + selectedTime.hour, + selectedTime.minute, + ), + onDateTimeChanged: (newTime) { + setState(() { + _selectedTime = null; + selectedTime = TimeOfDay(hour: newTime.hour, minute: newTime.minute); + bigTimeText = selectedTime.format(context).split(" ")[0]; + }); + }, + ), + ), + SizedBox(height: 25.h), + Row( + children: [ + Expanded( + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.successColor, + foregroundColor: AppColors.whiteColor, + elevation: 0, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + onPressed: () async { + final selectedFormattedTime = selectedTime.format(context); + widget.onTimeSelected(selectedFormattedTime); + try { + final parts = selectedFormattedTime.split(":"); + int hour = int.parse(parts[0]); + int minute = int.parse(parts[1].split(" ")[0]); + bool isPM = selectedFormattedTime.contains("PM"); + if (isPM && hour != 12) hour += 12; + if (!isPM && hour == 12) hour = 0; + int totalMinutes = hour * 60 + minute; + await setCalender( + context, + eventId: widget.med.itemId.toString(), + selectedMinutes: totalMinutes, + frequencyNumber: widget.frequencyNumber, + days: widget.med.days ?? 1, + orderDate: widget.med.orderDate ?? "", + itemDescriptionN: widget.med.itemDescription ?? "", + route: widget.med.route ?? "", + ); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(LocaleKeys.reminderAddedToCalendar.tr())), + ); + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(LocaleKeys.errorWhileSettingCalendar.tr(namedArgs: {'error': e.toString()}))), + ); + } + Navigator.pop(context); + }, + child: Text( + LocaleKeys.save.tr(), + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16.f, + ), + ), + ), + ), + ], + ), + ], + ).paddingAll(16), + ), + ); + } + + TimeOfDay _parseTime(String t) { + try { + int hour = int.parse(t.split(":")[0]); + int minute = int.parse(t.split(":")[1].split(" ")[0]); + bool pm = t.contains("PM"); + if (pm && hour != 12) hour += 12; + if (!pm && hour == 12) hour = 0; + return TimeOfDay(hour: hour, minute: minute); + } catch (_) { + return TimeOfDay.now(); + } + } +} + + + + + + diff --git a/lib/presentation/allergies/allergies_list_page.dart b/lib/presentation/allergies/allergies_list_page.dart index efcdd0a..adb63f0 100644 --- a/lib/presentation/allergies/allergies_list_page.dart +++ b/lib/presentation/allergies/allergies_list_page.dart @@ -123,7 +123,7 @@ class AllergiesListPage extends StatelessWidget { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "No allergies data found...".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noAllergiesDataFound.tr()); }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), ), diff --git a/lib/presentation/appointments/appointment_details_page.dart b/lib/presentation/appointments/appointment_details_page.dart index 831a29b..849c38f 100644 --- a/lib/presentation/appointments/appointment_details_page.dart +++ b/lib/presentation/appointments/appointment_details_page.dart @@ -15,6 +15,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart'; import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart'; +import 'package:hmg_patient_app_new/features/contact_us/models/feedback_type.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; @@ -59,6 +60,8 @@ class _AppointmentDetailsPageState extends State { late LabViewModel labViewModel; late RadiologyViewModel radiologyViewModel; + String mapURL = ""; + @override void initState() { scheduleMicrotask(() async { @@ -87,9 +90,10 @@ class _AppointmentDetailsPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Appointment Details".needTranslation, + title: LocaleKeys.appointmentDetails.tr(context: context), report: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) ? () { + contactUsViewModel.setSelectedFeedbackType(FeedbackType(id: 1, nameEN: "Complaint for appointment", nameAR: 'شكوى على موعد')); contactUsViewModel.setPatientFeedbackSelectedAppointment(widget.patientAppointmentHistoryResponseModel); Navigator.of(context).push( CustomPageRoute( @@ -105,14 +109,13 @@ class _AppointmentDetailsPageState extends State { AppointmentDoctorCard( patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, onAskDoctorTap: () async { - LoaderBottomSheet.showLoader(loadingText: "Checking doctor availability...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context)); await myAppointmentsViewModel.isDoctorAvailable( projectID: widget.patientAppointmentHistoryResponseModel.projectID, doctorId: widget.patientAppointmentHistoryResponseModel.doctorID, clinicId: widget.patientAppointmentHistoryResponseModel.clinicID, onSuccess: (value) async { if (value) { - print("Doctor is available"); await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( @@ -129,14 +132,14 @@ class _AppointmentDetailsPageState extends State { ); }); } else { - print("Doctor is not available"); + debugPrint("Doctor is not available"); } }); }, onCancelTap: () async { myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true); - LoaderBottomSheet.showLoader(loadingText: "Cancelling Appointment, Please Wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.cancellingAppointmentPleaseWait.tr(context: context)); await myAppointmentsViewModel.cancelAppointment( patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, onSuccess: (apiResponse) { @@ -145,7 +148,7 @@ class _AppointmentDetailsPageState extends State { myAppointmentsViewModel.getPatientAppointments(true, false); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Appointment Cancelled Successfully".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentCancelledSuccessfully.tr(context: context)), callBackFunc: () { Navigator.of(context).pop(); }, @@ -182,13 +185,13 @@ class _AppointmentDetailsPageState extends State { children: [ Row( children: [ - "Appointment Status".needTranslation.toText16(isBold: true), + LocaleKeys.appointmentStatus.tr(context: context).toText16(isBold: true), ], ), SizedBox(height: 4.h), (!AppointmentType.isConfirmed(widget.patientAppointmentHistoryResponseModel) - ? "Not Confirmed".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500) - : "Confirmed".needTranslation.toText12(color: AppColors.successColor, fontWeight: FontWeight.w500)), + ? LocaleKeys.notConfirmed.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500) + : LocaleKeys.confirmed.tr(context: context).toText12(color: AppColors.successColor, fontWeight: FontWeight.w500)), SizedBox(height: 16.h), //TODO Add countdown timer in case of LiveCare Appointment widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false @@ -200,9 +203,7 @@ class _AppointmentDetailsPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "The doctor will call you once the appointment time approaches." - .needTranslation - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.doctorWillCallYou.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -215,7 +216,7 @@ class _AppointmentDetailsPageState extends State { borderRadius: BorderRadius.circular(24.r), // Todo: what is this???? Api Key??? 😲 child: Image.network( - "https://maps.googleapis.com/maps/api/staticmap?center=${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&zoom=14&size=350x165&maptype=roadmap&markers=color:red%7C${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&key=${ApiKeyConstants.googleMapsApiKey}", + "https://maps.googleapis.com/maps/api/staticmap?center=${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&zoom=14&size=${(MediaQuery.of(context).size.width * 1.5).toInt()}x${(MediaQuery.of(context).size.height * 0.35).toInt()}&maptype=roadmap&markers=color:red%7C${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&key=${ApiKeyConstants.googleMapsApiKey}", fit: BoxFit.contain, ), ), @@ -224,11 +225,11 @@ class _AppointmentDetailsPageState extends State { child: SizedBox( width: MediaQuery.of(context).size.width * 0.785, child: CustomButton( - text: "Get Directions".needTranslation, onPressed: () { MapsLauncher.launchCoordinates(double.parse(widget.patientAppointmentHistoryResponseModel.latitude!), double.parse(widget.patientAppointmentHistoryResponseModel.longitude!), widget.patientAppointmentHistoryResponseModel.projectName); }, + text: LocaleKeys.getDirections.tr(context: context), backgroundColor: AppColors.textColor.withValues(alpha: 0.8), borderColor: AppointmentType.getNextActionButtonColor(widget.patientAppointmentHistoryResponseModel.nextAction).withValues(alpha: 0.01), textColor: AppColors.whiteColor, @@ -283,9 +284,7 @@ class _AppointmentDetailsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.setReminder.tr(context: context).toText13(isBold: true), - "Notify me before the appointment" - .needTranslation - .toText11(color: AppColors.textColorLight, weight: FontWeight.w500), + LocaleKeys.notifyMeBeforeAppointment.tr(context: context).toText11(color: AppColors.textColorLight, weight: FontWeight.w500), ], ), const Spacer(), @@ -307,8 +306,9 @@ class _AppointmentDetailsPageState extends State { "${widget.patientAppointmentHistoryResponseModel.appointmentNo}"??"", "", "", - title: "Appointment with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj}".needTranslation, - description:"${widget.patientAppointmentHistoryResponseModel.doctorNameObj} will be having an appointment on ${widget.patientAppointmentHistoryResponseModel.appointmentDate}".needTranslation, + title: "Appointment with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj}", + description: + "${widget.patientAppointmentHistoryResponseModel.doctorNameObj} will be having an appointment on ${widget.patientAppointmentHistoryResponseModel.appointmentDate}", onSuccess: () { setState(() { myAppointmentsViewModel.setAppointmentReminder(newValue, widget.patientAppointmentHistoryResponseModel); @@ -318,10 +318,10 @@ class _AppointmentDetailsPageState extends State { onMultiDateSuccess: (int selectedIndex) async { isEventAddedOrRemoved = await calender.createOrUpdateEvent( - title: "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} on ${DateUtil.convertStringToDate(widget - .patientAppointmentHistoryResponseModel.appointmentDate)}, Appointment #${widget.patientAppointmentHistoryResponseModel.appointmentNo}".needTranslation, - description: "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} in ${widget - .patientAppointmentHistoryResponseModel.projectName}", + title: + "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} on ${DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate)}, Appointment #${widget.patientAppointmentHistoryResponseModel.appointmentNo}", + description: + "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} in ${widget.patientAppointmentHistoryResponseModel.projectName}", scheduleDateTime: DateUtil.convertStringToDate(widget .patientAppointmentHistoryResponseModel.appointmentDate), eventId: "${widget.patientAppointmentHistoryResponseModel.appointmentNo}", @@ -367,7 +367,7 @@ class _AppointmentDetailsPageState extends State { isLargeText: true, iconSize: 36.w, ).onPress(() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Lab Results...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingLabResults.tr(context: context)); await labViewModel.getLabResultsByAppointmentNo( appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo, projectID: widget.patientAppointmentHistoryResponseModel.projectID, @@ -400,7 +400,7 @@ class _AppointmentDetailsPageState extends State { isLargeText: true, iconSize: 36.w, ).onPress(() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Radiology Results...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingRadiologyResults.tr(context: context)); await radiologyViewModel.getPatientRadiologyOrdersByAppointment( appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo, projectID: widget.patientAppointmentHistoryResponseModel.projectID, @@ -427,7 +427,7 @@ class _AppointmentDetailsPageState extends State { isLargeText: true, iconSize: 36.w, ).onPress(() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Appointment Prescriptions...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingAppointmentPrescriptions.tr(context: context)); await prescriptionsViewModel.getPrescriptionDetails( getPrescriptionRequestModel(), onSuccess: (val) { @@ -455,8 +455,7 @@ class _AppointmentDetailsPageState extends State { } else { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget( - loadingText: "You don't have any prescriptions for this appointment.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.noPrescriptionsForAppointment.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -525,7 +524,7 @@ class _AppointmentDetailsPageState extends State { // ], // ), // SizedBox(height: 16.h), - // LocaleKeys.prescriptions.tr().toText18(isBold: true), + // LocaleKeys.prescriptions.tr(context: context).toText18(isBold: true), // SizedBox(height: 16.h), // Consumer(builder: (context, prescriptionVM, child) { // return prescriptionVM.isPrescriptionsDetailsLoading @@ -711,7 +710,7 @@ class _AppointmentDetailsPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText18(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText18(isBold: true), Utils.getPaymentAmountWithSymbol( widget.patientAppointmentHistoryResponseModel.patientShare!.toString().toText16(isBold: true), AppColors.blackColor, @@ -728,7 +727,6 @@ class _AppointmentDetailsPageState extends State { .tr(context: context) .toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor)), "VAT 15%(${widget.patientAppointmentHistoryResponseModel.patientTaxAmount})" - .needTranslation .toText14(isBold: true, color: AppColors.greyTextColor, letterSpacing: -2), ], ), @@ -755,9 +753,10 @@ class _AppointmentDetailsPageState extends State { ], ).paddingOnly(left: 16.h, top: 24.h, right: 16.h, bottom: 0.h), AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) - ? CustomButton( - text: "Re-book Appointment".needTranslation, - onPressed: () { + ? !widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment! + ? CustomButton( + text: LocaleKeys.rebookAppointment.tr(context: context), + onPressed: () { openDoctorScheduleCalendar(); }, backgroundColor: AppColors.successColor, @@ -771,7 +770,8 @@ class _AppointmentDetailsPageState extends State { icon: AppAssets.add_icon, iconColor: AppColors.whiteColor, iconSize: 18.h, - ).paddingSymmetrical(16.h, 24.h) + ).paddingSymmetrical(16.h, 24.h) + : SizedBox.shrink() : CustomButton( text: AppointmentType.getNextActionText(widget.patientAppointmentHistoryResponseModel.nextAction), onPressed: () { @@ -814,13 +814,13 @@ class _AppointmentDetailsPageState extends State { projectName: widget.patientAppointmentHistoryResponseModel.projectName, ); bookAppointmentsViewModel.setSelectedDoctor(doctor); - LoaderBottomSheet.showLoader(loadingText: "Fetching Doctor Schedule, Please Wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingDoctorSchedulePleaseWait.tr(context: context)); await bookAppointmentsViewModel.getDoctorFreeSlots( isBookingForLiveCare: false, onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(context: context), context, child: AppointmentCalendar(), isFullScreen: false, @@ -845,15 +845,14 @@ class _AppointmentDetailsPageState extends State { case 0: break; case 10: - LoaderBottomSheet.showLoader(loadingText: "Confirming Appointment, Please Wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.confirmingAppointmentPleaseWait.tr(context: context)); await myAppointmentsViewModel.confirmAppointment( patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, onSuccess: (apiResponse) { LoaderBottomSheet.hideLoader(); myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true); myAppointmentsViewModel.getPatientAppointments(true, false); - showCommonBottomSheet(context, child: Utils.getSuccessWidget(loadingText: "Appointment Confirmed Successfully".needTranslation), - callBackFunc: (str) { + showCommonBottomSheet(context, child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentConfirmedSuccessfully.tr(context: context)), callBackFunc: (str) { Navigator.of(context).pop(); }, title: "", @@ -874,10 +873,10 @@ class _AppointmentDetailsPageState extends State { ), ); case 50: - // return LocaleKeys.confirmLiveCare.tr(); + // return LocaleKeys.confirmLiveCare.tr(context: context); case 90: showCommonBottomSheetWithoutHeight(context, - title: LocaleKeys.onlineCheckIn.tr(), + title: LocaleKeys.onlineCheckIn.tr(context: context), child: AppointmentCheckinBottomSheet( patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, myAppointmentsViewModel: myAppointmentsViewModel, diff --git a/lib/presentation/appointments/appointment_payment_page.dart b/lib/presentation/appointments/appointment_payment_page.dart index 475ee70..dc9213f 100644 --- a/lib/presentation/appointments/appointment_payment_page.dart +++ b/lib/presentation/appointments/appointment_payment_page.dart @@ -90,7 +90,7 @@ class _AppointmentPaymentPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Appointment Payment".needTranslation, + title: LocaleKeys.appointmentPayment.tr(context: context), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -111,7 +111,7 @@ class _AppointmentPaymentPageState extends State { Image.asset(AppAssets.mada, width: 72.h, height: 25.h) .toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), SizedBox(height: 16.h), - "Mada".needTranslation.toText16(isBold: true).toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), + "Mada".toText16(isBold: true).toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), ], ), SizedBox(width: 8.h), @@ -154,7 +154,6 @@ class _AppointmentPaymentPageState extends State { ).toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), SizedBox(height: 16.h), "Visa or Mastercard" - .needTranslation .toText16(isBold: true) .toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), ], @@ -195,7 +194,6 @@ class _AppointmentPaymentPageState extends State { .toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), SizedBox(height: 16.h), "Tamara" - .needTranslation .toText16(isBold: true) .toShimmer2(isShow: myAppointmentsVM.isAppointmentPatientShareLoading), ], @@ -250,8 +248,7 @@ class _AppointmentPaymentPageState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Insurance expired or inactive" - .needTranslation + LocaleKeys.insuranceExpiredOrInactive.tr(context: context) .toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500) .paddingSymmetrical(24.h, 0.h), CustomButton( @@ -277,12 +274,12 @@ class _AppointmentPaymentPageState extends State { ) : const SizedBox(), SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol( myAppointmentsVM.patientAppointmentShareResponseModel!.patientShare!.toString().toText16(isBold: true), AppColors.blackColor, @@ -293,7 +290,7 @@ class _AppointmentPaymentPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + "VAT 15%".toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( myAppointmentsVM.patientAppointmentShareResponseModel!.patientTaxAmount! .toString() @@ -307,7 +304,7 @@ class _AppointmentPaymentPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "".needTranslation.toText14(isBold: true), + "".toText14(isBold: true), Utils.getPaymentAmountWithSymbol( myAppointmentsVM.patientAppointmentShareResponseModel!.patientShareWithTax!.toString().toText24(isBold: true), AppColors.blackColor, @@ -383,7 +380,7 @@ class _AppointmentPaymentPageState extends State { } void checkPaymentStatus() async { - LoaderBottomSheet.showLoader(loadingText: "Checking payment status, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context)); if (selectedPaymentMethod == "TAMARA") { await payfortViewModel.checkTamaraPaymentStatus( transactionID: transID, @@ -441,7 +438,7 @@ class _AppointmentPaymentPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -462,7 +459,6 @@ class _AppointmentPaymentPageState extends State { await payfortViewModel.checkPaymentStatus( transactionID: transID, onSuccess: (apiResponse) async { - print(apiResponse.data); if (payfortViewModel.payfortCheckPaymentStatusResponseModel!.responseMessage!.toLowerCase() == "success") { await myAppointmentsViewModel.createAdvancePayment( paymentMethodName: selectedPaymentMethod, @@ -520,9 +516,10 @@ class _AppointmentPaymentPageState extends State { }); }); } else { + LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -567,14 +564,7 @@ class _AppointmentPaymentPageState extends State { } startApplePay() async { - showCommonBottomSheet(context, - child: Utils.getLoadingWidget(), - callBackFunc: (str) {}, - title: "", - height: ResponsiveExtension.screenHeight * 0.3, - isCloseButtonVisible: false, - isDismissible: false, - isFullScreen: false); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context)); transID = Utils.getAppointmentTransID( widget.patientAppointmentHistoryResponseModel.projectID, widget.patientAppointmentHistoryResponseModel.clinicID, @@ -645,7 +635,7 @@ class _AppointmentPaymentPageState extends State { currency: appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED", onFailed: (failureResult) async { log("failureResult: ${failureResult.message.toString()}"); - Navigator.of(context).pop(); + LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, child: Utils.getErrorWidget(loadingText: failureResult.message.toString()), @@ -655,6 +645,7 @@ class _AppointmentPaymentPageState extends State { ); }, onSucceeded: (successResult) async { + LoaderBottomSheet.hideLoader(); log("successResult: ${successResult.responseMessage.toString()}"); selectedPaymentMethod = successResult.paymentOption ?? "VISA"; checkPaymentStatus(); diff --git a/lib/presentation/appointments/appointment_queue_page.dart b/lib/presentation/appointments/appointment_queue_page.dart index 124bf25..f205aeb 100644 --- a/lib/presentation/appointments/appointment_queue_page.dart +++ b/lib/presentation/appointments/appointment_queue_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -7,6 +8,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -30,7 +32,7 @@ class AppointmentQueuePage extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Queueing".needTranslation, + title: LocaleKeys.queueing.tr(context: context), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.all(24.0), @@ -57,7 +59,7 @@ class AppointmentQueuePage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget( - labelText: myAppointmentsVM.currentQueueStatus == 0 ? "In Queue".needTranslation : "Your Turn".needTranslation, + labelText: myAppointmentsVM.currentQueueStatus == 0 ? LocaleKeys.inQueue.tr(context: context) : LocaleKeys.yourTurn.tr(context: context), backgroundColor: Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus).withValues(alpha: 0.20), textColor: Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus), ), @@ -66,12 +68,10 @@ class AppointmentQueuePage extends StatelessWidget { ).toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 10.h), "Hala ${appState!.getAuthenticatedUser()!.firstName}!!!" - .needTranslation .toText16(isBold: true) .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 8.h), - "Thank you for your patience, here is your queue number." - .needTranslation + LocaleKeys.thankYouForPatience.tr(context: context) .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight) .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 8.h), @@ -111,8 +111,7 @@ class AppointmentQueuePage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Serving Now" - .needTranslation + LocaleKeys.servingNow.tr(context: context) .toText16(isBold: true) .toShimmer2(isShow: myAppointmentsVM.isAppointmentQueueDetailsLoading), SizedBox(height: 18.h), @@ -138,8 +137,8 @@ class AppointmentQueuePage extends StatelessWidget { ? AppAssets.call_for_vitals : AppAssets.call_for_doctor, labelText: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 - ? "Call for vital signs".needTranslation - : "Call for Doctor".needTranslation, + ? LocaleKeys.callForVitalSigns.tr(context: context) + : LocaleKeys.callForDoctor.tr(context: context), iconColor: myAppointmentsVM.patientQueueDetailsList[index].callType == 1 ? AppColors.primaryRedColor : AppColors.successColor, @@ -180,35 +179,23 @@ class AppointmentQueuePage extends StatelessWidget { children: [ Utils.buildSvgWithAssets(icon: AppAssets.bulb_icon, width: 24.w, height: 24.h), SizedBox(width: 8.w), - "Things to ask your doctor today".needTranslation.toText16(isBold: true), + LocaleKeys.thingsToAskDoctor.tr(context: context).toText16(isBold: true), ], ), SizedBox(height: 8.h), - - // What can I do to improve my overall health? - // Are there any routine screenings I should get? - // What is this medication for? - // Are there any side effects I should know about? - // When should I come back for a follow-up? - - "• ${"What can I do to improve my overall health?"}" - .needTranslation + "• ${LocaleKeys.improveOverallHealth.tr(context: context)}" .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"Are there any routine screenings I should get?"}" - .needTranslation + "• ${LocaleKeys.routineScreenings.tr(context: context)}" .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"What is this medication for?"}" - .needTranslation + "• ${LocaleKeys.whatIsThisMedicationFor.tr(context: context)}" .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"Are there any side effects I should know about?"}" - .needTranslation + "• ${LocaleKeys.sideEffectsToKnow.tr(context: context)}" .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 4.h), - "• ${"When should I come back for a follow-up?"}" - .needTranslation + "• ${LocaleKeys.whenFollowUp.tr(context: context)}" .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), SizedBox(height: 16.h), @@ -229,7 +216,7 @@ class AppointmentQueuePage extends StatelessWidget { hasShadow: true, ), child: CustomButton( - text: "Go to homepage".needTranslation, + text: LocaleKeys.goToHomepage.tr(context: context), onPressed: () { Navigator.pushAndRemoveUntil( context, @@ -249,11 +236,10 @@ class AppointmentQueuePage extends StatelessWidget { icon: AppAssets.homeBottom, iconColor: AppColors.whiteColor, iconSize: 18.h, - ).paddingSymmetrical(16.h, 24.h), - ) + ).paddingSymmetrical(24.h, 24.h), + ), ], ); - }), - ); + })); } } diff --git a/lib/presentation/appointments/my_appointments_page.dart b/lib/presentation/appointments/my_appointments_page.dart index b4c3630..c9e7048 100644 --- a/lib/presentation/appointments/my_appointments_page.dart +++ b/lib/presentation/appointments/my_appointments_page.dart @@ -56,7 +56,7 @@ class _MyAppointmentsPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Appointments List".needTranslation, + title: LocaleKeys.appointmentsList.tr(context: context), child: SingleChildScrollView( child: Column( children: [ @@ -65,9 +65,9 @@ class _MyAppointmentsPageState extends State { activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ - CustomTabBarModel(null, "All Appt.".needTranslation), - CustomTabBarModel(null, "Upcoming".needTranslation), - CustomTabBarModel(null, "Completed".needTranslation), + CustomTabBarModel(null, LocaleKeys.allAppt.tr(context: context)), + CustomTabBarModel(null, LocaleKeys.upcoming.tr(context: context)), + CustomTabBarModel(null, LocaleKeys.completed.tr(context: context)), ], onTabChange: (index) { setState(() { @@ -155,7 +155,7 @@ class _MyAppointmentsPageState extends State { isLoading: true, isFromHomePage: false, ), - ).paddingSymmetrical(24.h, 0.h) + ) : filteredAppointmentList.isNotEmpty ? AnimationConfiguration.staggeredList( position: index, @@ -248,7 +248,7 @@ class _MyAppointmentsPageState extends State { ) : Utils.getNoDataWidget( context, - noDataText: "You don't have any appointments yet.".needTranslation, + noDataText: LocaleKeys.noAppointmentsYet.tr(context: context), callToActionButton: CustomButton( text: LocaleKeys.bookAppo.tr(context: context), onPressed: () { @@ -296,7 +296,7 @@ class _MyAppointmentsPageState extends State { onClicked: () { if (myAppointmentsVM.availableFilters[index] == AppointmentListingFilters.DATESELECTION) { showCommonBottomSheetWithoutHeight( - title: "Set The Date Range".needTranslation, + title: LocaleKeys.setTheDateRange.tr(context: context), context, child: DateRangeSelector( onRangeSelected: (start, end) { diff --git a/lib/presentation/appointments/my_doctors_page.dart b/lib/presentation/appointments/my_doctors_page.dart index 2c5d1b0..3795ce1 100644 --- a/lib/presentation/appointments/my_doctors_page.dart +++ b/lib/presentation/appointments/my_doctors_page.dart @@ -211,7 +211,7 @@ class _MyDoctorsPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - AppCustomChipWidget(labelText: "${group.length} ${'doctors'.needTranslation}"), + AppCustomChipWidget(labelText: "${group.length} ${'doctors'}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), @@ -284,7 +284,7 @@ class _MyDoctorsPageState extends State { icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, - text: "View Profile".needTranslation.tr(context: context), + text: LocaleKeys.viewProfile.tr(context: context), onPressed: () async { bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel( clinicID: doctor?.clinicID ?? 0, diff --git a/lib/presentation/appointments/widgets/appointment_card.dart b/lib/presentation/appointments/widgets/appointment_card.dart index 39e4e03..a8735d0 100644 --- a/lib/presentation/appointments/widgets/appointment_card.dart +++ b/lib/presentation/appointments/widgets/appointment_card.dart @@ -96,13 +96,13 @@ class AppointmentCard extends StatelessWidget { AppCustomChipWidget( icon: isLoading ? AppAssets.walkin_appointment_icon : (isLiveCare ? AppAssets.small_livecare_icon : AppAssets.walkin_appointment_icon), iconColor: isLoading ? AppColors.textColor : (isLiveCare ? AppColors.whiteColor : AppColors.textColor), - labelText: isLoading ? 'Walk In'.needTranslation : (isLiveCare ? LocaleKeys.livecare.tr(context: context) : 'Walk In'.needTranslation), + labelText: isLoading ? LocaleKeys.walkin.tr(context: context) : (isLiveCare ? LocaleKeys.livecare.tr(context: context) : LocaleKeys.walkin.tr(context: context)), backgroundColor: isLoading ? AppColors.greyColor : (isLiveCare ? AppColors.successColor : AppColors.greyColor), textColor: isLoading ? AppColors.textColor : (isLiveCare ? AppColors.whiteColor : AppColors.textColor), ).toShimmer2(isShow: isLoading), AppCustomChipWidget( labelText: isLoading - ? 'OutPatient'.needTranslation + ? 'OutPatient' : (appState.isArabic() ? patientAppointmentHistoryResponseModel.isInOutPatientDescriptionN! : patientAppointmentHistoryResponseModel.isInOutPatientDescription!), @@ -111,7 +111,7 @@ class AppointmentCard extends StatelessWidget { ).toShimmer2(isShow: isLoading), AppCustomChipWidget( labelText: isLoading - ? 'Booked'.needTranslation + ? 'Booked' : AppointmentType.getAppointmentStatusType(patientAppointmentHistoryResponseModel.patientStatusType!), backgroundColor: AppColors.successColor.withValues(alpha: 0.1), textColor: AppColors.successColor, @@ -151,7 +151,9 @@ class AppointmentCard extends StatelessWidget { children: [ Utils.buildSvgWithAssets(icon: AppAssets.rating_icon, width: 15.w, height: 15.h), SizedBox(height: 2.h), - "${patientAppointmentHistoryResponseModel.decimalDoctorRate}".toText11(isBold: true, color: AppColors.textColor), + (isFoldable || isTablet) + ? "${patientAppointmentHistoryResponseModel.decimalDoctorRate}".toText9(isBold: true, color: AppColors.textColor) + : "${patientAppointmentHistoryResponseModel.decimalDoctorRate ?? "0.0"}".toText11(isBold: true, color: AppColors.textColor), ], ), ).circle(100).toShimmer2(isShow: isLoading), @@ -175,15 +177,15 @@ class AppointmentCard extends StatelessWidget { AppCustomChipWidget( labelText: isLoading ? 'Cardiology' - : (patientAppointmentHistoryResponseModel.clinicName!.length > 15 - ? '${patientAppointmentHistoryResponseModel.clinicName!.substring(0, 12)}...' + : (patientAppointmentHistoryResponseModel.clinicName!.length > 20 + ? '${patientAppointmentHistoryResponseModel.clinicName!.substring(0, 20)}...' : patientAppointmentHistoryResponseModel.clinicName!), ).toShimmer2(isShow: isLoading), AppCustomChipWidget( labelText: isLoading ? 'Olaya' : patientAppointmentHistoryResponseModel.projectName!.length > 15 - ? '${patientAppointmentHistoryResponseModel.projectName!.substring(0, 12)}...' + ? '${patientAppointmentHistoryResponseModel.projectName!.substring(0, 15)}...' : patientAppointmentHistoryResponseModel.projectName!) .toShimmer2(isShow: isLoading), AppCustomChipWidget( @@ -224,83 +226,120 @@ class AppointmentCard extends StatelessWidget { } Widget _buildActionArea(BuildContext context, AppState appState) { - if (isFromMedicalReport) { - if (isForEyeMeasurements) { - return SizedBox.shrink(); - } else { - return CustomButton( - text: 'Select appointment'.needTranslation, - onPressed: () { + if ((patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false) && AppointmentType.isArrived(patientAppointmentHistoryResponseModel)) { + return CustomButton( + text: isFromMedicalReport ? LocaleKeys.selectAppointment.tr(context: context) : LocaleKeys.viewDetails.tr(context: context), + onPressed: () { + if (isFromMedicalReport) { if (isForFeedback) { contactUsViewModel!.setPatientFeedbackSelectedAppointment(patientAppointmentHistoryResponseModel); } else { medicalFileViewModel!.setSelectedMedicalReportAppointment(patientAppointmentHistoryResponseModel); } Navigator.pop(context, false); - }, - backgroundColor: AppColors.secondaryLightRedColor, - borderColor: AppColors.secondaryLightRedColor, - textColor: AppColors.primaryRedColor, - fontSize: 14.f, - fontWeight: FontWeight.w500, - borderRadius: 12.r, - padding: EdgeInsets.symmetric(horizontal: 10.w), - // height: isTablet || isFoldable ? 46.h : 40.h, - height: 40.h, - icon: AppAssets.checkmark_icon, - iconColor: AppColors.primaryRedColor, - iconSize: 16.h, - ); + } else { + Navigator.of(context) + .push( + CustomPageRoute( + page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel), + ), + ) + .then((_) { + myAppointmentsViewModel.initAppointmentsViewModel(); + myAppointmentsViewModel.getPatientAppointments(true, false); + }); + } + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(horizontal: 10.w), + // height: isTablet || isFoldable ? 46.h : 40.h, + height: 40.h, + icon: isFromMedicalReport ? AppAssets.checkmark_icon : null, + iconColor: AppColors.primaryRedColor, + iconSize: 16.h, + ); + } else { + if (isFromMedicalReport) { + if (isForEyeMeasurements) { + return SizedBox.shrink(); + } else { + return CustomButton( + text: LocaleKeys.selectAppointment.tr(context: context), + onPressed: () { + if (isForFeedback) { + contactUsViewModel!.setPatientFeedbackSelectedAppointment(patientAppointmentHistoryResponseModel); + } else { + medicalFileViewModel!.setSelectedMedicalReportAppointment(patientAppointmentHistoryResponseModel); + } + Navigator.pop(context, false); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(horizontal: 10.w), + // height: isTablet || isFoldable ? 46.h : 40.h, + height: 40.h, + icon: AppAssets.checkmark_icon, + iconColor: AppColors.primaryRedColor, + iconSize: 16.h, + ); + } } - } - return Row( - children: [ - Expanded( - flex: 6, - child: (AppointmentType.isArrived(patientAppointmentHistoryResponseModel) - ? _getArrivedButton(context) - : CustomButton( - text: AppointmentType.getNextActionText(patientAppointmentHistoryResponseModel.nextAction), - onPressed: () => _goToDetails(context), - backgroundColor: - AppointmentType.getNextActionButtonColor(patientAppointmentHistoryResponseModel.nextAction).withValues(alpha: 0.15), - borderColor: - AppointmentType.getNextActionButtonColor(patientAppointmentHistoryResponseModel.nextAction).withValues(alpha: 0.01), - textColor: AppointmentType.getNextActionTextColor(patientAppointmentHistoryResponseModel.nextAction), - fontSize: 14.f, - fontWeight: FontWeight.w500, - borderRadius: 12.r, - padding: EdgeInsets.symmetric(horizontal: 10.w), - height: 40.h, - icon: AppointmentType.getNextActionIcon(patientAppointmentHistoryResponseModel.nextAction), - iconColor: AppointmentType.getNextActionTextColor(patientAppointmentHistoryResponseModel.nextAction), - iconSize: 15.h, - )) - .toShimmer2(isShow: isLoading), - ), - SizedBox(width: 8.h), - Expanded( - flex: 1, - child: Container( - height: (isFoldable || isTablet) ? 50.h : 40.h, - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.textColor, borderRadius: 10.h), - child: Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, - iconColor: AppColors.whiteColor, - width: 24.w, - height: 24.h, - fit: BoxFit.contain, + return Row( + children: [ + Expanded( + flex: 6, + child: (AppointmentType.isArrived(patientAppointmentHistoryResponseModel) + ? _getArrivedButton(context) + : CustomButton( + text: AppointmentType.getNextActionText(patientAppointmentHistoryResponseModel.nextAction), + onPressed: () => _goToDetails(context), + backgroundColor: AppointmentType.getNextActionButtonColor(patientAppointmentHistoryResponseModel.nextAction).withValues(alpha: 0.15), + borderColor: AppointmentType.getNextActionButtonColor(patientAppointmentHistoryResponseModel.nextAction).withValues(alpha: 0.01), + textColor: AppointmentType.getNextActionTextColor(patientAppointmentHistoryResponseModel.nextAction), + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(horizontal: 10.w), + height: 40.h, + icon: AppointmentType.getNextActionIcon(patientAppointmentHistoryResponseModel.nextAction), + iconColor: AppointmentType.getNextActionTextColor(patientAppointmentHistoryResponseModel.nextAction), + iconSize: 15.h, + )) + .toShimmer2(isShow: isLoading), + ), + SizedBox(width: 8.h), + Expanded( + flex: 1, + child: Container( + height: (isFoldable || isTablet) ? 50.h : 40.h, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.textColor, borderRadius: 10.h), + child: Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon, + iconColor: AppColors.whiteColor, + width: 24.w, + height: 24.h, + fit: BoxFit.contain, + ), ), - ), - ).toShimmer2(isShow: isLoading).onPress(() { - _goToDetails(context); - }), - ), - ], - ); + ).toShimmer2(isShow: isLoading).onPress(() { + _goToDetails(context); + }), + ), + ], + ); + } } Widget _getArrivedButton(BuildContext context) { @@ -310,7 +349,7 @@ class AppointmentCard extends StatelessWidget { return CustomButton( text: LocaleKeys.askDoctor.tr(context: context), onPressed: () async { - LoaderBottomSheet.showLoader(loadingText: "Checking doctor availability...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context)); await myAppointmentsViewModel.isDoctorAvailable( projectID: patientAppointmentHistoryResponseModel.projectID, doctorId: patientAppointmentHistoryResponseModel.doctorID, @@ -340,7 +379,7 @@ class AppointmentCard extends StatelessWidget { backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, - fontSize: 14.f, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, fontWeight: FontWeight.w500, borderRadius: 12.r, padding: EdgeInsets.symmetric(horizontal: 10.w), @@ -353,12 +392,12 @@ class AppointmentCard extends StatelessWidget { } return CustomButton( - text: 'Rebook with same doctor'.needTranslation, + text: LocaleKeys.rebookSameDoctor.tr(context: context), onPressed: () => openDoctorScheduleCalendar(context), backgroundColor: AppColors.greyColor, borderColor: AppColors.greyColor, textColor: AppColors.blackColor, - fontSize: 14.f, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, fontWeight: FontWeight.w500, borderRadius: 12.r, padding: EdgeInsets.symmetric(horizontal: 10.w), @@ -417,7 +456,7 @@ class AppointmentCard extends StatelessWidget { context, child: AppointmentCalendar(), callBackFunc: () {}, - title: 'Pick a Date'.needTranslation, + title: LocaleKeys.pickADate.tr(context: context), isFullScreen: false, isCloseButtonVisible: true, ); diff --git a/lib/presentation/appointments/widgets/appointment_checkin_bottom_sheet.dart b/lib/presentation/appointments/widgets/appointment_checkin_bottom_sheet.dart index 2b1712b..2afd5e6 100644 --- a/lib/presentation/appointments/widgets/appointment_checkin_bottom_sheet.dart +++ b/lib/presentation/appointments/widgets/appointment_checkin_bottom_sheet.dart @@ -36,6 +36,7 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { @override Widget build(BuildContext context) { + locationUtils = getIt.get(); appState = getIt.get(); FlutterNfcKit.nfcAvailability.then((value) { _supportsNFC = (value == NFCAvailability.available); @@ -45,8 +46,8 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { children: [ checkInOptionCard( AppAssets.checkin_location_icon, - "Live Location".needTranslation, - "Verify your location to be at hospital to check in".needTranslation, + LocaleKeys.liveLocation.tr(context: context), + LocaleKeys.verifyYourLocationAtHospital.tr(context: context), ).onPress(() { // locationUtils = LocationUtils( // isShowConfirmDialog: false, @@ -61,8 +62,10 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { sendCheckInRequest(projectDetailListModel.checkInQrCode!, 3, context); } else { showCommonBottomSheetWithoutHeight(context, - title: "Error".needTranslation, - child: Utils.getErrorWidget(loadingText: "Please ensure you're within the hospital location to perform online check-in.".needTranslation), callBackFunc: () { + title: LocaleKeys.error.tr(context: context), + child: Utils.getErrorWidget( + loadingText: LocaleKeys.ensureWithinHospitalLocation.tr(context: context), + ), callBackFunc: () { Navigator.of(context).pop(); }, isFullScreen: false); } @@ -71,8 +74,8 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_nfc_icon, - "NFC (Near Field Communication)".needTranslation, - "Scan your phone via NFC board to check in".needTranslation, + LocaleKeys.nfcNearFieldCommunication.tr(context: context), + LocaleKeys.scanPhoneViaNFC.tr(context: context), ).onPress(() { Future.delayed(const Duration(milliseconds: 500), () { showNfcReader(context, onNcfScan: (String nfcId) { @@ -85,8 +88,8 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_qr_icon, - "QR Code".needTranslation, - "Scan QR code with your camera to check in".needTranslation, + LocaleKeys.qrCode.tr(context: context), + LocaleKeys.scanQRCodeToCheckIn.tr(context: context), ).onPress(() async { // String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent)); // if (onlineCheckInQRCode != "") { @@ -139,14 +142,16 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { } void sendCheckInRequest(String scannedCode, int checkInType, BuildContext context) async { - LoaderBottomSheet.showLoader(loadingText: "Processing Check-In...".needTranslation); + LoaderBottomSheet.showLoader( + loadingText: LocaleKeys.processingCheckIn.tr(context: context), + ); await myAppointmentsViewModel.sendCheckInNfcRequest( patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel, scannedCode: scannedCode, checkInType: checkInType, onSuccess: (apiResponse) { LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight(context, title: "Success".needTranslation, child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr()), callBackFunc: () async { + showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.success.tr(context: context), child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr()), callBackFunc: () async { await myAppointmentsViewModel.getPatientAppointmentQueueDetails(); Navigator.of(context).pop(); Navigator.pushAndRemoveUntil( @@ -164,7 +169,7 @@ class AppointmentCheckinBottomSheet extends StatelessWidget { }, onError: (error) { LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight(context, title: "Error".needTranslation, child: Utils.getErrorWidget(loadingText: error), callBackFunc: () { + showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.error.tr(context: context), child: Utils.getErrorWidget(loadingText: error), callBackFunc: () { Navigator.of(context).pop(); }, isFullScreen: false); }, diff --git a/lib/presentation/appointments/widgets/appointment_doctor_card.dart b/lib/presentation/appointments/widgets/appointment_doctor_card.dart index ccf6674..6eaa379 100644 --- a/lib/presentation/appointments/widgets/appointment_doctor_card.dart +++ b/lib/presentation/appointments/widgets/appointment_doctor_card.dart @@ -89,8 +89,8 @@ class AppointmentDoctorCard extends StatelessWidget { runSpacing: 6.h, children: [ AppCustomChipWidget( - labelText: (patientAppointmentHistoryResponseModel.clinicName!.length > 15 - ? '${patientAppointmentHistoryResponseModel.clinicName!.substring(0, 12)}...' + labelText: (patientAppointmentHistoryResponseModel.clinicName!.length > 20 + ? '${patientAppointmentHistoryResponseModel.clinicName!.substring(0, 20)}...' : patientAppointmentHistoryResponseModel.clinicName!), labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w), ), @@ -114,7 +114,7 @@ class AppointmentDoctorCard extends StatelessWidget { iconColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor, labelText: patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? LocaleKeys.livecare.tr(context: context) - : "Walk In".needTranslation, + : LocaleKeys.walkin.tr(context: context), backgroundColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.greyColor : AppColors.successColor, textColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor, @@ -159,8 +159,9 @@ class AppointmentDoctorCard extends StatelessWidget { icon: AppAssets.ask_doctor_icon, iconColor: AppColors.primaryRedColor, ) - : CustomButton( - text: "Rebook with same doctor".needTranslation, + : !patientAppointmentHistoryResponseModel.isLiveCareAppointment! + ? CustomButton( + text: LocaleKeys.rebookSameDoctor.tr(), onPressed: () { onRescheduleTap(); }, @@ -175,7 +176,8 @@ class AppointmentDoctorCard extends StatelessWidget { icon: AppAssets.rebook_appointment_icon, iconColor: AppColors.blackColor, iconSize: 14.h, - ); + ) + : SizedBox.shrink(); } else { return patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false ? CustomButton( diff --git a/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart b/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart index 01aab4e..376c27a 100644 --- a/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart +++ b/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart @@ -105,7 +105,7 @@ class AskDoctorRequestTypeSelect extends StatelessWidget { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Request has been sent successfully, you will be contacted soon.".needTranslation), + child: Utils.getSuccessWidget(loadingText: "Request has been sent successfully, you will be contacted soon."), callBackFunc: () { Navigator.of(context).pop(); }, diff --git a/lib/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart b/lib/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart index cb27f9f..b6366db 100644 --- a/lib/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart +++ b/lib/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart @@ -46,7 +46,7 @@ class FacilityTypeSelectionWidget extends StatelessWidget { SizedBox(height: 24.h), FacilitySelectionItem( svgPath: AppAssets.hmg, - title: "HMG".needTranslation, + title: "HMG", subTitle: LocaleKeys.hospitalsWithCount.tr(namedArgs: { 'count': "${bookAppointmentViewModel.hospitalList?.registeredDoctorMap?[selectedRegion]?.hmgSize ?? 0}" @@ -63,7 +63,7 @@ class FacilityTypeSelectionWidget extends StatelessWidget { SizedBox(height: 16.h), FacilitySelectionItem( svgPath: AppAssets.hmc, - title: "HMC".needTranslation, + title: "HMC", subTitle: LocaleKeys.medicalCentersWithCount.tr(namedArgs: { 'count': "${bookAppointmentViewModel.hospitalList?.registeredDoctorMap?[selectedRegion]?.hmcSize ?? 0}" diff --git a/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart b/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart index eed45df..f3301f0 100644 --- a/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart +++ b/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart @@ -32,7 +32,7 @@ import '../../../emergency_services/call_ambulance/widgets/type_selection_widget // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( -// LocaleKeys.selectHospital.tr(), +// LocaleKeys.selectHospital.tr(context: context), // style: TextStyle( // fontSize: 21, // fontWeight: FontWeight.w600, @@ -40,7 +40,7 @@ import '../../../emergency_services/call_ambulance/widgets/type_selection_widget // ), // ), // Text( -// LocaleKeys.selectHospitalSubTitle.tr(), +// LocaleKeys.selectHospitalSubTitle.tr(context: context), // style: TextStyle( // fontSize: 16, // fontWeight: FontWeight.w500, @@ -49,8 +49,8 @@ import '../../../emergency_services/call_ambulance/widgets/type_selection_widget // ), // SizedBox(height: 16.h), // TextInputWidget( -// labelText: LocaleKeys.search.tr(), -// hintText: LocaleKeys.searchHospital.tr(), +// labelText: LocaleKeys.search.tr(context: context), +// hintText: LocaleKeys.searchHospital.tr(context: context), // controller: searchText, // onChange: (value) { // appointmentsViewModel.filterHospitalListByString( @@ -135,8 +135,8 @@ class HospitalBottomSheetBody extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ TextInputWidget( - labelText: LocaleKeys.search.tr(), - hintText: LocaleKeys.searchHospital.tr(), + labelText: LocaleKeys.search.tr(context: context), + hintText: LocaleKeys.searchHospital.tr(context: context), controller: searchText, onChange: (value) { debouncer.run((){ diff --git a/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_list_items.dart b/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_list_items.dart index b01b541..5d9ed8d 100644 --- a/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_list_items.dart +++ b/lib/presentation/appointments/widgets/hospital_bottom_sheet/hospital_list_items.dart @@ -76,7 +76,7 @@ class HospitalListItem extends StatelessWidget { Visibility( visible: (hospitalData?.distanceInKMs != "0"), child: AppCustomChipWidget( - labelText: "${hospitalData?.distanceInKMs ?? ""} km".needTranslation, + labelText: "${hospitalData?.distanceInKMs ?? ""} km", deleteIcon: AppAssets.location_red, deleteIconSize: Size(9, 12), backgroundColor: AppColors.secondaryLightRedColor, @@ -88,7 +88,7 @@ class HospitalListItem extends StatelessWidget { child: Row( children: [ AppCustomChipWidget( - labelText: "Distance not available".needTranslation, + labelText: "Distance not available", textColor: AppColors.blackColor, ), // SizedBox( @@ -99,7 +99,7 @@ class HospitalListItem extends StatelessWidget { Visibility( visible: !isLocationEnabled, child: AppCustomChipWidget( - labelText: "Location turned off".needTranslation, + labelText: "Location turned off", deleteIcon: AppAssets.location_unavailable, deleteIconSize: Size(9.w, 12.h), textColor: AppColors.blackColor, diff --git a/lib/presentation/appointments/widgets/hospital_bottom_sheet/type_selection_widget.dart b/lib/presentation/appointments/widgets/hospital_bottom_sheet/type_selection_widget.dart index cbf68f6..e9a5e36 100644 --- a/lib/presentation/appointments/widgets/hospital_bottom_sheet/type_selection_widget.dart +++ b/lib/presentation/appointments/widgets/hospital_bottom_sheet/type_selection_widget.dart @@ -23,7 +23,7 @@ class TypeSelectionWidget extends StatelessWidget { mainAxisSize: MainAxisSize.max, children: [ AppCustomChipWidget( - labelText: "All Facilities".needTranslation, + labelText: "All Facilities", shape: RoundedRectangleBorder( side: BorderSide( color: data.currentlySelectedFacility == FacilitySelection.ALL @@ -45,7 +45,7 @@ class TypeSelectionWidget extends StatelessWidget { AppCustomChipWidget( icon: AppAssets.hmg, iconHasColor: false, - labelText: "Hospitals".needTranslation, + labelText: "Hospitals", shape: RoundedRectangleBorder( side: BorderSide( color: data.currentlySelectedFacility == FacilitySelection.HMG @@ -67,7 +67,7 @@ class TypeSelectionWidget extends StatelessWidget { AppCustomChipWidget( icon: AppAssets.hmc, iconHasColor: false, - labelText: "Medical Centers".needTranslation, + labelText: "Medical Centers", shape: RoundedRectangleBorder( side: BorderSide( color: data.currentlySelectedFacility == FacilitySelection.HMC diff --git a/lib/presentation/ask_doctor/ask_doctor_page.dart b/lib/presentation/ask_doctor/ask_doctor_page.dart new file mode 100644 index 0000000..4c2c267 --- /dev/null +++ b/lib/presentation/ask_doctor/ask_doctor_page.dart @@ -0,0 +1,104 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart'; +import 'package:hmg_patient_app_new/features/medical_file/models/patient_sickleave_response_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_card.dart'; +import 'package:hmg_patient_app_new/presentation/ask_doctor/doctor_response_page.dart'; +import 'package:hmg_patient_app_new/presentation/ask_doctor/widgets/ask_doctor_appointment_card.dart'; +import 'package:hmg_patient_app_new/presentation/medical_file/widgets/patient_sick_leave_card.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:provider/provider.dart'; + +class AskDoctorPage extends StatefulWidget { + const AskDoctorPage({super.key}); + + @override + State createState() => _AskDoctorPageState(); +} + +class _AskDoctorPageState extends State { + late MyAppointmentsViewModel myAppointmentsViewModel; + + @override + Widget build(BuildContext context) { + myAppointmentsViewModel = Provider.of(context, listen: false); + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: Consumer( + builder: (context, askDoctorVM, child) { + return CollapsingListView( + title: LocaleKeys.askDoctor.tr(context: context), + doctorResponse: () { + askDoctorVM.getDoctorResponses(); + Navigator.of(context).push( + CustomPageRoute( + page: DoctorResponsePage(), + ), + ); + }, + child: SingleChildScrollView( + child: Column(children: [ + SizedBox(height: 16.h), + ListView.builder( + padding: EdgeInsets.only(top: 8.h), + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemCount: askDoctorVM.isAskDoctorAppointmentsLoading + ? 4 + : askDoctorVM.askDoctorAppointmentsList.isNotEmpty + ? askDoctorVM.askDoctorAppointmentsList.length + : 1, + itemBuilder: (context, index) { + return askDoctorVM.isAskDoctorAppointmentsLoading + ? Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), + child: PatientSickLeaveCard( + patientSickLeavesResponseModel: PatientSickLeavesResponseModel(), + isLoading: true, + )).paddingSymmetrical(0.w, 12.h) + : askDoctorVM.askDoctorAppointmentsList.isNotEmpty + ? AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + verticalOffset: 100.0, + child: FadeInAnimation( + child: AnimatedContainer( + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + margin: EdgeInsets.symmetric(vertical: 8.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AskDoctorAppointmentCard( + askDoctorAppointmentHistoryList: askDoctorVM.askDoctorAppointmentsList[index], + myAppointmentsViewModel: myAppointmentsViewModel, + ) + ], + ), + ), + ), + ), + ) + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noAppointmentsYet.tr(context: context)); + }, + ).paddingSymmetrical(24.h, 0.h), + SizedBox(height: 24.h), + ]), + ), + ); + }, + ), + ); + } +} diff --git a/lib/presentation/ask_doctor/doctor_response_page.dart b/lib/presentation/ask_doctor/doctor_response_page.dart new file mode 100644 index 0000000..9cd19ef --- /dev/null +++ b/lib/presentation/ask_doctor/doctor_response_page.dart @@ -0,0 +1,157 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart'; +import 'package:hmg_patient_app_new/features/medical_file/models/patient_sickleave_response_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_card.dart'; +import 'package:hmg_patient_app_new/presentation/ask_doctor/widgets/ask_doctor_appointment_card.dart'; +import 'package:hmg_patient_app_new/presentation/ask_doctor/widgets/doctor_response_transactions.dart'; +import 'package:hmg_patient_app_new/presentation/medical_file/widgets/patient_sick_leave_card.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:provider/provider.dart'; + +class DoctorResponsePage extends StatefulWidget { + const DoctorResponsePage({super.key}); + + @override + State createState() => _DoctorResponsePageState(); +} + +class _DoctorResponsePageState extends State { + late MyAppointmentsViewModel myAppointmentsViewModel; + + @override + Widget build(BuildContext context) { + myAppointmentsViewModel = Provider.of(context, listen: false); + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: LocaleKeys.doctorResponses.tr(context: context), + child: SingleChildScrollView( + child: Column( + children: [ + SizedBox(height: 16.h), + Consumer(builder: (context, askDoctorVM, child) { + return ListView.builder( + padding: EdgeInsets.zero, + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemCount: askDoctorVM.isDoctorResponsesLoading + ? 4 + : askDoctorVM.doctorResponsesList.isNotEmpty + ? askDoctorVM.doctorResponsesList.length + : 1, + itemBuilder: (context, index) { + return askDoctorVM.isDoctorResponsesLoading + ? Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), + child: PatientSickLeaveCard( + patientSickLeavesResponseModel: PatientSickLeavesResponseModel(), + isLoading: true, + )).paddingSymmetrical(0.w, 12.h) + : askDoctorVM.doctorResponsesList.isNotEmpty + ? AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + verticalOffset: 100.0, + child: FadeInAnimation( + child: AnimatedContainer( + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + margin: EdgeInsets.symmetric(vertical: 8.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), + child: Padding( + padding: EdgeInsets.all(16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + askDoctorVM.doctorResponsesList[index].requestTypeDescription!.toText18(isBold: true), + SizedBox(height: 24.h), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png", + width: 50.w, + height: 50.h, + fit: BoxFit.cover, + ).circle(100.r), + ], + ), + SizedBox(width: 16.h), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + askDoctorVM.doctorResponsesList[index].doctorName!.toText16(isBold: true, maxlines: 1), + SizedBox(height: 8.h), + Wrap( + direction: Axis.horizontal, + spacing: 3.h, + runSpacing: 4.h, + children: [ + AppCustomChipWidget( + labelText: (askDoctorVM.doctorResponsesList[index].clinicName ?? "").length > 15 + ? '${askDoctorVM.doctorResponsesList[index].clinicName!.substring(0, 12)}...' + : askDoctorVM.doctorResponsesList[index].clinicName ?? "", + ), + AppCustomChipWidget( + labelText: (askDoctorVM.doctorResponsesList[index].projectName ?? "").length > 15 + ? '${askDoctorVM.doctorResponsesList[index].projectName!.substring(0, 12)}...' + : askDoctorVM.doctorResponsesList[index].projectName ?? ""), + AppCustomChipWidget( + labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w), + icon: AppAssets.appointment_calendar_icon, + labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(askDoctorVM.doctorResponsesList[index].createdOn), false), + ), + ], + ), + ], + ), + ), + ], + ), + ], + ), + ), + ).onPress(() { + showCommonBottomSheetWithoutHeight( + context, + title: askDoctorVM.doctorResponsesList[index].requestTypeDescription!, + child: DoctorResponseTransactions(doctorResponseModel: askDoctorVM.doctorResponsesList[index],), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }), + ), + ), + ) + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDataAvailable.tr(context: context)); + }, + ).paddingSymmetrical(24.h, 0.h); + }), + SizedBox(height: 24.h), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/ask_doctor/widgets/ask_doctor_appointment_card.dart b/lib/presentation/ask_doctor/widgets/ask_doctor_appointment_card.dart new file mode 100644 index 0000000..4ff24c7 --- /dev/null +++ b/lib/presentation/ask_doctor/widgets/ask_doctor_appointment_card.dart @@ -0,0 +1,205 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/ask_doctor_appointments_list.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/appointments/widgets/ask_doctor_request_type_select.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; + +class AskDoctorAppointmentCard extends StatelessWidget { + final AskDoctorAppointmentHistoryList askDoctorAppointmentHistoryList; + final MyAppointmentsViewModel myAppointmentsViewModel; + + const AskDoctorAppointmentCard({super.key, required this.askDoctorAppointmentHistoryList, required this.myAppointmentsViewModel}); + + @override + Widget build(BuildContext context) { + final appState = getIt.get(); + return Padding( + padding: EdgeInsets.all(14.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(context, appState), + SizedBox(height: 16.h), + _buildDoctorRow(context), + SizedBox(height: 16.h), + _buildActionArea(context, appState), + ], + ), + ); + } + + Widget _buildHeader(BuildContext context, AppState appState) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded(child: _buildChips(context, appState)), + ], + ); + } + + Widget _buildChips(BuildContext context, AppState appState) { + return Wrap( + alignment: WrapAlignment.start, + direction: Axis.horizontal, + spacing: 6.w, + runSpacing: 6.h, + children: [ + AppCustomChipWidget( + icon: AppAssets.walkin_appointment_icon, + iconColor: AppColors.textColor, + labelText: LocaleKeys.walkin.tr(context: context), + backgroundColor: AppColors.greyColor, + textColor: AppColors.textColor, + ), + AppCustomChipWidget( + labelText: LocaleKeys.outPatient.tr(context: context), + backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.1), + textColor: AppColors.primaryRedColor, + ), + AppCustomChipWidget( + labelText: LocaleKeys.booked.tr(context: context), + backgroundColor: AppColors.successColor.withValues(alpha: 0.1), + textColor: AppColors.successColor, + ), + ], + ); + } + + Widget _buildDoctorRow(BuildContext context) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + askDoctorAppointmentHistoryList.doctorImageURL!, + width: 63.h, + height: 63.h, + fit: BoxFit.cover, + ).circle(100.r), + Transform.translate( + offset: Offset(0.0, -20.h), + child: Container( + width: 40.w, + height: 40.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + shape: BoxShape.circle, // Makes the container circular + border: Border.all( + color: AppColors.scaffoldBgColor, // Color of the border + width: 1.5.w, // Width of the border + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.rating_icon, width: 15.w, height: 15.h), + SizedBox(height: 2.h), + "${askDoctorAppointmentHistoryList.decimalDoctorRate}".toText11(isBold: true, color: AppColors.textColor), + ], + ), + ).circle(100), + ), + ], + ), + SizedBox(width: 16.h), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ("${askDoctorAppointmentHistoryList.doctorTitle} ${askDoctorAppointmentHistoryList.doctorName!}").toText16(isBold: true, maxlines: 1), + SizedBox(height: 8.h), + Wrap( + direction: Axis.horizontal, + spacing: 3.h, + runSpacing: 4.h, + children: [ + AppCustomChipWidget( + labelText: + askDoctorAppointmentHistoryList.clinicName!.length > 15 ? '${askDoctorAppointmentHistoryList.clinicName!.substring(0, 12)}...' : askDoctorAppointmentHistoryList.clinicName!, + ), + AppCustomChipWidget( + labelText: askDoctorAppointmentHistoryList.projectName!.length > 15 + ? '${askDoctorAppointmentHistoryList.projectName!.substring(0, 12)}...' + : askDoctorAppointmentHistoryList.projectName!), + AppCustomChipWidget( + labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w), + icon: AppAssets.appointment_calendar_icon, + labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(askDoctorAppointmentHistoryList.appointmentDate), false), + ), + ], + ), + ], + ), + ), + ], + ); + } + + Widget _buildActionArea(BuildContext context, AppState appState) { + return CustomButton( + text: LocaleKeys.askDoctor.tr(context: context), + onPressed: () async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context)); + await myAppointmentsViewModel.isDoctorAvailable( + projectID: askDoctorAppointmentHistoryList.projectID!, + doctorId: askDoctorAppointmentHistoryList.doctorID!, + clinicId: askDoctorAppointmentHistoryList.clinicID!, + onSuccess: (value) async { + if (value) { + await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.askDoctor.tr(context: context), + child: AskDoctorRequestTypeSelect( + askDoctorRequestTypeList: myAppointmentsViewModel.askDoctorRequestTypeList, + myAppointmentsViewModel: myAppointmentsViewModel, + patientAppointmentHistoryResponseModel: PatientAppointmentHistoryResponseModel() + // myAppointmentsVM.patientAppointmentsHistoryList[index], + ), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + } else { + LoaderBottomSheet.hideLoader(); + } + }, + onError: (_) { + LoaderBottomSheet.hideLoader(); + }, + ); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: 14.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(horizontal: 10.w), + // height: isTablet || isFoldable ? 46.h : 40.h, + height: 40.h, + icon: AppAssets.ask_doctor_icon, + iconColor: AppColors.primaryRedColor, + iconSize: 16.h, + ); + } +} diff --git a/lib/presentation/ask_doctor/widgets/doctor_response_transactions.dart b/lib/presentation/ask_doctor/widgets/doctor_response_transactions.dart new file mode 100644 index 0000000..33b544d --- /dev/null +++ b/lib/presentation/ask_doctor/widgets/doctor_response_transactions.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/models/doctor_response_model.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; + +class DoctorResponseTransactions extends StatelessWidget { + const DoctorResponseTransactions({super.key, required this.doctorResponseModel}); + + final DoctorResponseModel doctorResponseModel; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png", + width: 50.w, + height: 50.h, + fit: BoxFit.cover, + ).circle(100.r), + ], + ), + SizedBox(width: 16.h), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + doctorResponseModel.doctorName!.toText16(isBold: true, maxlines: 1), + SizedBox(height: 8.h), + Wrap( + direction: Axis.horizontal, + spacing: 3.h, + runSpacing: 4.h, + children: [ + AppCustomChipWidget( + labelText: (doctorResponseModel.clinicName ?? "").length > 15 ? '${doctorResponseModel.clinicName!.substring(0, 12)}...' : doctorResponseModel.clinicName ?? "", + ), + AppCustomChipWidget( + labelText: (doctorResponseModel.projectName ?? "").length > 15 ? '${doctorResponseModel.projectName!.substring(0, 12)}...' : doctorResponseModel.projectName ?? ""), + AppCustomChipWidget( + labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w), + icon: AppAssets.appointment_calendar_icon, + labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(doctorResponseModel.createdOn), false), + ), + ], + ), + ], + ), + ), + ], + ), + SizedBox(height: 16.h), + Divider(color: AppColors.dividerColor, height: 1.h), + SizedBox(height: 16.h), + Padding( + padding: EdgeInsets.symmetric(horizontal: 72.w), + child: CustomButton( + text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(doctorResponseModel.createdOn), false), + onPressed: () {}, + backgroundColor: AppColors.greyColor, + borderColor: AppColors.greyColor, + textColor: AppColors.textColor, + fontSize: 14.f, + fontWeight: FontWeight.w500, + borderRadius: 10.r, + height: 40.h, + ).paddingSymmetrical(16.w, 0.h), + ), + SizedBox(height: 16.h), + Row( + children: [ + Image.asset(getIt.get().getAuthenticatedUser()?.gender == 1 ? AppAssets.maleImg : AppAssets.femaleImg, width: 42.w, height: 42.h), + SizedBox(width: 8.w), + Container( + padding: EdgeInsets.all(8.w), + decoration: BoxDecoration( + color: AppColors.infoColor.withAlpha(20), + borderRadius: BorderRadius.circular(8.r), + ), + child: doctorResponseModel.requestTypeDescription!.toText12(color: AppColors.infoColor, fontWeight: FontWeight.w500), + ), + ], + ), + SizedBox(height: 24.h), + ListView.builder( + padding: EdgeInsets.zero, + itemCount: doctorResponseModel.transactions!.length, + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemBuilder: (context, index) { + return Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Container( + padding: EdgeInsets.all(8.w), + decoration: BoxDecoration( + color: AppColors.infoColor.withAlpha(20), + borderRadius: BorderRadius.circular(8.r), + ), + child: doctorResponseModel.transactions![index].doctorResponse!.toText12(color: AppColors.textColor, fontWeight: FontWeight.w500), + ), + SizedBox(width: 8.w), + Image.network("https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png", fit: BoxFit.cover, width: 42.w, height: 42.h).circle(100.r), + ], + ), + ], + ); + }, + ), + ], + ); + } +} diff --git a/lib/presentation/authentication/login.dart b/lib/presentation/authentication/login.dart index c14e957..6dcf15f 100644 --- a/lib/presentation/authentication/login.dart +++ b/lib/presentation/authentication/login.dart @@ -71,10 +71,10 @@ class LoginScreenState extends State { children: [ Utils.showLottie(context: context, assetPath: AppAnimations.login, width: 200.h, height: 200.h, repeat: true, fit: BoxFit.cover), SizedBox(height: 130.h), // Adjusted to sizer unit - LocaleKeys.welcomeToDrSulaiman.tr().toText32(isBold: true, color: AppColors.textColor), + LocaleKeys.welcomeToDrSulaiman.tr(context: context).toText32(isBold: true, color: AppColors.textColor), SizedBox(height: 32.h), TextInputWidget( - labelText: "${LocaleKeys.nationalId.tr()} / ${LocaleKeys.fileNo.tr()}", + labelText: "${LocaleKeys.nationalId.tr(context: context)} / ${LocaleKeys.fileNo.tr(context: context)}", hintText: "xxxxxxxxx", controller: authVm.nationalIdController, focusNode: _nationalIdFocusNode, @@ -87,13 +87,13 @@ class LoginScreenState extends State { isAllowLeadingIcon: true, padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 10.h), leadingIcon: AppAssets.student_card, - errorMessage: "Please enter a valid national ID or file number".needTranslation, + errorMessage: LocaleKeys.enterValidIDorIqama.tr(context: context), hasError: false, ), SizedBox(height: 16.h), CustomButton( height: 50.h, - text: LocaleKeys.login.tr(), + text: LocaleKeys.login.tr(context: context), icon: AppAssets.login1, iconColor: Colors.white, onPressed: () { @@ -116,10 +116,10 @@ class LoginScreenState extends State { text: TextSpan( style: context.dynamicTextStyle(color: Colors.black, fontSize: 14.f, height: 26 / 16, fontWeight: FontWeight.w500), children: [ - TextSpan(text: LocaleKeys.dontHaveAccount.tr(), style: context.dynamicTextStyle()), + TextSpan(text: LocaleKeys.dontHaveAccount.tr(context: context), style: context.dynamicTextStyle()), TextSpan(text: " "), TextSpan( - text: LocaleKeys.registernow.tr(), + text: LocaleKeys.registernow.tr(context: context), style: context.dynamicTextStyle( color: AppColors.primaryRedColor, fontSize: 14.f, // Adjusted to sizer unit @@ -172,7 +172,7 @@ class LoginScreenState extends State { Padding( padding: EdgeInsets.only(bottom: 10.h), child: CustomButton( - text: LocaleKeys.sendOTPSMS.tr(), + text: LocaleKeys.sendOTPSMS.tr(context: context), onPressed: () async { if (ValidationUtils.isValidatePhone( phoneNumber: phoneNumberController!.text, @@ -196,14 +196,14 @@ class LoginScreenState extends State { children: [ Padding( padding: EdgeInsets.symmetric(horizontal: 8.h), - child: LocaleKeys.oR.tr().toText16(color: AppColors.textColor), + child: LocaleKeys.oR.tr(context: context).toText16(color: AppColors.textColor), ), ], ), Padding( padding: EdgeInsets.only(bottom: 10.h, top: 10.h), child: CustomButton( - text: LocaleKeys.sendOTPWHATSAPP.tr(), + text: LocaleKeys.sendOTPWHATSAPP.tr(context: context), onPressed: () async { if (ValidationUtils.isValidatePhone( phoneNumber: phoneNumberController!.text, diff --git a/lib/presentation/authentication/quick_login.dart b/lib/presentation/authentication/quick_login.dart index bdeb0ff..fbcb17d 100644 --- a/lib/presentation/authentication/quick_login.dart +++ b/lib/presentation/authentication/quick_login.dart @@ -49,7 +49,7 @@ class QuickLoginState extends State { ], ), Utils.showLottie(context: context, assetPath: AppAnimations.checkmark, width: 120, height: 120, repeat: true), - LocaleKeys.allSet.tr().toText16(textAlign: TextAlign.center, weight: FontWeight.w500) + LocaleKeys.allSet.tr(context: context).toText16(textAlign: TextAlign.center, weight: FontWeight.w500) // Text( // ' TranslationBase.of(context).allSet', // textAlign: TextAlign.center, @@ -67,7 +67,7 @@ class QuickLoginState extends State { children: [ Image.asset(AppAssets.lockIcon, height: 100), SizedBox(height: 10.h), - LocaleKeys.enableQuickLogin.tr().toText26(isBold: true), + LocaleKeys.enableQuickLogin.tr(context: context).toText26(isBold: true), // Text( // ' TranslationBase.of(context).enableQuickLogin', // style: context.dynamicTextStyle( @@ -77,7 +77,7 @@ class QuickLoginState extends State { // ), // ), SizedBox(height: 5.h), - LocaleKeys.enableQuickLogin.tr().toText16(color: AppColors.quickLoginColor), + LocaleKeys.enableQuickLogin.tr(context: context).toText16(color: AppColors.quickLoginColor), // Description // Text( // 'TranslationBase.of(context).enableMsg', @@ -94,7 +94,7 @@ class QuickLoginState extends State { children: [ Expanded( child: CustomButton( - text: LocaleKeys.enableQuickLogin.tr(), + text: LocaleKeys.enableQuickLogin.tr(context: context), onPressed: () { widget.onPressed(); }, @@ -114,7 +114,7 @@ class QuickLoginState extends State { children: [ Expanded( child: CustomButton( - text: LocaleKeys.notNow.tr(), + text: LocaleKeys.notNow.tr(context: context), onPressed: () { cacheService.saveBool(key: CacheConst.quickLoginEnabled, value: false); Navigator.pop(context, "true"); diff --git a/lib/presentation/authentication/register.dart b/lib/presentation/authentication/register.dart index f04f7dd..71bddb3 100644 --- a/lib/presentation/authentication/register.dart +++ b/lib/presentation/authentication/register.dart @@ -80,7 +80,7 @@ class _RegisterNew extends State { children: [ Utils.showLottie(context: context, assetPath: 'assets/animations/lottie/register.json', width: 200.w, height: 200.h, fit: BoxFit.cover, repeat: true), SizedBox(height: 16.h), - LocaleKeys.prepareToElevate.tr().toText32(isBold: true), + LocaleKeys.prepareToElevate.tr(context: context).toText32(isBold: true), SizedBox(height: 24.h), Directionality( textDirection: Directionality.of(context), @@ -96,7 +96,7 @@ class _RegisterNew extends State { ).withVerticalPadding(8.h), Divider(height: 1.h), TextInputWidget( - labelText: LocaleKeys.nationalIdNumber.tr(), + labelText: LocaleKeys.nationalIdNumber.tr(context: context), hintText: "xxxxxxxxx", controller: authVm.nationalIdController, focusNode: _nationalIdFocusNode, @@ -111,8 +111,8 @@ class _RegisterNew extends State { ).withVerticalPadding(8), Divider(height: 1), TextInputWidget( - labelText: LocaleKeys.dob.tr(), - hintText: "11 July, 1994".needTranslation, + labelText: LocaleKeys.dob.tr(context: context), + hintText: "11 July, 1994", controller: authVm.dobController, focusNode: _dobFocusNode, isEnable: true, @@ -156,16 +156,18 @@ class _RegisterNew extends State { Row( children: [ Text( - LocaleKeys.iAcceptThe.tr(), + LocaleKeys.iAcceptThe.tr(context: context), style: context.dynamicTextStyle(fontSize: 14.f, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)), ), GestureDetector( onTap: () { // Navigate to terms and conditions page - Navigator.of(context).pushNamed('/terms'); + Utils.openWebView( + url: 'https://hmg.com/en/Pages/Terms.aspx', + ); }, child: Text( - LocaleKeys.termsConditoins.tr(), + " ${LocaleKeys.termsConditoins.tr(context: context)}", style: context.dynamicTextStyle( fontSize: 14.f, fontWeight: FontWeight.w500, @@ -179,7 +181,7 @@ class _RegisterNew extends State { ), // Expanded( // child: Text( - // LocaleKeys.iAcceptTermsConditions.tr().split("the").first, + // LocaleKeys.iAcceptTermsConditions.tr(context: context).split("the").first, // style: context.dynamicTextStyle(fontSize: 14.fSize, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)), // ), // ), @@ -188,7 +190,7 @@ class _RegisterNew extends State { ), SizedBox(height: 25.h), CustomButton( - text: LocaleKeys.registernow.tr(), + text: LocaleKeys.registernow.tr(context: context), icon: AppAssets.note_edit, onPressed: () { // Dismiss keyboard before proceeding @@ -220,10 +222,10 @@ class _RegisterNew extends State { fontWeight: FontWeight.w500, ), children: [ - TextSpan(text: LocaleKeys.alreadyHaveAccount.tr(), style: context.dynamicTextStyle()), + TextSpan(text: LocaleKeys.alreadyHaveAccount.tr(context: context), style: context.dynamicTextStyle()), TextSpan(text: " "), TextSpan( - text: LocaleKeys.loginNow.tr(), + text: LocaleKeys.loginNow.tr(context: context), style: context.dynamicTextStyle( color: AppColors.primaryRedColor, fontSize: 16.f, @@ -271,7 +273,7 @@ class _RegisterNew extends State { Padding( padding: const EdgeInsets.only(bottom: 10), child: CustomButton( - text: LocaleKeys.sendOTPSMS.tr(), + text: LocaleKeys.sendOTPSMS.tr(context: context), onPressed: () async { // Dismiss keyboard before validation FocusScope.of(context).unfocus(); @@ -298,14 +300,14 @@ class _RegisterNew extends State { children: [ Padding( padding: EdgeInsets.symmetric(horizontal: 8.h), - child: LocaleKeys.oR.tr().toText16(color: AppColors.textColor), + child: LocaleKeys.oR.tr(context: context).toText16(color: AppColors.textColor), ), ], ), Padding( padding: EdgeInsets.only(bottom: 10.h, top: 10.h), child: CustomButton( - text: LocaleKeys.sendOTPWHATSAPP.tr(), + text: LocaleKeys.sendOTPWHATSAPP.tr(context: context), onPressed: () async { FocusScope.of(context).unfocus(); if (ValidationUtils.isValidatePhone( diff --git a/lib/presentation/authentication/register_step2.dart b/lib/presentation/authentication/register_step2.dart index 71cef96..c4bdf0f 100644 --- a/lib/presentation/authentication/register_step2.dart +++ b/lib/presentation/authentication/register_step2.dart @@ -73,7 +73,7 @@ class _RegisterNew extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.personalDetailsVerification.tr().toText26(color: AppColors.textColor, weight: FontWeight.w600, letterSpacing: -2), + LocaleKeys.personalDetailsVerification.tr(context: context).toText26(color: AppColors.textColor, weight: FontWeight.w600, letterSpacing: -2), SizedBox(height: 24.h), Container( decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24)), @@ -81,8 +81,8 @@ class _RegisterNew extends State { child: Column( children: [ TextInputWidget( - labelText: authVM!.isUserFromUAE() ? LocaleKeys.fullName.tr() : LocaleKeys.name.tr(), - hintText: authVM!.isUserFromUAE() ? LocaleKeys.enterNameHere.tr() : (name), + labelText: authVM!.isUserFromUAE() ? LocaleKeys.fullName.tr(context: context) : LocaleKeys.name.tr(context: context), + hintText: authVM!.isUserFromUAE() ? LocaleKeys.enterNameHere.tr(context: context) : (name), controller: authVM!.isUserFromUAE() ? authVM!.nameController : null, isEnable: true, prefix: null, @@ -100,7 +100,7 @@ class _RegisterNew extends State { ).paddingSymmetrical(0.h, 16.h), Divider(height: 1.h, color: AppColors.greyColor), TextInputWidget( - labelText: LocaleKeys.nationalIdNumber.tr(), + labelText: LocaleKeys.nationalIdNumber.tr(context: context), hintText: authVM!.isUserFromUAE() ? appState.getUserRegistrationPayload.patientIdentificationId.toString() : (appState.getNHICUserData.idNumber ?? ""), controller: null, isEnable: true, @@ -120,8 +120,8 @@ class _RegisterNew extends State { builder: (context, genderType, child) { final authVM = context.read(); return DropdownWidget( - labelText: LocaleKeys.gender.tr(), - hintText: LocaleKeys.malE.tr(), + labelText: LocaleKeys.gender.tr(context: context), + hintText: LocaleKeys.malE.tr(context: context), isEnable: true, dropdownItems: GenderTypeEnum.values.map((e) => appState.isArabic() ? e.typeAr : e.type).toList(), selectedValue: genderType != null ? (appState.isArabic() ? genderType.typeAr : genderType.type) : "", @@ -136,7 +136,7 @@ class _RegisterNew extends State { ).withVerticalPadding(8); }) : TextInputWidget( - labelText: LocaleKeys.gender.tr(), + labelText: LocaleKeys.gender.tr(context: context), hintText: (appState.getNHICUserData.gender ?? ""), controller: null, isEnable: true, @@ -157,8 +157,8 @@ class _RegisterNew extends State { builder: (context, maritalStatus, child) { final authVM = context.read(); // For onChange return DropdownWidget( - labelText: LocaleKeys.maritalStatus.tr(), - hintText: LocaleKeys.married.tr(), + labelText: LocaleKeys.maritalStatus.tr(context: context), + hintText: LocaleKeys.married.tr(context: context), isEnable: true, dropdownItems: MaritalStatusTypeEnum.values.map((e) => appState.isArabic() ? e.typeAr : e.type).toList(), selectedValue: maritalStatus != null ? (appState.isArabic() ? maritalStatus.typeAr : maritalStatus.type) : "", @@ -174,7 +174,7 @@ class _RegisterNew extends State { }, ) : TextInputWidget( - labelText: LocaleKeys.maritalStatus.tr(), + labelText: LocaleKeys.maritalStatus.tr(context: context), hintText: appState.isArabic() ? (MaritalStatusTypeExtension.fromValue(appState.getNHICUserData.maritalStatusCode)!.typeAr) : (MaritalStatusTypeExtension.fromValue(appState.getNHICUserData.maritalStatusCode)!.type), @@ -203,8 +203,8 @@ class _RegisterNew extends State { builder: (context, data, child) { final authVM = context.read(); return DropdownWidget( - labelText: LocaleKeys.country.tr(), - hintText: LocaleKeys.uae.tr(), + labelText: LocaleKeys.country.tr(context: context), + hintText: LocaleKeys.uae.tr(context: context), isEnable: true, dropdownItems: (data.countriesList ?? []).map((e) => data.isArabic ? e.nameN ?? "" : e.name ?? "").toList(), selectedValue: data.selectedCountry != null @@ -224,7 +224,7 @@ class _RegisterNew extends State { }, ) : TextInputWidget( - labelText: LocaleKeys.nationality.tr(), + labelText: LocaleKeys.nationality.tr(context: context), hintText: appState.isArabic() ? (authVM!.countriesList!.firstWhere((e) => e.id == (appState.getNHICUserData.nationalityCode ?? ""), orElse: () => NationalityCountries()).nameN ?? "") : (authVM!.countriesList!.firstWhere((e) => e.id == (appState.getNHICUserData.nationalityCode ?? ""), orElse: () => NationalityCountries()).name ?? ""), @@ -243,7 +243,7 @@ class _RegisterNew extends State { color: AppColors.greyColor, ), TextInputWidget( - labelText: LocaleKeys.mobileNumber.tr(), + labelText: LocaleKeys.mobileNumber.tr(context: context), hintText: (appState.getUserRegistrationPayload.patientMobileNumber.toString() ?? ""), controller: null, isEnable: false, @@ -260,7 +260,7 @@ class _RegisterNew extends State { color: AppColors.greyColor, ), TextInputWidget( - labelText: LocaleKeys.dob.tr(), + labelText: LocaleKeys.dob.tr(context: context), hintText: authVM!.isUserFromUAE() ? appState.getUserRegistrationPayload.dob! : appState.getNHICUserData.dateOfBirth ?? "", controller: authVM!.isUserFromUAE() ? authVM!.dobController : null, isEnable: false, @@ -280,7 +280,7 @@ class _RegisterNew extends State { children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), icon: AppAssets.cancel, onPressed: () { Navigator.of(context).pop(); @@ -298,7 +298,7 @@ class _RegisterNew extends State { backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, textColor: AppColors.whiteColor, - text: LocaleKeys.confirm.tr(), + text: LocaleKeys.confirm.tr(context: context), icon: AppAssets.confirm, iconColor: AppColors.whiteColor, onPressed: () { @@ -345,7 +345,7 @@ class _RegisterNew extends State { Padding( padding: const EdgeInsets.only(bottom: 10), child: CustomButton( - text: LocaleKeys.submit.tr(), + text: LocaleKeys.submit.tr(context: context), onPressed: () { if (ValidationUtils.isValidateEmail( email: authVM!.emailController.text, diff --git a/lib/presentation/blood_donation/blood_donation_page.dart b/lib/presentation/blood_donation/blood_donation_page.dart index 5f3fa86..26da599 100644 --- a/lib/presentation/blood_donation/blood_donation_page.dart +++ b/lib/presentation/blood_donation/blood_donation_page.dart @@ -7,25 +7,46 @@ import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart'; +import 'package:hmg_patient_app_new/features/blood_donation/widgets/hospital_selection.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_blood_group_widget.dart'; import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_city_widget.dart'; import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_gender_widget.dart'; +import 'package:hmg_patient_app_new/presentation/book_appointment/select_clinic_page.dart'; +import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; +import 'package:hmg_patient_app_new/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart'; -class BloodDonationPage extends StatelessWidget { +class BloodDonationPage extends StatefulWidget { BloodDonationPage({super.key}); + @override + State createState() => _BloodDonationPageState(); +} + +class _BloodDonationPageState extends State { late AppState appState; + @override + void initState() { + super.initState(); + Future.microtask(() => getIt.get().fetchAllData()); + } + @override Widget build(BuildContext context) { - appState = getIt.get(); + appState = getIt(); return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: Consumer(builder: (context, bloodDonationVM, child) { @@ -34,15 +55,82 @@ class BloodDonationPage extends StatelessWidget { Expanded( child: CollapsingListView( title: LocaleKeys.bloodDonation.tr(), + trailing: CustomButton( + text: "Book", + onPressed: () { + if (bloodDonationVM.isUserAuthanticated()) { + bloodDonationVM.fetchHospitalsList().then((value) { + showCommonBottomSheetWithoutHeight(context, title: "Select Hospital", isDismissible: false, child: Consumer(builder: (_, data, __) { + return HospitalBottomSheetBodySelection( + isHideTitle: true, + onUserHospitalSelection: (BdGetProjectsHaveBdClinic userChoice) { + bloodDonationVM.getFreeBloodDonationSlots(request: {"ClinicID": 134, "ProjectID": userChoice.projectId}); + }, + ); + }), callBackFunc: () {}); + }); + } else { + return showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.notice.tr(context: context), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), + SizedBox(height: 8.h), + (LocaleKeys.loginToUseService.tr()).toText16(color: AppColors.blackColor), + SizedBox(height: 16.h), + Row( + children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.cancel.tr(), + onPressed: () { + Navigator.of(context).pop(); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + icon: AppAssets.cancel, + iconColor: AppColors.primaryRedColor, + ), + ), + SizedBox(width: 8.h), + Expanded( + child: CustomButton( + text: LocaleKeys.confirm.tr(), + onPressed: () async { + Navigator.of(context).pop(); + // Navigator.pushAndRemoveUntil(context, CustomPageRoute(page: LandingNavigation()), (r) => false); + await getIt().onLoginPressed(); + }, + backgroundColor: AppColors.bgGreenColor, + borderColor: AppColors.bgGreenColor, + textColor: Colors.white, + icon: AppAssets.confirm, + ), + ), + ], + ), + SizedBox(height: 16.h), + ], + ).center, + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + }, + backgroundColor: AppColors.bgRedLightColor, + borderColor: AppColors.bgRedLightColor, + textColor: AppColors.primaryRedColor, + padding: EdgeInsetsGeometry.symmetric(vertical: 0.h, horizontal: 20.h)), child: Padding( padding: EdgeInsets.all(24.w), child: SingleChildScrollView( child: Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: false, - ), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false), child: Padding( padding: EdgeInsets.all(16.h), child: Column( @@ -60,8 +148,8 @@ class BloodDonationPage extends StatelessWidget { children: [ LocaleKeys.city.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), (appState.isArabic() - ? (bloodDonationVM.selectedCity.descriptionN ?? LocaleKeys.select.tr()) - : bloodDonationVM.selectedCity.description ?? LocaleKeys.select.tr(context: context)) + ? (bloodDonationVM.selectedCity?.descriptionN ?? LocaleKeys.select.tr()) + : bloodDonationVM.selectedCity?.description ?? LocaleKeys.select.tr(context: context)) .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), @@ -71,12 +159,7 @@ class BloodDonationPage extends StatelessWidget { ], ).onPress(() async { showCommonBottomSheetWithoutHeight(context, - title: LocaleKeys.selectCity.tr(context: context), - isDismissible: true, - child: SelectCityWidget( - bloodDonationViewModel: bloodDonationVM, - ), - callBackFunc: () {}); + title: LocaleKeys.selectCity.tr(context: context), isDismissible: true, child: SelectCityWidget(bloodDonationViewModel: bloodDonationVM), callBackFunc: () {}); }), SizedBox(height: 16.h), Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), @@ -86,13 +169,16 @@ class BloodDonationPage extends StatelessWidget { children: [ Row( children: [ - Utils.buildSvgWithAssets(icon: AppAssets.my_account_icon, width: 40.h, height: 40.h), + Utils.buildSvgWithAssets(icon: AppAssets.genderInputIcon, width: 40.h, height: 40.h), SizedBox(width: 12.w), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.gender.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), - "Male".toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + (appState.isArabic() + ? (bloodDonationVM.selectedGender?.typeAr ?? LocaleKeys.select.tr()) + : bloodDonationVM.selectedGender?.type ?? LocaleKeys.select.tr(context: context)) + .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ], @@ -103,10 +189,7 @@ class BloodDonationPage extends StatelessWidget { showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.selectGender.tr(context: context), isDismissible: true, - child: SelectGenderWidget( - isArabic: appState.isArabic(), - bloodDonationViewModel: bloodDonationVM, - ), + child: SelectGenderWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM), callBackFunc: () {}); }), SizedBox(height: 16.h), @@ -117,13 +200,17 @@ class BloodDonationPage extends StatelessWidget { children: [ Row( children: [ - Utils.buildSvgWithAssets(icon: AppAssets.my_account_icon, width: 40.h, height: 40.h), + Utils.buildSvgWithAssets(icon: AppAssets.bloodType, width: 40.h, height: 40.h), SizedBox(width: 12.w), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.bloodType.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), - bloodDonationVM.selectedBloodType.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + // bloodDonationVM.selectedBloodType?.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + (appState.isArabic() + ? (bloodDonationVM.selectedBloodType ?? LocaleKeys.select.tr()) + : bloodDonationVM.selectedBloodType ?? LocaleKeys.select.tr(context: context)) + .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500) ], ), ], @@ -134,10 +221,7 @@ class BloodDonationPage extends StatelessWidget { showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.select.tr(context: context), isDismissible: true, - child: SelectBloodGroupWidget( - isArabic: appState.isArabic(), - bloodDonationViewModel: bloodDonationVM, - ), + child: SelectBloodGroupWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM), callBackFunc: () {}); }), ], @@ -149,19 +233,126 @@ class BloodDonationPage extends StatelessWidget { ), ), Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, - ), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: SizedBox( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + GestureDetector( + onTap: bloodDonationVM.onTermAccepted, + child: Row( + children: [ + Selector( + selector: (_, viewModel) => viewModel.isTermsAccepted, + shouldRebuild: (previous, next) => previous != next, + builder: (context, isTermsAccepted, child) { + return AnimatedContainer( + duration: const Duration(milliseconds: 200), + height: 24.h, + width: 24.h, + decoration: BoxDecoration( + color: isTermsAccepted ? AppColors.primaryRedColor : Colors.transparent, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: isTermsAccepted ? AppColors.primaryRedBorderColor : AppColors.greyColor, width: 2.h), + ), + child: isTermsAccepted ? Icon(Icons.check, size: 16.f, color: Colors.white) : null, + ); + }, + ), + SizedBox(width: 12.h), + Row( + children: [ + Text( + LocaleKeys.iAcceptThe.tr(), + style: context.dynamicTextStyle(fontSize: 14.f, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)), + ), + GestureDetector( + onTap: () { + // Navigate to terms and conditions page + Navigator.of(context).pushNamed('/terms'); + }, + child: Text( + LocaleKeys.termsConditoins.tr(), + style: context.dynamicTextStyle( + fontSize: 14.f, + fontWeight: FontWeight.w500, + color: AppColors.primaryRedColor, + decoration: TextDecoration.underline, + decorationColor: AppColors.primaryRedBorderColor, + ), + ), + ), + ], + ), + // Expanded( + // child: Text( + // LocaleKeys.iAcceptTermsConditions.tr().split("the").first, + // style: context.dynamicTextStyle(fontSize: 14.fSize, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)), + // ), + // ), + ], + ), + ).paddingOnly(left: 16.h, right: 16.h, top: 24.h), CustomButton( text: LocaleKeys.save.tr(), - onPressed: () { - // openDoctorScheduleCalendar(); + onPressed: () async { + DialogService dialogService = getIt.get(); + if (await bloodDonationVM.validateSelections()) { + if (bloodDonationVM.isUserAuthanticated()) { + bloodDonationVM.updateBloodGroup(); + } else { + return showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.notice.tr(context: context), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), + SizedBox(height: 8.h), + (LocaleKeys.loginToUseService.tr()).toText16(color: AppColors.blackColor), + SizedBox(height: 16.h), + Row( + children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.cancel.tr(), + onPressed: () { + Navigator.of(context).pop(); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + icon: AppAssets.cancel, + iconColor: AppColors.primaryRedColor, + ), + ), + SizedBox(width: 8.h), + Expanded( + child: CustomButton( + text: LocaleKeys.confirm.tr(), + onPressed: () async { + Navigator.of(context).pop(); + // Navigator.pushAndRemoveUntil(context, CustomPageRoute(page: LandingNavigation()), (r) => false); + await getIt().onLoginPressed(); + }, + backgroundColor: AppColors.bgGreenColor, + borderColor: AppColors.bgGreenColor, + textColor: Colors.white, + icon: AppAssets.confirm, + ), + ), + ], + ), + SizedBox(height: 16.h), + ], + ).center, + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + } }, backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, diff --git a/lib/presentation/blood_donation/widgets/select_city_widget.dart b/lib/presentation/blood_donation/widgets/select_city_widget.dart index 8e2f9a0..bf5992d 100644 --- a/lib/presentation/blood_donation/widgets/select_city_widget.dart +++ b/lib/presentation/blood_donation/widgets/select_city_widget.dart @@ -26,9 +26,7 @@ class SelectCityWidget extends StatelessWidget { Navigator.of(context).pop(); }); }, - separatorBuilder: (_, __) => SizedBox( - height: 8.h, - ), + separatorBuilder: (_, __) => SizedBox(height: 8.h), itemCount: bloodDonationViewModel.citiesList.length), ) ], diff --git a/lib/presentation/blood_donation/widgets/select_gender_widget.dart b/lib/presentation/blood_donation/widgets/select_gender_widget.dart index 67cd4bb..0d360a8 100644 --- a/lib/presentation/blood_donation/widgets/select_gender_widget.dart +++ b/lib/presentation/blood_donation/widgets/select_gender_widget.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; @@ -8,10 +9,10 @@ import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_ import 'package:hmg_patient_app_new/theme/colors.dart'; class SelectGenderWidget extends StatelessWidget { - SelectGenderWidget({super.key, required this.bloodDonationViewModel, required this.isArabic}); + const SelectGenderWidget({super.key, required this.bloodDonationViewModel, required this.isArabic}); - BloodDonationViewModel bloodDonationViewModel; - bool isArabic; + final BloodDonationViewModel bloodDonationViewModel; + final bool isArabic; @override Widget build(BuildContext context) { @@ -20,46 +21,45 @@ class SelectGenderWidget extends StatelessWidget { children: [ SizedBox(height: 8.h), SizedBox( - height: MediaQuery.sizeOf(context).height * .4, - child: ListView.separated( - itemBuilder: (_, index) { - return DecoratedBox( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 20.h, - hasShadow: false, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - spacing: 8.h, - children: [bloodDonationViewModel.genderList[index].name.toText16(color: AppColors.textColor, isBold: true)], + height: MediaQuery.sizeOf(context).height * .4, + child: ListView.separated( + itemBuilder: (_, index) { + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8.h, + children: [GenderTypeEnum.values[index].name.toCamelCase.toText16(color: AppColors.textColor, isBold: true)], + ), ), - ), - Transform.flip( - flipX: isArabic, - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, - iconColor: AppColors.blackColor, - width: 40.h, - height: 40.h, - fit: BoxFit.contain, + Transform.flip( + flipX: isArabic, + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon, + iconColor: AppColors.blackColor, + width: 40.h, + height: 40.h, + fit: BoxFit.contain, + ), ), - ), - ], - ).paddingSymmetrical(16.h, 16.h).onPress(() { - // bloodDonationViewModel.setSelectedCity(bloodDonationViewModel.citiesList[index]); - Navigator.of(context).pop(); - })); - }, - separatorBuilder: (_, __) => SizedBox( - height: 8.h, - ), - itemCount: bloodDonationViewModel.genderList.length), - ) + ], + ).paddingSymmetrical(16.h, 16.h).onPress(() { + bloodDonationViewModel.onGenderChange(GenderTypeEnum.values[index].name.toCamelCase); + Navigator.of(context).pop(); + })); + }, + separatorBuilder: (_, __) => SizedBox( + height: 8.h, + ), + itemCount: GenderTypeEnum.values.length)) ], ); } diff --git a/lib/presentation/book_appointment/book_appointment_page.dart b/lib/presentation/book_appointment/book_appointment_page.dart index 76dc1be..fa23979 100644 --- a/lib/presentation/book_appointment/book_appointment_page.dart +++ b/lib/presentation/book_appointment/book_appointment_page.dart @@ -60,6 +60,9 @@ class _BookAppointmentPageState extends State { bookAppointmentsViewModel.getLocation(); immediateLiveCareViewModel.initImmediateLiveCare(); }); + WidgetsBinding.instance.addPostFrameCallback((_) { + showUnKnownClinicBottomSheet(); + }); super.initState(); } @@ -89,8 +92,8 @@ class _BookAppointmentPageState extends State { activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), initialIndex: bookAppointmentsVM.selectedTabIndex, tabs: [ - CustomTabBarModel(null, "General".needTranslation), - CustomTabBarModel(null, "LiveCare".needTranslation), + CustomTabBarModel(null, LocaleKeys.general.tr(context: context)), + CustomTabBarModel(null, LocaleKeys.liveCare.tr(context: context)), ], onTabChange: (index) { bookAppointmentsVM.onTabChanged(index); @@ -112,10 +115,7 @@ class _BookAppointmentPageState extends State { fit: BoxFit.cover, ).circle(100).toShimmer2(isShow: true, radius: 50.r), SizedBox(height: 8.h), - ("Dr. John Smith Smith Smith") - .toString() - .toText12(fontWeight: FontWeight.w500, isCenter: true, maxLine: 2) - .toShimmer2(isShow: true), + ("Dr. John Smith Smith Smith").toString().toText12(fontWeight: FontWeight.w500, isCenter: true, maxLine: 2).toShimmer2(isShow: true), ], ) : myAppointmentsVM.patientMyDoctorsList.isEmpty @@ -124,7 +124,7 @@ class _BookAppointmentPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (appState.isAuthenticated) ...[], - "Recent Visits".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0.h), + LocaleKeys.recentVisits.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.w, 0.h), SizedBox(height: 16.h), SizedBox( height: 110.h, @@ -235,16 +235,13 @@ class _BookAppointmentPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Search By Clinic".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "Tap to select clinic".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + LocaleKeys.searchByClinic.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.tapToSelectClinic.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), ], ), ], ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), ], ).onPress(() { bookAppointmentsViewModel.setIsClinicsListLoading(true); @@ -270,16 +267,13 @@ class _BookAppointmentPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Search By Doctor".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "Tap to select".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + LocaleKeys.searchByDoctor.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.tapToSelect.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), ], ), ], ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), ], ).onPress(() { bookAppointmentsViewModel.setIsDoctorSearchByNameStarted(false); @@ -303,16 +297,13 @@ class _BookAppointmentPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Search By Region".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "Central Region".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + LocaleKeys.searchByRegion.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.centralRegion.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), ], ), ], ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), ], ).onPress(() { bookAppointmentsViewModel.setProjectID(null); @@ -325,133 +316,121 @@ class _BookAppointmentPageState extends State { ], ).paddingSymmetrical(24.h, 0.h); case 1: - //TODO: Get LiveCare type Select UI from Hussain - return - // appState.isAuthenticated - // ? - Column( + //TODO: Get LiveCare type Select UI from Hussain + return appState.isAuthenticated + ? Column( children: [ Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.h, - hasShadow: false, - ), - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.search_by_clinic_icon, width: 40.h, height: 40.h), - SizedBox(width: 12.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Immediate Consultation".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "Tap to select clinic".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), - ], - ), - ], - ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), - ], - ).onPress(() async { - //TODO Implement API to check for existing LiveCare Requests + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: false, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.search_by_clinic_icon, width: 40.h, height: 40.h), + SizedBox(width: 12.h), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.immediateConsultation.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.tapToSelectClinic.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + ], + ), + ], + ), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + ], + ).onPress(() async { + //TODO Implement API to check for existing LiveCare Requests - LoaderBottomSheet.showLoader(); - await immediateLiveCareViewModel.getPatientLiveCareHistory(); - LoaderBottomSheet.hideLoader(); + LoaderBottomSheet.showLoader(); + await immediateLiveCareViewModel.getPatientLiveCareHistory(); + LoaderBottomSheet.hideLoader(); - if (immediateLiveCareViewModel.patientHasPendingLiveCareRequest) { - Navigator.of(context).push( - CustomPageRoute( - page: ImmediateLiveCarePendingRequestPage(), - ), - ); - } else { - Navigator.of(context).push( - CustomPageRoute( - page: SelectImmediateLiveCareClinicPage(), - ), - ); - } - }), - SizedBox(height: 16.h), - Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), - SizedBox(height: 16.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.search_by_doctor_icon, width: 40.h, height: 40.h), - SizedBox(width: 12.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Scheduled Consultation".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "Tap to select clinic".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), - ], - ), - ], - ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), - ], - ).onPress(() { - bookAppointmentsViewModel.setIsClinicsListLoading(true); - bookAppointmentsViewModel.setIsLiveCareSchedule(true); - Navigator.of(context).push( - CustomPageRoute( - page: SelectClinicPage(), - ), - ); - }), - SizedBox(height: 16.h), - Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), - SizedBox(height: 16.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.search_by_region_icon, width: 40.h, height: 40.h), - SizedBox(width: 12.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Pharma LiveCare".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500), - "".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), - ], - ), - ], - ), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), - ], - ).onPress(() { - openRegionListBottomSheet(context, RegionBottomSheetType.FOR_REGION); - }), - ], - ), - ), - ), - ], - ).paddingSymmetrical(24.h, 0.h) - // : getLiveCareNotLoggedInUI() - ; + if (immediateLiveCareViewModel.patientHasPendingLiveCareRequest) { + Navigator.of(context).push( + CustomPageRoute( + page: ImmediateLiveCarePendingRequestPage(), + ), + ); + } else { + Navigator.of(context).push( + CustomPageRoute( + page: SelectImmediateLiveCareClinicPage(), + ), + ); + } + }), + SizedBox(height: 16.h), + Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), + SizedBox(height: 16.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.search_by_doctor_icon, width: 40.h, height: 40.h), + SizedBox(width: 12.h), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.scheduledConsultation.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.tapToSelectClinic.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + ], + ), + ], + ), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + ], + ).onPress(() { + bookAppointmentsViewModel.setIsClinicsListLoading(true); + bookAppointmentsViewModel.setIsLiveCareSchedule(true); + Navigator.of(context).push( + CustomPageRoute( + page: SelectClinicPage(), + ), + ); + }), + SizedBox(height: 16.h), + Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), + SizedBox(height: 16.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.search_by_region_icon, width: 40.h, height: 40.h), + SizedBox(width: 12.h), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.pharmaLiveCare.tr(context: context).toText14(color: AppColors.textColor, weight: FontWeight.w500), + "".toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + ], + ), + ], + ), + Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 40.h, height: 40.h)), + ], + ).onPress(() { + openRegionListBottomSheet(context, RegionBottomSheetType.FOR_REGION); + }), + ], + ), + ), + ), + ], + ).paddingSymmetrical(24.h, 0.h) + : getLiveCareNotLoggedInUI(); default: SizedBox.shrink(); } @@ -468,21 +447,22 @@ class _BookAppointmentPageState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Not sure? help me choose a clinic!".needTranslation.toText16(weight: FontWeight.w600, color: AppColors.textColor), - SizedBox(height: 4.h), - "Mention your symptoms and find the list of doctors accordingly".needTranslation.toText12( - fontWeight: FontWeight.w500, - color: AppColors.greyTextColor, - ), + LocaleKeys.notSureHelpMeChooseClinic.tr(context: context).toText16(weight: FontWeight.w600, color: AppColors.textColor), + SizedBox(height: 8.h), + LocaleKeys.mentionYourSymptomsAndFindDoctors.tr(context: context).toText12( + fontWeight: FontWeight.w500, + color: AppColors.greyTextColor, + ), ], ), ), SizedBox(width: 16.w), CustomButton( - height: 40.h, + height: 42.h, + width: 42.w, text: "", onPressed: () => context.navigateWithName(AppRoutes.userInfoSelection), - icon: AppAssets.arrow_forward, + icon: getIt.get().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward, ) ], ).paddingAll(24.w), @@ -493,12 +473,13 @@ class _BookAppointmentPageState extends State { regionalViewModel.flush(); regionalViewModel.setBottomSheetType(type); // AppointmentViaRegionViewmodel? viewmodel = null; - showCommonBottomSheetWithoutHeight(context, - title: "", + showCommonBottomSheetWithoutHeight(context, title: "", titleWidget: Consumer(builder: (_, data, __) => getTitle(data)), - isDismissible: false, child: Consumer(builder: (_, data, __) { - return getRegionalSelectionWidget(data); - }), callBackFunc: () {}); + isDismissible: false, + child: Consumer(builder: (_, data, __) { + return getRegionalSelectionWidget(data); + }), + callBackFunc: () {}); } Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data) { @@ -554,7 +535,7 @@ class _BookAppointmentPageState extends State { getTitle(AppointmentViaRegionViewmodel data) { if (data.selectedRegionId == null) { - return LocaleKeys.selectRegion.tr().toText20(weight: FontWeight.w600); + return LocaleKeys.selectRegion.tr(context: context).toText20(weight: FontWeight.w600); } else { return Transform.flip( flipX: data.isArabic ? true : false, @@ -581,10 +562,8 @@ class _BookAppointmentPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Immediate service".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "No need to wait, you will get medical consultation immediately via video call" - .needTranslation - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.immediateService.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.noNeedToWaitGetMedicalConsultation.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -599,7 +578,7 @@ class _BookAppointmentPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "No visit required".needTranslation.toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.noVisitRequired.tr(context: context).toText18(color: AppColors.textColor, isBold: true), LocaleKeys.livecarePoint5.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), @@ -615,10 +594,8 @@ class _BookAppointmentPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Doctor will contact".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "A specialised doctor will contact you and will be able to view your medical history" - .needTranslation - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.doctorWillContact.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.specialisedDoctorWillContactYou.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -633,10 +610,8 @@ class _BookAppointmentPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Free medicine delivery".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "Offers free medicine delivery for the LiveCare appointment" - .needTranslation - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.freeMedicineDelivery.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.offersFreeMedicineDelivery.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -644,7 +619,7 @@ class _BookAppointmentPageState extends State { ), SizedBox(height: 36.h), CustomButton( - text: "Login to use this service".needTranslation, + text: "Login to use this service", onPressed: () async { await authVM.onLoginPressed(); }, @@ -663,4 +638,53 @@ class _BookAppointmentPageState extends State { ], ).paddingSymmetrical(24.h, 0.h); } + + void showUnKnownClinicBottomSheet() { + showCommonBottomSheetWithoutHeight( + context, + title: "", + isDismissible: true, + isCloseButtonVisible: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.notSureHelpMeChooseClinic.tr(context: context).toText28(color: AppColors.textColor, isBold: true, height: 1.5), + SizedBox(height: 4.h), + LocaleKeys.mentionYourSymptomsAndFindDoctors.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500,), + SizedBox(height: 24.h), + CustomButton( + text: LocaleKeys.yesPleaseINeedHelp.tr(context: context), + onPressed: () { + context.pop(); + context.navigateWithName(AppRoutes.userInfoSelection); + }, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 56.h, + ), + SizedBox(height: 8.h), + CustomButton( + text: LocaleKeys.noThanksIKnowTheClinic.tr(context: context), + onPressed: () { + context.pop(); + }, + backgroundColor: AppColors.chipSecondaryLightRedColor, + borderColor: AppColors.chipSecondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 56.h, + ), + ], + ).paddingSymmetrical(24.w, 20.h), + callBackFunc: () {}, + ); + } } diff --git a/lib/presentation/book_appointment/dental_chief_complaints_page.dart b/lib/presentation/book_appointment/dental_chief_complaints_page.dart index 4dc3881..d2f2239 100644 --- a/lib/presentation/book_appointment/dental_chief_complaints_page.dart +++ b/lib/presentation/book_appointment/dental_chief_complaints_page.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/dental_chief_complaints_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/select_doctor_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/chief_complaint_card.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -40,7 +42,7 @@ class _DentalChiefComplaintsPageState extends State { bookAppointmentsViewModel = Provider.of(context, listen: false); appState = getIt.get(); return CollapsingListView( - title: "Dental Chief Complaints".needTranslation, + title: LocaleKeys.dentalChiefComplaints.tr(), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.h), diff --git a/lib/presentation/book_appointment/doctor_filter/doctors_filter.dart b/lib/presentation/book_appointment/doctor_filter/doctors_filter.dart index e4d11bd..d9aa9e5 100644 --- a/lib/presentation/book_appointment/doctor_filter/doctors_filter.dart +++ b/lib/presentation/book_appointment/doctor_filter/doctors_filter.dart @@ -128,7 +128,7 @@ class DoctorsFilters extends StatelessWidget{ TextInputWidget( controller: TextEditingController()..text =context.watch().selectedClinicForFilters ??'', labelText: LocaleKeys.clinicName.tr(context: context), - hintText: LocaleKeys.searchClinic.tr().needTranslation, + hintText: LocaleKeys.searchClinic.tr(), isEnable: false, prefix: null, autoFocus: false, diff --git a/lib/presentation/book_appointment/doctor_profile_page.dart b/lib/presentation/book_appointment/doctor_profile_page.dart index 5ce7fac..c62404a 100644 --- a/lib/presentation/book_appointment/doctor_profile_page.dart +++ b/lib/presentation/book_appointment/doctor_profile_page.dart @@ -1,4 +1,5 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -8,7 +9,9 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.dart'; +import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/doctor_rating_details.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -33,7 +36,7 @@ class DoctorProfilePage extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Doctor Profile".needTranslation, + title: LocaleKeys.doctorProfile.tr(), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -84,11 +87,11 @@ class DoctorProfilePage extends StatelessWidget { children: [ AppCustomChipWidget( iconColor: AppColors.ratingColorYellow, - labelText: "Branch: ${bookAppointmentsViewModel.doctorsProfileResponseModel.projectName}".needTranslation, + labelText: "${bookAppointmentsViewModel.doctorsProfileResponseModel.projectName}", ), AppCustomChipWidget( iconColor: AppColors.ratingColorYellow, - labelText: "Clinic: ${bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription}".needTranslation, + labelText: "${bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription}", ), ], ), @@ -106,9 +109,21 @@ class DoctorProfilePage extends StatelessWidget { ), SizedBox(height: 16.h), "Ratings".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), - bookAppointmentsViewModel.doctorsProfileResponseModel.decimalDoctorRate.toString().toText16(isBold: true, color: AppColors.textColor), + bookAppointmentsViewModel.doctorsProfileResponseModel.decimalDoctorRate + .toString() + .toText16(isBold: true, color: AppColors.textColor, isUnderLine: true, decorationColor: AppColors.textColor), ], - ), + ).onPress(() { + bookAppointmentsViewModel.getDoctorRatingDetails(); + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.doctorRating.tr(context: context), + context, + child: DoctorRatingDetails(), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }), SizedBox(width: 36.w), Column( children: [ @@ -120,15 +135,28 @@ class DoctorProfilePage extends StatelessWidget { ), SizedBox(height: 16.h), "Reviews".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), - bookAppointmentsViewModel.doctorsProfileResponseModel.noOfPatientsRate.toString().toText16(isBold: true, color: AppColors.textColor), + bookAppointmentsViewModel.doctorsProfileResponseModel.noOfPatientsRate + .toString() + .toText16(isBold: true, color: AppColors.textColor, isUnderLine: true, decorationColor: AppColors.textColor), ], - ), + ).onPress(() { + bookAppointmentsViewModel.getDoctorRatingDetails(); + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.doctorRating.tr(context: context), + context, + child: DoctorRatingDetails(), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }), ], ), SizedBox(height: 16.h), Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), SizedBox(height: 16.h), - "Biography".toText14(weight: FontWeight.w600, color: AppColors.textColor), + LocaleKeys.docInfo.tr(context: context).toText14(weight: FontWeight.w600, color: AppColors.textColor), + SizedBox(height: 6.h), bookAppointmentsViewModel.doctorsProfileResponseModel.doctorProfileInfo!.toText12(fontWeight: FontWeight.w600, color: AppColors.greyTextColor), ], ).paddingSymmetrical(24.h, 0.h), @@ -142,7 +170,7 @@ class DoctorProfilePage extends StatelessWidget { hasShadow: true, ), child: CustomButton( - text: "View available appointments".needTranslation, + text: LocaleKeys.viewAvailableAppointments.tr(), onPressed: () async { LoaderBottomSheet.showLoader(); bookAppointmentsViewModel.isLiveCareSchedule @@ -151,7 +179,7 @@ class DoctorProfilePage extends StatelessWidget { onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(), context, child: AppointmentCalendar(), isFullScreen: false, @@ -174,7 +202,7 @@ class DoctorProfilePage extends StatelessWidget { onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(), context, child: AppointmentCalendar(), isFullScreen: false, diff --git a/lib/presentation/book_appointment/laser/laser_appointment.dart b/lib/presentation/book_appointment/laser/laser_appointment.dart index 19a3800..3b94b0e 100644 --- a/lib/presentation/book_appointment/laser/laser_appointment.dart +++ b/lib/presentation/book_appointment/laser/laser_appointment.dart @@ -1,6 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart' show CapExtension; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; @@ -82,8 +83,8 @@ class LaserAppointment extends StatelessWidget { activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ - CustomTabBarModel(null,LocaleKeys.malE.tr()), - CustomTabBarModel(null, "Female".needTranslation), + CustomTabBarModel(null, LocaleKeys.malE.tr()), + CustomTabBarModel(null, "Female"), ], onTabChange: (index) { var viewmodel = context.read(); diff --git a/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart b/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart index 2371f4a..d522b45 100644 --- a/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart +++ b/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart @@ -18,6 +18,7 @@ import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immed import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; import 'package:hmg_patient_app_new/presentation/insurance/insurance_home_page.dart'; +import 'package:hmg_patient_app_new/services/livecare_permission_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -45,7 +46,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Review LiveCare Request".needTranslation, + title: LocaleKeys.reviewLiveCareRequest.tr(context: context), child: SingleChildScrollView( padding: EdgeInsets.symmetric(horizontal: 24.h), child: Column( @@ -80,7 +81,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { spacing: 3.h, runSpacing: 4.h, children: [ - AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old".needTranslation), + AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} ${LocaleKeys.yearsOld.tr(context: context)}"), AppCustomChipWidget( labelText: "${LocaleKeys.clinic.tr()}: ${(appState.isArabic() ? immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceNameN : immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceName)!}"), @@ -93,7 +94,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { ), ), SizedBox(height: 24.h), - "Selected LiveCare Type".needTranslation.toText16(isBold: true), + LocaleKeys.selectedLiveCareType.tr(context: context).toText16(isBold: true), SizedBox(height: 16.h), Consumer(builder: (context, bookAppointmentsVM, child) { return Container( @@ -111,7 +112,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { children: [ Utils.buildSvgWithAssets(icon: AppAssets.livecare_clinic_icon, width: 32.h, height: 32.h, fit: BoxFit.contain), SizedBox(width: 8.h), - getLiveCareType(immediateLiveCareViewModel.liveCareSelectedCallType).toText16(isBold: true), + getLiveCareType(context, immediateLiveCareViewModel.liveCareSelectedCallType).toText16(isBold: true), ], ), Utils.buildSvgWithAssets(icon: AppAssets.edit_icon, width: 24.h, height: 24.h, fit: BoxFit.contain), @@ -121,7 +122,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { ).onPress(() { showCommonBottomSheetWithoutHeight(context, child: SelectLiveCareCallType(immediateLiveCareViewModel: immediateLiveCareViewModel), callBackFunc: () async { debugPrint("Selected Call Type: ${immediateLiveCareViewModel.liveCareSelectedCallType}"); - }, title: "Select LiveCare call type".needTranslation, isCloseButtonVisible: true, isFullScreen: false); + }, title: LocaleKeys.selectLiveCareCallType.tr(context: context), isCloseButtonVisible: true, isFullScreen: false); }); }), SizedBox(height: 24.h) @@ -152,7 +153,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Insurance expired or inactive".needTranslation.toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h), + LocaleKeys.insuranceExpiredOrInactive.tr(context: context).toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h), CustomButton( text: LocaleKeys.updateInsurance.tr(context: context), onPressed: () { @@ -176,12 +177,12 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { ) : const SizedBox(), SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol(immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.amount!.toText16(isBold: true), AppColors.blackColor, 13, isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"), ], @@ -189,7 +190,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.tax!.toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, 13, isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"), @@ -208,9 +209,9 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { ? CustomButton( text: LocaleKeys.confirmLiveCare.tr(context: context), onPressed: () async { - await askVideoCallPermission().then((val) async { + await askVideoCallPermission(context).then((val) async { if (val) { - LoaderBottomSheet.showLoader(loadingText: "Confirming LiveCare request, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.confirmingLiveCareRequest.tr(context: context)); await immediateLiveCareViewModel.addNewCallRequestForImmediateLiveCare("${appState.getAuthenticatedUser()!.patientId}${DateTime.now().millisecondsSinceEpoch}"); await immediateLiveCareViewModel.getPatientLiveCareHistory(); @@ -230,7 +231,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { } else { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Unknown error occurred...".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.unknownErrorOccurred.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -241,9 +242,7 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: - "LiveCare requires Camera, Microphone, Location & Notifications permissions to enable virtual consultation between patient & doctor, Please allow these to proceed." - .needTranslation, + loadingText: LocaleKeys.liveCarePermissionsMessage.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); @@ -273,33 +272,32 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { : CustomButton( text: LocaleKeys.payNow.tr(context: context), onPressed: () async { - await askVideoCallPermission().then((val) { + await askVideoCallPermission(context).then((val) { if (val) { Navigator.of(context).push( CustomPageRoute( page: ImmediateLiveCarePaymentPage(), ), ); - } else { - showCommonBottomSheetWithoutHeight( - title: LocaleKeys.notice.tr(context: context), - context, - child: Utils.getWarningWidget( - loadingText: - "LiveCare requires Camera, Microphone, Location & Notifications permissions to enable virtual consultation between patient & doctor, Please allow these to proceed." - .needTranslation, - isShowActionButtons: true, - onCancelTap: () { - Navigator.pop(context); - }, - onConfirmTap: () async { - openAppSettings(); - }), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); } + // else { + // showCommonBottomSheetWithoutHeight( + // title: LocaleKeys.notice.tr(context: context), + // context, + // child: Utils.getWarningWidget( + // loadingText: LocaleKeys.liveCarePermissionsMessage.tr(context: context), + // isShowActionButtons: true, + // onCancelTap: () { + // Navigator.pop(context); + // }, + // onConfirmTap: () async { + // openAppSettings(); + // }), + // callBackFunc: () {}, + // isFullScreen: false, + // isCloseButtonVisible: true, + // ); + // } }); }, backgroundColor: AppColors.infoColor, @@ -322,45 +320,121 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { ); } - Future askVideoCallPermission() async { - bool hasPermission = false; - if (Platform.isIOS) { - Map statuses = await [Permission.camera, Permission.microphone].request(); + Future askVideoCallPermission(BuildContext context) async { + final statuses = await LiveCarePermissionService.instance.requestCameraMicAndNotification(context); + + // If service returned nothing (error), treat as not granted + if (statuses.isEmpty) return false; + + bool cameraGranted = statuses[Permission.camera]?.isGranted ?? false; + bool micGranted = statuses[Permission.microphone]?.isGranted ?? false; + bool notifGranted = statuses[Permission.notification]?.isGranted ?? false; - if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted) { - // Camera permission granted - hasPermission = true; - } else { - hasPermission = false; - } - } else { - Map statuses = await [Permission.camera, Permission.microphone, Permission.notification].request(); + // If all required permissions are already granted + if (cameraGranted && micGranted && notifGranted) return true; - if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted && statuses[Permission.notification] == PermissionStatus.granted) { - // Camera permission granted - hasPermission = true; - } else { - hasPermission = false; - } + // Collect only the missing permissions + final missing = []; + if (!cameraGranted) missing.add(Permission.camera); + if (!micGranted) missing.add(Permission.microphone); + if (!notifGranted) missing.add(Permission.notification); + + // If any of the missing permissions are permanently denied/restricted -> open settings (single dialog) + final permanent = missing.where((p) => (statuses[p]?.isPermanentlyDenied ?? false) || (statuses[p]?.isRestricted ?? false)).toList(); + if (permanent.isNotEmpty) { + final names = permanent.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and '); + final message = permanent.length == 1 ? '$names permission is permanently denied. Open app settings to allow it.' : '$names permissions are permanently denied. Open app settings to allow them.'; + await LiveCarePermissionService.instance.showOpenSettingsDialog( + context, + title: "Permissions Required", + message: message, + ); + return false; } - return hasPermission; + // Show one combined retry dialog for all missing permissions + final missingNames = missing.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and '); + final retry = await showDialog( + context: context, + builder: (c) => AlertDialog( + title: const Text('Permissions required'), + content: Text('$missingNames permission${missing.length > 1 ? 's are' : ' is'} required to start the video call. Retry now?'), + actions: [ + TextButton(onPressed: () => Navigator.of(c).pop(false), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.of(c).pop(true), child: const Text('Retry')), + ], + ), + ); + + if (retry != true) return false; - // if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) { - // return false; - // } + // Request only the missing permissions + final newStatuses = {}; + for (final p in missing) { + newStatuses[p] = await p.request(); + } + + // Update grant state (preserve previously granted ones) + cameraGranted = newStatuses[Permission.camera]?.isGranted ?? cameraGranted; + micGranted = newStatuses[Permission.microphone]?.isGranted ?? micGranted; + notifGranted = newStatuses[Permission.notification]?.isGranted ?? notifGranted; + + // If any requested permission is now permanently denied -> open settings + final newlyPermanent = missing.where((p) => (newStatuses[p]?.isPermanentlyDenied ?? false) || (newStatuses[p]?.isRestricted ?? false)).toList(); + if (newlyPermanent.isNotEmpty) { + final names = newlyPermanent.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and '); + final message = + newlyPermanent.length == 1 ? '$names permission is permanently denied. Open app settings to allow it.' : '$names permissions are permanently denied. Open app settings to allow them.'; + await LiveCarePermissionService.instance.showOpenSettingsDialog( + context, + title: "Permissions Required", + message: message, + ); + return false; + } + + return cameraGranted && micGranted && notifGranted; } - String getLiveCareType(int callType) { + // Future askVideoCallPermission() async { + // bool hasPermission = false; + // if (Platform.isIOS) { + // Map statuses = await [Permission.camera, Permission.microphone].request(); + // + // if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted) { + // // Camera permission granted + // hasPermission = true; + // } else { + // hasPermission = false; + // } + // } else { + // Map statuses = await [Permission.camera, Permission.microphone, Permission.notification].request(); + // + // if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted && statuses[Permission.notification] == PermissionStatus.granted) { + // // Camera permission granted + // hasPermission = true; + // } else { + // hasPermission = false; + // } + // } + // + // return hasPermission; + // + // // if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) { + // // return false; + // // } + // } + + String getLiveCareType(BuildContext context, int callType) { switch (callType) { case 1: - return "Video Call".needTranslation; + return LocaleKeys.videoCall.tr(context: context); case 2: - return "Audio Call".needTranslation; + return LocaleKeys.audioCall.tr(context: context); case 3: - return "Phone Call".needTranslation; + return LocaleKeys.phoneCall.tr(context: context); default: - return "Video Call".needTranslation; + return LocaleKeys.videoCall.tr(context: context); } } } diff --git a/lib/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart b/lib/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart index 48e79b1..73da69f 100644 --- a/lib/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart +++ b/lib/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart @@ -84,7 +84,7 @@ class _ImmediateLiveCarePaymentPageState extends State { runSpacing: 8.h, children: [ AppCustomChipWidget( - labelText: "${LocaleKeys.clinic.tr(context: context)}: ${bookAppointmentsViewModel.selectedDoctor.clinicName}".needTranslation, + labelText: "${LocaleKeys.clinic.tr(context: context)}: ${bookAppointmentsViewModel.selectedDoctor.clinicName}", ), AppCustomChipWidget( - labelText: "${LocaleKeys.branch.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.projectName}".needTranslation, + labelText: "${LocaleKeys.branch.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.projectName}", ), AppCustomChipWidget( labelText: - "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? DateUtil.formatDateToDate(DateTime.now(), false) : bookAppointmentsViewModel.selectedAppointmentDate}" - .needTranslation, + "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? DateUtil.formatDateToDate(DateTime.now(), false) : bookAppointmentsViewModel.selectedAppointmentDate}", ), AppCustomChipWidget( labelText: - "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? "Waiting Appointment".needTranslation : bookAppointmentsViewModel.selectedAppointmentTime}" - .needTranslation, + "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? LocaleKeys.waitingAppointment.tr(context: context) : bookAppointmentsViewModel.selectedAppointmentTime}", ), ], ), @@ -166,7 +164,7 @@ class _ReviewAppointmentPageState extends State { ), ), SizedBox(height: 24.h), - "Hospital Information".needTranslation.toText16(isBold: true), + LocaleKeys.hospitalInformation.tr(context: context).toText16(isBold: true), SizedBox(height: 16.h), Container( width: double.infinity, @@ -241,7 +239,7 @@ class _ReviewAppointmentPageState extends State { } void getWalkInAppointmentPatientShare() async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Appointment Share...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingAppointmentShare.tr(context: context)); await bookAppointmentsViewModel.getWalkInPatientShareAppointment(onSuccess: (val) { LoaderBottomSheet.hideLoader(); Navigator.of(context).push( @@ -262,7 +260,7 @@ class _ReviewAppointmentPageState extends State { } void initiateBookAppointment() async { - LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: "Booking your appointment...".needTranslation); + LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: LocaleKeys.bookingYourAppointment.tr(context: context)); myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true); if (bookAppointmentsViewModel.isLiveCareSchedule) { diff --git a/lib/presentation/book_appointment/search_doctor_by_name.dart b/lib/presentation/book_appointment/search_doctor_by_name.dart index d008497..fa871f5 100644 --- a/lib/presentation/book_appointment/search_doctor_by_name.dart +++ b/lib/presentation/book_appointment/search_doctor_by_name.dart @@ -34,6 +34,14 @@ class _SearchDoctorByNameState extends State { TextEditingController searchEditingController = TextEditingController(); FocusNode textFocusNode = FocusNode(); late BookAppointmentsViewModel bookAppointmentsViewModel; + late ScrollController _scrollController; + final Map _itemKeys = {}; + + @override + void initState() { + _scrollController = ScrollController(); + super.initState(); + } @override Widget build(BuildContext context) { @@ -43,8 +51,8 @@ class _SearchDoctorByNameState extends State { body: Column( children: [ Expanded( - child: CollapsingListView( - title: "Choose Doctor".needTranslation, + child: CollapsingListView( + title: LocaleKeys.chooseDoctor.tr(), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.h), @@ -76,7 +84,7 @@ class _SearchDoctorByNameState extends State { ) : null, onChange: (value) { - // bookAppointmentsViewModel.filterClinics(value!); + // bookAppointmentsViewModel.filterClinics(value!); }, padding: EdgeInsets.symmetric( vertical: ResponsiveExtension(10).h, @@ -89,43 +97,41 @@ class _SearchDoctorByNameState extends State { child: SizedBox( height: 56.h, width: 56.h, - child: DecoratedBox(decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 10.h, - hasShadow: false, - ), - child: Utils.buildSvgWithAssets(icon: AppAssets.ic_filters, - height: 24.h, - width: 24.h, ).paddingAll(16.h).onPress((){ - context.read() + child: DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 10.h, + hasShadow: false, + ), + child: Utils.buildSvgWithAssets( + icon: AppAssets.ic_filters, + height: 24.h, + width: 24.h, + ).paddingAll(16.h).onPress(() { + context.read() ..clearSelection() - ..clearSearchFilters() - ..getFiltersFromDoctorList( - bookAppointmentsViewModel.doctorsList - )..setSelections( - bookAppointmentsViewModel.selectedFacilityForFilters?.toList(), - bookAppointmentsViewModel.selectedRegionForFilters?.toList(), - bookAppointmentsViewModel.selectedClinicForFilters, - bookAppointmentsViewModel.selectedHospitalForFilters, - bookAppointmentsViewModel.applyFilters) ; - Navigator.of(context).push( - PageRouteBuilder( - pageBuilder: (context, animation, secondaryAnimation) => DoctorsFilters(), // Replace YourNewPage with your actual page widget - transitionsBuilder: (context, animation, secondaryAnimation, child) { - const begin = Offset(0.0, 1.0); // Start from the bottom (y=1.0) - const end = Offset.zero; // End at the original position (y=0.0) - final tween = Tween(begin: begin, end: end); - final offsetAnimation = animation.drive(tween); + ..clearSearchFilters() + ..getFiltersFromDoctorList(bookAppointmentsViewModel.doctorsList) + ..setSelections(bookAppointmentsViewModel.selectedFacilityForFilters?.toList(), bookAppointmentsViewModel.selectedRegionForFilters?.toList(), + bookAppointmentsViewModel.selectedClinicForFilters, bookAppointmentsViewModel.selectedHospitalForFilters, bookAppointmentsViewModel.applyFilters); + Navigator.of(context).push( + PageRouteBuilder( + pageBuilder: (context, animation, secondaryAnimation) => DoctorsFilters(), // Replace YourNewPage with your actual page widget + transitionsBuilder: (context, animation, secondaryAnimation, child) { + const begin = Offset(0.0, 1.0); // Start from the bottom (y=1.0) + const end = Offset.zero; // End at the original position (y=0.0) + final tween = Tween(begin: begin, end: end); + final offsetAnimation = animation.drive(tween); - return SlideTransition( - position: offsetAnimation, - child: child, - ); - }, - transitionDuration: Duration(milliseconds: 200), // Adjust duration as needed - ), - ); - }), + return SlideTransition( + position: offsetAnimation, + child: child, + ); + }, + transitionDuration: Duration(milliseconds: 200), // Adjust duration as needed + ), + ); + }), ), ), ) @@ -136,13 +142,50 @@ class _SearchDoctorByNameState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + if (bookAppointmentsVM.isDoctorSearchByNameStarted) + Row( + children: [ + CustomButton( + text: LocaleKeys.byClinic.tr(context: context), + onPressed: () { + bookAppointmentsVM.sortFilteredDoctorList(true); + }, + backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, + borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2), + textColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + SizedBox(width: 8.h), + CustomButton( + text: LocaleKeys.byHospital.tr(context: context), + onPressed: () { + bookAppointmentsVM.sortFilteredDoctorList(false); + }, + backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, + borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.textColor.withOpacity(0.2) : AppColors.primaryRedColor, + textColor: bookAppointmentsVM.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + ], + ).paddingSymmetrical(0.h, 0.h), bookAppointmentsVM.isDoctorSearchByNameStarted ? ListView.separated( - padding: EdgeInsets.only(top: 24.h), + padding: EdgeInsets.only(top: 20.h), shrinkWrap: true, physics: NeverScrollableScrollPhysics(), - itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : bookAppointmentsVM.filteredDoctorList.length, + itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : bookAppointmentsVM.getGroupedFilteredDoctorsList().length, itemBuilder: (context, index) { + final isExpanded = bookAppointmentsVM.expandedGroupIndex == index; + final groupedDoctors = bookAppointmentsVM.getGroupedFilteredDoctorsList(); + return bookAppointmentsVM.isDoctorsListLoading ? DoctorCard( doctorsListResponseModel: DoctorsListResponseModel(), @@ -156,35 +199,112 @@ class _SearchDoctorByNameState extends State { verticalOffset: 100.0, child: FadeInAnimation( child: AnimatedContainer( + key: _itemKeys.putIfAbsent(index, () => GlobalKey()), duration: Duration(milliseconds: 300), curve: Curves.easeInOut, decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), - child: DoctorCard( - doctorsListResponseModel: bookAppointmentsVM.filteredDoctorList[index], - isLoading: false, - bookAppointmentsViewModel: bookAppointmentsViewModel, - ).onPress(() async { - bookAppointmentsVM.setSelectedDoctor(bookAppointmentsVM.filteredDoctorList[index]); - // bookAppointmentsVM.setSelectedDoctor(DoctorsListResponseModel()); - LoaderBottomSheet.showLoader(); - await bookAppointmentsVM.getDoctorProfile(onSuccess: (dynamic respData) { - LoaderBottomSheet.hideLoader(); - Navigator.of(context).push( - CustomPageRoute( - page: DoctorProfilePage(), - ), - ); - }, onError: (err) { - LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight( - context, - child: Utils.getErrorWidget(loadingText: err), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - }); - }), + child: InkWell( + onTap: () { + bookAppointmentsVM.toggleGroupExpansion(index); + // After rebuild, ensure the expanded item is visible + WidgetsBinding.instance.addPostFrameCallback((_) { + final key = _itemKeys[index]; + if (key != null && key.currentContext != null && bookAppointmentsVM.expandedGroupIndex == index) { + Scrollable.ensureVisible( + key.currentContext!, + duration: Duration(milliseconds: 350), + curve: Curves.easeInOut, + alignment: 0.1, + ); + } + }); + }, + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + CustomButton( + text: "${groupedDoctors[index].length} ${'doctors'}", + onPressed: () {}, + backgroundColor: AppColors.greyColor, + borderColor: AppColors.greyColor, + textColor: AppColors.blackColor, + fontSize: 10, + fontWeight: FontWeight.w500, + borderRadius: 8, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 30.h), + Icon(isExpanded ? Icons.expand_less : Icons.expand_more), + ], + ), + SizedBox(height: 8.h), + // Clinic/Hospital name as group title + Text( + bookAppointmentsVM.isSortByClinic + ? (groupedDoctors[index].first.clinicName ?? 'Unknown') + : (groupedDoctors[index].first.projectName ?? 'Unknown'), + style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600), + overflow: TextOverflow.ellipsis, + ), + // Expanded content - list of doctors in this group + AnimatedSwitcher( + duration: Duration(milliseconds: 400), + child: isExpanded + ? Container( + key: ValueKey(index), + padding: EdgeInsets.only(top: 12.h), + child: Column( + children: groupedDoctors[index].asMap().entries.map((entry) { + final doctorIndex = entry.key; + final doctor = entry.value; + final isLastDoctor = doctorIndex == groupedDoctors[index].length - 1; + return Column( + children: [ + DoctorCard( + doctorsListResponseModel: doctor, + isLoading: false, + bookAppointmentsViewModel: bookAppointmentsViewModel, + ).onPress(() async { + bookAppointmentsVM.setSelectedDoctor(doctor); + LoaderBottomSheet.showLoader(); + await bookAppointmentsVM.getDoctorProfile( + onSuccess: (dynamic respData) { + LoaderBottomSheet.hideLoader(); + Navigator.of(context).push( + CustomPageRoute( + page: DoctorProfilePage(), + ), + ); + }, + onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }, + ); + }), + if (!isLastDoctor) + Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), + ], + ); + }).toList(), + ), + ) + : SizedBox.shrink(), + ), + ], + ), + ), + ), ), ), ), @@ -261,8 +381,10 @@ class _SearchDoctorByNameState extends State { ), ); } + @override void dispose() { + _scrollController.dispose(); bookAppointmentsViewModel.doctorsList.clear(); super.dispose(); } diff --git a/lib/presentation/book_appointment/select_clinic_page.dart b/lib/presentation/book_appointment/select_clinic_page.dart index 48c0cd5..ac40d69 100644 --- a/lib/presentation/book_appointment/select_clinic_page.dart +++ b/lib/presentation/book_appointment/select_clinic_page.dart @@ -79,7 +79,7 @@ class _SelectClinicPageState extends State { decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.only(topLeft: Radius.circular(24.r), topRight: Radius.circular(24.r))), padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 20.h), child: CustomButton( - text: LocaleKeys.bookAppo.tr(), + text: LocaleKeys.bookAppo.tr(context: context), onPressed: () { if (widget.calculatedResult["clinicId"] == null) { bookAppointmentsViewModel.setIsDoctorsListLoading(true); @@ -103,7 +103,7 @@ class _SelectClinicPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: bookAppointmentsViewModel.isLiveCareSchedule ? "Select LiveCare Clinic".needTranslation : LocaleKeys.selectClinic.tr(context: context), + title: bookAppointmentsViewModel.isLiveCareSchedule ? LocaleKeys.selectLiveCareClinic.tr(context: context) : LocaleKeys.selectClinic.tr(context: context), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.h), @@ -941,7 +941,7 @@ class _SelectClinicPageState extends State { void onLiveCareClinicSelected(GetLiveCareClinicsResponseModel clinic) { bookAppointmentsViewModel.setLiveCareSelectedClinic(clinic); - bookAppointmentsViewModel.setIsDoctorsListLoading(true); + bookAppointmentsViewModel.setIsLiveCareDoctorsListLoading(true); Navigator.of(context).push( CustomPageRoute( page: SelectDoctorPage(), @@ -1097,7 +1097,7 @@ class _SelectClinicPageState extends State { getTitle(AppointmentViaRegionViewmodel data) { if (data.selectedRegionId == null) { - return LocaleKeys.selectRegion.tr().toText20(weight: FontWeight.w600); + return LocaleKeys.selectRegion.tr(context: context).toText20(weight: FontWeight.w600); } else { return Transform.flip( flipX: data.isArabic ? true : false, @@ -1114,18 +1114,18 @@ class _SelectClinicPageState extends State { void initDentalAppointmentBookingFlow(int projectID) async { bookAppointmentsViewModel.setProjectID(projectID.toString()); - LoaderBottomSheet.showLoader(loadingText: "Checking for an existing dental plan, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingForExistingDentalPlan.tr(context: context)); await bookAppointmentsViewModel.getPatientDentalEstimation(projectID: projectID).then((value) { LoaderBottomSheet.hideLoader(); if (bookAppointmentsViewModel.patientDentalPlanEstimationList.isNotEmpty) { showCommonBottomSheetWithoutHeight( // title: LocaleKeys.notice.tr(context: context), - title: "Dental treatment plan".needTranslation, + title: LocaleKeys.dentalTreatmentPlan.tr(context: context), context, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "You have an existing treatment plan: ".needTranslation.toText14(weight: FontWeight.w500), + LocaleKeys.youHaveExistingTreatmentPlan.tr(context: context).toText14(weight: FontWeight.w500), SizedBox(height: 8.h), Container( width: double.infinity, @@ -1156,7 +1156,7 @@ class _SelectClinicPageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ bookAppointmentsViewModel.patientDentalPlanEstimationList[index].procedureName!.toText12(isBold: true), - AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} Mins".needTranslation), + AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "${bookAppointmentsViewModel.totalTimeNeededForDentalProcedure} ${LocaleKeys.mins.tr(context: context)}"), ], ); }, @@ -1171,21 +1171,21 @@ class _SelectClinicPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Total time required".needTranslation.toText14(isBold: true), - AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "30 Mins".needTranslation), + LocaleKeys.totalTimeRequired.tr(context: context).toText14(isBold: true), + AppCustomChipWidget(icon: AppAssets.appointment_time_icon, labelText: "30 ${LocaleKeys.mins.tr(context: context)}"), ], ) ], ), ), SizedBox(height: 16.h), - "Would you like to continue it?".needTranslation.toText14(weight: FontWeight.w500), + LocaleKeys.wouldYouLikeToContinue.tr(context: context).toText14(weight: FontWeight.w500), SizedBox(height: 16.h), Row( children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), onPressed: () { bookAppointmentsViewModel.setIsContinueDentalPlan(false); bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true); @@ -1206,14 +1206,12 @@ class _SelectClinicPageState extends State { SizedBox(width: 8.h), Expanded( child: CustomButton( - text: LocaleKeys.confirm.tr(), + text: LocaleKeys.confirm.tr(context: context), onPressed: () async { bookAppointmentsViewModel.setIsContinueDentalPlan(true); Navigator.of(context).pop(); Navigator.of(context).push( - CustomPageRoute( - page: SelectDoctorPage(), - ), + CustomPageRoute(page: SelectDoctorPage()), ); }, backgroundColor: AppColors.bgGreenColor, diff --git a/lib/presentation/book_appointment/select_doctor_page.dart b/lib/presentation/book_appointment/select_doctor_page.dart index d77e152..f8a0ad9 100644 --- a/lib/presentation/book_appointment/select_doctor_page.dart +++ b/lib/presentation/book_appointment/select_doctor_page.dart @@ -33,16 +33,13 @@ class SelectDoctorPage extends StatefulWidget { class _SelectDoctorPageState extends State { TextEditingController searchEditingController = TextEditingController(); - int? expandedIndex; FocusNode textFocusNode = FocusNode(); late AppState appState; late BookAppointmentsViewModel bookAppointmentsViewModel; - // Scroll controller to control page scrolling when a group expands late ScrollController _scrollController; - // Map of keys for each item to allow scrolling to them final Map _itemKeys = {}; @override @@ -78,15 +75,79 @@ class _SelectDoctorPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Choose Doctor".needTranslation, + title: LocaleKeys.chooseDoctor.tr(), + // bottomChild: Container( + // decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, customBorder: BorderRadius.only(topLeft: Radius.circular(24.r), topRight: Radius.circular(24.r))), + // padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 20.h), + // child: CustomButton( + // text: LocaleKeys.search.tr(), + // onPressed: () { + // }, + // icon: null, + // fontSize: 16.f, + // backgroundColor: AppColors.primaryRedColor, + // borderColor: AppColors.primaryRedColor, + // borderRadius: 12.r, + // fontWeight: FontWeight.w500), + // ), child: SingleChildScrollView( controller: _scrollController, child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.h), child: Consumer(builder: (context, bookAppointmentsVM, child) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ + return bookAppointmentsViewModel.isLiveCareSchedule + ? Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListView.separated( + padding: EdgeInsets.only(top: 16.h), + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : (bookAppointmentsVM.liveCareDoctorsList.isNotEmpty ? bookAppointmentsVM.liveCareDoctorsList.length : 1), + itemBuilder: (context, index) { + // final isExpanded = bookAppointmentsVM.expandedGroupIndex == index; + final isExpanded = true; + return bookAppointmentsVM.isDoctorsListLoading + ? DoctorCard( + doctorsListResponseModel: DoctorsListResponseModel(), + isLoading: true, + bookAppointmentsViewModel: bookAppointmentsViewModel, + ) + : bookAppointmentsVM.liveCareDoctorsList.isEmpty + ? Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDoctorFound.tr()) + : AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + verticalOffset: 100.0, + child: FadeInAnimation( + child: AnimatedContainer( + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), + child: Padding( + padding: EdgeInsets.all(16.h), + child: DoctorCard( + isLoading: bookAppointmentsVM.isClinicsListLoading, + doctorsListResponseModel: bookAppointmentsVM.liveCareDoctorsList[index], + bookAppointmentsViewModel: bookAppointmentsViewModel, + ).onPress(() { + // onLiveCareClinicSelected(bookAppointmentsVM.liveCareClinicsList[index]); + }), + ), + ), + ), + ), + ); + }, + separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), + ), + SizedBox(height: 24.h), + ], + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ SizedBox(height: 16.h), Row( spacing: 8.h, @@ -124,40 +185,41 @@ class _SelectDoctorPageState extends State { ], ), SizedBox(height: 16.h), - Row( - children: [ - CustomButton( - text: LocaleKeys.byClinic.tr(context: context), - onPressed: () { - bookAppointmentsVM.setIsSortByClinic(true); - }, - backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, - borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2), - textColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, - fontSize: 12, - fontWeight: FontWeight.w500, - borderRadius: 10, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - ), - SizedBox(width: 8.h), - CustomButton( - text: LocaleKeys.byHospital.tr(context: context), - onPressed: () { - bookAppointmentsVM.setIsSortByClinic(false); - }, - backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, - borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.textColor.withOpacity(0.2) : AppColors.primaryRedColor, - textColor: bookAppointmentsVM.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, - fontSize: 12, - fontWeight: FontWeight.w500, - borderRadius: 10, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - ), - ], - ).paddingSymmetrical(0.h, 0.h), - SizedBox(height: 16.h), + if (bookAppointmentsViewModel.isGetDocForHealthCal && bookAppointmentsVM.showSortFilterButtons) + Row( + children: [ + CustomButton( + text: LocaleKeys.byClinic.tr(context: context), + onPressed: () { + bookAppointmentsVM.setIsSortByClinic(true); + }, + backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, + borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2), + textColor: bookAppointmentsVM.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + SizedBox(width: 8.h), + CustomButton( + text: LocaleKeys.byHospital.tr(context: context), + onPressed: () { + bookAppointmentsVM.setIsSortByClinic(false); + }, + backgroundColor: bookAppointmentsVM.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, + borderColor: bookAppointmentsVM.isSortByClinic ? AppColors.textColor.withOpacity(0.2) : AppColors.primaryRedColor, + textColor: bookAppointmentsVM.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + ], + ).paddingSymmetrical(0.h, 0.h), + if (bookAppointmentsViewModel.isGetDocForHealthCal && bookAppointmentsVM.showSortFilterButtons) SizedBox(height: 16.h), Row( mainAxisSize: MainAxisSize.max, children: [ @@ -166,7 +228,7 @@ class _SelectDoctorPageState extends State { children: [ LocaleKeys.nearestAppo.tr(context: context).toText13(isBold: true), SizedBox(height: 4.h), - "View nearest available appointments".needTranslation.toText11(color: AppColors.textColorLight, weight: FontWeight.w500), + LocaleKeys.viewNearestAppos.tr(context: context).toText11(color: AppColors.textColorLight, weight: FontWeight.w500), ], ), const Spacer(), @@ -176,7 +238,6 @@ class _SelectDoctorPageState extends State { value: bookAppointmentsVM.isNearestAppointmentSelected, onChanged: (newValue) async { bookAppointmentsVM.setIsNearestAppointmentSelected(newValue); - }, ), ], @@ -185,11 +246,10 @@ class _SelectDoctorPageState extends State { padding: EdgeInsets.only(top: 16.h), shrinkWrap: true, physics: NeverScrollableScrollPhysics(), - itemCount: bookAppointmentsVM.isDoctorsListLoading - ? 5 - : (bookAppointmentsVM.doctorsListGrouped.isNotEmpty ? bookAppointmentsVM.doctorsListGrouped.length : 1), + itemCount: bookAppointmentsVM.isDoctorsListLoading ? 5 : (bookAppointmentsVM.doctorsListGrouped.isNotEmpty ? bookAppointmentsVM.doctorsListGrouped.length : 1), itemBuilder: (context, index) { - final isExpanded = expandedIndex == index; + // final isExpanded = bookAppointmentsVM.expandedGroupIndex == index; + final isExpanded = true; return bookAppointmentsVM.isDoctorsListLoading ? DoctorCard( doctorsListResponseModel: DoctorsListResponseModel(), @@ -197,7 +257,7 @@ class _SelectDoctorPageState extends State { bookAppointmentsViewModel: bookAppointmentsViewModel, ) : bookAppointmentsVM.doctorsListGrouped.isEmpty - ? Utils.getNoDataWidget(context, noDataText: "No Doctor found for selected criteria...".needTranslation) + ? Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDoctorFound.tr()) : AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), @@ -211,13 +271,11 @@ class _SelectDoctorPageState extends State { decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), child: InkWell( onTap: () { - setState(() { - expandedIndex = isExpanded ? null : index; - }); + bookAppointmentsVM.toggleGroupExpansion(index); // After rebuild, ensure the expanded item is visible WidgetsBinding.instance.addPostFrameCallback((_) { final key = _itemKeys[index]; - if (key != null && key.currentContext != null && expandedIndex == index) { + if (key != null && key.currentContext != null && bookAppointmentsVM.expandedGroupIndex == index) { Scrollable.ensureVisible( key.currentContext!, duration: Duration(milliseconds: 350), @@ -237,7 +295,7 @@ class _SelectDoctorPageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomButton( - text: "${bookAppointmentsVM.doctorsListGrouped[index].length} ${'doctors'.needTranslation}", + text: "${bookAppointmentsVM.doctorsListGrouped[index].length} ${'doctors'}", onPressed: () {}, backgroundColor: AppColors.greyColor, borderColor: AppColors.greyColor, @@ -268,34 +326,41 @@ class _SelectDoctorPageState extends State { key: ValueKey(index), padding: EdgeInsets.only(top: 12.h), child: Column( - children: bookAppointmentsVM.doctorsListGrouped[index].map((doctor) { - return Container( - margin: EdgeInsets.only(bottom: 12.h), - child: DoctorCard( - doctorsListResponseModel: doctor, - isLoading: false, - bookAppointmentsViewModel: bookAppointmentsViewModel, - ).onPress(() async { - bookAppointmentsVM.setSelectedDoctor(doctor); - LoaderBottomSheet.showLoader(); - await bookAppointmentsVM.getDoctorProfile(onSuccess: (dynamic respData) { - LoaderBottomSheet.hideLoader(); - Navigator.of(context).push( - CustomPageRoute( - page: DoctorProfilePage(), - ), - ); - }, onError: (err) { - LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight( - context, - child: Utils.getErrorWidget(loadingText: err), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - }); - }), + children: bookAppointmentsVM.doctorsListGrouped[index].asMap().entries.map((entry) { + final doctorIndex = entry.key; + final doctor = entry.value; + final isLastDoctor = doctorIndex == bookAppointmentsVM.doctorsListGrouped[index].length - 1; + + return Column( + children: [ + DoctorCard( + doctorsListResponseModel: doctor, + isLoading: false, + bookAppointmentsViewModel: bookAppointmentsViewModel, + ).onPress(() async { + bookAppointmentsVM.setSelectedDoctor(doctor); + LoaderBottomSheet.showLoader(); + await bookAppointmentsVM.getDoctorProfile(onSuccess: (dynamic respData) { + LoaderBottomSheet.hideLoader(); + Navigator.of(context).push( + CustomPageRoute( + page: DoctorProfilePage(), + ), + ); + }, onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + }), + if (!isLastDoctor) + Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), + ], ); }).toList(), ), diff --git a/lib/presentation/book_appointment/select_livecare_clinic_page.dart b/lib/presentation/book_appointment/select_livecare_clinic_page.dart index 502e38d..87ab0eb 100644 --- a/lib/presentation/book_appointment/select_livecare_clinic_page.dart +++ b/lib/presentation/book_appointment/select_livecare_clinic_page.dart @@ -54,8 +54,8 @@ class SelectLivecareClinicPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Immediate service".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "No need to wait, you will get medical consultation immediately via video call".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.immediateService.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.noNeedToWaitGetMedicalConsultation.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -70,7 +70,7 @@ class SelectLivecareClinicPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "No visit required".needTranslation.toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.noVisitRequired.tr(context: context).toText18(color: AppColors.textColor, isBold: true), LocaleKeys.livecarePoint5.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), @@ -86,8 +86,8 @@ class SelectLivecareClinicPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Doctor will contact".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "A specialised doctor will contact you and will be able to view your medical history".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.doctorWillContact.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.specialisedDoctorWillContactYou.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -102,8 +102,8 @@ class SelectLivecareClinicPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Free medicine delivery".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "Offers free medicine delivery for the LiveCare appointment".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.freeMedicineDelivery.tr(context: context).toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.offersFreeMedicineDelivery.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -117,7 +117,7 @@ class SelectLivecareClinicPage extends StatelessWidget { Column( children: [ CustomButton( - text: "Yes please, I am in a hurry".needTranslation, + text: LocaleKeys.yesPleasImInAHurry.tr(context: context), onPressed: () async { Navigator.pop(context); GetLiveCareClinicListResponseModel liveCareClinic = GetLiveCareClinicListResponseModel( @@ -129,7 +129,7 @@ class SelectLivecareClinicPage extends StatelessWidget { immediateLiveCareViewModel.setLiveCareSelectedCallType(1); immediateLiveCareViewModel.setImmediateLiveCareSelectedClinic(liveCareClinic); - LoaderBottomSheet.showLoader(loadingText: "Fetching fees, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingFeesPleaseWait.tr(context: context)); await immediateLiveCareViewModel.getLiveCareImmediateAppointmentFees(onSuccess: (val) { LoaderBottomSheet.hideLoader(); Navigator.of(getIt.get().navigatorKey.currentContext!).push( @@ -162,7 +162,7 @@ class SelectLivecareClinicPage extends StatelessWidget { ).paddingSymmetrical(24.h, 0.h), SizedBox(height: 16.h), CustomButton( - text: "No, Thanks. I would like a physical visit".needTranslation, + text: LocaleKeys.noThanksPhysicalVisit.tr(context: context), onPressed: () { Navigator.of(context).pop(); onNegativeClicked?.call(); diff --git a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart index f832db6..19d0fb4 100644 --- a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart @@ -28,7 +28,7 @@ class WaitingAppointmentInfo extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Waiting Appointment".needTranslation, + title: LocaleKeys.waitingAppointment.tr(), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -47,13 +47,11 @@ class WaitingAppointmentInfo extends StatelessWidget { children: [ Utils.buildSvgWithAssets(icon: AppAssets.waiting_appointment_icon, width: 48.h, height: 48.h, fit: BoxFit.contain), SizedBox(height: 16.h), - "What is Waiting Appointment?".needTranslation.toText16(isBold: true), + LocaleKeys.whatIsWaitingAppointment.tr(context: context).toText16(isBold: true), SizedBox(height: 16.h), - "The waiting appointments feature allows you to book an appointment while you are inside the hospital building, and in case there is no available slot in the doctor’s schedule." - .needTranslation - .toText14(isBold: false), + LocaleKeys.waitingAppointmentsFeature.tr(context: context).toText14(isBold: false), SizedBox(height: 16.h), - "The appointment with the doctor is confirmed, but the time of entry is uncertain.".needTranslation.toText14(isBold: false), + LocaleKeys.appointmentWithDoctorConfirmed.tr(context: context).toText14(isBold: false), SizedBox(height: 24.h), Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -66,9 +64,7 @@ class WaitingAppointmentInfo extends StatelessWidget { SizedBox(width: 10.w), SizedBox( width: MediaQuery.of(context).size.width * 0.7, - child: "Note: You must have to pay within 10 minutes of booking, otherwise your appointment will be cancelled automatically" - .needTranslation - .toText14(isBold: true, color: AppColors.warningColorYellow), + child: LocaleKeys.paymentWithinTenMinutes.tr(context: context).toText14(isBold: true, color: AppColors.warningColorYellow), ), ], ), @@ -88,7 +84,7 @@ class WaitingAppointmentInfo extends StatelessWidget { hasShadow: true, ), child: CustomButton( - text: "Continue".needTranslation, + text: LocaleKeys.continueString.tr(), onPressed: () async { showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.onlineCheckIn.tr(), diff --git a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_online_checkin_sheet.dart b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_online_checkin_sheet.dart index 5451df9..3b16825 100644 --- a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_online_checkin_sheet.dart +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_online_checkin_sheet.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_nfc_kit/flutter_nfc_kit.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -10,6 +11,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/review_appointment_page.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; // import 'package:barcode_scan2/barcode_scan2.dart'; @@ -42,14 +44,9 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { children: [ checkInOptionCard( AppAssets.checkin_location_icon, - "Live Location".needTranslation, - "Verify your location to be at hospital to check in".needTranslation, + LocaleKeys.liveLocation.tr(), + LocaleKeys.verifyYourLocationAtHospital.tr(), ).onPress(() { - // locationUtils = LocationUtils( - // isShowConfirmDialog: false, - // navigationService: myAppointmentsViewModel.navigationService, - // appState: myAppointmentsViewModel.appState, - // ); locationUtils.getCurrentLocation(onSuccess: (value) { projectDetailListModel = Utils.getProjectDetailObj(appState, bookAppointmentsViewModel.waitingAppointmentProjectID); double dist = Utils.distance(value.latitude, value.longitude, double.parse(projectDetailListModel.latitude!), double.parse(projectDetailListModel.longitude!)).ceilToDouble() * 1000; @@ -58,8 +55,8 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { checkScannedNFCAndQRCode(projectDetailListModel.checkInQrCode!, context); } else { showCommonBottomSheetWithoutHeight(context, - title: "Error".needTranslation, - child: Utils.getErrorWidget(loadingText: "Please ensure you're within the hospital location to perform online check-in.".needTranslation), callBackFunc: () { + title: LocaleKeys.error.tr(), + child: Utils.getErrorWidget(loadingText: LocaleKeys.ensureWithinHospitalLocation.tr()), callBackFunc: () { Navigator.of(context).pop(); }, isFullScreen: false); } @@ -68,8 +65,8 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_nfc_icon, - "NFC (Near Field Communication)".needTranslation, - "Scan your phone via NFC board to check in".needTranslation, + LocaleKeys.nfcNearFieldCommunication.tr(), + LocaleKeys.scanPhoneViaNFC.tr(), ).onPress(() { Future.delayed(const Duration(milliseconds: 500), () { showNfcReader(context, onNcfScan: (String nfcId) { @@ -82,8 +79,8 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_qr_icon, - "QR Code".needTranslation, - "Scan QR code with your camera to check in".needTranslation, + LocaleKeys.qrCode.tr(), + LocaleKeys.scanQRCodeToCheckIn.tr() ).onPress(() async { // String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent)); // if (onlineCheckInQRCode != "") { @@ -136,7 +133,7 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { } void checkScannedNFCAndQRCode(String scannedCode, BuildContext context) async { - LoaderBottomSheet.showLoader(loadingText: "Processing Check-In...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingCheckIn.tr()); bookAppointmentsViewModel.checkScannedNFCAndQRCode( scannedCode, bookAppointmentsViewModel.waitingAppointmentProjectID, @@ -152,7 +149,7 @@ class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { }, onError: (err) { LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight(context, title: "Error".needTranslation, child: Utils.getErrorWidget(loadingText: err), callBackFunc: () { + showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.error.tr(), child: Utils.getErrorWidget(loadingText: err), callBackFunc: () { // Navigator.of(context).pop(); }, isFullScreen: false); }, diff --git a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart index 8cfe6dd..ca60e9e 100644 --- a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart @@ -94,7 +94,7 @@ class _WaitingAppointmentPaymentPageState extends State { ), SizedBox(height: 16.h), CustomButton( - text: "Select".needTranslation, + text: LocaleKeys.select.tr(context: context), onPressed: () async { if (appState.isAuthenticated) { - if(selectedTime == "Waiting Appointment".needTranslation){ + if(selectedTime == LocaleKeys.waitingAppointment.tr(context: context)){ bookAppointmentsViewModel.setWaitingAppointmentProjectID(bookAppointmentsViewModel.selectedDoctor.projectID!); bookAppointmentsViewModel.setWaitingAppointmentDoctor(bookAppointmentsViewModel.selectedDoctor); @@ -204,13 +204,13 @@ class _AppointmentCalendarState extends State { children: [ Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), SizedBox(height: 8.h), - (LocaleKeys.loginToUseService.tr()).toText16(color: AppColors.blackColor), + (LocaleKeys.loginToUseService.tr(context: context)).toText16(color: AppColors.blackColor), SizedBox(height: 16.h), Row( children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), onPressed: () { Navigator.of(context).pop(); }, @@ -224,7 +224,7 @@ class _AppointmentCalendarState extends State { SizedBox(width: 8.h), Expanded( child: CustomButton( - text: LocaleKeys.confirm.tr(), + text: LocaleKeys.confirm.tr(context: context), onPressed: () async { Navigator.of(context).pop(); Navigator.pushAndRemoveUntil( @@ -293,7 +293,7 @@ class _AppointmentCalendarState extends State { dayEvents.clear(); DateTime dateStartObj = new DateTime(dateStart.year, dateStart.month, dateStart.day, 0, 0, 0, 0, 0); if (bookAppointmentsViewModel.isWaitingAppointmentAvailable && DateUtils.isSameDay(dateStart, DateTime.now())) { - dayEvents.add(TimeSlot(isoTime: "Waiting Appointment".needTranslation, start: DateTime.now(), end: DateTime.now(), vidaDate: "")); + dayEvents.add(TimeSlot(isoTime: LocaleKeys.waitingAppointment.tr(context: context), start: DateTime.now(), end: DateTime.now(), vidaDate: "")); } freeSlots.forEach((v) { if (v.start == dateStartObj) dayEvents.add(v); @@ -332,7 +332,7 @@ class TimeSlotChip extends StatelessWidget { Widget build(BuildContext context) { return GestureDetector( onTap: onTap, - child: label == "Waiting Appointment".needTranslation + child: label == LocaleKeys.waitingAppointment.tr(context: context) ? Container( padding: EdgeInsets.symmetric(horizontal: 14.h, vertical: 8.h), decoration: ShapeDecoration( diff --git a/lib/presentation/book_appointment/widgets/clinic_card.dart b/lib/presentation/book_appointment/widgets/clinic_card.dart index cab3b1a..7e3c8df 100644 --- a/lib/presentation/book_appointment/widgets/clinic_card.dart +++ b/lib/presentation/book_appointment/widgets/clinic_card.dart @@ -32,9 +32,9 @@ class ClinicCard extends StatelessWidget { child: Column( children: [ Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Utils.buildSvgWithAssets(icon: AppAssets.generic_clinic_icon, width: 24.h, height: 24.h, fit: BoxFit.contain).toShimmer2(isShow: isLoading), + Utils.buildSvgWithAssets(icon: "assets/images/clinicIcons/${clinicsListResponseModel.clinicID ?? 1}.svg", width: 24.w, height: 24.h, fit: BoxFit.contain).toShimmer2(isShow: isLoading), (clinicsListResponseModel.isLiveCareClinicAndOnline ?? true) - ? Utils.buildSvgWithAssets(icon: AppAssets.livecare_clinic_icon, width: 32.h, height: 32.h, fit: BoxFit.contain).toShimmer2(isShow: isLoading) + ? Utils.buildSvgWithAssets(icon: AppAssets.livecare_clinic_icon, width: 32.w, height: 32.h, fit: BoxFit.contain).toShimmer2(isShow: isLoading) : SizedBox.shrink(), ], ), diff --git a/lib/presentation/book_appointment/widgets/doctor_card.dart b/lib/presentation/book_appointment/widgets/doctor_card.dart index ffe26ff..e2009bb 100644 --- a/lib/presentation/book_appointment/widgets/doctor_card.dart +++ b/lib/presentation/book_appointment/widgets/doctor_card.dart @@ -38,20 +38,49 @@ class DoctorCard extends StatelessWidget { hasShadow: false, ), child: Padding( - padding: EdgeInsets.all(14.h), + padding: EdgeInsets.only(top: 14.h,bottom: 20.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Image.network( - isLoading - ? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png" - : doctorsListResponseModel.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png", - width: 63.h, - height: 63.h, - fit: BoxFit.cover, - ).circle(100).toShimmer2(isShow: isLoading), + Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + isLoading + ? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png" + : doctorsListResponseModel.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png", + width: 63.h, + height: 63.h, + fit: BoxFit.cover, + ).circle(100).toShimmer2(isShow: isLoading), + Transform.translate( + offset: Offset(0.0, -20.h), + child: Container( + width: 40.w, + height: 40.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + shape: BoxShape.circle, // Makes the container circular + border: Border.all( + color: AppColors.scaffoldBgColor, // Color of the border + width: 1.5.w, // Width of the border + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.rating_icon, width: 15.w, height: 15.h), + SizedBox(height: 2.h), + "${isLoading ? 4.78 : doctorsListResponseModel.decimalDoctorRate}".toText11(isBold: true, color: AppColors.textColor), + ], + ), + ).circle(100).toShimmer2(isShow: isLoading), + ), + ], + ), SizedBox(width: 8.h), Expanded( flex: 9, @@ -61,7 +90,7 @@ class DoctorCard extends StatelessWidget { Row( children: [ SizedBox( - width: MediaQuery.of(context).size.width * 0.49, + width: MediaQuery.of(context).size.width * 0.55, child: (isLoading ? "Dr John Smith" : "${doctorsListResponseModel.doctorTitle} ${doctorsListResponseModel.name}") .toString() .toText16(isBold: true, maxlines: 1), @@ -71,14 +100,18 @@ class DoctorCard extends StatelessWidget { SizedBox(height: 2.h), Row( children: [ - (isLoading - ? "Consultant Cardiologist" - : doctorsListResponseModel.speciality!.isNotEmpty - ? doctorsListResponseModel.speciality!.first - : "") - .toString() - .toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor, maxLine: 1) - .toShimmer2(isShow: isLoading), + SizedBox( + child: (isLoading + ? "Consultant Cardiologist" + : doctorsListResponseModel.speciality!.isNotEmpty + ? (doctorsListResponseModel.speciality!.first.length > 32 + ? '${doctorsListResponseModel.speciality!.first.substring(0, 32)}...' + : doctorsListResponseModel.speciality!.first) + : "") + .toString() + .toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor, maxLine: 2) + .toShimmer2(isShow: isLoading), + ), SizedBox(width: 6.w), Image.network( isLoading ? "https://hmgwebservices.com/Images/flag/SYR.png" : doctorsListResponseModel.nationalityFlagURL ?? "https://hmgwebservices.com/Images/flag/SYR.png", @@ -88,6 +121,29 @@ class DoctorCard extends StatelessWidget { ).toShimmer2(isShow: isLoading), ], ), + SizedBox(height: 6.h), + Wrap( + direction: Axis.horizontal, + spacing: 3.h, + runSpacing: 4.h, + children: [ + AppCustomChipWidget( + labelText: "${isLoading ? "Cardiologist" : doctorsListResponseModel.clinicName}", + ).toShimmer2(isShow: isLoading), + AppCustomChipWidget( + labelText: "${isLoading ? "Olaya Hospital" : doctorsListResponseModel.projectName}", + ).toShimmer2(isShow: isLoading), + bookAppointmentsViewModel.isNearestAppointmentSelected + ? doctorsListResponseModel.nearestFreeSlot != null + ? AppCustomChipWidget( + labelText: (isLoading ? "Cardiologist" : DateUtil.getDateStringForNearestSlot(doctorsListResponseModel.nearestFreeSlot)), + backgroundColor: AppColors.successColor, + textColor: AppColors.whiteColor, + ).toShimmer2(isShow: isLoading) + : SizedBox.shrink() + : SizedBox.shrink(), + ], + ), ], ), ), @@ -99,34 +155,6 @@ class DoctorCard extends StatelessWidget { ], ), SizedBox(height: 12.h), - Wrap( - direction: Axis.horizontal, - spacing: 3.h, - runSpacing: 4.h, - children: [ - AppCustomChipWidget( - labelText: "Clinic: ${isLoading ? "Cardiologist" : doctorsListResponseModel.clinicName}".needTranslation, - ).toShimmer2(isShow: isLoading), - AppCustomChipWidget( - labelText: "Branch: ${isLoading ? "Olaya Hospital" : doctorsListResponseModel.projectName}".needTranslation, - ).toShimmer2(isShow: isLoading), - doctorsListResponseModel.decimalDoctorRate != null ? AppCustomChipWidget( - icon: AppAssets.rating_icon, - iconColor: AppColors.ratingColorYellow, - labelText: "Rating: ${isLoading ? 4.78 : doctorsListResponseModel.decimalDoctorRate}".needTranslation, - ).toShimmer2(isShow: isLoading) : SizedBox(), - bookAppointmentsViewModel.isNearestAppointmentSelected - ? doctorsListResponseModel.nearestFreeSlot != null - ? AppCustomChipWidget( - labelText: (isLoading ? "Cardiologist" : DateUtil.getDateStringForNearestSlot(doctorsListResponseModel.nearestFreeSlot)).needTranslation, - backgroundColor: AppColors.successColor, - textColor: AppColors.whiteColor, - ).toShimmer2(isShow: isLoading) - : SizedBox.shrink() - : SizedBox.shrink(), - ], - ), - SizedBox(height: 12.h), CustomButton( text: LocaleKeys.bookAppo.tr(context: context), onPressed: () async { @@ -138,7 +166,7 @@ class DoctorCard extends StatelessWidget { onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(context: context), context, child: AppointmentCalendar(), isFullScreen: false, @@ -161,7 +189,7 @@ class DoctorCard extends StatelessWidget { onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(context: context), context, child: AppointmentCalendar(), isFullScreen: false, diff --git a/lib/presentation/book_appointment/widgets/doctor_rating_details.dart b/lib/presentation/book_appointment/widgets/doctor_rating_details.dart new file mode 100644 index 0000000..0ed5486 --- /dev/null +++ b/lib/presentation/book_appointment/widgets/doctor_rating_details.dart @@ -0,0 +1,195 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_rating_bar/flutter_rating_bar.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:provider/provider.dart'; + +class DoctorRatingDetails extends StatelessWidget { + const DoctorRatingDetails({super.key}); + + @override + Widget build(BuildContext context) { + return Consumer(builder: (context, bookAppointmentsVM, child) { + return bookAppointmentsVM.isDoctorRatingDetailsLoading + ? Utils.getLoadingWidget() + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + bookAppointmentsVM.doctorsProfileResponseModel.actualDoctorRate!.ceilToDouble().toString().toText44(isBold: true), + SizedBox(height: 4.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "${bookAppointmentsVM.doctorsProfileResponseModel.noOfPatientsRate} ${LocaleKeys.reviews.tr(context: context)}" + .toText16(weight: FontWeight.w500, color: AppColors.greyInfoTextColor), + RatingBar( + initialRating: bookAppointmentsVM.doctorsProfileResponseModel.actualDoctorRate!.toDouble(), + direction: Axis.horizontal, + allowHalfRating: true, + itemCount: 5, + itemSize: 20.h, + ignoreGestures: true, + ratingWidget: RatingWidget( + full: Icon( + Icons.star, + color: AppColors.ratingColorYellow, + size: 24.h, + ), + half: Icon( + Icons.star_half, + color: AppColors.ratingColorYellow, + ), + empty: Icon( + Icons.star, + color: AppColors.ratingColorYellow, + ), + ), + tapOnlyMode: true, + unratedColor: Colors.grey[500], + itemPadding: EdgeInsets.symmetric(horizontal: 4.0), + onRatingUpdate: (rating) { + print(rating); + }, + ), + ], + ), + SizedBox(height: 8.h), + Container( + margin: EdgeInsets.only(top: 10.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 100.0, + margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0), + child: Text(LocaleKeys.excellent.tr(context: context), style: TextStyle(fontSize: 13.0, color: Colors.black, fontWeight: FontWeight.w600))), + getRatingLine(bookAppointmentsVM.doctorDetailsList[0].ratio, Colors.green[700]!), + ], + ), + Container( + margin: EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0), + child: Text("${getRatingWidth(bookAppointmentsVM.doctorDetailsList[0].ratio).round()}%", style: TextStyle(fontSize: 14.0, color: Colors.black, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + Container( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 100.0, + margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0), + child: Text(LocaleKeys.vGood.tr(context: context), style: TextStyle(fontSize: 13.0, color: Colors.black, fontWeight: FontWeight.w600))), + getRatingLine(bookAppointmentsVM.doctorDetailsList[1].ratio, Color(0xffB7B723)), + ], + ), + Container( + margin: EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0), + child: Text("${bookAppointmentsVM.doctorDetailsList[1].ratio.round()}%", style: TextStyle(fontSize: 14.0, color: Colors.black, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + Container( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 100.0, + margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0), + child: Text(LocaleKeys.good.tr(context: context), style: TextStyle(fontSize: 13.0, color: Colors.black, fontWeight: FontWeight.w600))), + getRatingLine(bookAppointmentsVM.doctorDetailsList[2].ratio, Color(0xffEBA727)), + ], + ), + Container( + margin: EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0), + child: Text("${bookAppointmentsVM.doctorDetailsList[2].ratio.round()}%", style: TextStyle(fontSize: 14.0, color: Colors.black, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + Container( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 100.0, + margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0), + child: Text(LocaleKeys.average.tr(context: context), style: TextStyle(fontSize: 13.0, color: Colors.black, fontWeight: FontWeight.w600))), + getRatingLine(bookAppointmentsVM.doctorDetailsList[3].ratio, Color(0xffEB7227)), + ], + ), + Container( + margin: EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0), + child: Text("${bookAppointmentsVM.doctorDetailsList[3].ratio.round()}%", style: TextStyle(fontSize: 14.0, color: Colors.black, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + Container( + margin: EdgeInsets.only(bottom: 30.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 100.0, + margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0), + child: Text(LocaleKeys.average.tr(context: context), style: TextStyle(fontSize: 13.0, color: Colors.black, fontWeight: FontWeight.w600))), + getRatingLine(bookAppointmentsVM.doctorDetailsList[4].ratio, Color(0xffE20C0C)), + ], + ), + Container( + margin: EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0), + child: Text("${bookAppointmentsVM.doctorDetailsList[4].ratio.round()}%", style: TextStyle(fontSize: 14.0, color: Colors.black, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + ], + ); + }); + } + + double getRatingWidth(num patientNumber) { + var width = patientNumber; + return width.roundToDouble(); + } + + Widget getRatingLine(double patientNumber, Color color) { + return Container( + margin: EdgeInsets.only(top: 10.0), + child: Stack(children: [ + SizedBox( + width: 150.0, + height: 7.h, + child: Container( + color: Colors.grey[300], + ), + ), + SizedBox( + width: patientNumber * 1.55, + height: 7.h, + child: Container( + color: color, + ), + ), + ]), + ); + } +} diff --git a/lib/presentation/child_vaccine/my_child_vaccine_page.dart b/lib/presentation/child_vaccine/my_child_vaccine_page.dart new file mode 100644 index 0000000..6a226ab --- /dev/null +++ b/lib/presentation/child_vaccine/my_child_vaccine_page.dart @@ -0,0 +1,376 @@ +// import 'package:easy_localization/easy_localization.dart'; +// import 'package:flutter/material.dart'; +// import 'package:hmg_patient_app_new/core/app_assets.dart'; +// import 'package:hmg_patient_app_new/core/app_state.dart'; +// import 'package:hmg_patient_app_new/core/dependencies.dart'; +// import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +// import 'package:hmg_patient_app_new/core/utils/utils.dart'; +// import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +// import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +// import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; +// import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; +// import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart'; +// import 'package:hmg_patient_app_new/features/blood_donation/widgets/hospital_selection.dart'; +// import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +// import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_blood_group_widget.dart'; +// import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_city_widget.dart'; +// import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_gender_widget.dart'; +// import 'package:hmg_patient_app_new/presentation/book_appointment/select_clinic_page.dart'; +// import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; +// import 'package:hmg_patient_app_new/services/dialog_service.dart'; +// import 'package:hmg_patient_app_new/theme/colors.dart'; +// import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +// import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +// import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +// import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +// import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +// import 'package:lottie/lottie.dart'; +// import 'package:provider/provider.dart'; +// import 'package:hmg_patient_app_new/presentation/appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart'; +// +// class MyChildVaccinePage extends StatefulWidget { +// MyChildVaccinePage({super.key}); +// +// @override +// State createState() => _MyChildVaccinePageState(); +// } +// +// class _MyChildVaccinePageState extends State { +// late AppState appState; +// +// @override +// void initState() { +// super.initState(); +// Future.microtask(() => getIt.get().fetchAllData()); +// } +// +// @override +// Widget build(BuildContext context) { +// appState = getIt(); +// return Scaffold( +// backgroundColor: AppColors.bgScaffoldColor, +// body: Consumer(builder: (context, bloodDonationVM, child) { +// return Column( +// children: [ +// Expanded( +// child: CollapsingListView( +// title: "Child Vaccines".needTranslation, +// trailing: CustomButton( +// icon: AppAssets.add_icon, +// text: "Add Child", +// onPressed: () {}, +// backgroundColor: AppColors.bgRedLightColor, +// borderColor: AppColors.bgRedLightColor, +// textColor: AppColors.primaryRedColor, +// iconColor: AppColors.primaryRedColor, +// padding: EdgeInsetsGeometry.symmetric(vertical: 0.h, horizontal: 10.h)), +// child: Padding( +// padding: EdgeInsets.all(24.w), +// child: SingleChildScrollView( +// child: Container( +// decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false), +// child: Padding( +// padding: EdgeInsets.all(16.h), +// child: Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// Row( +// mainAxisAlignment: MainAxisAlignment.spaceBetween, +// children: [ +// Row( +// children: [ +// Utils.buildSvgWithAssets(icon: AppAssets.select_city_icon, width: 40.h, height: 40.h), +// SizedBox(width: 12.w), +// Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// LocaleKeys.city.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), +// (appState.isArabic() +// ? (bloodDonationVM.selectedCity?.descriptionN ?? LocaleKeys.select.tr()) +// : bloodDonationVM.selectedCity?.description ?? LocaleKeys.select.tr(context: context)) +// .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), +// ], +// ), +// ], +// ), +// Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h), +// ], +// ).onPress(() async { +// showCommonBottomSheetWithoutHeight(context, +// title: LocaleKeys.selectCity.tr(context: context), isDismissible: true, child: SelectCityWidget(bloodDonationViewModel: bloodDonationVM), callBackFunc: () {}); +// }), +// SizedBox(height: 16.h), +// Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), +// SizedBox(height: 16.h), +// Row( +// mainAxisAlignment: MainAxisAlignment.spaceBetween, +// children: [ +// Row( +// children: [ +// Utils.buildSvgWithAssets(icon: AppAssets.genderInputIcon, width: 40.h, height: 40.h), +// SizedBox(width: 12.w), +// Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// LocaleKeys.gender.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), +// (appState.isArabic() +// ? (bloodDonationVM.selectedGender?.typeAr ?? LocaleKeys.select.tr()) +// : bloodDonationVM.selectedGender?.type ?? LocaleKeys.select.tr(context: context)) +// .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), +// ], +// ), +// ], +// ), +// Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h), +// ], +// ).onPress(() { +// showCommonBottomSheetWithoutHeight(context, +// title: LocaleKeys.selectGender.tr(context: context), +// isDismissible: true, +// child: SelectGenderWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM), +// callBackFunc: () {}); +// }), +// SizedBox(height: 16.h), +// Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), +// SizedBox(height: 16.h), +// Row( +// mainAxisAlignment: MainAxisAlignment.spaceBetween, +// children: [ +// Row( +// children: [ +// Utils.buildSvgWithAssets(icon: AppAssets.bloodType, width: 40.h, height: 40.h), +// SizedBox(width: 12.w), +// Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// LocaleKeys.bloodType.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), +// // bloodDonationVM.selectedBloodType?.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), +// (appState.isArabic() +// ? (bloodDonationVM.selectedBloodType ?? LocaleKeys.select.tr()) +// : bloodDonationVM.selectedBloodType ?? LocaleKeys.select.tr(context: context)) +// .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500) +// ], +// ), +// ], +// ), +// Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h), +// ], +// ).onPress(() { +// showCommonBottomSheetWithoutHeight(context, +// title: LocaleKeys.select.tr(context: context), +// isDismissible: true, +// child: SelectBloodGroupWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM), +// callBackFunc: () {}); +// }), +// ], +// ), +// ), +// ), +// ), +// ), +// ), +// ), +// Container( +// decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), +// child: SizedBox( +// child: Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// ], +// ), +// ), +// ), +// ], +// ); +// }), +// ); +// } +// } + + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; + +class MyChildVaccinePage extends StatefulWidget { + const MyChildVaccinePage({super.key}); + + @override + State createState() => _MyChildVaccinePageState(); +} + +class _MyChildVaccinePageState extends State { + int selectedChildIndex = 0; + + final List> children = [ + {"name": "Faris", "gender": "Son", "image": AppAssets.babyBoyImg}, + {"name": "Zaina", "gender": "Daughter", "image": AppAssets.babyGirlImg}, + {"name": "Ahmed", "gender": "Son", "image": AppAssets.babyBoyImg}, + ]; + + final List> vaccinesData = [ + { + "age": "4 months", + "dueDate": "19 Aug, 2025", + "vaccines": ["IPV", "DTap", "Hepatitis B", "HIB", "Pneumococcal Conjugate (PCV)", "Rota"] + }, + { + "age": "2 months", + "dueDate": "19 June, 2025", + "vaccines": ["IPV", "DTap", "Hepatitis B", "HIB", "Pneumococcal Conjugate (PCV)", "Rota"] + } + ]; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: Column( + children: [ + Expanded( + child: CollapsingListView( + title: "Child Vaccines".needTranslation, + trailing: CustomButton( + icon: AppAssets.add_icon, + text: "Add Child", + onPressed: () {}, + backgroundColor: AppColors.bgRedLightColor, + borderColor: AppColors.bgRedLightColor, + textColor: AppColors.primaryRedColor, + iconColor: AppColors.primaryRedColor, + padding: EdgeInsets.symmetric(vertical: 0.h, horizontal: 10.w), + ), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + _buildChildSelector(), + SizedBox(height: 24.h), + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.symmetric(horizontal: 24.w), + itemCount: vaccinesData.length, + separatorBuilder: (context, index) => SizedBox(height: 16.h), + itemBuilder: (context, index) { + return _buildVaccineCard(vaccinesData[index]); + }, + ), + SizedBox(height: 24.h), + ], + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildChildSelector() { + return SizedBox( + height: 50.h, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: EdgeInsets.symmetric(horizontal: 24.w), + itemCount: children.length, + separatorBuilder: (context, index) => SizedBox(width: 12.w), + itemBuilder: (context, index) { + bool isSelected = selectedChildIndex == index; + return GestureDetector( + onTap: () => setState(() => selectedChildIndex = index), + child: Container( + padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h), + decoration: BoxDecoration( + color: isSelected ? AppColors.bgRedLightColor : AppColors.whiteColor, + borderRadius: BorderRadius.circular(12.r), + border: Border.all( + color: isSelected ? AppColors.primaryRedColor : AppColors.borderOnlyColor.withValues(alpha: 0.1), + width: 1, + ), + ), + child: Row( + children: [ + Image.asset(children[index]['image'], width: 24.h, height: 24.h), + SizedBox(width: 8.w), + Text( + "${children[index]['name']} (${children[index]['gender']})", + style: TextStyle( + color: isSelected ? AppColors.primaryRedColor : AppColors.textColor, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500, + fontSize: 14.f, + ), + ), + ], + ), + ), + ); + }, + ), + ); + } + + Widget _buildVaccineCard(Map data) { + return Container( + padding: EdgeInsets.all(20.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + data['age'].toString().toText18(weight: FontWeight.bold, color: AppColors.textColor), + SizedBox(height: 12.h), + Container( + padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h), + decoration: BoxDecoration( + color: AppColors.bgScaffoldColor, + borderRadius: BorderRadius.circular(8.r), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.calendar, width: 16.h, height: 16.h, iconColor: AppColors.textColor), + SizedBox(width: 8.w), + "Due Date : ${data['dueDate']}".toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ), + ), + SizedBox(height: 16.h), + ... (data['vaccines'] as List).map((vaccine) => Padding( + padding: EdgeInsets.only(bottom: 12.h), + child: Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.tickIcon, width: 20.h, height: 20.h, iconColor: Colors.green), + SizedBox(width: 12.w), + vaccine.toString().toText14(weight: FontWeight.w500, color: AppColors.textColor), + ], + ), + )), + SizedBox(height: 8.h), + CustomButton( + text: "Send via email", + onPressed: () {}, + backgroundColor: AppColors.bgRedLightColor, + borderColor: Colors.transparent, + textColor: AppColors.primaryRedColor, + icon: AppAssets.email, + iconColor: AppColors.primaryRedColor, + width: double.infinity, + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/presentation/comprehensive_checkup/cmc_order_detail_page.dart b/lib/presentation/comprehensive_checkup/cmc_order_detail_page.dart index 7547fd0..dd836a6 100644 --- a/lib/presentation/comprehensive_checkup/cmc_order_detail_page.dart +++ b/lib/presentation/comprehensive_checkup/cmc_order_detail_page.dart @@ -10,6 +10,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -124,7 +125,7 @@ class _CmcOrderDetailPageState extends State { Row( children: [ if (!isLoading) ...[ - "Request ID:".needTranslation.toText14( + LocaleKeys.requestID.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -164,7 +165,7 @@ class _CmcOrderDetailPageState extends State { children: [ Expanded( child: CustomButton( - text: "Cancel Order".needTranslation, + text: LocaleKeys.cancelOrder.tr(context: context), onPressed: isLoading ? () {} : () => CmcUiSelectionHelper.showCancelConfirmationDialog(context: context, order: order), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -196,7 +197,7 @@ class _CmcOrderDetailPageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any CMC orders yet.".needTranslation, + noDataText: LocaleKeys.noCMCOrdersYet.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -209,7 +210,7 @@ class _CmcOrderDetailPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "CMC Orders".needTranslation, + title: LocaleKeys.cmcOrders.tr(context: context), isLeading: true, child: SingleChildScrollView( child: Column( diff --git a/lib/presentation/comprehensive_checkup/cmc_selection_review_page.dart b/lib/presentation/comprehensive_checkup/cmc_selection_review_page.dart index 18b656c..9b78eca 100644 --- a/lib/presentation/comprehensive_checkup/cmc_selection_review_page.dart +++ b/lib/presentation/comprehensive_checkup/cmc_selection_review_page.dart @@ -55,7 +55,7 @@ class _CmcSelectionReviewPageState extends State { final isArabic = appState.isArabic(); return CollapsingListView( - title: "Summary".needTranslation, + title: LocaleKeys.summary.tr(context: context), bottomChild: _buildBottomButton(), child: SingleChildScrollView( padding: EdgeInsets.all(16.w), @@ -89,7 +89,7 @@ class _CmcSelectionReviewPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Select Hospital".needTranslation, + LocaleKeys.selectHospital.tr(context: context), style: TextStyle( fontSize: 16.f, fontWeight: FontWeight.w700, @@ -132,7 +132,7 @@ class _CmcSelectionReviewPageState extends State { Text( isLocationSelected && selectedHospital != null ? (isArabic ? (selectedHospital.nameN ?? selectedHospital.name ?? '') : (selectedHospital.name ?? '')) - : "Select Hospital".needTranslation, + : LocaleKeys.selectHospital.tr(context: context), style: TextStyle( fontSize: 14.f, fontWeight: isLocationSelected ? FontWeight.w600 : FontWeight.w400, @@ -189,7 +189,7 @@ class _CmcSelectionReviewPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Selected Service".needTranslation.toText14( + LocaleKeys.selectedService.tr(context: context).toText14( weight: FontWeight.w600, color: AppColors.greyTextColor, letterSpacing: -0.4, @@ -226,14 +226,14 @@ class _CmcSelectionReviewPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), // Amount before tax Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol( amountBeforeTax.toString().toText16(isBold: true), AppColors.blackColor, @@ -247,7 +247,7 @@ class _CmcSelectionReviewPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( taxAmount.toString().toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, @@ -261,7 +261,7 @@ class _CmcSelectionReviewPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "".needTranslation.toText14(isBold: true), + "".toText14(isBold: true), Utils.getPaymentAmountWithSymbol( totalAmount.toString().toText24(isBold: true), AppColors.blackColor, @@ -298,7 +298,7 @@ class _CmcSelectionReviewPageState extends State { ], ), child: CustomButton( - text: "Confirm".needTranslation, + text: LocaleKeys.confirm.tr(context: context), onPressed: () { isLocationSelected ? _handleConfirm() : null; }, @@ -339,10 +339,10 @@ class _CmcSelectionReviewPageState extends State { padding: EdgeInsets.all(16.w), child: Column( children: [ - Utils.getSuccessWidget(loadingText: "Your request has been successfully submitted.".needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)), Row( children: [ - "Here is your request #: ".needTranslation.toText14( + LocaleKeys.hereIsYourRequestNumber.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -383,7 +383,7 @@ class _CmcSelectionReviewPageState extends State { if (selectedHospital == null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text("Please select a hospital to continue".needTranslation), + content: Text(LocaleKeys.pleaseSelectHospitalToContinue.tr(context: context)), backgroundColor: AppColors.errorColor, ), ); @@ -395,7 +395,7 @@ class _CmcSelectionReviewPageState extends State { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to submit this request?".needTranslation, + loadingText: LocaleKeys.confirmSubmitRequest.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); diff --git a/lib/presentation/comprehensive_checkup/comprehensive_checkup_page.dart b/lib/presentation/comprehensive_checkup/comprehensive_checkup_page.dart index 8b9ad89..da926cd 100644 --- a/lib/presentation/comprehensive_checkup/comprehensive_checkup_page.dart +++ b/lib/presentation/comprehensive_checkup/comprehensive_checkup_page.dart @@ -12,6 +12,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_services_resp_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/cmc_order_detail_page.dart'; import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/cmc_selection_review_page.dart'; import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart'; @@ -128,7 +129,7 @@ class _ComprehensiveCheckupPageState extends State { // Request ID Row( children: [ - "Request ID:".needTranslation.toText14(color: AppColors.textColorLight, weight: FontWeight.w500), + LocaleKeys.requestID.tr(context: context).toText14(color: AppColors.textColorLight, weight: FontWeight.w500), SizedBox(width: 4.w), "${order.iD ?? '-'}".toText16(isBold: true), ], @@ -179,7 +180,7 @@ class _ComprehensiveCheckupPageState extends State { ), SizedBox(width: 8.w), Expanded( - child: "You have a pending order. Please wait for it to be processed.".needTranslation.toText12( + child: LocaleKeys.pendingOrderWait.tr(context: context).toText12( color: AppColors.infoBannerTextColor, fontWeight: FontWeight.w500, ), @@ -193,7 +194,7 @@ class _ComprehensiveCheckupPageState extends State { children: [ Expanded( child: CustomButton( - text: "Cancel Order".needTranslation, + text: LocaleKeys.cancelOrder.tr(context: context), onPressed: () => CmcUiSelectionHelper.showCancelConfirmationDialog(context: context, order: order), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -219,7 +220,7 @@ class _ComprehensiveCheckupPageState extends State { child: Padding( padding: EdgeInsets.all(24.h), child: Text( - 'No services available'.needTranslation, + LocaleKeys.noServicesAvailable.tr(context: context), style: TextStyle( fontSize: 16.h, color: AppColors.greyTextColor, @@ -234,7 +235,7 @@ class _ComprehensiveCheckupPageState extends State { children: [ SizedBox(height: 16.h), Text( - 'Select a Service'.needTranslation, + LocaleKeys.selectAService.tr(context: context), style: TextStyle( fontSize: 20.h, fontWeight: FontWeight.w700, @@ -357,7 +358,7 @@ class _ComprehensiveCheckupPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "Comprehensive Checkup".needTranslation, + title: LocaleKeys.comprehensiveCheckup.tr(context: context), history: () => Navigator.of(context).push(CustomPageRoute(page: CmcOrderDetailPage(), direction: AxisDirection.up)), bottomChild: Consumer( builder: (context, hmgServicesViewModel, child) { @@ -375,7 +376,7 @@ class _ComprehensiveCheckupPageState extends State { padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 12.h), child: CustomButton( borderWidth: 0, - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: _proceedWithSelectedService, textColor: AppColors.whiteColor, borderRadius: 12.r, diff --git a/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_bottom_sheet_body.dart b/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_bottom_sheet_body.dart index 98e91b8..93c8d5f 100644 --- a/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_bottom_sheet_body.dart +++ b/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_bottom_sheet_body.dart @@ -55,7 +55,7 @@ class CmcHospitalBottomSheetBody extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Choose your preferred hospital for the service".needTranslation.toText14( + LocaleKeys.choosePreferredHospitalForService.tr(context: context).toText14( weight: FontWeight.w400, color: AppColors.greyTextColor, letterSpacing: -0.4, @@ -85,7 +85,7 @@ class CmcHospitalBottomSheetBody extends StatelessWidget { ? _buildLoadingShimmer() : hmgServicesViewModel.filteredHospitalsList.isEmpty ? Center( - child: "No hospitals Found".needTranslation.toText16(weight: FontWeight.w500, color: AppColors.greyTextColor), + child: LocaleKeys.noHospitalsFound.tr(context: context).toText16(weight: FontWeight.w500, color: AppColors.greyTextColor), ) : ListView.separated( itemCount: hmgServicesViewModel.filteredHospitalsList.length, diff --git a/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_list_item.dart b/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_list_item.dart index 39d6d7c..25cd506 100644 --- a/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_list_item.dart +++ b/lib/presentation/comprehensive_checkup/widgets/cmc_hospital_list_item.dart @@ -97,7 +97,7 @@ class CmcHospitalListItem extends StatelessWidget { Visibility( visible: (hospital.distanceInKilometers != null && hospital.distanceInKilometers! > 0), child: AppCustomChipWidget( - labelText: "$distanceText km".needTranslation, + labelText: "$distanceText km", icon: AppAssets.location_red, iconColor: AppColors.errorColor, backgroundColor: AppColors.secondaryLightRedColor, @@ -107,7 +107,7 @@ class CmcHospitalListItem extends StatelessWidget { Visibility( visible: (hospital.distanceInKilometers == null || hospital.distanceInKilometers == 0), child: AppCustomChipWidget( - labelText: " Distance not available".needTranslation, + labelText: " Distance not available", textColor: AppColors.blackColor, ), ), diff --git a/lib/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart b/lib/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart index 908aac9..fcce480 100644 --- a/lib/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart +++ b/lib/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.dart @@ -24,7 +24,7 @@ class CmcUiSelectionHelper { showCommonBottomSheetWithoutHeight( context, - title: "Select Hospital".needTranslation, + title: LocaleKeys.selectHospital.tr(context: context), child: CmcHospitalBottomSheetBody( onHospitalSelected: (hospital) { hmgServicesViewModel.setSelectedHospitalForOrder(hospital); @@ -44,7 +44,7 @@ class CmcUiSelectionHelper { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to cancel this order?".needTranslation, + loadingText: LocaleKeys.cancelOrderConfirmation.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); @@ -70,7 +70,7 @@ class CmcUiSelectionHelper { padding: EdgeInsets.all(16.w), child: Column( children: [ - Utils.getSuccessWidget(loadingText: "Order has been cancelled successfully".needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.orderCancelledSuccessfully.tr(context: context)), SizedBox(height: 24.h), Row( children: [ diff --git a/lib/presentation/contact_us/contact_us.dart b/lib/presentation/contact_us/contact_us.dart index d7ea9c5..40d42d5 100644 --- a/lib/presentation/contact_us/contact_us.dart +++ b/lib/presentation/contact_us/contact_us.dart @@ -36,7 +36,7 @@ class ContactUs extends StatelessWidget { checkInOptionCard( AppAssets.checkin_location_icon, LocaleKeys.findUs.tr(), - "View your nearest HMG locations".needTranslation, + LocaleKeys.viewNearestHMGLocations.tr(), ).onPress(() { locationUtils.getCurrentLocation(onSuccess: (value) { contactUsViewModel.initContactUsViewModel(); @@ -52,7 +52,7 @@ class ContactUs extends StatelessWidget { checkInOptionCard( AppAssets.checkin_location_icon, LocaleKeys.feedback.tr(), - "Provide your feedback on our services".needTranslation, + LocaleKeys.provideFeedbackOnServices.tr(), ).onPress(() { contactUsViewModel.setSelectedFeedbackType( FeedbackType(id: 5, nameEN: "Not classified", nameAR: 'غير محدد'), @@ -68,7 +68,7 @@ class ContactUs extends StatelessWidget { checkInOptionCard( AppAssets.checkin_location_icon, LocaleKeys.liveChat.tr(), - "Live chat option with HMG".needTranslation, + LocaleKeys.liveChatWithHMG.tr(), ).onPress(() { locationUtils.getCurrentLocation(onSuccess: (value) { contactUsViewModel.getLiveChatProjectsList(); diff --git a/lib/presentation/contact_us/feedback_page.dart b/lib/presentation/contact_us/feedback_page.dart index 078b3a1..8f10bc5 100644 --- a/lib/presentation/contact_us/feedback_page.dart +++ b/lib/presentation/contact_us/feedback_page.dart @@ -55,8 +55,8 @@ class FeedbackPage extends StatelessWidget { activeTextColor: AppColors.primaryRedColor, activeBackgroundColor: AppColors.primaryRedColor.withValues(alpha: .1), tabs: [ - CustomTabBarModel(null, "Send".needTranslation), - CustomTabBarModel(null, "Status".needTranslation), + CustomTabBarModel(null, LocaleKeys.send.tr(context: context)), + CustomTabBarModel(null, LocaleKeys.status.tr(context: context)), ], onTabChange: (index) { contactUsViewModel.setIsSendFeedbackTabSelected(index == 0); @@ -93,7 +93,7 @@ class FeedbackPage extends StatelessWidget { ); return; } - LoaderBottomSheet.showLoader(loadingText: "Sending Feedback...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.sendingFeedback.tr(context: context)); contactUsViewModel.insertCOCItem( subject: subjectTextController.text, message: messageTextController.text, @@ -148,20 +148,18 @@ class FeedbackPage extends StatelessWidget { ), child: Padding( padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.ask_doctor_icon, width: 24.w, height: 24.h, iconColor: AppColors.greyTextColor), - SizedBox(width: 12.w), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - LocaleKeys.feedbackType.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.ask_doctor_icon, width: 24.w, height: 24.h, iconColor: AppColors.greyTextColor), + SizedBox(width: 12.w), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.feedbackType.tr().toText16(color: AppColors.textColor, weight: FontWeight.w500), (getIt.get().isArabic() ? contactUsViewModel.selectedFeedbackType.nameAR : contactUsViewModel.selectedFeedbackType.nameEN) .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], @@ -172,7 +170,7 @@ class FeedbackPage extends StatelessWidget { ], ).onPress(() { showCommonBottomSheetWithoutHeight(context, - title: "Select Feedback Type".needTranslation, + title: LocaleKeys.selectFeedbackType.tr(context: context), child: Container( width: double.infinity, decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24), @@ -207,7 +205,7 @@ class FeedbackPage extends StatelessWidget { Navigator.pop(context); contactUsViewModel.setSelectedFeedbackType(newValue!); if (contactUsViewModel.selectedFeedbackType.id == 1) { - LoaderBottomSheet.showLoader(loadingText: "Loading appointments list...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingAppointmentsList.tr(context: context)); await medicalFileViewModel.getPatientMedicalReportAppointmentsList(onSuccess: (val) async { LoaderBottomSheet.hideLoader(); bool? value = await Navigator.of(context).push( @@ -224,7 +222,7 @@ class FeedbackPage extends StatelessWidget { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "You do not have any appointments to submit a feedback.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.noAppointmentsForFeedback.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -248,7 +246,7 @@ class FeedbackPage extends StatelessWidget { ), if (contactUsViewModel.patientFeedbackSelectedAppointment != null) ...[ SizedBox(height: 16.h), - "Selected Appointment:".needTranslation.toText16(isBold: true), + LocaleKeys.selectedAppointment.tr(context: context).toText16(isBold: true), SizedBox(height: 8.h), Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( @@ -295,8 +293,8 @@ class FeedbackPage extends StatelessWidget { ], SizedBox(height: 16.h), TextInputWidget( - labelText: "Subject".needTranslation, - hintText: "Enter subject here".needTranslation, + labelText: LocaleKeys.subject.tr(context: context), + hintText: LocaleKeys.enterSubjectHere.tr(context: context), controller: subjectTextController, isEnable: true, prefix: null, @@ -310,8 +308,8 @@ class FeedbackPage extends StatelessWidget { ), SizedBox(height: 16.h), TextInputWidget( - labelText: "Message".needTranslation, - hintText: "Enter message here".needTranslation, + labelText: LocaleKeys.message.tr(context: context), + hintText: LocaleKeys.enterMessageHere.tr(context: context), controller: messageTextController, isEnable: true, prefix: null, diff --git a/lib/presentation/contact_us/live_chat_page.dart b/lib/presentation/contact_us/live_chat_page.dart index 7cbdee3..a602eb1 100644 --- a/lib/presentation/contact_us/live_chat_page.dart +++ b/lib/presentation/contact_us/live_chat_page.dart @@ -1,6 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; @@ -8,12 +9,17 @@ import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -23,10 +29,12 @@ class LiveChatPage extends StatelessWidget { String chatURL = ""; late AppState appState; + late AuthenticationViewModel authVm; @override Widget build(BuildContext context) { appState = getIt.get(); + authVm = context.read(); return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: Consumer(builder: (context, contactUsVM, child) { @@ -114,7 +122,6 @@ class LiveChatPage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ("${appState.isArabic() ? contactUsVM.liveChatProjectsList[index].projectNameN! : contactUsVM.liveChatProjectsList[index].projectName!}\n${contactUsVM.liveChatProjectsList[index].distanceInKilometers!} KM") - .needTranslation .toText14(isBold: true, color: contactUsVM.selectedLiveChatProjectIndex == index ? AppColors.whiteColor : AppColors.textColor), Transform.flip( flipX: getIt.get().isArabic(), @@ -130,9 +137,13 @@ class LiveChatPage extends StatelessWidget { ).paddingSymmetrical(16.h, 16.h), ).onPress(() { contactUsVM.setSelectedLiveChatProjectIndex(index); - chatURL = - "https://chat.hmg.com/Index.aspx?Name=${appState.getAuthenticatedUser()!.firstName}&PatientID=${appState.getAuthenticatedUser()!.patientId}&MobileNo=${appState.getAuthenticatedUser()!.mobileNumber}&Language=${appState.isArabic() ? 'ar' : 'en'}&WorkGroup=${contactUsVM.liveChatProjectsList[index].value}"; - debugPrint("Chat URL: $chatURL"); + _getChatRequestID( + context, + contactUsVM, + name: appState.getAuthenticatedUser()!.firstName ?? '', + mobileNo: appState.getAuthenticatedUser()!.mobileNumber ?? '', + workGroup: contactUsVM.liveChatProjectsList[index].value ?? '', + ); }), ).paddingSymmetrical(24.h, 0.h), ), @@ -155,8 +166,72 @@ class LiveChatPage extends StatelessWidget { child: CustomButton( text: LocaleKeys.liveChat.tr(context: context), onPressed: () async { - Uri uri = Uri.parse(chatURL); - launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: ""); + if(appState.isAuthenticated) { + if (contactUsVM.chatRequestID != null) { + chatURL = "${ApiConsts.CHAT_URL}${contactUsVM.chatRequestID}"; + debugPrint("Chat URL: $chatURL"); + Uri uri = Uri.parse(chatURL); + launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: ""); + } else { + debugPrint("Chat Request ID is null"); + } + } else { + showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.notice.tr(context: context), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill), + SizedBox(height: 8.h), + (LocaleKeys.loginToUseService.tr(context: context)).toText16(color: AppColors.blackColor), + SizedBox(height: 16.h), + Row( + children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.cancel.tr(context: context), + onPressed: () { + Navigator.of(context).pop(); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + icon: AppAssets.cancel, + iconColor: AppColors.primaryRedColor, + ), + ), + SizedBox(width: 8.h), + Expanded( + child: CustomButton( + text: LocaleKeys.confirm.tr(context: context), + onPressed: () async { + Navigator.of(context).pop(); + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + await authVm.onLoginPressed(); + }, + backgroundColor: AppColors.bgGreenColor, + borderColor: AppColors.bgGreenColor, + textColor: Colors.white, + icon: AppAssets.confirm, + ), + ), + ], + ), + SizedBox(height: 16.h), + ], + ).center, + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } }, backgroundColor: contactUsVM.selectedLiveChatProjectIndex == -1 ? AppColors.greyColor : AppColors.primaryRedColor, borderColor: contactUsVM.selectedLiveChatProjectIndex == -1 ? AppColors.greyColor : AppColors.primaryRedColor, @@ -173,4 +248,20 @@ class LiveChatPage extends StatelessWidget { }), ); } + + void _getChatRequestID(BuildContext context, ContactUsViewModel contactUsVM, {required String name, required String mobileNo, required String workGroup}) { + contactUsVM.getChatRequestID( + name: name, + mobileNo: mobileNo, + workGroup: workGroup, + onSuccess: (response) { + debugPrint("Chat Request ID received: ${contactUsVM.chatRequestID}"); + chatURL = "https://chat.hmg.com/Index.aspx?RequestedId=${contactUsVM.chatRequestID}"; + debugPrint("Chat URL: $chatURL"); + }, + onError: (error) { + debugPrint("Error getting chat request ID: $error"); + }, + ); + } } diff --git a/lib/presentation/contact_us/widgets/find_us_item_card.dart b/lib/presentation/contact_us/widgets/find_us_item_card.dart index 96375c0..6e295e0 100644 --- a/lib/presentation/contact_us/widgets/find_us_item_card.dart +++ b/lib/presentation/contact_us/widgets/find_us_item_card.dart @@ -68,7 +68,7 @@ class FindUsItemCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget( - labelText: "${getHMGLocationsModel.distanceInKilometers ?? ""} km".needTranslation, + labelText: "${getHMGLocationsModel.distanceInKilometers ?? ""} km", icon: AppAssets.location_red, iconColor: AppColors.primaryRedColor, backgroundColor: AppColors.secondaryLightRedColor, @@ -77,7 +77,7 @@ class FindUsItemCard extends StatelessWidget { Row( children: [ AppCustomChipWidget( - labelText: "Get Directions".needTranslation, + labelText: LocaleKeys.getDirections.tr(), icon: AppAssets.directions_icon, iconColor: AppColors.whiteColor, backgroundColor: AppColors.textColor.withValues(alpha: 0.8), diff --git a/lib/presentation/covid19test/covid19_landing_page.dart b/lib/presentation/covid19test/covid19_landing_page.dart index 62bd651..a241da6 100644 --- a/lib/presentation/covid19test/covid19_landing_page.dart +++ b/lib/presentation/covid19test/covid19_landing_page.dart @@ -94,7 +94,7 @@ class _Covid19LandingPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomButton( - text: "SelectLocation".needTranslation, + text: "Select Location", onPressed: () { _showBranchBottomSheet(context); }, @@ -124,7 +124,7 @@ class _Covid19LandingPageState extends State { showCommonBottomSheet( context, - title: "Select Branch".needTranslation, + title: "Select Branch", height: ResponsiveExtension.screenHeight * 0.651, child: StatefulBuilder( builder: (context, setBottomSheetState) { @@ -240,7 +240,7 @@ class _Covid19LandingPageState extends State { child: SafeArea( top: false, child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: (){ Navigator.of(context) diff --git a/lib/presentation/covid19test/covid_19_questionnaire.dart b/lib/presentation/covid19test/covid_19_questionnaire.dart index 8608d80..f7b1f4c 100644 --- a/lib/presentation/covid19test/covid_19_questionnaire.dart +++ b/lib/presentation/covid19test/covid_19_questionnaire.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; @@ -7,6 +8,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/covid_questionnare_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/covid19test/covid_review_screen.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -61,7 +63,7 @@ class _Covid19QuestionnaireState extends State { topRight: Radius.circular(24.r), ), ),child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () { moveToNextPage(context); }, diff --git a/lib/presentation/covid19test/covid_payment_screen.dart b/lib/presentation/covid19test/covid_payment_screen.dart index 42e7736..e395a42 100644 --- a/lib/presentation/covid19test/covid_payment_screen.dart +++ b/lib/presentation/covid19test/covid_payment_screen.dart @@ -89,7 +89,7 @@ class _CovidPaymentScreenState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: widget.title.needTranslation, + title: widget.title, bottomChild: Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, @@ -100,19 +100,19 @@ class _CovidPaymentScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol(( (widget.amount - widget.taxAmount).toString()).toText16(isBold: true), AppColors.blackColor, 13, isSaudiCurrency: true), ], ).paddingSymmetrical(24.h, 0.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), // Show VAT amount passed from review screen Utils.getPaymentAmountWithSymbol((widget.taxAmount.toString()).toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, 13, isSaudiCurrency: true), ], @@ -121,7 +121,7 @@ class _CovidPaymentScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "".needTranslation.toText14(isBold: true), + "".toText14(isBold: true), Utils.getPaymentAmountWithSymbol(widget.amount.toString().toText24(isBold: true), AppColors.blackColor, 17, isSaudiCurrency: true), ], ).paddingSymmetrical(24.h, 0.h), @@ -212,7 +212,7 @@ class _CovidPaymentScreenState extends State { children: [ Image.asset(AppAssets.mada, width: 72.h, height: 25.h), SizedBox(height: 16.h), - "Mada".needTranslation.toText16(isBold: true), + LocaleKeys.mada.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -257,7 +257,7 @@ class _CovidPaymentScreenState extends State { ], ), SizedBox(height: 16.h), - "Visa or Mastercard".needTranslation.toText16(isBold: true), + LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -312,7 +312,7 @@ class _CovidPaymentScreenState extends State { }, ), SizedBox(height: 16.h), - "Tamara".needTranslation.toText16(isBold: true), + LocaleKeys.tamara.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -387,7 +387,7 @@ class _CovidPaymentScreenState extends State { } Future checkPaymentStatus() async { - LoaderBottomSheet.showLoader(loadingText: "Checking payment status, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context)); try { await payfortViewModel.checkPaymentStatus(transactionID: transID, onSuccess: (apiResponse) async { // treat any successful responseMessage as success; otherwise show generic error @@ -396,7 +396,7 @@ class _CovidPaymentScreenState extends State { if (success) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Payment successful".needTranslation), + child: Utils.getSuccessWidget(loadingText: "Payment successful"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -404,7 +404,7 @@ class _CovidPaymentScreenState extends State { } else { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/covid19test/covid_review_screen.dart b/lib/presentation/covid19test/covid_review_screen.dart index 7ccbb02..3440129 100644 --- a/lib/presentation/covid19test/covid_review_screen.dart +++ b/lib/presentation/covid19test/covid_review_screen.dart @@ -75,7 +75,7 @@ class _CovidReviewScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText18(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText18(isBold: true), Utils.getPaymentAmountWithSymbol( (info.patientShareField ?? 0).toString().toText16(isBold: true), AppColors.blackColor, @@ -87,7 +87,7 @@ class _CovidReviewScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Tax Amount".needTranslation.toText14(isBold: true), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol( (info.patientTaxAmountField ?? 0).toString().toText16(isBold: true), AppColors.blackColor, @@ -208,13 +208,13 @@ class _CovidReviewScreenState extends State { Expanded( child: CustomButton( height: 56.h, - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () async { // Validate selection and payment info if (_selectedProcedure == null) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Please select a procedure".needTranslation), + child: Utils.getErrorWidget(loadingText: "Please select a procedure"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -236,7 +236,7 @@ class _CovidReviewScreenState extends State { if (hmgServicesViewModel.covidPaymentInfo == null) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment information not available".needTranslation), + child: Utils.getErrorWidget(loadingText: "Payment information not available"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/e_referral/e-referral_validator.dart b/lib/presentation/e_referral/e-referral_validator.dart index e0a8006..b662122 100644 --- a/lib/presentation/e_referral/e-referral_validator.dart +++ b/lib/presentation/e_referral/e-referral_validator.dart @@ -1,64 +1,65 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/e_referral_form_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; class ReferralValidator { - static FormValidationErrors validateStep1(ReferralFormData formData) { + static FormValidationErrors validateStep1(ReferralFormData formData, BuildContext context) { final errors = FormValidationErrors(); if (formData.requesterName.trim().isEmpty) { - errors.requesterName = 'Referral requester name is required'.needTranslation; + errors.requesterName = LocaleKeys.requesterNameRequired.tr(context: context); } - - if (formData.relationship == null) { - errors.relationship = 'Please select a relationship'.needTranslation; + errors.relationship = LocaleKeys.selectRelationshipRequired.tr(context: context); } if (formData.relationship != null && formData.relationship?.iD == 5 && formData.otherRelationshipName.trim().isEmpty) { - errors.otherRelationshipName = 'Other relationship name is required'.needTranslation; + errors.otherRelationshipName = LocaleKeys.otherRelationshipNameRequired.tr(context: context); } return errors; } - static FormValidationErrors validateStep2(ReferralFormData formData) { + static FormValidationErrors validateStep2(ReferralFormData formData, BuildContext context) { final errors = FormValidationErrors(); if (formData.patientIdentification.trim().isEmpty) { - errors.patientIdentification = 'Identification number is required'.needTranslation; + errors.patientIdentification = LocaleKeys.identificationNumberRequired.tr(context: context); } if (formData.patientName.trim().isEmpty) { - errors.patientName = 'Patient name is required'.needTranslation; + errors.patientName = LocaleKeys.patientNameRequired.tr(context: context); } if (formData.patientPhone == null) { - errors.patientPhone = 'Please Enter patient phone number'.needTranslation; + errors.patientPhone = LocaleKeys.enterPatientPhoneRequired.tr(context: context); } if (formData.patientCity == null) { - errors.patientCity = 'Please select patient city'.needTranslation; + errors.patientCity = LocaleKeys.selectPatientCityRequired.tr(context: context); } return errors; } - static FormValidationErrors validateStep3(ReferralFormData formData) { + static FormValidationErrors validateStep3(ReferralFormData formData, BuildContext context) { final errors = FormValidationErrors(); if (formData.medicalReportImages.isEmpty) { - errors.medicalReport = 'At least one medical report is required'.needTranslation; + errors.medicalReport = LocaleKeys.medicalReportRequired.tr(context: context); } if (formData.branch == null) { - errors.branch = 'Please select a branch'.needTranslation; + errors.branch = LocaleKeys.selectBranchRequired.tr(context: context); } if (formData.isPatientInsured && formData.insuredPatientImages.isEmpty) { - errors.insuredDocument = 'Insurance document is required for insured patients'.needTranslation; + errors.insuredDocument = LocaleKeys.insuranceDocumentRequired.tr(context: context); } return errors; diff --git a/lib/presentation/e_referral/e_referral_search_result.dart b/lib/presentation/e_referral/e_referral_search_result.dart index 8702d5a..6a4b831 100644 --- a/lib/presentation/e_referral/e_referral_search_result.dart +++ b/lib/presentation/e_referral/e_referral_search_result.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; @@ -5,6 +6,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:provider/provider.dart'; @@ -31,7 +33,7 @@ class _SearchResultPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "Search Result".needTranslation, + title: LocaleKeys.searchResult.tr(context: context), child: Column( children: [ // List of referrals @@ -61,10 +63,7 @@ class _SearchResultPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - - 'Referral No ${referral.referralNumber}'.needTranslation.toText18(isBold: true, color: AppColors.textColor), - - + LocaleKeys.referralNo.tr(context: context, namedArgs: {'number': '${referral.referralNumber}'}).toText18(isBold: true, color: AppColors.textColor), Container( padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( diff --git a/lib/presentation/e_referral/new_e_referral.dart b/lib/presentation/e_referral/new_e_referral.dart index 3083de1..0288173 100644 --- a/lib/presentation/e_referral/new_e_referral.dart +++ b/lib/presentation/e_referral/new_e_referral.dart @@ -81,13 +81,13 @@ class _NewReferralPageState extends State { switch (_currentStep) { case 0: - stepErrors = ReferralValidator.validateStep1(_formManager.formData); + stepErrors = ReferralValidator.validateStep1(_formManager.formData, context); break; case 1: - stepErrors = ReferralValidator.validateStep2(_formManager.formData); + stepErrors = ReferralValidator.validateStep2(_formManager.formData, context); break; case 2: - stepErrors = ReferralValidator.validateStep3(_formManager.formData); + stepErrors = ReferralValidator.validateStep3(_formManager.formData, context); break; default: stepErrors = FormValidationErrors(); @@ -159,7 +159,7 @@ class _NewReferralPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "E Referral".needTranslation, + title: LocaleKeys.eReferral.tr(context: context), isClose: false, search: () async { await Navigator.of(context).push( @@ -222,10 +222,10 @@ class _NewReferralPageState extends State { padding: EdgeInsets.all(16.w), child: Column( children: [ - Utils.getSuccessWidget(loadingText: "Your Referral has been created Successfully.".needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.referralCreatedSuccessfully.tr(context: context)), Row( children: [ - "Here is your Referral #: ".needTranslation.toText14( + LocaleKeys.hereIsYourReferralNumber.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), diff --git a/lib/presentation/e_referral/search_e_referral.dart b/lib/presentation/e_referral/search_e_referral.dart index 1a243da..b9bf592 100644 --- a/lib/presentation/e_referral/search_e_referral.dart +++ b/lib/presentation/e_referral/search_e_referral.dart @@ -80,7 +80,7 @@ class _SearchEReferralPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "Search E-Referral".needTranslation, + title: LocaleKeys.searchEReferral.tr(context: context), isClose: true, bottomChild: Container( color: Colors.white, @@ -111,7 +111,7 @@ class _SearchEReferralPageState extends State { padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, - children: [SizedBox(height: 8), 'Please enter the required information to search for an e-referral'.needTranslation.toText12()], + children: [SizedBox(height: 8), LocaleKeys.enterRequiredInfoToSearch.tr(context: context).toText12()], ), ); } diff --git a/lib/presentation/e_referral/widget/e_referral_other_details.dart b/lib/presentation/e_referral/widget/e_referral_other_details.dart index 6efd063..da955f8 100644 --- a/lib/presentation/e_referral/widget/e_referral_other_details.dart +++ b/lib/presentation/e_referral/widget/e_referral_other_details.dart @@ -1,10 +1,12 @@ import 'dart:io'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/utils/validation_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -46,14 +48,14 @@ class _OtherDetailsStepState extends State { void _updateMedicalReportText() { final hasMedicalReports = _formManager.formData.medicalReportImages.isNotEmpty; _medicalReportController.text = hasMedicalReports - ? '${_formManager.formData.medicalReportImages.length} file(s) selected'.needTranslation + ? '${_formManager.formData.medicalReportImages.length} file(s) selected' : ''; } void _updateInsuranceText() { final hasInsuranceDocs = _formManager.formData.insuredPatientImages.isNotEmpty; _insuranceController.text = hasInsuranceDocs - ? '${_formManager.formData.insuredPatientImages.length} file(s) selected'.needTranslation + ? '${_formManager.formData.insuredPatientImages.length} file(s) selected' : ''; } @@ -68,7 +70,7 @@ class _OtherDetailsStepState extends State { physics: const BouncingScrollPhysics(), children: [ const SizedBox(height: 12), - _buildSectionTitle('Other Details'.needTranslation), + _buildSectionTitle(LocaleKeys.otherDetails.tr(context: context)), const SizedBox(height: 12), _buildMedicalReportField(formManager), _buildBranchField(context, formManager), @@ -96,8 +98,8 @@ class _OtherDetailsStepState extends State { child: TextInputWidget( controller: _medicalReportController, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Medical Report'.needTranslation, - labelText: 'Select Attachment'.needTranslation, + hintText: LocaleKeys.medicalReport.tr(context: context), + labelText: LocaleKeys.selectAttachment.tr(context: context), suffix: const Icon(Icons.attachment), isReadOnly: true, errorMessage: formManager.errors.medicalReport, @@ -121,7 +123,7 @@ class _OtherDetailsStepState extends State { children: formManager.formData.medicalReportImages.asMap().entries.map((entry) { final index = entry.key; return Chip( - label: Text('Medical Report ${index + 1}'.needTranslation), + label: Text(LocaleKeys.medicalReportNumber.tr(context: context, namedArgs: {'number': '${index + 1}'})), deleteIcon: const Icon(Icons.close, size: 16), onDeleted: () { _removeMedicalReport(index, formManager); @@ -172,7 +174,7 @@ class _OtherDetailsStepState extends State { Padding( padding: EdgeInsets.all(5.0), child: - "Patient is Insured".needTranslation.toText14( + LocaleKeys.patientIsInsured.tr(context: context).toText14( color: Colors.black, weight: FontWeight.w600, ), @@ -193,8 +195,8 @@ class _OtherDetailsStepState extends State { child: TextInputWidget( controller: _insuranceController, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Insurance Document'.needTranslation, - labelText: 'Select Attachment'.needTranslation, + hintText: LocaleKeys.insuranceDocument.tr(context: context), + labelText: LocaleKeys.selectAttachment.tr(context: context), suffix: const Icon(Icons.attachment), isReadOnly: true, errorMessage: formManager.errors.insuredDocument, @@ -235,7 +237,7 @@ class _OtherDetailsStepState extends State { showCommonBottomSheetWithoutHeight( context, - title: "Select Branch".needTranslation, + title: LocaleKeys.selectBranch.tr(context: context), child: Consumer( builder: (context, habibWalletVM, child) { final hospitals = habibWalletVM.advancePaymentHospitals; diff --git a/lib/presentation/e_referral/widget/e_referral_patient_info.dart b/lib/presentation/e_referral/widget/e_referral_patient_info.dart index 469755c..0cc5c7e 100644 --- a/lib/presentation/e_referral/widget/e_referral_patient_info.dart +++ b/lib/presentation/e_referral/widget/e_referral_patient_info.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/utils/validation_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -65,14 +67,14 @@ class PatientInformationStepState extends State { physics: const BouncingScrollPhysics(), children: [ const SizedBox(height: 12), - _buildSectionTitle('Patient information'.needTranslation), + _buildSectionTitle(LocaleKeys.patientInfo.tr(context: context)), const SizedBox(height: 12), _buildIdentificationField(formManager), _buildPatientNameField(formManager), // _buildPatientCountryField(context, formManager), _buildPatientPhoneField(formManager), const SizedBox(height: 20), - _buildSectionTitle('Where the patient located'.needTranslation), + _buildSectionTitle(LocaleKeys.patientLocation.tr(context: context)), _buildPatientCityField(context, formManager), ], ), @@ -94,8 +96,8 @@ class PatientInformationStepState extends State { child: TextInputWidget( controller: _identificationController, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Enter Identification Number*'.needTranslation, - labelText: 'Identification Number'.needTranslation, + hintText: LocaleKeys.enterIdentificationNumber.tr(context: context), + labelText: LocaleKeys.identificationNumber.tr(context: context), errorMessage: formManager.errors.patientIdentification, hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientIdentification), onChange: (value) { @@ -114,8 +116,8 @@ class PatientInformationStepState extends State { child: TextInputWidget( controller: _nameController, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Patient Name*'.needTranslation, - labelText: 'Name'.needTranslation, + hintText: LocaleKeys.patientName.tr(context: context), + labelText: LocaleKeys.name.tr(context: context), keyboardType: TextInputType.text, errorMessage: formManager.errors.patientName, hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientName), @@ -133,7 +135,7 @@ class PatientInformationStepState extends State { return Focus( focusNode: _phoneFocusNode, child: TextInputWidget( - labelText: 'Phone Number'.needTranslation, + labelText: LocaleKeys.phoneNumber.tr(context: context), hintText: "5xxxxxxxx", controller: _phoneController, padding: const EdgeInsets.all(8), @@ -159,7 +161,7 @@ class PatientInformationStepState extends State { Widget _buildPatientCityField(BuildContext context, ReferralFormManager formManager) { return DropdownWidget( labelText: 'City', - hintText: formManager.formData.patientCity?.description ?? "Select City".needTranslation, + hintText: formManager.formData.patientCity?.description ?? LocaleKeys.selectCity.tr(context: context), isEnable: false, hasSelectionCustomIcon: true, labelColor: Colors.black, @@ -179,7 +181,7 @@ class PatientInformationStepState extends State { showCommonBottomSheetWithoutHeight( context, - title: "Select City".needTranslation, + title: LocaleKeys.selectCity.tr(context: context), child: Consumer( builder: (context, hmgServicesVM, child) { final cities = hmgServicesVM.getAllCitiesList; diff --git a/lib/presentation/e_referral/widget/e_referral_requester_form.dart b/lib/presentation/e_referral/widget/e_referral_requester_form.dart index cc981a9..d2b75cc 100644 --- a/lib/presentation/e_referral/widget/e_referral_requester_form.dart +++ b/lib/presentation/e_referral/widget/e_referral_requester_form.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/utils/validation_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -67,8 +69,8 @@ class RequesterFormStepState extends State { physics: const BouncingScrollPhysics(), children: [ // const SizedBox(height: 12), - _buildSectionTitle('Referral requester information'.needTranslation), - const SizedBox(height: 12), + _buildSectionTitle(LocaleKeys.referralRequesterInformation.tr(context: context)), + const SizedBox(height: 12), _buildNameField(formManager), // _buildPhoneField(formManager), _buildRelationshipField(context, formManager), @@ -93,8 +95,8 @@ class RequesterFormStepState extends State { child: TextInputWidget( controller: _nameController, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Enter Referral Requester Name*'.needTranslation, - labelText: 'Requester Name'.needTranslation, + hintText: LocaleKeys.enterReferralRequesterName.tr(context: context), + labelText: LocaleKeys.requesterName.tr(context: context), keyboardType: TextInputType.text, errorMessage: formManager.errors.requesterName, isAllowLeadingIcon: true, @@ -109,10 +111,10 @@ class RequesterFormStepState extends State { } Widget _buildRelationshipField(BuildContext context, ReferralFormManager formManager) { return DropdownWidget( - labelText: "Relationship".needTranslation, - hintText: formManager.formData.relationship?.textEn ?? "Select Relation".needTranslation, + labelText: LocaleKeys.relationship.tr(context: context), + hintText: formManager.formData.relationship?.textEn ?? LocaleKeys.selectRelation.tr(context: context), isEnable: false, - selectedValue: formManager.formData.relationship?.textEn ?? "Select Relation".needTranslation, + selectedValue: formManager.formData.relationship?.textEn ?? LocaleKeys.selectRelation.tr(context: context), errorMessage: formManager.errors.relationship, hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.relationship), hasSelectionCustomIcon: false, @@ -132,8 +134,8 @@ class RequesterFormStepState extends State { controller: _otherNameController, keyboardType: TextInputType.text, padding: const EdgeInsets.symmetric(horizontal: 16.0), - hintText: 'Other Name*'.needTranslation, - labelText: 'Other Name'.needTranslation, + hintText: LocaleKeys.otherNameHint.tr(context: context), + labelText: LocaleKeys.otherName.tr(context: context), errorMessage: formManager.errors.otherRelationshipName, onChange: (value) { formManager.updateOtherRelationshipName(value ?? ''); @@ -152,7 +154,7 @@ class RequesterFormStepState extends State { showCommonBottomSheetWithoutHeight( context, - title: "Select Relation".needTranslation, + title: LocaleKeys.selectRelation.tr(context: context), child: Consumer( builder: (context, hmgServicesVM, child) { if (hmgServicesVM.relationTypes.isEmpty) { @@ -164,8 +166,8 @@ class RequesterFormStepState extends State { ); } - return DecoratedBox( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: Colors.white, customBorder: BorderRadius.all(Radius.circular(24.h)) , diff --git a/lib/presentation/emergency_services/RRT/rrt_map_screen.dart b/lib/presentation/emergency_services/RRT/rrt_map_screen.dart index afe68b6..530152b 100644 --- a/lib/presentation/emergency_services/RRT/rrt_map_screen.dart +++ b/lib/presentation/emergency_services/RRT/rrt_map_screen.dart @@ -1,4 +1,3 @@ - import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -135,19 +134,19 @@ class RrtMapScreen extends StatelessWidget { Column( spacing: 4.h, children: [ - "Select Location".needTranslation.toText21( + LocaleKeys.selectLocation.tr().toText21( weight: FontWeight.w600, color: AppColors.textColor, ), - "Please select the location".needTranslation.toText12( + LocaleKeys.pleaseSelectTheLocation.tr().toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ) ], ), CustomButton( - text: "Submit Request".needTranslation, - onPressed: () { + text: LocaleKeys.submitRequest.tr(), + onPressed: () { LocationViewModel locationViewModel = context.read(); GeocodeResponse? response = locationViewModel.geocodeResponse; PlaceDetails? placeDetails = locationViewModel.placeDetails; @@ -235,7 +234,7 @@ class RrtMapScreen extends StatelessWidget { height: 40.h, backgroundColor: AppColors.lightRedButtonColor, borderColor: Colors.transparent, - text: "Add new address".needTranslation, + text: LocaleKeys.addNewAddress.tr(), textColor: AppColors.primaryRedColor, iconColor: AppColors.primaryRedColor, onPressed: () {}, @@ -245,9 +244,7 @@ class RrtMapScreen extends StatelessWidget { isSelected: index == 0, address: "Flat No 301, Building No 12, Palm Spring Apartment, Sector 45, Gurugram, Haryana 122003", - title: index == 0 - ? "Home".needTranslation - : "Work".needTranslation, + title: index == 0 ? LocaleKeys.home.tr() : LocaleKeys.work.tr(), onTap: () {}, ); } @@ -291,8 +288,8 @@ class RrtMapScreen extends StatelessWidget { Row( children: [ hospitalAndPickUpItemContent( - title: "Pick".needTranslation, - subTitle: "Inside the home".needTranslation, + title: LocaleKeys.pick.tr(), + subTitle: LocaleKeys.insideTheHome.tr(), leadingIcon: AppAssets.pickup_bed, ), CustomSwitch( @@ -312,7 +309,7 @@ class RrtMapScreen extends StatelessWidget { children: [ hospitalAndPickUpItemContent( title: '', - subTitle: "Have any appointment".needTranslation, + subTitle: LocaleKeys.haveAnyAppointment.tr(), leadingIcon: AppAssets.appointment_checkin_icon, ), CustomSwitch( @@ -416,8 +413,8 @@ class RrtMapScreen extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, spacing: 4.h, children: [ - "Total amount to pay".needTranslation.toText18( - weight: FontWeight.w600, + LocaleKeys.totalAmountToPay.tr().toText18( + weight: FontWeight.w600, color: AppColors.textColor, ), Row( @@ -425,9 +422,7 @@ class RrtMapScreen extends StatelessWidget { Utils.buildSvgWithAssets(icon: AppAssets.warning, height: 18.h, width: 18.h), SizedBox(width: 4.h,), - "Amount will be paid at the hospital" - .needTranslation - .toText12( + LocaleKeys.amountPaidAtHospital.tr().toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ), @@ -452,7 +447,7 @@ class RrtMapScreen extends StatelessWidget { ], ), CustomButton( - text: "Submit Request".needTranslation, + text: LocaleKeys.submitRequest.tr(), onPressed: () { LocationViewModel locationViewModel = context.read(); GeocodeResponse? response = locationViewModel.geocodeResponse; @@ -530,8 +525,8 @@ class RrtMapScreen extends StatelessWidget { return SizedBox( width: MediaQuery.sizeOf(context).width, child: TextInputWidget( - labelText: "Enter Pickup Location Manually".needTranslation, - hintText: "Enter Pickup Location".needTranslation, + labelText: LocaleKeys.enterPickupLocationManually.tr(), + hintText: LocaleKeys.enterPickupLocation.tr(), controller: TextEditingController( text: vm.geocodeResponse?.results.first.formattedAddress ?? vm.selectedPrediction?.description, @@ -562,7 +557,7 @@ class RrtMapScreen extends StatelessWidget { openLocationInputBottomSheet(BuildContext context) { context.read().flushSearchPredictions(); showCommonBottomSheetWithoutHeight( - title: "".needTranslation, + title: "", context, child: SizedBox( height: MediaQuery.sizeOf(context).height * .8, @@ -583,11 +578,10 @@ class RrtMapScreen extends StatelessWidget { child: Row( children: [ hospitalAndPickUpItemContent( - title: "Select Hospital".needTranslation, + title: "Select Hospital".tr(), subTitle: context .read() - .getSelectedHospitalName() ?? - "Select Hospital".needTranslation, + .getSelectedHospitalName() ?? "Select Hospital".tr(), leadingIcon: AppAssets.hospital, ), Utils.buildSvgWithAssets( @@ -606,7 +600,7 @@ class RrtMapScreen extends StatelessWidget { void openAppointmentList(BuildContext context) { showCommonBottomSheetWithoutHeight( - title: "Select Appointment".needTranslation, + title: LocaleKeys.selectAppointment.tr(), context, child: SizedBox( height: MediaQuery.sizeOf(context).height * .5, diff --git a/lib/presentation/emergency_services/RRT/rrt_request_type_select.dart b/lib/presentation/emergency_services/RRT/rrt_request_type_select.dart index 13e0106..91db0de 100644 --- a/lib/presentation/emergency_services/RRT/rrt_request_type_select.dart +++ b/lib/presentation/emergency_services/RRT/rrt_request_type_select.dart @@ -18,12 +18,11 @@ class RrtRequestTypeSelect extends StatelessWidget { @override Widget build(BuildContext context) { return Consumer(builder: (context, emergencyServicesVM, child) { - print("the checkbox is ${emergencyServicesVM.agreedToTermsAndCondition}"); return Column( children: [ Column( children: [ - "Rapid Response Team (RRT) options".needTranslation.toText20(color: AppColors.textColor, isBold: true), + LocaleKeys.rapidResponseTeam.tr(context: context).toText20(color: AppColors.textColor, isBold: true), SizedBox( height: 16.h, ), @@ -74,7 +73,7 @@ class RrtRequestTypeSelect extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Total amount to pay".needTranslation.toText18( + LocaleKeys.totalAmountToPay.tr(context: context).toText18( weight: FontWeight.w600, color: AppColors.textColor, ), @@ -94,19 +93,19 @@ class RrtRequestTypeSelect extends StatelessWidget { SizedBox( width: 4.h, ), - "Amount will be paid at the hospital".needTranslation.toText11( + LocaleKeys.amountPaidAtHospital.tr(context: context).toText11( color: AppColors.greyTextColor, ), ], ), Row( children: [ - "+ VAT 15%(".needTranslation.toText12( + LocaleKeys.vat15.tr(context: context).toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ), - "${emergencyServicesVM.selectedRRTProcedure?.patientTaxAmount})".needTranslation.toText14( - weight: FontWeight.w600, + "${emergencyServicesVM.selectedRRTProcedure?.patientTaxAmount})".toText14( + weight: FontWeight.w600, color: AppColors.greyTextColor, ), ], diff --git a/lib/presentation/emergency_services/RRT/terms_and_condition.dart b/lib/presentation/emergency_services/RRT/terms_and_condition.dart index 1d1dac1..bd0d6fd 100644 --- a/lib/presentation/emergency_services/RRT/terms_and_condition.dart +++ b/lib/presentation/emergency_services/RRT/terms_and_condition.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -18,7 +20,7 @@ class TermsAndCondition extends StatelessWidget { Expanded( child: CollapsingListView( - title: "Terms And Condition".needTranslation, + title: LocaleKeys.termsConditoins.tr(context: context), child:DecoratedBox(decoration:RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, borderRadius: 20.h, diff --git a/lib/presentation/emergency_services/call_ambulance/call_ambulance_page.dart b/lib/presentation/emergency_services/call_ambulance/call_ambulance_page.dart index 043c231..e86104b 100644 --- a/lib/presentation/emergency_services/call_ambulance/call_ambulance_page.dart +++ b/lib/presentation/emergency_services/call_ambulance/call_ambulance_page.dart @@ -156,18 +156,18 @@ class CallAmbulancePage extends StatelessWidget { Column( spacing: 4.h, children: [ - "Select Pickup Details".needTranslation.toText21( + LocaleKeys.selectPickupDetails.tr(context: context).toText21( weight: FontWeight.w600, color: AppColors.textColor, ), - " Please select the details of pickup".needTranslation.toText12( + LocaleKeys.pleaseSelectDetailsOfPickup.tr(context: context).toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ) ], ), CustomButton( - text: "Select Details".needTranslation, + text: LocaleKeys.selectDetails.tr(context: context), onPressed: () { context.read().updateBottomSheetState(BottomSheetType.EXPANDED); }) @@ -256,7 +256,7 @@ class CallAmbulancePage extends StatelessWidget { height: 40.h, backgroundColor: AppColors.lightRedButtonColor, borderColor: Colors.transparent, - text: "Add new address".needTranslation, + text: LocaleKeys.addNewAddress.tr(context: context), textColor: AppColors.primaryRedColor, iconColor: AppColors.primaryRedColor, onPressed: () {}, @@ -265,7 +265,7 @@ class CallAmbulancePage extends StatelessWidget { return AddressItem( isSelected: index == 0, address: "Flat No 301, Building No 12, Palm Spring Apartment, Sector 45, Gurugram, Haryana 122003", - title: index == 0 ? "Home".needTranslation : "Work".needTranslation, + title: index == 0 ? LocaleKeys.home.tr(context: context) : LocaleKeys.work.tr(context: context), onTap: () {}, ); } @@ -309,8 +309,8 @@ class CallAmbulancePage extends StatelessWidget { Row( children: [ hospitalAndPickUpItemContent( - title: "Pick".needTranslation, - subTitle: "Inside the home".needTranslation, + title: LocaleKeys.pick.tr(context: context), + subTitle: LocaleKeys.insideTheHome.tr(context: context), leadingIcon: AppAssets.pickup_bed, ), CustomSwitch( @@ -325,8 +325,8 @@ class CallAmbulancePage extends StatelessWidget { Row( children: [ hospitalAndPickUpItemContent( - title: 'Appointment', - subTitle: "Have any appointment".needTranslation, + title: LocaleKeys.appointment.tr(context: context), + subTitle: LocaleKeys.haveAnyAppointment.tr(context: context), leadingIcon: AppAssets.appointment_calendar_icon, ), CustomSwitch( @@ -426,7 +426,7 @@ class CallAmbulancePage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, spacing: 4.h, children: [ - "Total amount to pay".needTranslation.toText18( + LocaleKeys.totalAmountToPay.tr(context: context).toText18( weight: FontWeight.w600, color: AppColors.textColor, ), @@ -436,7 +436,7 @@ class CallAmbulancePage extends StatelessWidget { SizedBox( width: 4.h, ), - "Amount will be paid at the hospital".needTranslation.toText12( + LocaleKeys.amountPaidAtHospital.tr(context: context).toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ), @@ -455,7 +455,7 @@ class CallAmbulancePage extends StatelessWidget { ], ), CustomButton( - text: "Submit Request".needTranslation, + text: LocaleKeys.submitRequest.tr(context: context), onPressed: () { LocationViewModel locationViewModel = context.read(); GeocodeResponse? response = locationViewModel.geocodeResponse; @@ -530,8 +530,8 @@ class CallAmbulancePage extends StatelessWidget { return SizedBox( width: MediaQuery.sizeOf(context).width, child: TextInputWidget( - labelText: "Enter Pickup Location Manually".needTranslation, - hintText: "Enter Pickup Location".needTranslation, + labelText: LocaleKeys.enterPickupLocationManually.tr(context: context), + hintText: LocaleKeys.enterPickupLocation.tr(context: context), controller: TextEditingController( text: vm.geocodeResponse?.results.first.formattedAddress ?? vm.selectedPrediction?.description, ), @@ -563,7 +563,7 @@ class CallAmbulancePage extends StatelessWidget { openLocationInputBottomSheet(BuildContext context) { context.read().flushSearchPredictions(); showCommonBottomSheetWithoutHeight( - title: "".needTranslation, + title: "", context, child: SizedBox( height: MediaQuery.sizeOf(context).height * .8, @@ -583,25 +583,22 @@ class CallAmbulancePage extends StatelessWidget { child: Row( children: [ hospitalAndPickUpItemContent( - title: "Select Hospital".needTranslation, - subTitle: context.read().getSelectedHospitalName() ?? "Select Hospital".needTranslation, + title: LocaleKeys.selectHospital.tr(context: context), + subTitle: context.read().getSelectedHospitalName() ?? LocaleKeys.selectHospital.tr(context: context), leadingIcon: AppAssets.hospital, ), Utils.buildSvgWithAssets(icon: AppAssets.down_cheveron, width: 24.h, height: 24.h).paddingAll(16.h) ], ).onPress(() { - print("the item is clicked"); showHospitalBottomSheet(context); }).paddingSymmetrical( - 10.w, - 12.h, - ), + 10.w, 12.h), ); } void openAppointmentList(BuildContext context) { showCommonBottomSheetWithoutHeight( - title: "Select Appointment".needTranslation, + title: LocaleKeys.selectAppointment.tr(context: context), context, child: SizedBox( height: MediaQuery.sizeOf(context).height * .5, diff --git a/lib/presentation/emergency_services/call_ambulance/requesting_services_page.dart b/lib/presentation/emergency_services/call_ambulance/requesting_services_page.dart index 396e509..bc6d9b0 100644 --- a/lib/presentation/emergency_services/call_ambulance/requesting_services_page.dart +++ b/lib/presentation/emergency_services/call_ambulance/requesting_services_page.dart @@ -1,9 +1,11 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:lottie/lottie.dart'; @@ -27,8 +29,7 @@ class RequestingServicesPage extends StatelessWidget { .center, Positioned( bottom: 1, - child: "Submitting your request. \nPlease wait for a moment" - .needTranslation + child: LocaleKeys.submitRequest.tr(context: context) .toText16(color: AppColors.textColor, weight: FontWeight.w500) .paddingOnly(bottom: 100.h, left: 100.h, right: 100.h)) ], diff --git a/lib/presentation/emergency_services/call_ambulance/tracking_screen.dart b/lib/presentation/emergency_services/call_ambulance/tracking_screen.dart index e5dc0b9..9a49dd0 100644 --- a/lib/presentation/emergency_services/call_ambulance/tracking_screen.dart +++ b/lib/presentation/emergency_services/call_ambulance/tracking_screen.dart @@ -1,5 +1,6 @@ import 'dart:io'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/AmbulanceRequestOrdersModel.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/RRTServiceData.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -60,14 +62,14 @@ class TrackingScreen extends StatelessWidget { iconSize: 18.w, backgroundColor: AppColors.bgGreenColor, borderColor: Colors.transparent, - text: "Close".needTranslation, + text: LocaleKeys.close.tr(context: context), textColor: AppColors.whiteColor, onPressed: () {}, ).paddingOnly(left: 16.h, right: 16.h), ), ), body: CollapsingListView( - title: "Tracking Details".needTranslation, + title: LocaleKeys.trackingDetails.tr(context: context), child: SingleChildScrollView( child: Column( children: [ @@ -136,7 +138,7 @@ class TrackingScreen extends StatelessWidget { height: 16, ), CustomButton( - text: "Cancel Request".needTranslation, + text: LocaleKeys.cancelRequest.tr(context: context), onPressed: () async { openCancelOrderBottomSheet(context); }, @@ -162,7 +164,7 @@ class TrackingScreen extends StatelessWidget { iconSize: 18.w, backgroundColor: AppColors.lightRedButtonColor, borderColor: Colors.transparent, - text: "Share Your Live Location on Whatsapp".needTranslation, + text: LocaleKeys.shareLocationWhatsapp.tr(context: context), fontSize: 12.f, textColor: AppColors.primaryRedColor, iconColor: AppColors.primaryRedColor, @@ -280,7 +282,7 @@ class TrackingScreen extends StatelessWidget { return RichText( text: TextSpan(children: [ TextSpan( - text: "Please wait for the call".needTranslation, + text: LocaleKeys.pleaseWaitForCall.tr(), style: TextStyle( fontSize: 21.f, fontWeight: FontWeight.w600, @@ -288,7 +290,7 @@ class TrackingScreen extends StatelessWidget { ), ), TextSpan( - text: "...".needTranslation, + text: "...", style: TextStyle( fontSize: 21.f, fontWeight: FontWeight.w600, @@ -301,7 +303,7 @@ class TrackingScreen extends StatelessWidget { return RichText( text: TextSpan(children: [ TextSpan( - text: "15:30".needTranslation, + text: "15:30", style: TextStyle( fontSize: 21.f, fontWeight: FontWeight.w600, @@ -309,7 +311,7 @@ class TrackingScreen extends StatelessWidget { ), ), TextSpan( - text: " mins ".needTranslation, + text: LocaleKeys.mins.tr(), style: TextStyle( fontSize: 21.f, fontWeight: FontWeight.w600, @@ -317,7 +319,7 @@ class TrackingScreen extends StatelessWidget { ), ), TextSpan( - text: "to hospital".needTranslation, + text: LocaleKeys.toHospitalLower.tr(), style: TextStyle( fontSize: 21.f, fontWeight: FontWeight.w600, @@ -328,7 +330,7 @@ class TrackingScreen extends StatelessWidget { ); case OrderTrackingState.ended: - return "Arrived".needTranslation.toText21(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.arrived.tr().toText21(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.failed: case OrderTrackingState.cancel: return SizedBox.shrink(); @@ -386,8 +388,8 @@ class TrackingScreen extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, spacing: 4.h, children: [ - "Contact".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w600), - "0115259555".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500).onPress((){ + LocaleKeys.contact.tr().toText14(color: AppColors.textColor, weight: FontWeight.w600), + "0115259555".toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500).onPress((){ launchUrl( Uri.parse("tel://0115259555"), ); @@ -429,23 +431,24 @@ class TrackingScreen extends StatelessWidget { // } getTitle(OrderTrackingState? state) { - if(state == null) - return "Failed".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + if(state == null) { + return LocaleKeys.failed.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); + } switch (state) { case OrderTrackingState.waitingForCall: - return "Confirmation Call".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.confirmationCall.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.dispactched: - return "Pickup Up from Home".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.pickupFromHome.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.returning: - return " On The Way To Hospital".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.onTheWayToHospital.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.ended: - return "Arrived at Hospital".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.arrivedAtHospital.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.failed: - return "Failed".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.failed.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); case OrderTrackingState.cancel: - return "Order Cancel".needTranslation.toText16(color: AppColors.textColor, weight: FontWeight.w600); + return LocaleKeys.orderCancel.tr().toText16(color: AppColors.textColor, weight: FontWeight.w600); } } diff --git a/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart b/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart index 051c850..56a94e0 100644 --- a/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart +++ b/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart @@ -21,14 +21,12 @@ class PickupLocation extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Select Pickup Direction" - .needTranslation + LocaleKeys.selectPickupDirection.tr(context: context) .toText24(color: AppColors.textColor, isBold: true), SizedBox( height: 16.h, ), - "Select Direction" - .needTranslation + LocaleKeys.selectDirection.tr(context: context) .toText16(color: AppColors.textColor, weight: FontWeight.w600), SizedBox( height: 12.h, @@ -58,8 +56,7 @@ class PickupLocation extends StatelessWidget { activeColor: AppColors.primaryRedColor, fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), ), - "To Hospital" - .needTranslation + LocaleKeys.toHospital.tr(context: context) .toText14(color: AppColors.textColor, weight: FontWeight.w500) ], ).onPress(() { @@ -84,8 +81,7 @@ class PickupLocation extends StatelessWidget { activeColor: AppColors.primaryRedColor, fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), ), - "From Hospital" - .needTranslation + LocaleKeys.fromHospital.tr(context: context) .toText14(color: AppColors.textColor, weight: FontWeight.w500) ], ).onPress(() { @@ -105,8 +101,7 @@ class PickupLocation extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 16.h), - "Select Way" - .needTranslation + LocaleKeys.selectWay.tr(context: context) .toText16(color: AppColors.textColor, weight: FontWeight.w600), SizedBox(height: 12.h), Row( @@ -128,8 +123,7 @@ class PickupLocation extends StatelessWidget { activeColor: AppColors.primaryRedColor, fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), ), - "One Way" - .needTranslation + LocaleKeys.oneWay.tr(context: context) .toText12(color: AppColors.textColor, fontWeight: FontWeight.w500) ], ).onPress(() { @@ -154,8 +148,7 @@ class PickupLocation extends StatelessWidget { activeColor: AppColors.primaryRedColor, fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), ), - "Two Way" - .needTranslation + LocaleKeys.twoWay.tr(context: context) .toText14(color: AppColors.textColor, weight: FontWeight.w500) ], ).onPress(() { diff --git a/lib/presentation/emergency_services/call_ambulance/widgets/type_selection_widget.dart b/lib/presentation/emergency_services/call_ambulance/widgets/type_selection_widget.dart index 1b85165..3ae93d0 100644 --- a/lib/presentation/emergency_services/call_ambulance/widgets/type_selection_widget.dart +++ b/lib/presentation/emergency_services/call_ambulance/widgets/type_selection_widget.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/facility_selection.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -27,7 +29,7 @@ class TypeSelectionWidget extends StatelessWidget { mainAxisSize: MainAxisSize.max, children: [ AppCustomChipWidget( - labelText: "All Facilities".needTranslation, + labelText: LocaleKeys.all.tr(context: context), shape: RoundedRectangleBorder( side: BorderSide( color: selectedFacility == FacilitySelection.ALL @@ -50,7 +52,7 @@ class TypeSelectionWidget extends StatelessWidget { child: AppCustomChipWidget( icon: AppAssets.hmg, iconHasColor: false, - labelText: "Hospitals".needTranslation, + labelText: LocaleKeys.hmgHospitals.tr(context: context), shape: RoundedRectangleBorder( side: BorderSide( color: selectedFacility == FacilitySelection.HMG @@ -74,7 +76,7 @@ class TypeSelectionWidget extends StatelessWidget { child: AppCustomChipWidget( icon: AppAssets.hmc, iconHasColor: false, - labelText: "Medical Centers".needTranslation, + labelText: LocaleKeys.hmcMedicalClinic.tr(context: context), shape: RoundedRectangleBorder( side: BorderSide( color: selectedFacility == FacilitySelection.HMC diff --git a/lib/presentation/emergency_services/emergency_services_page.dart b/lib/presentation/emergency_services/emergency_services_page.dart index 3833d32..a5281ca 100644 --- a/lib/presentation/emergency_services/emergency_services_page.dart +++ b/lib/presentation/emergency_services/emergency_services_page.dart @@ -59,9 +59,8 @@ class EmergencyServicesPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Call Ambulance".needTranslation.toText16(isBold: true, color: AppColors.blackColor), - "Request an ambulance in emergency from home or hospital" - .needTranslation + LocaleKeys.callAmbulance.tr().toText16(isBold: true, color: AppColors.blackColor), + LocaleKeys.requestAmbulanceInEmergency.tr() .toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), ], ), @@ -100,10 +99,9 @@ class EmergencyServicesPage extends StatelessWidget { Lottie.asset(AppAnimations.ambulanceAlert, repeat: false, reverse: false, frameRate: FrameRate(60), width: 120.h, height: 120.h, fit: BoxFit.contain), SizedBox(height: 8.h), - "Confirmation".needTranslation.toText28(color: AppColors.whiteColor, isBold: true), + LocaleKeys.confirmation.tr().toText28(color: AppColors.whiteColor, isBold: true), SizedBox(height: 8.h), - "Are you sure you want to call an ambulance?" - .needTranslation + LocaleKeys.areYouSureYouWantToCallAmbulance.tr() .toText14(color: AppColors.whiteColor, weight: FontWeight.w500), SizedBox(height: 24.h), CustomButton( @@ -148,9 +146,8 @@ class EmergencyServicesPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Nearest ER Location".needTranslation.toText16(isBold: true, color: AppColors.blackColor), - "Get the details of nearest branch including directions" - .needTranslation + LocaleKeys.nearester.tr(context: context).toText16(isBold: true, color: AppColors.blackColor), + LocaleKeys.getDetailsOfNearestBranch.tr() .toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), ], ), @@ -178,7 +175,7 @@ class EmergencyServicesPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Rapid Response Team (RRT)".toText16(isBold: true, color: AppColors.blackColor), + LocaleKeys.rapidResponseTeam.tr(context: context).toText16(isBold: true, color: AppColors.blackColor), "Comprehensive medical service for all sorts of urgent and stable cases" .toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), ], @@ -204,8 +201,7 @@ class EmergencyServicesPage extends StatelessWidget { SizedBox(height: 8.h), LocaleKeys.confirm.tr().toText28(color: AppColors.whiteColor, isBold: true), SizedBox(height: 8.h), - "Are you sure you want to call Rapid Response Team (RRT)?" - .needTranslation + LocaleKeys.areYouSureYouWantToCallRRT.tr() .toText14(color: AppColors.whiteColor, weight: FontWeight.w500), SizedBox(height: 24.h), CustomButton( @@ -278,9 +274,8 @@ class EmergencyServicesPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Emergency Check-In".needTranslation.toText16(isBold: true, color: AppColors.blackColor), - "Prior ER Check-In to skip the line & payment at the reception." - .needTranslation + LocaleKeys.emergencyCheckIn.tr(context: context).toText16(isBold: true, color: AppColors.blackColor), + LocaleKeys.priorERCheckInToSkipLine.tr() .toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), ], ), @@ -318,13 +313,13 @@ class EmergencyServicesPage extends StatelessWidget { SizedBox(height: 8.h), LocaleKeys.confirm.tr().toText28(color: AppColors.whiteColor, isBold: true), SizedBox(height: 8.h), - "Are you sure you want to make ER Check-In?".needTranslation.toText14(color: AppColors.whiteColor, weight: FontWeight.w500), + LocaleKeys.areYouSureYouWantToMakeERCheckIn.tr().toText14(color: AppColors.whiteColor, weight: FontWeight.w500), SizedBox(height: 24.h), CustomButton( text: LocaleKeys.confirm.tr(context: context), onPressed: () async { Navigator.of(context).pop(); - LoaderBottomSheet.showLoader(loadingText: "Checking your ER Appointment status...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingYourERAppointmentStatus.tr()); await context.read().checkPatientERAdvanceBalance(onSuccess: (dynamic response) { LoaderBottomSheet.hideLoader(); context.read().navigateToEROnlineCheckIn(); @@ -389,7 +384,7 @@ class EmergencyServicesPage extends StatelessWidget { void openTranportationSelectionBottomSheet(BuildContext context) { if (emergencyServicesViewModel.transportationOptions.isNotEmpty) { showCommonBottomSheetWithoutHeight( - title: "Transport Options".needTranslation, + title: LocaleKeys.transportOptions.tr(), context, child: SizedBox( height: 400.h, diff --git a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_home.dart b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_home.dart index ee061b7..999a43e 100644 --- a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_home.dart +++ b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_home.dart @@ -38,7 +38,7 @@ class ErOnlineCheckinHome extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Emergency Check-In".needTranslation, + title: LocaleKeys.emergencyCheckIn.tr(context: context), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.all(24.h), @@ -53,8 +53,8 @@ class ErOnlineCheckinHome extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Online Check-In".needTranslation.toText18(color: AppColors.textColor, isBold: true), - "This service lets patients to register their ER appointment prior to arrival.".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.onlineCheckIn.tr().toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.erOnlineCheckInDescription.tr().toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ), @@ -74,7 +74,7 @@ class ErOnlineCheckinHome extends StatelessWidget { showNfcReader(context, onNcfScan: (String nfcId) { Future.delayed(const Duration(milliseconds: 100), () async { print(nfcId); - LoaderBottomSheet.showLoader(loadingText: "Processing check-in...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingCheckIn.tr()); await emergencyServicesViewModel.getProjectIDFromNFC( nfcCode: nfcId, onSuccess: (value) async { @@ -84,7 +84,7 @@ class ErOnlineCheckinHome extends StatelessWidget { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.onlineCheckIn.tr(), - child: Utils.getSuccessWidget(loadingText: "Your ER Online Check-In has been successfully done. Please proceed to the waiting area.".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.erOnlineCheckInSuccess.tr()), callBackFunc: () { Navigator.pushAndRemoveUntil( context, @@ -98,7 +98,7 @@ class ErOnlineCheckinHome extends StatelessWidget { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Unexpected error occurred during check-in. Please contact support.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.erOnlineCheckInError.tr()), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -117,7 +117,7 @@ class ErOnlineCheckinHome extends StatelessWidget { // callBackFunc: () {}, // isFullScreen: false); } else { - LoaderBottomSheet.showLoader(loadingText: "Fetching hospitals list...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingHospitalsList.tr()); await context.read().getProjects(); LoaderBottomSheet.hideLoader(); //Project Selection Dropdown @@ -155,10 +155,19 @@ class ErOnlineCheckinHome extends StatelessWidget { onHospitalClicked: (hospital) async { Navigator.pop(context); vm.setSelectedHospital(hospital); - LoaderBottomSheet.showLoader(loadingText: "Fetching payment information...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPaymentInformation.tr(context: context)); await vm.getPatientERPaymentInformation(onSuccess: (response) { LoaderBottomSheet.hideLoader(); vm.navigateToEROnlineCheckInPaymentPage(); + }, onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err.toString()), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); }); }, onHospitalSearch: (value) { diff --git a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_details_page.dart b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_details_page.dart index f48efe7..463121d 100644 --- a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_details_page.dart +++ b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_details_page.dart @@ -34,7 +34,7 @@ class ErOnlineCheckinPaymentDetailsPage extends StatelessWidget { children: [ Expanded( child: CollapsingListView( - title: "Emergency Check-In".needTranslation, + title: LocaleKeys.emergencyCheckIn.tr(context: context), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.all(24.h), @@ -52,7 +52,7 @@ class ErOnlineCheckinPaymentDetailsPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "ER Visit Details".needTranslation.toText18(color: AppColors.textColor, isBold: true), + LocaleKeys.erVisitDetails.tr().toText18(color: AppColors.textColor, isBold: true), SizedBox(height: 24.h), Row( children: [ @@ -62,25 +62,22 @@ class ErOnlineCheckinPaymentDetailsPage extends StatelessWidget { SizedBox(height: 12.h), Wrap( direction: Axis.horizontal, - spacing: 6.w, + spacing: 4.w, runSpacing: 6.h, children: [ AppCustomChipWidget( - labelText: "File No.: ${appState.getAuthenticatedUser()!.patientId!.toString()}", - labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w), + labelText: "${LocaleKeys.fileno.tr(context: context)}.: ${appState.getAuthenticatedUser()!.patientId!.toString()}", ), AppCustomChipWidget( - labelText: "ER Clinic".needTranslation, - labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w), + labelText: LocaleKeys.erClinic.tr(), ), AppCustomChipWidget( labelText: emergencyServicesViewModel.selectedHospital!.name, - labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w), ), AppCustomChipWidget( icon: AppAssets.calendar, labelText: DateUtil.formatDateToDate(DateTime.now(), false), - labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w), + labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 8.w), ), ], ), @@ -111,7 +108,7 @@ class ErOnlineCheckinPaymentDetailsPage extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText18(isBold: true), + LocaleKeys.amountBeforeTax.tr().toText18(isBold: true), Utils.getPaymentAmountWithSymbol(emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientShare.toString().toText16(isBold: true), AppColors.blackColor, 13, isSaudiCurrency: true), ], @@ -121,8 +118,8 @@ class ErOnlineCheckinPaymentDetailsPage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(child: "".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor)), - "VAT 15% (${emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientTaxAmount})" - .needTranslation + LocaleKeys.vatWithAmount + .tr(namedArgs: {"amount": emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientTaxAmount.toString()}) .toText14(isBold: true, color: AppColors.greyTextColor, letterSpacing: -1), ], ), diff --git a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_page.dart b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_page.dart index 8de7518..3510197 100644 --- a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_page.dart +++ b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_payment_page.dart @@ -80,7 +80,7 @@ class _ErOnlineCheckinPaymentPageState extends State children: [ Expanded( child: CollapsingListView( - title: "Emergency Check-In".needTranslation, + title: LocaleKeys.emergencyCheckIn.tr(context: context), child: SingleChildScrollView( child: Column( children: [ @@ -99,7 +99,7 @@ class _ErOnlineCheckinPaymentPageState extends State children: [ Image.asset(AppAssets.mada, width: 72.h, height: 25.h), SizedBox(height: 16.h), - "Mada".needTranslation.toText16(isBold: true), + LocaleKeys.mada.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -141,7 +141,7 @@ class _ErOnlineCheckinPaymentPageState extends State ], ), SizedBox(height: 16.h), - "Visa or Mastercard".needTranslation.toText16(isBold: true), + LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -178,7 +178,7 @@ class _ErOnlineCheckinPaymentPageState extends State children: [ Image.asset(AppAssets.tamaraEng, width: 72.h, height: 25.h), SizedBox(height: 16.h), - "Tamara".needTranslation.toText16(isBold: true), + LocaleKeys.tamara.tr(context: context).toText16(isBold: true), ], ), SizedBox(width: 8.h), @@ -229,8 +229,8 @@ class _ErOnlineCheckinPaymentPageState extends State child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Insurance expired or inactive".needTranslation.toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h), - CustomButton( + LocaleKeys.insuranceExpiredOrInactive.tr(context: context).toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h), + CustomButton( text: LocaleKeys.updateInsurance.tr(context: context), onPressed: () { Navigator.of(context).push( @@ -253,12 +253,12 @@ class _ErOnlineCheckinPaymentPageState extends State ) : const SizedBox(), SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol(emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientShare.toString().toText16(isBold: true), AppColors.blackColor, 13, isSaudiCurrency: true), ], @@ -266,7 +266,7 @@ class _ErOnlineCheckinPaymentPageState extends State Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientTaxAmount.toString().toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, 13, isSaudiCurrency: true), @@ -276,7 +276,7 @@ class _ErOnlineCheckinPaymentPageState extends State Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "".needTranslation.toText14(isBold: true), + "".toText14(isBold: true), Utils.getPaymentAmountWithSymbol(emergencyServicesViewModel.erOnlineCheckInPaymentDetailsResponse.patientShareWithTax.toString().toText24(isBold: true), AppColors.blackColor, 17, isSaudiCurrency: true), ], @@ -337,8 +337,6 @@ class _ErOnlineCheckinPaymentPageState extends State } startApplePay() async { - // showCommonBottomSheet(context, - // child: Utils.getLoadingWidget(), callBackFunc: (str) {}, title: "", height: ResponsiveExtension.screenHeight * 0.3, isCloseButtonVisible: false, isDismissible: false, isFullScreen: false); LoaderBottomSheet.showLoader(); transID = Utils.getAdvancePaymentTransID( emergencyServicesViewModel.selectedHospital!.iD, @@ -405,8 +403,8 @@ class _ErOnlineCheckinPaymentPageState extends State applePayShaRequestPhrase: payfortViewModel.payfortProjectDetailsRespModel!.shaRequest, currency: appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED", onFailed: (failureResult) async { + LoaderBottomSheet.hideLoader(); log("failureResult: ${failureResult.message.toString()}"); - Navigator.of(context).pop(); showCommonBottomSheetWithoutHeight( context, child: Utils.getErrorWidget(loadingText: failureResult.message.toString()), @@ -416,6 +414,7 @@ class _ErOnlineCheckinPaymentPageState extends State ); }, onSucceeded: (successResult) async { + LoaderBottomSheet.hideLoader(); log("successResult: ${successResult.responseMessage.toString()}"); selectedPaymentMethod = successResult.paymentOption ?? "VISA"; checkPaymentStatus(); @@ -425,7 +424,7 @@ class _ErOnlineCheckinPaymentPageState extends State } void checkPaymentStatus() async { - LoaderBottomSheet.showLoader(loadingText: "Checking payment status, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context)); await payfortViewModel.checkPaymentStatus( transactionID: transID, onSuccess: (apiResponse) async { @@ -445,7 +444,7 @@ class _ErOnlineCheckinPaymentPageState extends State if (emergencyServicesViewModel.isERBookAppointment) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Your appointment has been booked successfully. Please perform Check-In once you arrive at the hospital.".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.erAppointmentBookedSuccess.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -458,7 +457,7 @@ class _ErOnlineCheckinPaymentPageState extends State LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_select_checkin_bottom_sheet.dart b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_select_checkin_bottom_sheet.dart index e717d0f..28c7d2a 100644 --- a/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_select_checkin_bottom_sheet.dart +++ b/lib/presentation/emergency_services/er_online_checkin/er_online_checkin_select_checkin_bottom_sheet.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_nfc_kit/flutter_nfc_kit.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; // import 'package:barcode_scan2/barcode_scan2.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; @@ -35,8 +37,8 @@ class ErOnlineCheckinSelectCheckinBottomSheet extends StatelessWidget { children: [ checkInOptionCard( AppAssets.checkin_location_icon, - "Live Location".needTranslation, - "Verify your location to be at hospital to check in".needTranslation, + LocaleKeys.liveLocation.tr(context: context), + LocaleKeys.verifyYourLocationAtHospital.tr(context: context), ).onPress(() { // locationUtils = LocationUtils( // isShowConfirmDialog: false, @@ -51,8 +53,8 @@ class ErOnlineCheckinSelectCheckinBottomSheet extends StatelessWidget { sendCheckInRequest(projectDetailListModel.checkInQrCode!, context); } else { showCommonBottomSheetWithoutHeight(context, - title: "Error".needTranslation, - child: Utils.getErrorWidget(loadingText: "Please ensure you're within the hospital location to perform online check-in.".needTranslation), callBackFunc: () { + title: LocaleKeys.error.tr(context: context), + child: Utils.getErrorWidget(loadingText: LocaleKeys.ensureWithinHospitalLocation.tr(context: context),), callBackFunc: () { Navigator.of(context).pop(); }, isFullScreen: false); } @@ -61,8 +63,8 @@ class ErOnlineCheckinSelectCheckinBottomSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_nfc_icon, - "NFC (Near Field Communication)".needTranslation, - "Scan your phone via NFC board to check in".needTranslation, + LocaleKeys.nfcNearFieldCommunication.tr(context: context), + LocaleKeys.scanPhoneViaNFC.tr(context: context), ).onPress(() { Future.delayed(const Duration(milliseconds: 500), () { showNfcReader(context, onNcfScan: (String nfcId) { @@ -75,8 +77,8 @@ class ErOnlineCheckinSelectCheckinBottomSheet extends StatelessWidget { SizedBox(height: 16.h), checkInOptionCard( AppAssets.checkin_qr_icon, - "QR Code".needTranslation, - "Scan QR code with your camera to check in".needTranslation, + LocaleKeys.qrCode.tr(context: context), + LocaleKeys.scanQRCodeToCheckIn.tr(context: context), ).onPress(() async { // String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent)); // if (onlineCheckInQRCode != "") { diff --git a/lib/presentation/emergency_services/history/er_history_listing.dart b/lib/presentation/emergency_services/history/er_history_listing.dart index fe1ed31..a60d455 100644 --- a/lib/presentation/emergency_services/history/er_history_listing.dart +++ b/lib/presentation/emergency_services/history/er_history_listing.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart' show AppAssets; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -8,6 +9,7 @@ import 'package:hmg_patient_app_new/features/emergency_services/emergency_servic import 'package:hmg_patient_app_new/features/emergency_services/models/OrderDisplay.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/AmbulanceRequestOrdersModel.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/RRTServiceData.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/history/widget/ambulance_history_item.dart' show AmbulanceHistoryItem; import 'package:hmg_patient_app_new/presentation/emergency_services/history/widget/rrt_item.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -24,7 +26,7 @@ class ErHistoryListing extends StatelessWidget { Expanded( child: CollapsingListView( - title: "History Log".needTranslation, + title: LocaleKeys.history.tr(context: context), child: SingleChildScrollView( physics: NeverScrollableScrollPhysics(), child: Column( @@ -55,12 +57,10 @@ class ErHistoryListing extends StatelessWidget { }), ), Visibility( - visible: data.$1 - ?.isEmpty == true, child: Center( - child: Utils.getNoDataWidget(context, - noDataText: "You don't have any history" - .needTranslation), - )), + visible: data.$1.isEmpty == true, + child: Center( + child: Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDataAvailable.tr(context: context)), + )), ], ); } @@ -92,9 +92,9 @@ class ErHistoryListing extends StatelessWidget { return Row( spacing: 8.h, children: [ - if(dataList?.isNotEmpty == true) + if(dataList.isNotEmpty == true) AppCustomChipWidget( - labelText: "All Facilities".needTranslation, + labelText: LocaleKeys.allFacilities.tr(context: context), shape: RoundedRectangleBorder( side: BorderSide( color: value == OrderDislpay.ALL ? AppColors.errorColor : AppColors.chipBorderColorOpacity20, @@ -111,7 +111,7 @@ class ErHistoryListing extends StatelessWidget { .ambulanceOrders ?.isNotEmpty == true) AppCustomChipWidget( - labelText: "Ambulance".needTranslation, + labelText: LocaleKeys.ambulancerequest.tr(context: context), icon: AppAssets.ambulance, shape: RoundedRectangleBorder( side: BorderSide( @@ -130,7 +130,7 @@ class ErHistoryListing extends StatelessWidget { ?.completedOrders .isNotEmpty == true) AppCustomChipWidget( - labelText: "Rapid Response Team".needTranslation, + labelText: LocaleKeys.rapidResponseTeam.tr(context: context), icon: AppAssets.ic_rrt_vehicle, shape: RoundedRectangleBorder( side: BorderSide( diff --git a/lib/presentation/emergency_services/history/widget/RequestStatus.dart b/lib/presentation/emergency_services/history/widget/RequestStatus.dart index 4f39a49..849565a 100644 --- a/lib/presentation/emergency_services/history/widget/RequestStatus.dart +++ b/lib/presentation/emergency_services/history/widget/RequestStatus.dart @@ -1,8 +1,9 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; - class RequestStatus extends StatelessWidget { final int status; @@ -21,14 +22,13 @@ class RequestStatus extends StatelessWidget { switch (status) { case 1: //pending case 2: //processing - return "Under Processing".needTranslation; - case 3: //completed - return "Completed".needTranslation; - break; + return LocaleKeys.underProcessing.tr(); + case 3: + return LocaleKeys.completed.tr(); case 4: //cancel case 6: case 7: - return "Canceled by patient".needTranslation; + return LocaleKeys.canceledByPatient.tr(); break; } return null; diff --git a/lib/presentation/emergency_services/history/widget/ambulance_history_item.dart b/lib/presentation/emergency_services/history/widget/ambulance_history_item.dart index f3ec388..7b17eab 100644 --- a/lib/presentation/emergency_services/history/widget/ambulance_history_item.dart +++ b/lib/presentation/emergency_services/history/widget/ambulance_history_item.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/AmbulanceRequestOrdersModel.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/history/widget/RequestStatus.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -40,7 +42,7 @@ class AmbulanceHistoryItem extends StatelessWidget { spacing: 4.w, children: [ chip( Utils.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(order.time)), AppAssets.calendar, AppColors.blackBgColor), - chip("Ambulance".needTranslation, AppAssets.ambulance, AppColors.blackBgColor), + chip(LocaleKeys.ambulancerequest.tr(context: context), AppAssets.ambulance, AppColors.blackBgColor), ], ), Row( @@ -52,7 +54,7 @@ class AmbulanceHistoryItem extends StatelessWidget { ), if (order.statusId == 1 || order.statusId == 2) CustomButton( - text: "Cancel Request".needTranslation, + text: LocaleKeys.cancelRequest.tr(context: context), onPressed: () async { openCancelOrderBottomSheet(context); }, diff --git a/lib/presentation/emergency_services/history/widget/rrt_item.dart b/lib/presentation/emergency_services/history/widget/rrt_item.dart index dfb6e79..d345e2d 100644 --- a/lib/presentation/emergency_services/history/widget/rrt_item.dart +++ b/lib/presentation/emergency_services/history/widget/rrt_item.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/RRTServiceData.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/history/widget/RequestStatus.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -40,13 +42,13 @@ class RRTItem extends StatelessWidget { spacing: 4.w, children: [ chip( Utils.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(order.time)), AppAssets.calendar, AppColors.blackBgColor), - chip("Rapid Response Team(RRT)".needTranslation, AppAssets.ic_rrt_vehicle, AppColors.blackBgColor), + chip(LocaleKeys.rapidResponseTeam.tr(context: context), AppAssets.ic_rrt_vehicle, AppColors.blackBgColor), ], ), SizedBox(height: 4.h), if (order.statusId == 1 || order.statusId == 2) CustomButton( - text: "Cancel Request".needTranslation, + text: LocaleKeys.cancelRequest.tr(context: context), onPressed: () async { openCancelOrderBottomSheet(context); }, diff --git a/lib/presentation/emergency_services/nearest_er_page.dart b/lib/presentation/emergency_services/nearest_er_page.dart index 16863bf..0ea3ab8 100644 --- a/lib/presentation/emergency_services/nearest_er_page.dart +++ b/lib/presentation/emergency_services/nearest_er_page.dart @@ -36,7 +36,7 @@ class _NearestErPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "Nearest ER".needTranslation, + title: LocaleKeys.nearester.tr(context: context), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -44,7 +44,7 @@ class _NearestErPageState extends State { children: [ TextInputWidget( labelText: LocaleKeys.search.tr(), - hintText: 'Type any facility name'.needTranslation, + hintText: 'Type any facility name', controller: searchText, onChange: (value) { debouncer.run(() { @@ -92,7 +92,7 @@ class _NearestErPageState extends State { }, ); } else { - return Center(child: Utils.getNoDataWidget(context, noDataText: "No nearest Er Arround you".needTranslation)); + return Center(child: Utils.getNoDataWidget(context, noDataText: "No nearest Er Around you")); } }), ), diff --git a/lib/presentation/emergency_services/widgets/location_input_bottom_sheet.dart b/lib/presentation/emergency_services/widgets/location_input_bottom_sheet.dart index c5301ea..db45654 100644 --- a/lib/presentation/emergency_services/widgets/location_input_bottom_sheet.dart +++ b/lib/presentation/emergency_services/widgets/location_input_bottom_sheet.dart @@ -31,7 +31,7 @@ class LocationInputBottomSheet extends StatelessWidget { children: [ TextInputWidget( labelText: LocaleKeys.search.tr(), - hintText: "Search Location".needTranslation, + hintText: LocaleKeys.selectLocation.tr(context: context), controller: TextEditingController(), onChange: (value){ debouncer.run(() { diff --git a/lib/presentation/emergency_services/widgets/nearestERItem.dart b/lib/presentation/emergency_services/widgets/nearestERItem.dart index bbce56a..2226f82 100644 --- a/lib/presentation/emergency_services/widgets/nearestERItem.dart +++ b/lib/presentation/emergency_services/widgets/nearestERItem.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/ProjectAvgERWaitingTime.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -67,14 +69,14 @@ class NearestERItem extends StatelessWidget { spacing: 8.h, children: [ AppCustomChipWidget( - labelText: "${nearestERItem.distanceInKilometers} km".needTranslation, + labelText: "${nearestERItem.distanceInKilometers} km", icon: AppAssets.location, iconHasColor: false, labelPadding: EdgeInsetsDirectional.only(start: 4.h, end: 0.h), padding: EdgeInsets.all(8.h), ).toShimmer2(isShow: isLoading), AppCustomChipWidget( - labelText: "Expected waiting time: ${nearestERItem.getTime()} mins".needTranslation, + labelText: "Expected waiting time: ${nearestERItem.getTime()} mins", icon: AppAssets.waiting_time_clock, iconHasColor: false, labelPadding: EdgeInsetsDirectional.only(start: 4.h, end: 0.h), @@ -87,7 +89,7 @@ class NearestERItem extends StatelessWidget { children: [ Expanded( child: CustomButton( - text: "View Location on Google Maps".needTranslation, + text: LocaleKeys.viewLocationGoogleMaps.tr(context: context), iconSize: 18.h, icon: AppAssets.location, onPressed: () { diff --git a/lib/presentation/habib_wallet/habib_wallet_page.dart b/lib/presentation/habib_wallet/habib_wallet_page.dart index a7ec23d..c90003a 100644 --- a/lib/presentation/habib_wallet/habib_wallet_page.dart +++ b/lib/presentation/habib_wallet/habib_wallet_page.dart @@ -82,28 +82,26 @@ class _HabibWalletState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( + height: 40.h, icon: AppAssets.recharge_icon, - iconSize: 21.h, - text: "Recharge".needTranslation, + iconSize: 24.w, + backgroundColor: AppColors.infoColor, + textColor: AppColors.whiteColor, + text: LocaleKeys.recharge.tr(context: context), + borderWidth: 0.w, + fontWeight: FontWeight.w500, + borderColor: Colors.transparent, + padding: EdgeInsets.fromLTRB(4, 0, 12, 0), + fontSize: 14.f, onPressed: () { Navigator.of(context) - .push( - CustomPageRoute( - page: RechargeWalletPage(), - ), - ) + .push(CustomPageRoute( + page: RechargeWalletPage(), + )) .then((val) { habibWalletVM.getPatientBalanceAmount(); }); }, - backgroundColor: AppColors.infoColor, - borderColor: AppColors.infoColor, - textColor: AppColors.whiteColor, - fontSize: 14, - fontWeight: FontWeight.bold, - borderRadius: 12, - // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, ), ], ), diff --git a/lib/presentation/habib_wallet/recharge_wallet_page.dart b/lib/presentation/habib_wallet/recharge_wallet_page.dart index 74eebec..b8e2d01 100644 --- a/lib/presentation/habib_wallet/recharge_wallet_page.dart +++ b/lib/presentation/habib_wallet/recharge_wallet_page.dart @@ -80,37 +80,33 @@ class _RechargeWalletPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ //TODO: Check with hussain to show AED or SAR - "Enter an amount".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.amount.tr(context: context).toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), Spacer(), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ - Utils.getPaymentAmountWithSymbol( - SizedBox( - width: 150.h, - child: TextInputWidget( - controller: amountTextController, - labelText: "", - hintText: "", - isEnable: true, - prefix: null, - isAllowRadius: true, - isBorderAllowed: false, - isAllowLeadingIcon: true, - autoFocus: true, - fontSize: 40, - padding: EdgeInsets.symmetric(horizontal: 8.h, vertical: 0.h), - focusNode: textFocusNode, - isWalletAmountInput: true, - keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true), - // leadingIcon: AppAssets.student_card, - ), - ), - AppColors.textColor, - 13.h, - isExpanded: false), + SizedBox( + width: 150.h, + child: TextInputWidget( + controller: amountTextController, + labelText: "", + hintText: "", + isEnable: true, + prefix: null, + isAllowRadius: true, + isBorderAllowed: false, + isAllowLeadingIcon: true, + autoFocus: true, + fontSize: 40, + padding: EdgeInsets.symmetric(horizontal: 8.h, vertical: 0.h), + focusNode: textFocusNode, + isWalletAmountInput: true, + keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true), + // leadingIcon: AppAssets.student_card, + ), + ), const Spacer(), - "SAR".needTranslation.toText20(color: AppColors.greyTextColor, weight: FontWeight.w500), + LocaleKeys.sar.tr(context: context).toText20(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), ], @@ -140,9 +136,9 @@ class _RechargeWalletPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - (habibWalletVM.getSelectedRechargeTypeValue()).toText16(color: AppColors.textColor, weight: FontWeight.w500), + (habibWalletVM.getSelectedRechargeTypeValue()).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), "${LocaleKeys.medicalFile.tr(context: context)}: ${habibWalletVM.fileNumber}" - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + .toText14(color: AppColors.textColor, weight: FontWeight.w500, letterSpacing: -0.2), ], ), ], @@ -151,7 +147,7 @@ class _RechargeWalletPageState extends State { ], ).onPress(() async { habibWalletVM.setCurrentIndex(0); - showCommonBottomSheetWithoutHeight(context, title: "Select Medical File".needTranslation, + showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.medicalFile.tr(context: context), titleWidget: Consumer(builder: (context, habibWalletVM, child) { return habibWalletVM.currentIndex != 0 ? IconButton( @@ -160,7 +156,7 @@ class _RechargeWalletPageState extends State { onPressed: () => habibWalletVM.setCurrentIndex(0), highlightColor: Colors.transparent, ) - : "Select Medical File".needTranslation.toText20(weight: FontWeight.w600); + : LocaleKeys.medicalFile.tr(context: context).toText20(weight: FontWeight.w600); }), child: Consumer(builder: (context, habibWalletVM, child) { return MultiPageBottomSheet(); }), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true); @@ -178,11 +174,11 @@ class _RechargeWalletPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.hospital.tr(context: context).toText16(color: AppColors.textColor, weight: FontWeight.w500), + LocaleKeys.hospital.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), SizedBox( width: MediaQuery.of(context).size.width * 0.55, child: (habibWalletVM.selectedHospital != null ? habibWalletVM.selectedHospital!.name : LocaleKeys.selectHospital.tr(context: context))! - .toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + .toText14(color: AppColors.textColor, weight: FontWeight.w500), ), ], ), @@ -198,19 +194,14 @@ class _RechargeWalletPageState extends State { Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h), SizedBox(height: 16.h), Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Row( + Utils.buildSvgWithAssets(icon: AppAssets.email_icon, width: 40.h, height: 40.h), + SizedBox(width: 8.h), + Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Utils.buildSvgWithAssets(icon: AppAssets.email_icon, width: 40.h, height: 40.h), - SizedBox(width: 8.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - LocaleKeys.email.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), - "${appState.getAuthenticatedUser()!.emailAddress}".toText16(color: AppColors.textColor, weight: FontWeight.w500), - ], - ), + LocaleKeys.email.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), + "${appState.getAuthenticatedUser()!.emailAddress}".toText14(color: AppColors.textColor, weight: FontWeight.w500, letterSpacing: -0.2), ], ), ], @@ -229,7 +220,7 @@ class _RechargeWalletPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.notes.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), - "Lorem Ipsum".toText16(color: AppColors.textColor, weight: FontWeight.w500), + "Lorem Ipsum".toText14(color: AppColors.textColor, weight: FontWeight.w500, letterSpacing: -0.2), ], ), ], @@ -261,7 +252,7 @@ class _RechargeWalletPageState extends State { if (amountTextController.text.isEmpty) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Please enter amount to continue.".needTranslation), + child: Utils.getErrorWidget(loadingText: "Please enter amount to continue."), callBackFunc: () { textFocusNode.requestFocus(); }, @@ -271,7 +262,7 @@ class _RechargeWalletPageState extends State { } else if (habibWalletVM.selectedHospital == null) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Please select hospital to continue.".needTranslation), + child: Utils.getErrorWidget(loadingText: "Please select hospital to continue."), callBackFunc: () { textFocusNode.requestFocus(); }, diff --git a/lib/presentation/habib_wallet/wallet_payment_confirm_page.dart b/lib/presentation/habib_wallet/wallet_payment_confirm_page.dart index 1341af7..4585b7d 100644 --- a/lib/presentation/habib_wallet/wallet_payment_confirm_page.dart +++ b/lib/presentation/habib_wallet/wallet_payment_confirm_page.dart @@ -82,7 +82,7 @@ class _WalletPaymentConfirmPageState extends State { children: [ Image.asset(AppAssets.mada, width: 72.h, height: 25.h).toShimmer2(isShow: false), SizedBox(height: 16.h), - "Mada".needTranslation.toText16(isBold: true).toShimmer2(isShow: false), + LocaleKeys.mada.tr(context: context).toText16(isBold: true).toShimmer2(isShow: false), ], ), SizedBox(width: 8.h), @@ -124,7 +124,7 @@ class _WalletPaymentConfirmPageState extends State { ], ).toShimmer2(isShow: false), SizedBox(height: 16.h), - "Visa or Mastercard".needTranslation.toText16(isBold: true).toShimmer2(isShow: false), + LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true).toShimmer2(isShow: false), ], ), SizedBox(width: 8.h), @@ -180,7 +180,7 @@ class _WalletPaymentConfirmPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Total amount to pay".needTranslation.toText16(isBold: true), + LocaleKeys.totalAmountToPay.tr(context: context).toText16(isBold: true), Utils.getPaymentAmountWithSymbol(habibWalletVM.walletRechargeAmount.toString().toText24(isBold: true), AppColors.blackColor, 15.h, isSaudiCurrency: true), ], ).paddingSymmetrical(24.h, 0.h), @@ -314,8 +314,10 @@ class _WalletPaymentConfirmPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Payment Successful!".needTranslation), + child: Utils.getSuccessWidget(loadingText: "Payment Successful!"), callBackFunc: () { + habibWalletVM.initHabibWalletProvider(); + habibWalletVM.getPatientBalanceAmount(); Navigator.of(context).pop(); Navigator.of(context).pop(); }, @@ -327,7 +329,7 @@ class _WalletPaymentConfirmPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed - ${err}".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -339,7 +341,7 @@ class _WalletPaymentConfirmPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/habib_wallet/widgets/select-medical_file.dart b/lib/presentation/habib_wallet/widgets/select-medical_file.dart index 73a7dfe..aaa0036 100644 --- a/lib/presentation/habib_wallet/widgets/select-medical_file.dart +++ b/lib/presentation/habib_wallet/widgets/select-medical_file.dart @@ -76,7 +76,7 @@ class _MultiPageBottomSheetState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Enter File Number".needTranslation.toText20(weight: FontWeight.w600), + "Enter File Number".toText20(weight: FontWeight.w600), SizedBox(height: 12.h), TextInputWidget( labelText: LocaleKeys.fileNumber.tr(), @@ -98,9 +98,9 @@ class _MultiPageBottomSheetState extends State { await habibWalletVM.getPatientInfoByPatientID( patientID: fileNumberEditingController.text, onSuccess: (response) async { - print(response.data["GetPatientInfoByPatientIDList"][0]["FullName"]); + debugPrint(response.data["GetPatientInfoByPatientIDList"][0]["FullName"]); await _dialogService.showCommonBottomSheetWithoutH( - message: "A file was found with name: ${response.data["GetPatientInfoByPatientIDList"][0]["FullName"]}, Would you like to recharge wallet for this file number?".needTranslation, + message: "A file was found with name: ${response.data["GetPatientInfoByPatientIDList"][0]["FullName"]}, Would you like to recharge wallet for this file number?", label: LocaleKeys.notice.tr(), onOkPressed: () { habibWalletVM.setSelectedRechargeType(3); @@ -161,7 +161,7 @@ class _MultiPageBottomSheetState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.familyTitle.tr(context: context).toText16(color: AppColors.textColor, weight: FontWeight.w500), - "Select a medical file from your family".needTranslation.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), + "Select a medical file from your family".toText14(color: AppColors.greyTextColor, weight: FontWeight.w500), ], ), Utils.buildSvgWithAssets(icon: AppAssets.forward_chevron_icon, iconColor: AppColors.textColor, width: 15.h, height: 15.h), diff --git a/lib/presentation/habib_wallet/widgets/select_hospital_bottom_sheet.dart b/lib/presentation/habib_wallet/widgets/select_hospital_bottom_sheet.dart index 086e0da..da374a0 100644 --- a/lib/presentation/habib_wallet/widgets/select_hospital_bottom_sheet.dart +++ b/lib/presentation/habib_wallet/widgets/select_hospital_bottom_sheet.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/habib_wallet/widgets/hospital_list_item.dart'; import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors; import 'package:provider/provider.dart'; @@ -28,7 +30,7 @@ class SelectHospitalBottomSheet extends StatelessWidget { // ), // ), Text( - "Please select the hospital you want to make an advance payment for.".needTranslation, + LocaleKeys.selectHospitalForAdvancePayment.tr(context: context), style: TextStyle( fontSize: 16, fontWeight: FontWeight.w500, diff --git a/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart b/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart index eb22ab6..4a83f51 100644 --- a/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart +++ b/lib/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart @@ -1,4 +1,11 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/select_clinic_page.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/widgets/bf.dart'; @@ -12,17 +19,12 @@ import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/widgets/ibw.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/widgets/ovulation.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/widgets/triglycerides.dart'; -import 'package:provider/provider.dart'; -import 'package:hmg_patient_app_new/core/dependencies.dart'; -import 'package:hmg_patient_app_new/core/enums.dart'; -import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; -import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; -import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:provider/provider.dart'; class HealthCalculatorDetailedPage extends StatefulWidget { HealthCalculatorsTypeEnum calculatorType; @@ -50,15 +52,15 @@ class _HealthCalculatorDetailedPageState extends State months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + const List months = [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December' + ]; return months[month - 1]; } @@ -828,7 +846,8 @@ class HealthCalcualtorViewModel extends ChangeNotifier { // expose map-like results for widgets to forward to parent Map? get bmiResultMap => bmiResult == null ? null : {'bmiResult': bmiResult, 'bmiCategory': bmiCategory}; - Map? get caloriesResultMap => caloriesResult == null ? null : {'calories': caloriesResult, 'bmr': bmrResult, 'calorieRange': calorieRange, 'bmrRange': bmrRange}; + Map? get caloriesResultMap => + caloriesResult == null ? null : {'calories': caloriesResult, 'bmr': bmrResult, 'calorieRange': calorieRange, 'bmrRange': bmrRange}; Map? get ibwResultMap => ibwResult == null ? null : {'ibw': ibwResult, 'difference': weightDifference, 'status': weightStatus}; diff --git a/lib/presentation/health_calculators_and_converts/health_calculators_page.dart b/lib/presentation/health_calculators_and_converts/health_calculators_page.dart index faf97a1..aae25b0 100644 --- a/lib/presentation/health_calculators_and_converts/health_calculators_page.dart +++ b/lib/presentation/health_calculators_and_converts/health_calculators_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_detailed_page.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/widgets/health_card.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; @@ -32,7 +34,7 @@ class _HealthCalculatorsPageState extends State { Widget build(BuildContext context) { DialogService dialogService = getIt.get(); return CollapsingListView( - title: widget.type == HealthCalConEnum.calculator ? "Health Calculators".needTranslation : "Health Converters".needTranslation, + title: widget.type == HealthCalConEnum.calculator ? LocaleKeys.healthCalculators.tr(context: context) : LocaleKeys.healthConverters.tr(), child: widget.type == HealthCalConEnum.calculator ? Column( children: [ @@ -47,8 +49,8 @@ class _HealthCalculatorsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - "General Health".needTranslation.toText16(weight: FontWeight.w600), - "Related To BMI, calories, body fat, etc to stay updated with your health.".needTranslation.toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) + LocaleKeys.generalHealth.tr().toText16(weight: FontWeight.w600), + LocaleKeys.relatedToBMICalories.tr().toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) ], ), ), @@ -60,7 +62,7 @@ class _HealthCalculatorsPageState extends State { ).paddingAll(16.w)) .onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Calculator".needTranslation, + label: LocaleKeys.selectCalculator.tr(), message: "", child: showCalculatorsItems(type: HealthCalculatorEnum.general), onOkPressed: () {}, @@ -78,8 +80,8 @@ class _HealthCalculatorsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - "Women's Health".needTranslation.toText16(weight: FontWeight.w600), - "Related To periods, ovulation, pregnancy, and other topics.".needTranslation.toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) + LocaleKeys.womensHealth.tr().toText16(weight: FontWeight.w600), + LocaleKeys.relatedToPeriodsOvulation.tr().toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) ], ), ), @@ -89,7 +91,7 @@ class _HealthCalculatorsPageState extends State { ).paddingAll(16.w)) .onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Calculator".needTranslation, + label: LocaleKeys.selectCalculator.tr(), message: "", child: showCalculatorsItems(type: HealthCalculatorEnum.women), onOkPressed: () {}, @@ -111,8 +113,8 @@ class _HealthCalculatorsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - "Blood Sugar".needTranslation.toText16(weight: FontWeight.w600), - "Track your glucose levels, understand trends, and get personalized insights for better health.".needTranslation.toText12( + LocaleKeys.bloodSugar.tr().toText16(weight: FontWeight.w600), + LocaleKeys.trackYourGlucoseLevels.tr().toText12( fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3), ) @@ -145,9 +147,8 @@ class _HealthCalculatorsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - "Blood Cholesterol".needTranslation.toText16(weight: FontWeight.w600), - "Monitor your cholesterol levels, track your LDL, HDL, and triglycerides. Get personalized recommendations for a healthy heart." - .needTranslation + LocaleKeys.bloodCholesterol.tr().toText16(weight: FontWeight.w600), + LocaleKeys.monitorCholesterolLevels.tr() .toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) ], ), @@ -176,9 +177,8 @@ class _HealthCalculatorsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - "Triglycerides Fat Blood".needTranslation.toText16(weight: FontWeight.w600), - "Manage triglycerides, a key blood fat. Understand levels, diet impacts, and heart health strategies." - .needTranslation + LocaleKeys.triglyceridesFatBlood.tr().toText16(weight: FontWeight.w600), + LocaleKeys.understandTriglyceridesImpact.tr() .toText12(fontWeight: FontWeight.w500, color: Color(0xFF8F9AA3)) ], ), @@ -204,7 +204,7 @@ class _HealthCalculatorsPageState extends State { crossAxisCount: 3, // 4 icons per row crossAxisSpacing: 16.w, mainAxisSpacing: 16.w, - childAspectRatio: 0.80), + childAspectRatio: 0.85), physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: type == HealthCalculatorEnum.general ? generalHealthServices.length : womenHealthServices.length, @@ -214,6 +214,7 @@ class _HealthCalculatorsPageState extends State { icon: type == HealthCalculatorEnum.general ? generalHealthServices[index].icon : womenHealthServices[index].icon, labelText: type == HealthCalculatorEnum.general ? generalHealthServices[index].title : womenHealthServices[index].title, onTap: () { + Navigator.pop(context); Navigator.of(context).push( CustomPageRoute( page: HealthCalculatorDetailedPage( @@ -230,17 +231,17 @@ class _HealthCalculatorsPageState extends State { } final List generalHealthServices = [ - HealthComponentModel(title: "BMI\nCalculator".needTranslation, icon: AppAssets.bmi, type: HealthCalculatorsTypeEnum.bmi, clinicID: 108, calculationID: null), - HealthComponentModel(title: "Calories\nCalculator".needTranslation, icon: AppAssets.calories, type: HealthCalculatorsTypeEnum.calories, clinicID: null, calculationID: 2), - HealthComponentModel(title: "BMR\nCalculator".needTranslation, icon: AppAssets.bmr, type: HealthCalculatorsTypeEnum.bmr, clinicID: null, calculationID: 3), - HealthComponentModel(title: "Ideal Body\nWeight".needTranslation, icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.idealBodyWeight, clinicID: null, calculationID: 4), - HealthComponentModel(title: "Body Fat\nCalculator".needTranslation, icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.bodyFat, clinicID: null, calculationID: 5), - HealthComponentModel(title: "Carbs\nProtein & Fat".needTranslation, icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.crabsProteinFat, clinicID: null, calculationID: 11), + HealthComponentModel(title: LocaleKeys.bmiCalculator.tr(), icon: AppAssets.bmi, type: HealthCalculatorsTypeEnum.bmi, clinicID: 108, calculationID: null), + HealthComponentModel(title: LocaleKeys.caloriesCalculator.tr(), icon: AppAssets.calories, type: HealthCalculatorsTypeEnum.calories, clinicID: null, calculationID: 2), + HealthComponentModel(title: LocaleKeys.bmrCalculator.tr(), icon: AppAssets.bmr, type: HealthCalculatorsTypeEnum.bmr, clinicID: null, calculationID: 3), + HealthComponentModel(title: LocaleKeys.idealBodyWeight.tr(), icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.idealBodyWeight, clinicID: null, calculationID: 4), + HealthComponentModel(title: LocaleKeys.bodyFatCalculator.tr(), icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.bodyFat, clinicID: null, calculationID: 5), + HealthComponentModel(title: LocaleKeys.carbsProteinFat.tr(), icon: AppAssets.ibw, type: HealthCalculatorsTypeEnum.crabsProteinFat, clinicID: null, calculationID: 11), ]; final List womenHealthServices = [ - HealthComponentModel(title: "Ovulation\nPeriod".needTranslation, icon: AppAssets.locate_me, type: HealthCalculatorsTypeEnum.ovulation, clinicID: null, calculationID: 6 ), - HealthComponentModel(title: "Delivery\nDue Date".needTranslation, icon: AppAssets.activeCheck, type: HealthCalculatorsTypeEnum.deliveryDueDate, clinicID: null, calculationID: 6), + HealthComponentModel(title: LocaleKeys.ovulationPeriod.tr(), icon: AppAssets.locate_me, type: HealthCalculatorsTypeEnum.ovulation, clinicID: null, calculationID: 6 ), + HealthComponentModel(title: LocaleKeys.deliveryDueDate.tr(), icon: AppAssets.activeCheck, type: HealthCalculatorsTypeEnum.deliveryDueDate, clinicID: null, calculationID: 6), ]; } diff --git a/lib/presentation/health_calculators_and_converts/widgets/bf.dart b/lib/presentation/health_calculators_and_converts/widgets/bf.dart index 3a88eb3..b00846b 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/bf.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/bf.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -92,7 +94,7 @@ class _BodyFatWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Select Gender".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.selectGender.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedGender.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -105,7 +107,7 @@ class _BodyFatWidgetState extends State { ).paddingSymmetrical(0.w, 16.w).onPress(() { List _genders = ["Male", "Female"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Gender".needTranslation, + label: LocaleKeys.selectGender.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -215,7 +217,7 @@ class _BodyFatWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -323,7 +325,7 @@ class _BodyFatWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.unit.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedNeckUnit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -332,7 +334,7 @@ class _BodyFatWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -449,7 +451,7 @@ class _BodyFatWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -557,7 +559,7 @@ class _BodyFatWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.unit.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedHipUnit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -566,7 +568,7 @@ class _BodyFatWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/bmi.dart b/lib/presentation/health_calculators_and_converts/widgets/bmi.dart index 49b77c0..3969db4 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/bmi.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/bmi.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -10,6 +11,8 @@ import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart'; +import '../../../generated/locale_keys.g.dart'; + class BMIWidget extends StatefulWidget { Function(dynamic result)? onChange; @@ -116,7 +119,7 @@ class _BMIWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -233,7 +236,7 @@ class _BMIWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/bmr.dart b/lib/presentation/health_calculators_and_converts/widgets/bmr.dart index 5f429ff..f19c6b5 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/bmr.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/bmr.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -87,7 +89,7 @@ class _BMRWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Select Gender".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.selectGender.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedGender.toCamelCase.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -101,7 +103,7 @@ class _BMRWidgetState extends State { List _genders = ["Male", "Female"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Gender".needTranslation, + label: LocaleKeys.selectGender.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -168,7 +170,7 @@ class _BMRWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Age (11-120) yrs".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + "Age (11-120) yrs".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), Container( height: 20.w, alignment: Alignment.centerLeft, @@ -240,7 +242,7 @@ class _BMRWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.unit.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedHeightUnit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -249,7 +251,7 @@ class _BMRWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -367,7 +369,7 @@ class _BMRWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -437,7 +439,7 @@ class _BMRWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Activity Level".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.activityLevel.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedActivityLevel.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -450,7 +452,7 @@ class _BMRWidgetState extends State { ).paddingSymmetrical(0.w, 16.w).onPress(() { List _activity = ["Almost Inactive (no exercise)", "Lightly active", "Lightly active (1-3) days per week", "Super active (very hard exercise)"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Activity Level".needTranslation, + label: LocaleKeys.selectActivityLevel.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/calories.dart b/lib/presentation/health_calculators_and_converts/widgets/calories.dart index fbe15a6..b1a4b77 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/calories.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/calories.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -102,7 +104,7 @@ class _CaloriesWidgetState extends State { List _genders = ["Male", "Female"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Gender".needTranslation, + label: LocaleKeys.selectGender.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -168,7 +170,7 @@ class _CaloriesWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Age (11-120) yrs".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + "Age (11-120) yrs".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), Container( height: 20.w, alignment: Alignment.centerLeft, @@ -249,7 +251,7 @@ class _CaloriesWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -366,7 +368,7 @@ class _CaloriesWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -436,7 +438,7 @@ class _CaloriesWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Activity Level".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.activityLevel.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedActivityLevel.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -449,7 +451,7 @@ class _CaloriesWidgetState extends State { ).paddingSymmetrical(0.w, 16.w).onPress(() { List _activity = ["Almost Inactive (no exercise)", "Lightly active", "Lightly active (1-3) days per week", "Super active (very hard exercise)"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Activity Level".needTranslation, + label: LocaleKeys.selectActivityLevel.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/crabs.dart b/lib/presentation/health_calculators_and_converts/widgets/crabs.dart index 5fe1215..83130fe 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/crabs.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/crabs.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; @@ -68,7 +70,7 @@ class _CrabsWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Calories Per Day".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.caloriesPerDay.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), Container( height: 20.w, alignment: Alignment.centerLeft, @@ -111,7 +113,7 @@ class _CrabsWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Diet Type".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.dietType.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedDietType.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -124,7 +126,7 @@ class _CrabsWidgetState extends State { ).paddingSymmetrical(0.w, 16.w).onPress(() { List _activity = ["Very Low Crabs", "Low Crabs", "Moderate Crabs", "USDA Guidelines ", "Zone Diet"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Diet Type".needTranslation, + label: LocaleKeys.selectDietType.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/dduedate.dart b/lib/presentation/health_calculators_and_converts/widgets/dduedate.dart index 15c0a0c..3ecf2a5 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/dduedate.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/dduedate.dart @@ -36,7 +36,7 @@ class _DeliveryDueDWidgetState extends State { children: [ TextInputWidget( labelText: "Last Period Date", - hintText: "11 July, 1994".needTranslation, + hintText: "11 July, 1994", controller: _date, focusNode: FocusNode(), isEnable: true, diff --git a/lib/presentation/health_calculators_and_converts/widgets/ibw.dart b/lib/presentation/health_calculators_and_converts/widgets/ibw.dart index 5f67511..1665ccd 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/ibw.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/ibw.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; @@ -114,7 +116,7 @@ class _IdealBodyWeightWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.unit.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedHeightUnit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -123,7 +125,7 @@ class _IdealBodyWeightWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -231,7 +233,7 @@ class _IdealBodyWeightWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.unit.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedWeightUnit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -240,7 +242,7 @@ class _IdealBodyWeightWidgetState extends State { ], ).onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Unit".needTranslation, + label: LocaleKeys.unit.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -308,7 +310,7 @@ class _IdealBodyWeightWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Body Frame Size".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.bodyFrameSize.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), selectedBodyFrameSize.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), ], ), @@ -321,7 +323,7 @@ class _IdealBodyWeightWidgetState extends State { ).paddingSymmetrical(0.w, 16.w).onPress(() { List _activity = ["Small (fingers overlaps)", "Medium (fingers touch)", "Large (fingers don't touch)"]; dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Select Body Frame Size".needTranslation, + label: LocaleKeys.selectBodyFrameSize.tr(context: context), message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), diff --git a/lib/presentation/health_calculators_and_converts/widgets/ovulation.dart b/lib/presentation/health_calculators_and_converts/widgets/ovulation.dart index de209cb..8d7591e 100644 --- a/lib/presentation/health_calculators_and_converts/widgets/ovulation.dart +++ b/lib/presentation/health_calculators_and_converts/widgets/ovulation.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:provider/provider.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; @@ -63,7 +65,7 @@ class _OvulationWidgetState extends State { children: [ TextInputWidget( labelText: "Date", - hintText: "11 July, 1994".needTranslation, + hintText: "11 July, 1994", controller: _ageController, isEnable: true, prefix: null, @@ -95,7 +97,7 @@ class _OvulationWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Average Cycle Length (Usually 28 days)".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.averageCycleLength.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), Container( height: 20.w, alignment: Alignment.centerLeft, @@ -132,7 +134,7 @@ class _OvulationWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - "Average Luteal Phase Length(Usually 14 days)".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + LocaleKeys.averageLutealPhase.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), Container( height: 20.w, alignment: Alignment.centerLeft, diff --git a/lib/presentation/health_trackers/add_health_tracker_entry_page.dart b/lib/presentation/health_trackers/add_health_tracker_entry_page.dart new file mode 100644 index 0000000..702875d --- /dev/null +++ b/lib/presentation/health_trackers/add_health_tracker_entry_page.dart @@ -0,0 +1,569 @@ +import 'dart:developer'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class AddHealthTrackerEntryPage extends StatefulWidget { + final HealthTrackerTypeEnum trackerType; + + const AddHealthTrackerEntryPage({ + super.key, + required this.trackerType, + }); + + @override + State createState() => _AddHealthTrackerEntryPageState(); +} + +class _AddHealthTrackerEntryPageState extends State { + late DialogService dialogService; + + // Controllers for date and time + final TextEditingController dateController = TextEditingController(); + final TextEditingController timeController = TextEditingController(); + + @override + void initState() { + super.initState(); + dialogService = getIt.get(); + } + + @override + void dispose() { + dateController.dispose(); + timeController.dispose(); + super.dispose(); + } + + /// Get page title based on tracker type + String _getPageTitle() { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return LocaleKeys.addBloodSugar.tr(context: context); + case HealthTrackerTypeEnum.bloodPressure: + return LocaleKeys.addBloodPressure.tr(context: context); + case HealthTrackerTypeEnum.weightTracker: + return LocaleKeys.addWeight.tr(context: context); + } + } + + /// Get success message based on tracker type + String _getSuccessMessage() { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return LocaleKeys.bloodSugarDataSavedSuccessfully.tr(context: context); + case HealthTrackerTypeEnum.bloodPressure: + return LocaleKeys.bloodPressureDataSavedSuccessfully.tr(context: context); + case HealthTrackerTypeEnum.weightTracker: + return LocaleKeys.weightDataSavedSuccessfully.tr(context: context); + } + } + + /// Save entry based on tracker type + Future _saveEntry(HealthTrackersViewModel viewModel) async { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + await _saveBloodSugarEntry(viewModel); + break; + case HealthTrackerTypeEnum.bloodPressure: + await _saveBloodPressureEntry(viewModel); + break; + case HealthTrackerTypeEnum.weightTracker: + await _saveWeightEntry(viewModel); + break; + } + } + + // Save Blood Sugar entry + Future _saveBloodSugarEntry(HealthTrackersViewModel viewModel) async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + // Combine date and time + final dateTime = "${dateController.text} ${timeController.text}"; + + // Call ViewModel method with callbacks + await viewModel.saveBloodSugarEntry( + dateTime: dateTime, + measureTime: viewModel.selectedBloodSugarMeasureTime, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + _showSuccessAndPop(); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + dialogService.showErrorBottomSheet(message: error); + }, + ); + } + + // Save Weight entry + Future _saveWeightEntry(HealthTrackersViewModel viewModel) async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + // Combine date and time + final dateTime = "${dateController.text} ${timeController.text}"; + + // Call ViewModel method with callbacks + await viewModel.saveWeightEntry( + dateTime: dateTime, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + _showSuccessAndPop(); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + dialogService.showErrorBottomSheet(message: error); + }, + ); + } + + // Save Blood Pressure entry + Future _saveBloodPressureEntry(HealthTrackersViewModel viewModel) async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + // Combine date and time + final dateTime = "${dateController.text} ${timeController.text}"; + + // Call ViewModel method with callbacks + await viewModel.saveBloodPressureEntry( + dateTime: dateTime, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + _showSuccessAndPop(); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + dialogService.showErrorBottomSheet(message: error); + }, + ); + } + + // Show success message and pop back + void _showSuccessAndPop() { + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getSuccessWidget( + loadingText: _getSuccessMessage(), + ), + callBackFunc: () { + Navigator.pop(context); + }, + isCloseButtonVisible: false, + isDismissible: true, + isFullScreen: false, + ); + } + + // Reusable method to build selection row widget + Widget _buildSelectionRow({ + required String value, + required String groupValue, + required VoidCallback onTap, + bool useUpperCase = false, + }) { + return SizedBox( + height: 70.h, + child: Row( + spacing: 8.h, + children: [ + Radio( + value: value, + groupValue: groupValue, + activeColor: AppColors.errorColor, + onChanged: (_) => onTap(), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + (useUpperCase ? value.toUpperCase() : value.toCamelCase) + .toText16(weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1) + .expanded, + ], + ).onPress(onTap), + ); + } + + // Reusable method to show selection bottom sheet + void _showSelectionBottomSheet({ + required BuildContext context, + required String title, + required List items, + required String selectedValue, + required Function(String) onSelected, + bool useUpperCase = false, + }) { + dialogService.showFamilyBottomSheetWithoutHWithChild( + label: title, + message: "", + child: Container( + constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.7), + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20.r)), + child: ListView.separated( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return _buildSelectionRow( + value: item, + groupValue: selectedValue, + useUpperCase: useUpperCase, + onTap: () { + onSelected(item); + Navigator.pop(context); + }, + ); + }, + separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor), + ), + ), + onOkPressed: () {}, + ); + } + + // Blood Sugar unit selection + void _showBloodSugarUnitSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) { + FocusScope.of(context).unfocus(); + _showSelectionBottomSheet( + context: context, + title: LocaleKeys.selectUnit.tr(context: context), + items: viewModel.bloodSugarUnit, + selectedValue: viewModel.selectedBloodSugarUnit, + onSelected: viewModel.setBloodSugarUnit, + useUpperCase: false, + ); + } + + // Blood Sugar measure time selection + void _showBloodSugarEntryTimeBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) { + FocusScope.of(context).unfocus(); + _showSelectionBottomSheet( + context: context, + title: LocaleKeys.selectMeasureTime.tr(context: context), + items: viewModel.bloodSugarMeasureTimeEnList, + selectedValue: viewModel.selectedBloodSugarMeasureTime, + onSelected: viewModel.setBloodSugarMeasureTime, + useUpperCase: false, + ); + } + + // Weight unit selection + void _showWeightUnitSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) { + FocusScope.of(context).unfocus(); + _showSelectionBottomSheet( + context: context, + title: LocaleKeys.selectUnit.tr(context: context), + items: viewModel.weightUnits, + selectedValue: viewModel.selectedWeightUnit, + onSelected: viewModel.setWeightUnit, + useUpperCase: false, + ); + } + + // Blood Pressure measured arm selection + void _showMeasuredArmSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) { + FocusScope.of(context).unfocus(); + _showSelectionBottomSheet( + context: context, + title: LocaleKeys.selectArm.tr(context: context), + items: viewModel.measuredArmList, + selectedValue: viewModel.selectedMeasuredArm, + onSelected: viewModel.setMeasuredArm, + useUpperCase: false, + ); + } + + // Reusable method to build text field + Widget _buildTextField(TextEditingController controller, String hintText, {TextInputType keyboardType = TextInputType.name}) { + return TextField( + controller: controller, + keyboardType: keyboardType, + maxLines: 1, + cursorHeight: 14.h, + textAlignVertical: TextAlignVertical.center, + decoration: InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + isCollapsed: true, + hintText: hintText, + hintStyle: const TextStyle(color: Colors.grey), + ), + style: TextStyle( + fontSize: 14.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ); + } + + // Reusable method to build settings row + Widget _buildSettingsRow({ + required String icon, + required String label, + String? value, + Widget? inputField, + String? unit, + VoidCallback? onUnitTap, + VoidCallback? onRowTap, + Color? iconColor, + bool showDivider = true, + }) { + return Column( + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + height: 40.w, + width: 40.w, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.greyColor, + borderRadius: 10.r, + hasShadow: false, + ), + child: Center(child: Utils.buildSvgWithAssets(icon: icon, height: 22.w, width: 22.w, iconColor: iconColor)), + ), + SizedBox(width: 12.w), + Expanded( + flex: unit != null ? 2 : 1, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + label.toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + if (inputField != null) + Container( + height: 20.w, + alignment: Alignment.centerLeft, + child: inputField, + ) + else if (value != null && value.isNotEmpty) + value.toCamelCase.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ), + ), + if (unit != null) ...[ + Container( + width: 1.w, + height: 30.w, + color: AppColors.dividerColor, + ).paddingOnly(right: 10.w), + Expanded( + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + "Unit".toText12(fontWeight: FontWeight.w500, color: AppColors.inputLabelTextColor), + unit.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ), + SizedBox(width: 12.w), + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down) + ], + ).onPress(onUnitTap ?? () {}), + ), + ] else if (onRowTap != null) ...[ + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down), + SizedBox(width: 8.w), + ], + ], + ).paddingSymmetrical(0.w, 16.w).onPress(onRowTap ?? () {}), + if (showDivider) Divider(height: 1, color: AppColors.dividerColor), + ], + ); + } + + /// Build form fields based on tracker type + Widget _buildFormFields(HealthTrackersViewModel viewModel) { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return _buildBloodSugarForm(viewModel); + case HealthTrackerTypeEnum.bloodPressure: + return _buildBloodPressureForm(viewModel); + case HealthTrackerTypeEnum.weightTracker: + return _buildWeightForm(viewModel); + } + } + + /// Blood Sugar form fields + Widget _buildBloodSugarForm(HealthTrackersViewModel viewModel) { + return Column( + children: [ + _buildSettingsRow( + icon: AppAssets.heightIcon, + label: LocaleKeys.enterBloodSugar.tr(context: context), + inputField: _buildTextField(viewModel.bloodSugarController, '', keyboardType: TextInputType.number), + unit: viewModel.selectedBloodSugarUnit, + onUnitTap: () => _showBloodSugarUnitSelectionBottomSheet(context, viewModel), + ), + _buildDateTimeFields(), + Divider(height: 1, color: AppColors.dividerColor), + _buildSettingsRow( + icon: AppAssets.weight_tracker_icon, + label: LocaleKeys.selectMeasureTime.tr(context: context), + value: viewModel.selectedBloodSugarMeasureTime, + onRowTap: () => _showBloodSugarEntryTimeBottomSheet(context, viewModel), + ), + ], + ); + } + + /// Blood Pressure form fields + Widget _buildBloodPressureForm(HealthTrackersViewModel viewModel) { + return Column( + children: [ + _buildSettingsRow( + icon: AppAssets.bloodPressureIcon, + iconColor: AppColors.greyTextColor, + label: LocaleKeys.enterSystolicValue.tr(context: context), + inputField: _buildTextField(viewModel.systolicController, '', keyboardType: TextInputType.number), + ), + _buildSettingsRow( + icon: AppAssets.bloodPressureIcon, + iconColor: AppColors.greyTextColor, + label: LocaleKeys.enterDiastolicValue.tr(context: context), + inputField: _buildTextField(viewModel.diastolicController, '', keyboardType: TextInputType.number), + ), + _buildSettingsRow( + icon: AppAssets.bodyIcon, + iconColor: AppColors.greyTextColor, + label: LocaleKeys.selectArm.tr(context: context), + value: viewModel.selectedMeasuredArm, + onRowTap: () => _showMeasuredArmSelectionBottomSheet(context, viewModel), + ), + _buildDateTimeFields(), + ], + ); + } + + /// Weight form fields + Widget _buildWeightForm(HealthTrackersViewModel viewModel) { + return Column( + children: [ + _buildSettingsRow( + icon: AppAssets.weightScale, + label: LocaleKeys.enterWeight.tr(context: context), + inputField: _buildTextField(viewModel.weightController, '', keyboardType: TextInputType.number), + unit: viewModel.selectedWeightUnit, + onUnitTap: () => _showWeightUnitSelectionBottomSheet(context, viewModel), + ), + _buildDateTimeFields(), + ], + ); + } + + /// Common date and time fields + Widget _buildDateTimeFields() { + return Column( + children: [ + TextInputWidget( + controller: dateController, + isReadOnly: true, + isArrowTrailing: true, + labelText: "Date", + hintText: LocaleKeys.pickADate.tr(context: context), + focusNode: FocusNode(), + isEnable: true, + prefix: null, + isAllowRadius: true, + isBorderAllowed: false, + isAllowLeadingIcon: true, + padding: EdgeInsets.symmetric(vertical: 8.h), + leadingIcon: AppAssets.calendarGrey, + selectionType: SelectionTypeEnum.calendar, + isHideSwitcher: true, + onCalendarTypeChanged: (val) {}, + onChange: (val) { + if (val == null) return; + try { + final parsedDate = DateTime.parse(val); + final formattedDate = DateFormat('dd MMM yyyy').format(parsedDate); + dateController.text = formattedDate; + log("date: $formattedDate"); + } catch (e) { + dateController.text = val; + log("date: $val"); + } + }, + ), + TextInputWidget( + controller: timeController, + isReadOnly: true, + isArrowTrailing: true, + labelText: "Time", + hintText: LocaleKeys.selectMeasureTime.tr(context: context), + focusNode: FocusNode(), + isEnable: true, + prefix: null, + isAllowRadius: true, + isBorderAllowed: false, + isAllowLeadingIcon: true, + padding: EdgeInsets.symmetric(vertical: 8.h), + leadingIcon: AppAssets.calendarGrey, + selectionType: SelectionTypeEnum.time, + isHideSwitcher: true, + onCalendarTypeChanged: (val) {}, + onChange: (val) { + if (val == null) return; + timeController.text = val; + log("time: $val"); + }, + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return GestureDetector( + onTap: () { + FocusScope.of(context).unfocus(); + }, + child: Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: _getPageTitle(), + bottomChild: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.w), + child: CustomButton( + text: LocaleKeys.save.tr(context: context), + onPressed: () async => await _saveEntry(viewModel), + borderRadius: 12.r, + padding: EdgeInsets.symmetric(vertical: 14.h), + ), + ), + ), + child: Container( + margin: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h), + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), + child: _buildFormFields(viewModel), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/health_trackers/health_tracker_detail_page.dart b/lib/presentation/health_trackers/health_tracker_detail_page.dart new file mode 100644 index 0000000..b5f41da --- /dev/null +++ b/lib/presentation/health_trackers/health_tracker_detail_page.dart @@ -0,0 +1,1305 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/common_models/data_points.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/week_diabetic_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/blood_sugar/year_diabetic_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/week_weight_measurement_result_average.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/models/weight/year_weight_measurement_result_average.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart'; +import 'package:hmg_patient_app_new/presentation/health_trackers/widgets/tracker_last_value_card.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +import 'package:provider/provider.dart'; +import 'package:shimmer/shimmer.dart'; + +class HealthTrackerDetailPage extends StatefulWidget { + final HealthTrackerTypeEnum trackerType; + + const HealthTrackerDetailPage({super.key, required this.trackerType}); + + @override + State createState() => _HealthTrackerDetailPageState(); +} + +class _HealthTrackerDetailPageState extends State { + @override + void initState() { + super.initState(); + // Load data based on tracker type + WidgetsBinding.instance.addPostFrameCallback((_) async { + final viewModel = context.read(); + await _loadTrackerData(viewModel); + }); + } + + /// Load data based on tracker type + Future _loadTrackerData(HealthTrackersViewModel viewModel) async { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + await viewModel.getBloodSugar(); + break; + case HealthTrackerTypeEnum.bloodPressure: + await viewModel.getBloodPressure(); + break; + case HealthTrackerTypeEnum.weightTracker: + await viewModel.getWeight(); + break; + } + } + + /// Get page title based on tracker type + String _getPageTitle() { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return LocaleKeys.bloodSugar.tr(context: context); + case HealthTrackerTypeEnum.bloodPressure: + return LocaleKeys.bloodPressure.tr(context: context); + case HealthTrackerTypeEnum.weightTracker: + return LocaleKeys.weight.tr(context: context); + } + } + + /// Get unit based on tracker type + String _getUnit() { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return 'mg/dL'; + case HealthTrackerTypeEnum.bloodPressure: + return 'mmHg'; + case HealthTrackerTypeEnum.weightTracker: + return 'kg'; + } + } + + /// Get empty state message based on tracker type + String _getEmptyStateMessage() { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return "Please add data to track your Blood Sugar"; + case HealthTrackerTypeEnum.bloodPressure: + return "Please add data to track your Blood Pressure"; + case HealthTrackerTypeEnum.weightTracker: + return "Please add data to track your Weight"; + } + } + + /// Check if data is empty based on tracker type + bool _hasNoData(HealthTrackersViewModel viewModel) { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return viewModel.weekDiabeticPatientResult.isEmpty && + viewModel.monthDiabeticPatientResult.isEmpty && + viewModel.yearDiabeticPatientResult.isEmpty; + case HealthTrackerTypeEnum.bloodPressure: + return viewModel.weekBloodPressureResult.isEmpty && viewModel.monthBloodPressureResult.isEmpty && viewModel.yearBloodPressureResult.isEmpty; + case HealthTrackerTypeEnum.weightTracker: + return viewModel.weekWeightMeasurementResult.isEmpty && + viewModel.monthWeightMeasurementResult.isEmpty && + viewModel.yearWeightMeasurementResult.isEmpty; + } + } + + // Reusable method to build selection row widget + Widget _buildSelectionRow({ + required String value, + required String groupValue, + required VoidCallback onTap, + bool useUpperCase = false, + }) { + return SizedBox( + height: 70.h, + child: Row( + spacing: 8.h, + children: [ + Radio( + value: value, + groupValue: groupValue, + activeColor: AppColors.errorColor, + onChanged: (_) => onTap(), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + (useUpperCase ? value.toUpperCase() : value.toCamelCase) + .toText16(weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1) + .expanded, + ], + ).onPress(onTap), + ); + } + + void _showSelectionBottomSheet({ + required BuildContext context, + required String title, + required List items, + required String selectedValue, + required Function(String) onSelected, + bool useUpperCase = false, + }) { + final dialogService = getIt.get(); + + dialogService.showFamilyBottomSheetWithoutHWithChild( + label: title, + message: "", + child: Container( + padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), + decoration: BoxDecoration(color: AppColors.whiteColor, borderRadius: BorderRadius.circular(20.r)), + child: ListView.separated( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return _buildSelectionRow( + value: item, + groupValue: selectedValue, + useUpperCase: useUpperCase, + onTap: () { + onSelected(item); + Navigator.pop(context); + }, + ); + }, + separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor), + ), + ), + onOkPressed: () {}, + ); + } + + void _showHistoryDurationBottomsheet(BuildContext context, HealthTrackersViewModel viewModel) { + _showSelectionBottomSheet( + context: context, + title: LocaleKeys.selectDuration.tr(), + items: viewModel.durationFilters, + selectedValue: viewModel.selectedDurationFilter, + onSelected: viewModel.setFilterDuration, + ); + } + + Widget buildHistoryListTile({required String title, required String subTitle, required String measureDesc, double? value}) { + // Get status color and rotation based on value and tracker type + Color statusColor = AppColors.successColor; + double rotation = 0; + + if (value != null) { + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + if (value < 70) { + statusColor = AppColors.errorColor; + rotation = 0; // pointing down + } else if (value <= 100) { + statusColor = AppColors.successColor; + rotation = -3.14159 / 2; // pointing right + } else if (value <= 125) { + statusColor = AppColors.ratingColorYellow; + rotation = 3.14159; // pointing up + } else { + statusColor = AppColors.errorColor; + rotation = 3.14159; // pointing up + } + break; + case HealthTrackerTypeEnum.bloodPressure: + // Systolic pressure ranges + if (value < 90) { + statusColor = AppColors.errorColor; + rotation = 0; // Low - pointing down + } else if (value <= 120) { + statusColor = AppColors.successColor; + rotation = -3.14159 / 2; // Normal - pointing right + } else if (value <= 140) { + statusColor = AppColors.ratingColorYellow; + rotation = 3.14159; // Elevated - pointing up + } else { + statusColor = AppColors.errorColor; + rotation = 3.14159; // High - pointing up + } + break; + case HealthTrackerTypeEnum.weightTracker: + // Weight doesn't have good/bad indicators, just show neutral + statusColor = AppColors.transparent; + rotation = -3.14159 / 2; // pointing right (neutral) + break; + } + } + + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + AppCustomChipWidget(labelText: title), + if (measureDesc.isNotEmpty) ...[ + SizedBox(width: 8.w), + AppCustomChipWidget(labelText: measureDesc), + ], + ], + ), + SizedBox(height: 4.h), + subTitle.toText16(weight: FontWeight.w600, color: AppColors.textColor), + ], + ), + Transform.rotate( + angle: rotation, + child: Utils.buildSvgWithAssets( + icon: AppAssets.lowIndicatorIcon, + iconColor: statusColor, + height: 20.h, + width: 20.h, + ), + ), + ], + ).paddingSymmetrical(0, 8.h); + } + + Widget _buildHistoryGraphOrList() { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Consumer(builder: (BuildContext context, HealthTrackersViewModel viewModel, Widget? child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + LocaleKeys.history.tr(context: context).toText16(isBold: true), + if (viewModel.isGraphView) ...[ + SizedBox(width: 12.w), + InkWell( + onTap: () => _showHistoryDurationBottomsheet(context, viewModel), + child: Container( + padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 6.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + backgroundColor: AppColors.greyColor, + borderRadius: 8.r, + hasShadow: true, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + viewModel.selectedDurationFilter.toText12(fontWeight: FontWeight.w500), + SizedBox(width: 4.w), + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 16.h), + ], + ), + ), + ), + ], + ], + ), + InkWell( + onTap: () => viewModel.setGraphView(!viewModel.isGraphView), + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + transitionBuilder: (Widget child, Animation animation) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + child: child, + ), + ); + }, + child: Container( + key: ValueKey(viewModel.isGraphView), + child: Utils.buildSvgWithAssets( + icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon, + height: 24.h, + width: 24.h, + ), + ), + ), + ), + ], + ), + if (!viewModel.isGraphView) _buildHistoryListView(viewModel) else ...[SizedBox(height: 16.h), _buildHistoryGraph()] + ], + ); + }), + ); + } + + String _formatTime(DateTime time) { + final hour = time.hour; + final minute = time.minute; + final hour12 = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour); + final period = hour >= 12 ? 'PM' : 'AM'; + return '${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period'; + } + + String _getDayName(DateTime date) { + const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; + return days[date.weekday - 1]; + } + + String _getMonthName(int monthNumber) { + const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + if (monthNumber < 1 || monthNumber > 12) return 'Unknown'; + return months[monthNumber - 1]; + } + + Widget _buildHistoryListView(HealthTrackersViewModel viewModel) { + List listItems = []; + final unit = _getUnit(); + + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + listItems = _buildBloodSugarListItems(viewModel, unit); + break; + case HealthTrackerTypeEnum.bloodPressure: + listItems = _buildBloodPressureListItems(viewModel); + break; + case HealthTrackerTypeEnum.weightTracker: + listItems = _buildWeightListItems(viewModel, unit); + break; + } + + if (viewModel.isLoading) { + return _buildLoadingShimmer().paddingOnly(top: 16.h); + } + + if (listItems.isEmpty) { + return _buildEmptyStateWidget(); + } + + return ListView.separated( + padding: EdgeInsets.only(top: 16.h), + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: listItems.length, + separatorBuilder: (context, index) => SizedBox.shrink(), + itemBuilder: (context, index) => listItems[index], + ); + } + + /// Build list items for Blood Sugar + List _buildBloodSugarListItems(HealthTrackersViewModel viewModel, String unit) { + List listItems = []; + final allResults = []; + + allResults.addAll(viewModel.weekDiabeticPatientResult); + allResults.addAll(viewModel.monthDiabeticPatientResult); + allResults.addAll(viewModel.yearDiabeticPatientResult); + + final seenIds = {}; + final uniqueResults = allResults.where((result) { + final id = '${result.lineItemNo}_${result.dateChart?.millisecondsSinceEpoch ?? 0}'; + if (seenIds.contains(id)) return false; + seenIds.add(id); + return true; + }).toList(); + + uniqueResults.sort((a, b) { + final dateA = a.dateChart ?? DateTime(1900); + final dateB = b.dateChart ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + + for (var result in uniqueResults) { + final resultValue = result.resultValue?.toDouble() ?? 0.0; + final value = result.resultValue?.toString() ?? '0'; + final resultUnit = result.unit ?? unit; + final measuredDesc = result.measuredDesc ?? ''; + final date = result.dateChart; + final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : ''; + final timeLabel = date != null ? _formatTime(date) : 'Unknown'; + final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown'; + final subTitleText = '$value $resultUnit'; + + listItems.add( + Column( + children: [ + buildHistoryListTile( + title: displayLabel, + subTitle: subTitleText, + value: resultValue, + measureDesc: measuredDesc, + ), + Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h), + ], + ), + ); + } + return listItems; + } + + /// Build list items for Blood Pressure + List _buildBloodPressureListItems(HealthTrackersViewModel viewModel) { + List listItems = []; + final allResults = []; + + allResults.addAll(viewModel.weekBloodPressureResult); + allResults.addAll(viewModel.monthBloodPressureResult); + allResults.addAll(viewModel.yearBloodPressureResult); + + final seenIds = {}; + final uniqueResults = allResults.where((result) { + final id = '${result.lineItemNo}_${result.bloodPressureDate?.millisecondsSinceEpoch ?? 0}'; + if (seenIds.contains(id)) return false; + seenIds.add(id); + return true; + }).toList(); + + uniqueResults.sort((a, b) { + final dateA = a.bloodPressureDate ?? DateTime(1900); + final dateB = b.bloodPressureDate ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + + for (var result in uniqueResults) { + final systolic = result.systolicePressure ?? 0; + final diastolic = result.diastolicPressure ?? 0; + final measuredArmDesc = result.measuredArmDesc ?? ''; + final date = result.bloodPressureDate; + final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : ''; + final timeLabel = date != null ? _formatTime(date) : 'Unknown'; + final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown'; + final subTitleText = '$systolic/$diastolic mmHg'; + + listItems.add( + Column( + children: [ + buildHistoryListTile( + title: displayLabel, + subTitle: subTitleText, + value: systolic.toDouble(), + measureDesc: measuredArmDesc, + ), + Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h), + ], + ), + ); + } + return listItems; + } + + /// Build list items for Weight + List _buildWeightListItems(HealthTrackersViewModel viewModel, String unit) { + List listItems = []; + final allResults = []; + + allResults.addAll(viewModel.weekWeightMeasurementResult); + allResults.addAll(viewModel.monthWeightMeasurementResult); + allResults.addAll(viewModel.yearWeightMeasurementResult); + + final seenIds = {}; + final uniqueResults = allResults.where((result) { + final id = '${result.lineItemNo}_${result.weightDate?.millisecondsSinceEpoch ?? 0}'; + if (seenIds.contains(id)) return false; + seenIds.add(id); + return true; + }).toList(); + + uniqueResults.sort((a, b) { + final dateA = a.weightDate ?? DateTime(1900); + final dateB = b.weightDate ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + + for (var result in uniqueResults) { + final weightValue = result.weightMeasured?.toDouble() ?? 0.0; + final weightUnit = result.unit ?? unit; + final date = result.weightDate; + final dateLabel = date != null ? '${_getDayName(date)} ${date.day} ${_getMonthName(date.month).substring(0, 3)}, ${date.year}' : ''; + final timeLabel = date != null ? _formatTime(date) : 'Unknown'; + final displayLabel = date != null ? '$dateLabel, $timeLabel' : 'Unknown'; + final subTitleText = '${weightValue.toInt()} $weightUnit'; + + listItems.add( + Column( + children: [ + buildHistoryListTile( + title: displayLabel, + subTitle: subTitleText, + value: weightValue, + measureDesc: '', + ), + Divider(height: 1, color: AppColors.dividerColor).paddingOnly(bottom: 8.h), + ], + ), + ); + } + return listItems; + } + + Widget _buildLoadingShimmer({bool isForHistory = true}) { + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.all(0.w), + itemCount: 4, + separatorBuilder: (_, __) => SizedBox(height: 12.h), + itemBuilder: (context, index) { + return Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Container( + height: isForHistory ? 60.h : 40.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(10.r), + ), + ), + ); + }, + ); + } + + Widget _buildEmptyStateWidget() { + return SizedBox( + height: MediaQuery.of(context).size.height * 0.5, + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.calendar, + iconColor: AppColors.textColor, + height: 48.w, + width: 48.w, + ), + SizedBox(height: 16.h), + "You do not have any data available.".toText14( + weight: FontWeight.w500, + color: AppColors.textColor, + isCenter: true, + ), + SizedBox(height: 8.h), + _getEmptyStateMessage().toText12( + color: AppColors.greyTextColor, + isCenter: true, + ), + ], + ), + ), + ); + } + + Widget _buildHistoryGraph() { + return Consumer( + builder: (context, viewModel, _) { + final selectedDuration = viewModel.selectedDurationFilter; + List dataPoints = []; + List? secondaryDataPoints; + + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + dataPoints = _buildBloodSugarGraphData(viewModel, selectedDuration); + break; + case HealthTrackerTypeEnum.bloodPressure: + final (systolicData, diastolicData) = _buildBloodPressureGraphData(viewModel, selectedDuration); + dataPoints = systolicData; // Systolic (primary line) + secondaryDataPoints = diastolicData; // Diastolic (secondary line) + break; + case HealthTrackerTypeEnum.weightTracker: + dataPoints = _buildWeightGraphData(viewModel, selectedDuration); + break; + } + + if (dataPoints.isEmpty) { + return _buildEmptyStateWidget(); + } + + if (viewModel.isLoading) { + return Container( + padding: EdgeInsets.symmetric(vertical: 40.h), + child: _buildLoadingShimmer(), + ); + } + + // Calculate max value from both lines for blood pressure + double maxDataValue = dataPoints.isNotEmpty ? dataPoints.map((p) => p.value).reduce((a, b) => a > b ? a : b) : 0.0; + if (secondaryDataPoints != null && secondaryDataPoints.isNotEmpty) { + final secondaryMax = secondaryDataPoints.map((p) => p.value).reduce((a, b) => a > b ? a : b); + if (secondaryMax > maxDataValue) maxDataValue = secondaryMax; + } + + double maxY = maxDataValue > 200 ? (maxDataValue * 1.2) : 250; + double minY = 0; + double horizontalInterval = maxY / 4; + double leftLabelInterval = horizontalInterval; + + // Set colors based on tracker type + Color graphColor = AppColors.successColor; + Color? secondaryGraphColor; + + if (widget.trackerType == HealthTrackerTypeEnum.bloodPressure) { + graphColor = AppColors.errorColor; // Red for Systolic + secondaryGraphColor = AppColors.blueColor; // Blue for Diastolic + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Legend for blood pressure + if (widget.trackerType == HealthTrackerTypeEnum.bloodPressure) ...[ + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildLegendItem(AppColors.errorColor, LocaleKeys.systolic.tr()), + SizedBox(width: 24.w), + _buildLegendItem(AppColors.blueColor, LocaleKeys.diastolic.tr()), + ], + ), + SizedBox(height: 12.h), + ], + CustomGraph( + bottomLabelReservedSize: 30, + dataPoints: dataPoints, + secondaryDataPoints: secondaryDataPoints, + makeGraphBasedOnActualValue: false, + leftLabelReservedSize: 50.h, + showGridLines: true, + maxY: maxY, + minY: minY, + showLinePoints: true, + maxX: dataPoints.length > 1 ? dataPoints.length.toDouble() - 0.75 : 1.0, + horizontalInterval: horizontalInterval, + leftLabelInterval: leftLabelInterval, + showShadow: widget.trackerType != HealthTrackerTypeEnum.bloodPressure, + graphColor: graphColor, + secondaryGraphColor: secondaryGraphColor, + graphShadowColor: graphColor.withValues(alpha: 0.15), + getDrawingHorizontalLine: (value) { + if (value % horizontalInterval == 0 && value > 0) { + return FlLine( + color: AppColors.greyTextColor.withValues(alpha: 0.3), + strokeWidth: 1.5, + dashArray: [8, 4], + ); + } + return FlLine(color: AppColors.transparent, strokeWidth: 0); + }, + leftLabelFormatter: (value) { + final interval = maxY / 4; + final positions = [0.0, interval, interval * 2, interval * 3, maxY]; + for (var position in positions) { + if ((value - position).abs() < 1) { + return '${value.toInt()}'.toText10(weight: FontWeight.w600); + } + } + return SizedBox.shrink(); + }, + bottomLabelFormatter: (value, data) { + if (data.isEmpty) return SizedBox.shrink(); + if ((value - value.round()).abs() > 0.01) return SizedBox.shrink(); + int index = value.round(); + if (index < 0 || index >= data.length) return SizedBox.shrink(); + + if (selectedDuration == 'Week' && index < 7) { + return Padding( + padding: EdgeInsets.only(top: 10.h), + child: data[index].label.toText10(weight: FontWeight.w600, color: AppColors.labelTextColor), + ); + } + if (selectedDuration == 'Month' && index < 6) { + return Padding( + padding: EdgeInsets.only(top: 10.h), + child: data[index].label.toText10(weight: FontWeight.w600, color: AppColors.labelTextColor), + ); + } + if (selectedDuration == 'Year' && index < 12) { + return Padding( + padding: EdgeInsets.only(top: 10.h), + child: data[index].label.toText8(fontWeight: FontWeight.w600, color: AppColors.labelTextColor), + ); + } + return SizedBox.shrink(); + }, + scrollDirection: selectedDuration == 'Year' ? Axis.horizontal : Axis.vertical, + height: 250.h, + spotColor: graphColor, + ), + ], + ); + }, + ); + } + + /// Build legend item for graph + Widget _buildLegendItem(Color color, String label) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 12.w, + height: 12.w, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(2.r), + ), + ), + SizedBox(width: 6.w), + label.toText12(fontWeight: FontWeight.w500, color: AppColors.textColor), + ], + ); + } + + /// Build graph data for Blood Sugar + List _buildBloodSugarGraphData(HealthTrackersViewModel viewModel, String selectedDuration) { + List dataPoints = []; + final unit = _getUnit(); + + if (selectedDuration == 'Week') { + final weekResults = viewModel.weekDiabeticResultAverage; + if (weekResults.isNotEmpty) { + final sortedResults = List.from(weekResults); + sortedResults.sort((a, b) => (a.dateChart ?? DateTime.now()).compareTo(b.dateChart ?? DateTime.now())); + final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults; + + for (var result in last7Days) { + final value = result.dailyAverageResult?.toDouble() ?? 0.0; + final date = result.dateChart ?? DateTime.now(); + final label = _getDayName(date).substring(0, 3); + dataPoints.add(DataPoint( + value: value, + label: label, + actualValue: value.toStringAsFixed(1), + time: date, + displayTime: _getDayName(date), + unitOfMeasurement: unit)); + } + } + } else if (selectedDuration == 'Month') { + final monthResults = viewModel.monthDiabeticResultAverage; + if (monthResults.isNotEmpty) { + for (int i = 0; i < monthResults.length; i++) { + final weekData = monthResults[i]; + final value = (weekData.weekAverageResult is num) + ? (weekData.weekAverageResult as num).toDouble() + : double.tryParse(weekData.weekAverageResult?.toString() ?? '0') ?? 0.0; + final weekLabel = weekData.weekDesc ?? 'Week ${i + 1}'; + dataPoints.add(DataPoint( + value: value, + label: 'W${i + 1}', + actualValue: value.toStringAsFixed(1), + time: DateTime.now(), + displayTime: weekLabel, + unitOfMeasurement: unit)); + } + } + } else if (selectedDuration == 'Year') { + final yearResults = viewModel.yearDiabeticResultAverage; + if (yearResults.isNotEmpty) { + for (int targetMonth = 1; targetMonth <= 12; targetMonth++) { + final monthData = yearResults.firstWhere((m) => m.monthNumber == targetMonth, + orElse: () => YearDiabeticResultAverage(monthAverageResult: 0.0, monthNumber: targetMonth, monthName: _getMonthName(targetMonth))); + final value = monthData.monthAverageResult?.toDouble() ?? 0.0; + final monthName = monthData.monthName ?? _getMonthName(targetMonth); + final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName; + dataPoints.add(DataPoint( + value: value, + label: label, + actualValue: value.toStringAsFixed(1), + time: DateTime(DateTime.now().year, targetMonth, 1), + displayTime: monthName, + unitOfMeasurement: unit)); + } + } + } + return dataPoints; + } + + /// Build graph data for Blood Pressure - returns (systolicData, diastolicData) + (List, List) _buildBloodPressureGraphData(HealthTrackersViewModel viewModel, String selectedDuration) { + List systolicDataPoints = []; + List diastolicDataPoints = []; + const unit = 'mmHg'; + + if (selectedDuration == 'Week') { + final weekResults = viewModel.weekBloodPressureResult; + if (weekResults.isNotEmpty) { + final sortedResults = List.from(weekResults); + sortedResults.sort((a, b) => (a.bloodPressureDate ?? DateTime.now()).compareTo(b.bloodPressureDate ?? DateTime.now())); + final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults; + + for (var result in last7Days) { + final systolic = (result.systolicePressure ?? 0).toDouble(); + final diastolic = (result.diastolicPressure ?? 0).toDouble(); + final date = result.bloodPressureDate ?? DateTime.now(); + final label = _getDayName(date).substring(0, 3); + + systolicDataPoints.add(DataPoint( + value: systolic, + label: label, + actualValue: '${systolic.toInt()}/${diastolic.toInt()}', + time: date, + displayTime: _getDayName(date), + unitOfMeasurement: unit)); + + diastolicDataPoints.add(DataPoint( + value: diastolic, + label: label, + actualValue: diastolic.toStringAsFixed(0), + time: date, + displayTime: _getDayName(date), + unitOfMeasurement: unit)); + } + } + } else if (selectedDuration == 'Month') { + final monthResults = viewModel.monthBloodPressureResult; + if (monthResults.isNotEmpty) { + // Group by week and calculate averages + final Map> weekGroups = {}; + for (var result in monthResults) { + final weekDesc = result.weekDesc ?? 'Week 1'; + weekGroups.putIfAbsent(weekDesc, () => []); + weekGroups[weekDesc]!.add(result); + } + + int weekIndex = 0; + for (var entry in weekGroups.entries) { + final weekData = entry.value; + double avgSystolic = 0; + double avgDiastolic = 0; + + for (var result in weekData) { + avgSystolic += (result.systolicePressure ?? 0); + avgDiastolic += (result.diastolicPressure ?? 0); + } + + if (weekData.isNotEmpty) { + avgSystolic = avgSystolic / weekData.length; + avgDiastolic = avgDiastolic / weekData.length; + } + + final weekLabel = entry.key; + systolicDataPoints.add(DataPoint( + value: avgSystolic, + label: 'W${weekIndex + 1}', + actualValue: '${avgSystolic.toInt()}/${avgDiastolic.toInt()}', + time: DateTime.now(), + displayTime: weekLabel, + unitOfMeasurement: unit)); + + diastolicDataPoints.add(DataPoint( + value: avgDiastolic, + label: 'W${weekIndex + 1}', + actualValue: avgDiastolic.toStringAsFixed(0), + time: DateTime.now(), + displayTime: weekLabel, + unitOfMeasurement: unit)); + + weekIndex++; + } + } + } else if (selectedDuration == 'Year') { + final yearResults = viewModel.yearBloodPressureResult; + if (yearResults.isNotEmpty) { + // Group by month and calculate averages + final Map> monthGroups = {}; + for (var result in yearResults) { + final chartMonth = result.chartMonth; + final monthNum = _getMonthNumber(chartMonth ?? 'January'); + monthGroups.putIfAbsent(monthNum, () => []); + monthGroups[monthNum]!.add(result); + } + + for (int targetMonth = 1; targetMonth <= 12; targetMonth++) { + double avgSystolic = 0; + double avgDiastolic = 0; + + if (monthGroups.containsKey(targetMonth) && monthGroups[targetMonth]!.isNotEmpty) { + final monthData = monthGroups[targetMonth]!; + for (var result in monthData) { + avgSystolic += (result.systolicePressure ?? 0); + avgDiastolic += (result.diastolicPressure ?? 0); + } + avgSystolic = avgSystolic / monthData.length; + avgDiastolic = avgDiastolic / monthData.length; + } + + final monthName = _getMonthName(targetMonth); + final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName; + + systolicDataPoints.add(DataPoint( + value: avgSystolic, + label: label, + actualValue: '${avgSystolic.toInt()}/${avgDiastolic.toInt()}', + time: DateTime(DateTime.now().year, targetMonth, 1), + displayTime: monthName, + unitOfMeasurement: unit)); + + diastolicDataPoints.add(DataPoint( + value: avgDiastolic, + label: label, + actualValue: avgDiastolic.toStringAsFixed(0), + time: DateTime(DateTime.now().year, targetMonth, 1), + displayTime: monthName, + unitOfMeasurement: unit)); + } + } + } + return (systolicDataPoints, diastolicDataPoints); + } + + /// Helper to get month number from name + int _getMonthNumber(String monthName) { + const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + final index = months.indexWhere((m) => m.toLowerCase() == monthName.toLowerCase()); + return index >= 0 ? index + 1 : 1; + } + + /// Build graph data for Weight + List _buildWeightGraphData(HealthTrackersViewModel viewModel, String selectedDuration) { + List dataPoints = []; + final unit = _getUnit(); + + if (selectedDuration == 'Week') { + final weekResults = viewModel.weekWeightMeasurementResultAverage; + if (weekResults.isNotEmpty) { + final sortedResults = List.from(weekResults); + sortedResults.sort((a, b) => (a.weightDate ?? DateTime.now()).compareTo(b.weightDate ?? DateTime.now())); + final last7Days = sortedResults.length > 7 ? sortedResults.sublist(sortedResults.length - 7) : sortedResults; + + for (var result in last7Days) { + final value = result.dailyAverageResult?.toDouble() ?? 0.0; + final date = result.weightDate ?? DateTime.now(); + final label = _getDayName(date).substring(0, 3); + dataPoints.add(DataPoint( + value: value, + label: label, + actualValue: value.toStringAsFixed(1), + time: date, + displayTime: _getDayName(date), + unitOfMeasurement: unit)); + } + } + } else if (selectedDuration == 'Month') { + final monthResults = viewModel.monthWeightMeasurementResultAverage; + if (monthResults.isNotEmpty) { + for (int i = 0; i < monthResults.length; i++) { + final weekData = monthResults[i]; + final value = weekData.weekAverageResult?.toDouble() ?? 0.0; + final weekLabel = weekData.weekDesc ?? 'Week ${i + 1}'; + dataPoints.add(DataPoint( + value: value, + label: 'W${i + 1}', + actualValue: value.toStringAsFixed(1), + time: DateTime.now(), + displayTime: weekLabel, + unitOfMeasurement: unit)); + } + } + } else if (selectedDuration == 'Year') { + final yearResults = viewModel.yearWeightMeasurementResultAverage; + if (yearResults.isNotEmpty) { + for (int targetMonth = 1; targetMonth <= 12; targetMonth++) { + final monthData = yearResults.firstWhere((m) => m.monthNumber == targetMonth, + orElse: () => + YearWeightMeasurementResultAverage(monthAverageResult: 0.0, monthNumber: targetMonth, monthName: _getMonthName(targetMonth))); + final value = monthData.monthAverageResult?.toDouble() ?? 0.0; + final monthName = monthData.monthName ?? _getMonthName(targetMonth); + final label = monthName.length >= 3 ? monthName.substring(0, 3) : monthName; + dataPoints.add(DataPoint( + value: value, + label: label, + actualValue: value.toStringAsFixed(1), + time: DateTime(DateTime.now().year, targetMonth, 1), + displayTime: monthName, + unitOfMeasurement: unit)); + } + } + } + return dataPoints; + } + + void onSendEmailPressed(BuildContext context) async { + _showEmailInputBottomSheet(context); + } + + /// Show email input bottom sheet + void _showEmailInputBottomSheet(BuildContext context) { + final viewModel = context.read(); + final appState = getIt.get(); + final dialogService = getIt.get(); + + // Get user's email from authenticated user + final userEmail = appState.getAuthenticatedUser()?.emailAddress ?? ''; + + // Create email controller and pre-fill if available + final emailController = TextEditingController(text: userEmail); + + dialogService.showFamilyBottomSheetWithoutHWithChild( + label: LocaleKeys.sendReportByEmail.tr(), + message: "", + child: _buildEmailInputContent( + context: context, + emailController: emailController, + viewModel: viewModel, + dialogService: dialogService, + ), + onOkPressed: () {}, + ); + } + + /// Build email input content + Widget _buildEmailInputContent({ + required BuildContext context, + required TextEditingController emailController, + required HealthTrackersViewModel viewModel, + required DialogService dialogService, + }) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.enterYourEmailToReceiveReport.tr().toText14( + color: AppColors.textColor, + weight: FontWeight.w400, + ), + SizedBox(height: 16.h), + + // Email Input Field using TextInputWidget + TextInputWidget( + padding: EdgeInsets.symmetric(horizontal: 8.w), + labelText: LocaleKeys.email.tr(context: context), + hintText: LocaleKeys.enterEmail.tr(context: context), + controller: emailController, + keyboardType: TextInputType.emailAddress, + isEnable: true, + isBorderAllowed: true, + isAllowRadius: true, + ), + + SizedBox(height: 24.h), + + // Send Button + Row( + children: [ + Expanded( + child: CustomButton( + height: 56.h, + text: LocaleKeys.send.tr(context: context), + onPressed: () { + _sendEmailReport( + context: context, + email: emailController.text.trim(), + viewModel: viewModel, + dialogService: dialogService, + ); + }, + textColor: AppColors.whiteColor, + ), + ), + ], + ), + ], + ); + } + + /// Send email report based on tracker type + Future _sendEmailReport({ + required BuildContext context, + required String email, + required HealthTrackersViewModel viewModel, + required DialogService dialogService, + }) async { + // Validate email + if (email.isEmpty) { + dialogService.showErrorBottomSheet( + message: LocaleKeys.enterEmail.tr(context: context), + ); + return; + } + + // Basic email validation + final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); + if (!emailRegex.hasMatch(email)) { + dialogService.showErrorBottomSheet( + message: LocaleKeys.pleaseEnterAValidEmail.tr(context: context), + ); + return; + } + + // Close the email input bottom sheet + Navigator.of(context).pop(); + + // Call appropriate email function based on tracker type + switch (widget.trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + await viewModel.sendBloodSugarReportByEmail( + email: email, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + + _showSuccessMessage(context, dialogService); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + dialogService.showErrorBottomSheet(message: error); + }, + ); + break; + + case HealthTrackerTypeEnum.bloodPressure: + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + + await viewModel.sendBloodPressureReportByEmail( + email: email, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + + _showSuccessMessage(context, dialogService); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + + dialogService.showErrorBottomSheet(message: error); + }, + ); + break; + + case HealthTrackerTypeEnum.weightTracker: + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context)); + await viewModel.sendWeightReportByEmail( + email: email, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + + _showSuccessMessage(context, dialogService); + }, + onFailure: (error) { + LoaderBottomSheet.hideLoader(); + + dialogService.showErrorBottomSheet(message: error); + }, + ); + break; + } + } + + /// Show success message + void _showSuccessMessage(BuildContext context, DialogService dialogService) { + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getSuccessWidget( + loadingText: LocaleKeys.emailSentSuccessfully.tr(context: context), + ), + callBackFunc: () {}, + isCloseButtonVisible: false, + isDismissible: true, + isFullScreen: false, + ); + } + + Widget _buildPageShimmer() { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + child: Column( + children: [ + SizedBox(height: 16.h), + Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Container( + height: 120.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(24.r), + ), + ), + ), + SizedBox(height: 16.h), + Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Container( + height: 300.h, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(24.r), + ), + ), + ), + SizedBox(height: 16.h), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + sendEmail: () async => onSendEmailPressed(context), + title: _getPageTitle(), + bottomChild: Consumer( + builder: (context, viewModel, child) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.w), + child: CustomButton( + text: LocaleKeys.addNewRecord.tr(), + onPressed: () { + if (!viewModel.isLoading) { + context.navigateWithName(AppRoutes.addHealthTrackerEntryPage, arguments: widget.trackerType); + } + }, + icon: AppAssets.add_icon, + borderRadius: 12.r, + borderColor: AppColors.transparent, + padding: EdgeInsets.symmetric(vertical: 14.h), + ), + ), + ); + }, + ), + child: Consumer( + builder: (context, viewModel, child) { + if (viewModel.isLoading) { + return _buildPageShimmer(); + } + + if (_hasNoData(viewModel)) { + return _buildEmptyStateWidget(); + } + + return Column( + children: [ + SizedBox(height: 16.h), + TrackerLastValueCard(trackerType: widget.trackerType), + SizedBox(height: 16.h), + _buildHistoryGraphOrList(), + SizedBox(height: 16.h), + ], + ); + }, + ), + ), + ); + } +} diff --git a/lib/presentation/health_trackers/health_trackers_page.dart b/lib/presentation/health_trackers/health_trackers_page.dart new file mode 100644 index 0000000..9c68281 --- /dev/null +++ b/lib/presentation/health_trackers/health_trackers_page.dart @@ -0,0 +1,120 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; + +class HealthTrackersPage extends StatefulWidget { + const HealthTrackersPage({super.key}); + + @override + State createState() => _HealthTrackersPageState(); +} + +Widget buildHealthTrackerCard({ + required String icon, + required String title, + required String description, + required Color iconBgColor, + required VoidCallback onTap, +}) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: Colors.white, borderRadius: 20.r), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: iconBgColor, borderRadius: 10.r), + height: 40.w, + width: 40.w, + child: Utils.buildSvgWithAssets( + icon: icon, + fit: BoxFit.none, + height: 22.w, + width: 22.w, + ), + ), + SizedBox(width: 12.w), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + title.toText16(weight: FontWeight.w600), + description.toText12( + fontWeight: FontWeight.w500, + color: Color(0xFF8F9AA3), + ), + ], + ), + ), + SizedBox(width: 12.w), + Utils.buildSvgWithAssets( + icon: AppAssets.arrowRight, + width: 24.w, + height: 24.h, + fit: BoxFit.contain, + iconColor: AppColors.textColor, + ), + ], + ).paddingAll(16.w), + ).onPress(onTap); +} + +class _HealthTrackersPageState extends State { + @override + Widget build(BuildContext context) { + return CollapsingListView( + title: LocaleKeys.healthTrackers.tr(context: context), + child: Column( + children: [ + buildHealthTrackerCard( + iconBgColor: AppColors.primaryRedColor, + icon: AppAssets.bloodSugarOnlyIcon, + title: LocaleKeys.bloodSugar.tr(context: context), + description: "Track your glucose levels, understand trends, and get personalized insights for better health.", + onTap: () { + context.navigateWithName( + AppRoutes.healthTrackerDetailPage, + arguments: HealthTrackerTypeEnum.bloodSugar, + ); + }, + ), + SizedBox(height: 16.h), + buildHealthTrackerCard( + iconBgColor: AppColors.infoColor, + icon: AppAssets.bloodPressureIcon, + title: LocaleKeys.bloodPressure.tr(context: context), + description: LocaleKeys.monitorBloodPressureLevels.tr(context: context), + onTap: () { + context.navigateWithName( + AppRoutes.healthTrackerDetailPage, + arguments: HealthTrackerTypeEnum.bloodPressure, + ); + }, + ), + SizedBox(height: 16.h), + buildHealthTrackerCard( + iconBgColor: AppColors.successColor, + icon: AppAssets.weightIcon, + title: LocaleKeys.weight.tr(context: context), + description: LocaleKeys.trackWeightProgress.tr(context: context), + onTap: () { + context.navigateWithName( + AppRoutes.healthTrackerDetailPage, + arguments: HealthTrackerTypeEnum.weightTracker, + ); + }, + ), + ], + ).paddingSymmetrical(20.w, 24.h), + ); + } +} diff --git a/lib/presentation/health_trackers/widgets/tracker_last_value_card.dart b/lib/presentation/health_trackers/widgets/tracker_last_value_card.dart new file mode 100644 index 0000000..7e4ac2c --- /dev/null +++ b/lib/presentation/health_trackers/widgets/tracker_last_value_card.dart @@ -0,0 +1,272 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:provider/provider.dart'; +import 'package:shimmer/shimmer.dart'; + +class TrackerLastValueCard extends StatelessWidget { + final HealthTrackerTypeEnum trackerType; + + const TrackerLastValueCard({super.key, required this.trackerType}); + + /// Get status text and color based on blood sugar value + (String status, Color color, Color bgColor) _getBloodSugarStatus(double value) { + if (value < 70) { + return (LocaleKeys.low.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.5)); + } else if (value <= 100) { + return (LocaleKeys.normal.tr(), AppColors.successColor, AppColors.successLightBgColor); + } else if (value <= 125) { + return (LocaleKeys.preDiabetic.tr(), AppColors.ratingColorYellow, AppColors.errorColor.withValues(alpha: 0.4)); + } else { + return (LocaleKeys.high.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.4)); + } + } + + /// Get status text and color based on blood pressure value (systolic) + (String status, Color color, Color bgColor) _getBloodPressureStatus(int systolic) { + if (systolic < 90) { + return (LocaleKeys.low.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.5)); + } else if (systolic <= 120) { + return (LocaleKeys.normal.tr(), AppColors.successColor, AppColors.successLightBgColor); + } else if (systolic <= 140) { + return (LocaleKeys.elevated.tr(), AppColors.ratingColorYellow, AppColors.errorColor.withValues(alpha: 0.4)); + } else { + return (LocaleKeys.high.tr(), AppColors.errorColor, AppColors.errorColor.withValues(alpha: 0.4)); + } + } + + /// Get status for weight (neutral - no good/bad status) + (String status, Color color, Color bgColor) _getWeightStatus() { + return (LocaleKeys.recorded.tr(), AppColors.successColor, AppColors.successLightBgColor); + } + + /// Get default unit based on tracker type + String _getDefaultUnit() { + switch (trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + return 'mg/dL'; + case HealthTrackerTypeEnum.bloodPressure: + return 'mmHg'; + case HealthTrackerTypeEnum.weightTracker: + return 'kg'; + } + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, viewModel, child) { + // Get the last record based on tracker type + dynamic lastRecord; + String displayValue = '--'; + String unit = _getDefaultUnit(); + DateTime? lastDate; + String status = ''; + Color statusColor = AppColors.greyTextColor; + + switch (trackerType) { + case HealthTrackerTypeEnum.bloodSugar: + final allResults = [ + ...viewModel.weekDiabeticPatientResult, + ...viewModel.monthDiabeticPatientResult, + ...viewModel.yearDiabeticPatientResult, + ]; + if (allResults.isNotEmpty) { + allResults.sort((a, b) { + final dateA = a.dateChart ?? DateTime(1900); + final dateB = b.dateChart ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + lastRecord = allResults.first; + final lastValue = lastRecord.resultValue?.toDouble() ?? 0.0; + displayValue = lastValue.toStringAsFixed(0); + unit = lastRecord.unit ?? 'mg/dL'; + lastDate = lastRecord.dateChart; + final (s, c, _) = _getBloodSugarStatus(lastValue); + status = s; + statusColor = c; + } + break; + + case HealthTrackerTypeEnum.bloodPressure: + final allResults = [ + ...viewModel.weekBloodPressureResult, + ...viewModel.monthBloodPressureResult, + ...viewModel.yearBloodPressureResult, + ]; + if (allResults.isNotEmpty) { + allResults.sort((a, b) { + final dateA = a.bloodPressureDate ?? DateTime(1900); + final dateB = b.bloodPressureDate ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + lastRecord = allResults.first; + final systolic = lastRecord.systolicePressure ?? 0; + final diastolic = lastRecord.diastolicPressure ?? 0; + displayValue = '$systolic/$diastolic'; + unit = 'mmHg'; + lastDate = lastRecord.bloodPressureDate; + final (s, c, _) = _getBloodPressureStatus(systolic); + status = s; + statusColor = c; + } + break; + + case HealthTrackerTypeEnum.weightTracker: + final allResults = [ + ...viewModel.weekWeightMeasurementResult, + ...viewModel.monthWeightMeasurementResult, + ...viewModel.yearWeightMeasurementResult, + ]; + if (allResults.isNotEmpty) { + allResults.sort((a, b) { + final dateA = a.weightDate ?? DateTime(1900); + final dateB = b.weightDate ?? DateTime(1900); + return dateB.compareTo(dateA); + }); + lastRecord = allResults.first; + final weightValue = lastRecord.weightMeasured?.toDouble() ?? 0.0; + displayValue = weightValue.toStringAsFixed(0); + unit = lastRecord.unit ?? 'kg'; + lastDate = lastRecord.weightDate; + final (s, c, _) = _getWeightStatus(); + status = s; + statusColor = c; + } + break; + } + + final formattedDate = lastDate != null ? DateFormat('EEE DD MMM, yy').format(lastDate) : DateFormat('EEE DD MMM, yy').format(DateTime.now()); + + // Show shimmer while loading + if (viewModel.isLoading) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Shimmer.fromColors( + baseColor: AppColors.shimmerBaseColor, + highlightColor: AppColors.shimmerHighlightColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + height: 40.h, + width: 120.w, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(8.r), + ), + ), + SizedBox(height: 8.h), + Row( + children: [ + Container( + height: 32.h, + width: 150.w, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(16.r), + ), + ), + SizedBox(width: 8.w), + Container( + height: 32.h, + width: 80.w, + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(16.r), + ), + ), + ], + ), + ], + ), + ), + ); + } + + // Show empty state if no records + if (lastRecord == null) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + "--".toText32(isBold: true, color: AppColors.greyTextColor), + SizedBox(width: 6.w), + unit.toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500).paddingOnly(top: 8.h), + ], + ), + SizedBox(height: 8.h), + AppCustomChipWidget( + labelText: LocaleKeys.noRecordsYet.tr(), + icon: AppAssets.doctor_calendar_icon, + ), + ], + ), + ); + } + + return Container( + margin: EdgeInsets.symmetric(horizontal: 24.w), + padding: EdgeInsets.all(16.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + displayValue.toText32(isBold: true, color: statusColor), + SizedBox(width: 6.w), + unit.toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500).paddingOnly(top: 8.h), + ], + ), + SizedBox(height: 8.h), + Row( + children: [ + AppCustomChipWidget( + labelText: "${LocaleKeys.lastRecord.tr()}: $formattedDate", + icon: AppAssets.doctor_calendar_icon, + ), + SizedBox(width: 8.w), + if (trackerType != HealthTrackerTypeEnum.weightTracker) ...[ + AppCustomChipWidget( + labelText: status, + icon: AppAssets.normalStatusGreenIcon, + iconColor: statusColor, + ), + ] + ], + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/presentation/hmg_services/services_page.dart b/lib/presentation/hmg_services/services_page.dart index f2cab90..10b9342 100644 --- a/lib/presentation/hmg_services/services_page.dart +++ b/lib/presentation/hmg_services/services_page.dart @@ -4,15 +4,18 @@ import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/hmg_services_component_model.dart'; +import 'package:hmg_patient_app_new/features/hospital/hospital_selection_view_model.dart'; import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; @@ -25,6 +28,7 @@ import 'package:hmg_patient_app_new/presentation/hmg_services/services_view.dart import 'package:hmg_patient_app_new/presentation/home/data/landing_page_data.dart'; import 'package:hmg_patient_app_new/presentation/home/widgets/large_service_card.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/medical_file_page.dart'; +import 'package:hmg_patient_app_new/presentation/parking/paking_page.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -36,105 +40,141 @@ import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; import '../../core/dependencies.dart' show getIt; +import '../../features/qr_parking/qr_parking_view_model.dart'; +import '../emergency_services/call_ambulance/widgets/HospitalBottomSheetBody.dart'; class ServicesPage extends StatelessWidget { - ServicesPage({super.key}); + bool showBackIcon; + + ServicesPage({super.key, this.showBackIcon = true}); late BloodDonationViewModel bloodDonationViewModel; late MedicalFileViewModel medicalFileViewModel; late final List hmgServices = [ HmgServicesComponentModel( - 11, - "Emergency Services".needTranslation, - "".needTranslation, - AppAssets.emergency_services_icon, - bgColor: AppColors.primaryRedColor, - true, route: null, onTap: () { - getIt.get().flushData(); - getIt.get().getTransportationOrders( - showLoader: false, - ); - getIt.get().getRRTOrders( - showLoader: false, - ); - Navigator.of(GetIt.instance().navigatorKey.currentContext!).push( - CustomPageRoute( - page: EmergencyServicesPage(), - settings: const RouteSettings(name: '/EmergencyServicesPage'), - ), - ); + 11, + LocaleKeys.emergencyServices.tr(), + "", + AppAssets.emergency_services_icon, + bgColor: AppColors.primaryRedColor, + true, + route: null, onTap: () async { + if (getIt.get().isAuthenticated) { + getIt.get().flushData(); + getIt.get().getTransportationOrders( + showLoader: false, + ); + getIt.get().getRRTOrders( + showLoader: false, + ); + Navigator.of(getIt.get().navigatorKey.currentContext!).push( + CustomPageRoute( + page: EmergencyServicesPage(), + settings: const RouteSettings(name: '/EmergencyServicesPage'), + ), + ); + } else { + await getIt.get().onLoginPressed(); + } }), HmgServicesComponentModel( 11, - "Book\nAppointment".needTranslation, - "".needTranslation, + LocaleKeys.bookAppointment.tr(), + "", AppAssets.appointment_calendar_icon, bgColor: AppColors.bookAppointment, true, route: AppRoutes.bookAppointmentPage, ), HmgServicesComponentModel( - 5, - "Complete Checkup".needTranslation, - "".needTranslation, - AppAssets.comprehensiveCheckup, - bgColor: AppColors.bgGreenColor, - true, - route: AppRoutes.comprehensiveCheckupPage, - ), + 5, LocaleKeys.completeCheckup.tr(), "", AppAssets.comprehensiveCheckup, bgColor: AppColors.bgGreenColor, true, route: null, onTap: () async { + if (getIt.get().isAuthenticated) { + getIt.get().pushPageRoute(AppRoutes.comprehensiveCheckupPage); + } else { + await getIt.get().onLoginPressed(); + } + }), HmgServicesComponentModel( 11, - "Indoor Navigation".needTranslation, - "".needTranslation, + LocaleKeys.indoorNavigation.tr(), + "", AppAssets.indoor_nav_icon, bgColor: Color(0xff45A2F8), true, route: null, - onTap: () {}, + onTap: () { + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.selectHospital.tr(), + GetIt.instance().navigatorKey.currentContext!, + child: ChangeNotifierProvider( + create: (context) => HospitalSelectionBottomSheetViewModel(getIt()), + child: Consumer( + builder: (_, vm, __) => HospitalBottomSheetBody( + searchText: vm.searchController, + displayList: vm.displayList, + onFacilityClicked: (value) { + vm.setSelectedFacility(value); + vm.getDisplayList(); + }, + onHospitalClicked: (hospital) { + Navigator.pop(GetIt.instance().navigatorKey.currentContext!); + vm.openPenguin(hospital); + }, + onHospitalSearch: (value) { + vm.searchHospitals(value ?? ""); + }, + selectedFacility: vm.selectedFacility, + hmcCount: vm.hmcCount, + hmgCount: vm.hmgCount, + ), + ), + ), + isFullScreen: false, + isCloseButtonVisible: true, + hasBottomPadding: false, + backgroundColor: AppColors.bottomSheetBgColor, + callBackFunc: () { + GetIt.instance().navigatorKey.currentContext!.read().clearSearchText(); + }, + ); + }, ), HmgServicesComponentModel( - 11, - "E-Referral Services".needTranslation, + 11, LocaleKeys.eReferralServices.tr(), "", AppAssets.eReferral, bgColor: AppColors.eReferralCardColor, true, route: null, onTap: () async { + if (getIt.get().isAuthenticated) { + getIt.get().pushPageRoute(AppRoutes.eReferralPage); + } else { + await getIt.get().onLoginPressed(); + } + }), + HmgServicesComponentModel( + 3, + "Blood Donation".needTranslation, "".needTranslation, - AppAssets.eReferral, - bgColor: AppColors.eReferralCardColor, + AppAssets.blood_donation_icon, + bgColor: AppColors.bloodDonationCardColor, true, - route: AppRoutes.eReferralPage, + route: AppRoutes.bloodDonationPage, ), HmgServicesComponentModel( - 3, - "Blood Donation".needTranslation, - "".needTranslation, - AppAssets.blood_donation_icon, - bgColor: AppColors.bloodDonationCardColor, - true, - route: null, onTap: () async { - LoaderBottomSheet.showLoader(loadingText: "Fetching Data..."); - await bloodDonationViewModel.getRegionSelectedClinics(onSuccess: (val) async { - // await bloodDonationViewModel.getPatientBloodGroupDetails(onSuccess: (val) { - LoaderBottomSheet.hideLoader(); - Navigator.of(GetIt.instance().navigatorKey.currentContext!).push( - CustomPageRoute( - page: BloodDonationPage(), - ), - ); - // }, onError: (err) { - // LoaderBottomSheet.hideLoader(); - // }); - }, onError: (err) { - LoaderBottomSheet.hideLoader(); - }); - }), - // HmgServicesComponentModel( - // 11, - // "Covid 19 Test".needTranslation, - // "".needTranslation, - // AppAssets.covid19icon, - // bgColor: AppColors.covid29Color, - // true, - // route: AppRoutes.covid19Test, - // ), + 3, + "My Child Vaccine".needTranslation, + "".needTranslation, + AppAssets.my_child_vaccine_icon, + bgColor: AppColors.myChildVaccineCardColor, + true, + route: AppRoutes.myChildVaccine, + ), +// HmgServicesComponentModel( +// 11, +// "Covid 19 Test".needTranslation, +// "".needTranslation, +// AppAssets.covid19icon, +// bgColor: AppColors.covid29Color, +// true, +// route: AppRoutes.covid19Test, +// ), // HmgServicesComponentModel( // 11, @@ -174,37 +214,57 @@ class ServicesPage extends StatelessWidget { late final List hmgHealthToolServices = [ HmgServicesComponentModel( 11, - "Daily Water Monitor".needTranslation, - "".needTranslation, + LocaleKeys.healthTrackers.tr(), + "", + AppAssets.general_health, + bgColor: AppColors.whiteColor, + true, + route: null, + onTap: () async { + if (getIt.get().isAuthenticated) { + getIt.get().pushPageRoute(AppRoutes.healthTrackersPage); + } else { + await getIt.get().onLoginPressed(); + } + }, + ), + HmgServicesComponentModel( + 11, + LocaleKeys.dailyWaterMonitor.tr(), + "", AppAssets.daily_water_monitor_icon, bgColor: AppColors.whiteColor, true, route: null, // Set to null since we handle navigation in onTap onTap: () async { - LoaderBottomSheet.showLoader(loadingText: "Fetching your water intake details.".needTranslation); - final waterMonitorVM = getIt.get(); - final context = getIt.get().navigatorKey.currentContext!; - await waterMonitorVM.fetchUserDetailsForMonitoring( - onSuccess: (userDetail) { - LoaderBottomSheet.hideLoader(); - if (userDetail == null) { - waterMonitorVM.populateFromAuthenticatedUser(); - context.navigateWithName(AppRoutes.waterMonitorSettingsScreen); - } else { - context.navigateWithName(AppRoutes.waterConsumptionScreen); - } - }, - onError: (error) { - LoaderBottomSheet.hideLoader(); - context.navigateWithName(AppRoutes.waterConsumptionScreen); - }, - ); + if (getIt.get().isAuthenticated) { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingYourWaterIntakeDetails.tr()); + final waterMonitorVM = getIt.get(); + final context = getIt.get().navigatorKey.currentContext!; + await waterMonitorVM.fetchUserDetailsForMonitoring( + onSuccess: (userDetail) { + LoaderBottomSheet.hideLoader(); + if (userDetail == null) { + waterMonitorVM.populateFromAuthenticatedUser(); + context.navigateWithName(AppRoutes.waterMonitorSettingsPage); + } else { + context.navigateWithName(AppRoutes.waterConsumptionPage); + } + }, + onError: (error) { + LoaderBottomSheet.hideLoader(); + context.navigateWithName(AppRoutes.waterConsumptionPage); + }, + ); + } else { + await getIt.get().onLoginPressed(); + } }, ), HmgServicesComponentModel( 11, - "Health\nCalculators".needTranslation, - "".needTranslation, + LocaleKeys.healthCalculatorsServices.tr(), + "", AppAssets.health_calculators_services_icon, bgColor: AppColors.whiteColor, true, @@ -212,8 +272,8 @@ class ServicesPage extends StatelessWidget { ), HmgServicesComponentModel( 5, - "Health\nConverters".needTranslation, - "".needTranslation, + LocaleKeys.healthConvertersServices.tr(), + "", AppAssets.health_converters_icon, bgColor: AppColors.whiteColor, true, @@ -221,12 +281,19 @@ class ServicesPage extends StatelessWidget { ), HmgServicesComponentModel( 11, - "Smart\nWatches".needTranslation, - "".needTranslation, + LocaleKeys.smartWatchesServices.tr(), + "", AppAssets.smartwatch_icon, bgColor: AppColors.whiteColor, true, - route: AppRoutes.smartWatches, + route: null, + onTap: () async { + if (getIt.get().isAuthenticated) { + getIt.get().pushPageRoute(AppRoutes.smartWatches); + } else { + await getIt.get().onLoginPressed(); + } + }, // route: AppRoutes.huaweiHealthExample, ), ]; @@ -238,21 +305,20 @@ class ServicesPage extends StatelessWidget { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Explore Services".needTranslation, - isLeading: false, + title: LocaleKeys.exploreServices.tr(), + isLeading: showBackIcon, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 16.h), - "Medical & Care Services".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0), + LocaleKeys.medicalAndCareServices.tr().toText18(weight: FontWeight.w600).paddingSymmetrical(24.w, 0), SizedBox(height: 16.h), GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: (isFoldable || isTablet) ? 6 : 4, // 4 icons per row - crossAxisSpacing: 12.w, - mainAxisSpacing: 18.h, - childAspectRatio: 0.8, - ), + crossAxisCount: (isFoldable || isTablet) ? 6 : 4, // 4 icons per row + crossAxisSpacing: 21.w, + mainAxisSpacing: 18.h, + childAspectRatio: 80 / 94), physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: hmgServices.length, @@ -262,7 +328,7 @@ class ServicesPage extends StatelessWidget { }, ).paddingSymmetrical(24.w, 0), SizedBox(height: 24.h), - "HMG Services".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0), + LocaleKeys.hmgServices.tr().toText18(weight: FontWeight.w600).paddingSymmetrical(24.w, 0), SizedBox(height: 16.h), SizedBox( height: 350.h, @@ -293,13 +359,14 @@ class ServicesPage extends StatelessWidget { ), ), SizedBox(height: 24.h), - "Personal Services".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0), + LocaleKeys.personalServices.tr().toText18(weight: FontWeight.w600).paddingSymmetrical(24.w, 0), SizedBox(height: 16.h), Row( children: [ Expanded( child: Container( - height: 170.h, + height: 183.h, + width: 183.h, padding: EdgeInsets.all(16.w), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, @@ -313,44 +380,53 @@ class ServicesPage extends StatelessWidget { spacing: 8.w, crossAxisAlignment: CrossAxisAlignment.center, children: [ - Utils.buildSvgWithAssets(icon: AppAssets.wallet, width: 30.w, height: 30.h), - "Habib Wallet".needTranslation.toText14(weight: FontWeight.w600, maxlines: 2).expanded, + Utils.buildSvgWithAssets(icon: AppAssets.wallet, width: 40.w, height: 40.h), + LocaleKeys.habibWallet.tr().toText14(weight: FontWeight.w600, maxlines: 2).expanded, Utils.buildSvgWithAssets(icon: AppAssets.arrow_forward), ], ), Spacer(), - Consumer(builder: (context, habibWalletVM, child) { - return Utils.getPaymentAmountWithSymbol2(habibWalletVM.habibWalletAmount, isExpanded: false) - .toShimmer2(isShow: habibWalletVM.isWalletAmountLoading, radius: 12.r, width: 80.w, height: 24.h); - }), + getIt.get().isAuthenticated + ? Consumer(builder: (context, habibWalletVM, child) { + return Utils.getPaymentAmountWithSymbol2(habibWalletVM.habibWalletAmount, isExpanded: false) + .toShimmer2(isShow: habibWalletVM.isWalletAmountLoading, radius: 12.r, width: 80.w, height: 24.h); + }) + : LocaleKeys.loginToViewWalletBalance.tr().toText12(fontWeight: FontWeight.w500, maxLine: 2), Spacer(), - CustomButton( - height: 40.h, - icon: AppAssets.recharge_icon, - iconSize: 16.w, + getIt.get().isAuthenticated + ? CustomButton( + height: 40.h, + icon: AppAssets.recharge_icon, + iconSize: 24.w, iconColor: AppColors.infoColor, textColor: AppColors.infoColor, - text: "Recharge".needTranslation, + text: LocaleKeys.recharge.tr(), borderWidth: 0.w, fontWeight: FontWeight.w500, borderColor: Colors.transparent, backgroundColor: Color(0xff45A2F8).withValues(alpha: 0.08), padding: EdgeInsets.all(8.w), - fontSize: 12.f, + fontSize: 14.f, onPressed: () { Navigator.of(context).push(CustomPageRoute(page: RechargeWalletPage())); }, - ), + ) + : SizedBox.shrink(), ], - ).onPress(() { - Navigator.of(context).push(CustomPageRoute(page: HabibWalletPage())); + ).onPress(() async { + if (getIt.get().isAuthenticated) { + Navigator.of(context).push(CustomPageRoute(page: HabibWalletPage())); + } else { + await getIt.get().onLoginPressed(); + } }), ), ), SizedBox(width: 16.w), Expanded( child: Container( - height: 170.h, + height: 183.h, + width: 183.h, padding: EdgeInsets.all(16.w), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, @@ -364,88 +440,96 @@ class ServicesPage extends StatelessWidget { spacing: 8.w, crossAxisAlignment: CrossAxisAlignment.center, children: [ - Utils.buildSvgWithAssets(icon: AppAssets.services_medical_file_icon, width: 30.w, height: 30.h), - "Medical Files".needTranslation.toText14(weight: FontWeight.w600, maxlines: 2).expanded, + Utils.buildSvgWithAssets(icon: AppAssets.services_medical_file_icon, width: 40.w, height: 40.h), + LocaleKeys.medicalFile.tr().toText16(weight: FontWeight.w600, maxlines: 2).expanded, Utils.buildSvgWithAssets(icon: AppAssets.arrow_forward), ], ), Spacer(), - Wrap( - spacing: -8.h, + getIt.get().isAuthenticated + ? Wrap( + spacing: -12.h, // runSpacing: 0.h, children: [ Utils.buildImgWithAssets( icon: AppAssets.babyGirlImg, - height: 28.h, - width: 28.w, + height: 32.h, + width: 32.w, border: 1, fit: BoxFit.contain, borderRadius: 50.r, ), Utils.buildImgWithAssets( icon: AppAssets.femaleImg, - height: 28.h, - width: 28.w, + height: 32.h, + width: 32.w, border: 1, borderRadius: 50.r, fit: BoxFit.contain, ), Utils.buildImgWithAssets( icon: AppAssets.maleImg, - height: 28.h, - width: 28.w, + height: 32.h, + width: 32.w, border: 1, borderRadius: 50.r, fit: BoxFit.contain, ), ], - ), + ) + : LocaleKeys.loginToViewMedicalFile.tr().toText12(fontWeight: FontWeight.w500, maxLine: 2), Spacer(), - CustomButton( - height: 40.h, + getIt.get().isAuthenticated + ? CustomButton( + height: 40.h, icon: AppAssets.add_icon, - iconSize: 16.w, + iconSize: 24.h, iconColor: AppColors.primaryRedColor, textColor: AppColors.primaryRedColor, - text: "Add Member".needTranslation, + text: LocaleKeys.addMember.tr(), borderWidth: 0.w, fontWeight: FontWeight.w500, borderColor: Colors.transparent, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.08), padding: EdgeInsets.all(8.w), - fontSize: 12.f, + fontSize: 14.f, onPressed: () { DialogService dialogService = getIt.get(); medicalFileViewModel.clearAuthValues(); dialogService.showAddFamilyFileSheet( - label: "Add Family Member".needTranslation, - message: "Please fill the below field to add a new family member to your profile".needTranslation, + label: LocaleKeys.addFamilyMember.tr(), + message: LocaleKeys.pleaseFillBelowFieldToAddNewFamilyMember.tr(), onVerificationPress: () { medicalFileViewModel.addFamilyFile(otpTypeEnum: OTPTypeEnum.sms); }); }, - ), + ) + : SizedBox.shrink(), ], - ).onPress(() { - Navigator.of(context).push( - CustomPageRoute( - page: MedicalFilePage(), - ), - ); + ).onPress(() async { + if (getIt.get().isAuthenticated) { + Navigator.of(context).push( + CustomPageRoute( + page: MedicalFilePage(), + ), + ); + } else { + await getIt.get().onLoginPressed(); + } }), ), ), ], ).paddingSymmetrical(24.w, 0), SizedBox(height: 24.h), - "Health Tools".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0), + LocaleKeys.healthTools.tr().toText18(weight: FontWeight.w600).paddingSymmetrical(24.w, 0), SizedBox(height: 16.h), GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: (isFoldable || isTablet) ? 6 : 4, // 4 icons per row - crossAxisSpacing: 12.w, + crossAxisSpacing: 21.w, mainAxisSpacing: 18.h, - childAspectRatio: 0.8, + childAspectRatio: 80.w / 94.h, ), physics: NeverScrollableScrollPhysics(), shrinkWrap: true, @@ -461,7 +545,7 @@ class ServicesPage extends StatelessWidget { }, ).paddingSymmetrical(24.w, 0), SizedBox(height: 24.h), - "Support Services".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0), + LocaleKeys.supportServices.tr().toText18(weight: FontWeight.w600).paddingSymmetrical(24.w, 0), SizedBox(height: 16.h), Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -486,7 +570,7 @@ class ServicesPage extends StatelessWidget { fit: BoxFit.contain, ), SizedBox(width: 8.w), - "Virtual Tour".needTranslation.toText12(fontWeight: FontWeight.w500) + LocaleKeys.virtualTour.tr().toText14(weight: FontWeight.w500) ], ), ), @@ -515,9 +599,19 @@ class ServicesPage extends StatelessWidget { fit: BoxFit.contain, ), SizedBox(width: 8.w), - "Car Parking".needTranslation.toText12(fontWeight: FontWeight.w500) + LocaleKeys.carParking.tr().toText14(weight: FontWeight.w500) ], - ), + ).onPress(() { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChangeNotifierProvider( + create: (_) => getIt(), + child: const ParkingPage(), + ), + ), + ); + }), ), ), ), @@ -544,7 +638,7 @@ class ServicesPage extends StatelessWidget { fit: BoxFit.contain, ), SizedBox(width: 8.w), - "Latest News".needTranslation.toText12(fontWeight: FontWeight.w500) + LocaleKeys.latestNews.tr().toText14(weight: FontWeight.w500) ], ), ), @@ -573,7 +667,7 @@ class ServicesPage extends StatelessWidget { fit: BoxFit.contain, ), SizedBox(width: 8.w), - "HMG Contact".needTranslation.toText12(fontWeight: FontWeight.w500) + LocaleKeys.hmgContact.tr().toText14(weight: FontWeight.w500) ], ), ), diff --git a/lib/presentation/hmg_services/services_view.dart b/lib/presentation/hmg_services/services_view.dart index 3f0c44e..3dd5c46 100644 --- a/lib/presentation/hmg_services/services_view.dart +++ b/lib/presentation/hmg_services/services_view.dart @@ -7,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/hmg_services_component_model.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:url_launcher/url_launcher.dart'; class ServiceGridViewItem extends StatelessWidget { final HmgServicesComponentModel hmgServiceComponentModel; @@ -16,25 +17,26 @@ class ServiceGridViewItem extends StatelessWidget { final bool isHealthToolIcon; final Function? onTap; - const ServiceGridViewItem(this.hmgServiceComponentModel, this.index, this.isHomePage, {super.key, this.isLocked = false, this.onTap, this.isHealthToolIcon = false}); + const ServiceGridViewItem( + this.hmgServiceComponentModel, this.index, this.isHomePage, + {super.key, this.isLocked = false, required this.isHealthToolIcon, this.onTap}); @override Widget build(BuildContext context) { return InkWell( - onTap: () { - hmgServiceComponentModel.route != null - ? getIt.get().pushPageRoute(hmgServiceComponentModel.route!) - : hmgServiceComponentModel.onTap != null - ? hmgServiceComponentModel.onTap!() - : null; - }, + onTap: () => hmgServiceComponentModel.route != null ? getIt.get().pushPageRoute(hmgServiceComponentModel.route!) : hmgServiceComponentModel.onTap!(), + // onTap: () => hmgServiceComponentModel.isExternalLink + // ? _openLink(hmgServiceComponentModel.route!) + // : getIt + // .get() + // .pushPageRoute(hmgServiceComponentModel.route!), child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 48.h, - width: 48.w, + width: 48.h, decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: hmgServiceComponentModel.bgColor, borderRadius: 12.r, @@ -49,7 +51,7 @@ class ServiceGridViewItem extends StatelessWidget { ), ), ), - SizedBox(height: 5.h), + SizedBox(height: 4.h), hmgServiceComponentModel.title.toText12( fontWeight: FontWeight.w500, color: AppColors.textColor, @@ -58,4 +60,14 @@ class ServiceGridViewItem extends StatelessWidget { ], )); } + + Future _openLink(String link) async { + final Uri url = Uri.parse(link); + + if (await canLaunchUrl(url)) { + await launchUrl(url, mode: LaunchMode.externalApplication); + } else { + throw "Could not launch $url"; + } + } } diff --git a/lib/presentation/home/data/landing_page_data.dart b/lib/presentation/home/data/landing_page_data.dart index c693479..c52d5e1 100644 --- a/lib/presentation/home/data/landing_page_data.dart +++ b/lib/presentation/home/data/landing_page_data.dart @@ -1,4 +1,6 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/home/data/service_card_data.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -7,8 +9,8 @@ class LandingPageData { ServiceCardData( serviceName: "emergency", icon: AppAssets.emergency_services_icon, - title: "Emergency", - subtitle: "Services", + title: LocaleKeys.emergency, + subtitle: LocaleKeys.services2, backgroundColor: AppColors.primaryRedColor, iconColor: AppColors.whiteColor, textColor: AppColors.whiteColor, @@ -17,8 +19,8 @@ class LandingPageData { ServiceCardData( serviceName: "indoor_navigation", icon: AppAssets.indoor_nav_icon, - title: "Indoor", - subtitle: "Navigation", + title: LocaleKeys.indoor, + subtitle: LocaleKeys.navigation, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -27,8 +29,8 @@ class LandingPageData { ServiceCardData( serviceName: "search_doctor", icon: AppAssets.search_doctor_icon, - title: "Search", - subtitle: "Doctor", + title: LocaleKeys.search, + subtitle: LocaleKeys.doctor, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -37,8 +39,8 @@ class LandingPageData { ServiceCardData( serviceName: "health_calculators_and_converts", icon: AppAssets.health_calculators_icon, - title: "Health", - subtitle: "Calculators", + title: LocaleKeys.health, + subtitle: LocaleKeys.calculators, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -46,9 +48,9 @@ class LandingPageData { ), ServiceCardData( serviceName: "health_converters", - icon: AppAssets.health_calculators_icon, - title: "Health", - subtitle: "Converters", + icon: AppAssets.health_converters_icon, + title: LocaleKeys.health, + subtitle: LocaleKeys.converters, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -56,9 +58,9 @@ class LandingPageData { ), ServiceCardData( serviceName: "parking_guide", - icon: AppAssets.health_calculators_icon, - title: "Parking", - subtitle: "Guide", + icon: AppAssets.car_parking_icon, + title: LocaleKeys.parking, + subtitle: LocaleKeys.guide, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -70,8 +72,8 @@ class LandingPageData { ServiceCardData( serviceName: "emergency", icon: AppAssets.emergency_services_icon, - title: "Emergency", - subtitle: "Services", + title: LocaleKeys.emergency, + subtitle: LocaleKeys.services2, backgroundColor: AppColors.primaryRedColor, iconColor: AppColors.whiteColor, textColor: AppColors.whiteColor, @@ -80,8 +82,8 @@ class LandingPageData { ServiceCardData( serviceName: "lab_results", icon: AppAssets.home_lab_result_icon, - title: "Lab", - subtitle: "Results", + title: LocaleKeys.lab, + subtitle: LocaleKeys.labSubtitle, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -90,8 +92,8 @@ class LandingPageData { ServiceCardData( serviceName: "radiology_results", icon: AppAssets.my_radiology_icon, - title: "Radiology", - subtitle: "Results", + title: LocaleKeys.radiology, + subtitle: LocaleKeys.radiologySubtitle, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -100,8 +102,8 @@ class LandingPageData { ServiceCardData( serviceName: "prescriptions", icon: AppAssets.my_prescription_icon, - title: "Prescriptions", - subtitle: "Details", + title: LocaleKeys.medicinesSubtitle, + subtitle: LocaleKeys.details, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -110,8 +112,8 @@ class LandingPageData { ServiceCardData( serviceName: "insurance_update", icon: AppAssets.insurance_update_icon, - title: "Insurance", - subtitle: "Details", + title: LocaleKeys.insurance, + subtitle: LocaleKeys.details, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -130,8 +132,8 @@ class LandingPageData { ServiceCardData( serviceName: "sick_leaves", icon: AppAssets.my_sick_leave_icon, - title: "Sick", - subtitle: "Leaves", + title: LocaleKeys.sick, + subtitle: LocaleKeys.sickSubtitle, backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -143,8 +145,8 @@ class LandingPageData { ServiceCardData( serviceName: "livecare", icon: AppAssets.small_livecare_icon, - title: "LiveCare", - subtitle: "Explore our app, View our services and offers", + title: LocaleKeys.liveCare, + subtitle: LocaleKeys.liveCareServiceDesc, largeCardIcon: AppAssets.liveCareService, backgroundColor: AppColors.successColor, iconColor: AppColors.whiteColor, @@ -161,8 +163,8 @@ class LandingPageData { ServiceCardData( serviceName: "home_health_care", icon: AppAssets.homeBottom, - title: "Home Health Care", - subtitle: "Explore our app, View our services and offers", + title: LocaleKeys.homeHealthCare, + subtitle: LocaleKeys.liveCareServiceDesc, largeCardIcon: AppAssets.homeHealthCareService, backgroundColor: AppColors.primaryRedColor, iconColor: AppColors.whiteColor, @@ -171,8 +173,8 @@ class LandingPageData { ServiceCardData( serviceName: "pharmacy", icon: AppAssets.pharmacy_icon, //359846 - title: "Pharmacy", - subtitle: "Explore our app, View our services and offers", + title: LocaleKeys.hmgPharmacy, + subtitle: LocaleKeys.liveCareServiceDesc, largeCardIcon: AppAssets.pharmacyService, backgroundColor: AppColors.pharmacyBGColor, iconColor: null, diff --git a/lib/presentation/home/landing_page.dart b/lib/presentation/home/landing_page.dart index d3a8960..a8a64fa 100644 --- a/lib/presentation/home/landing_page.dart +++ b/lib/presentation/home/landing_page.dart @@ -21,12 +21,13 @@ import 'package:hmg_patient_app_new/features/authentication/authentication_view_ import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; +import 'package:hmg_patient_app_new/features/hospital/hospital_selection_view_model.dart'; import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart'; import 'package:hmg_patient_app_new/features/insurance/insurance_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; -import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_view_model.dart'; import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/appointments/appointment_queue_page.dart'; @@ -44,12 +45,14 @@ import 'package:hmg_patient_app_new/presentation/home/widgets/large_service_card import 'package:hmg_patient_app_new/presentation/home/widgets/small_service_card.dart'; import 'package:hmg_patient_app_new/presentation/home/widgets/welcome_widget.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/medical_file_page.dart'; +import 'package:hmg_patient_app_new/presentation/notifications/notifications_list_page.dart'; import 'package:hmg_patient_app_new/presentation/profile_settings/profile_settings.dart'; import 'package:hmg_patient_app_new/presentation/rate_appointment/rate_appointment_doctor.dart'; import 'package:hmg_patient_app_new/presentation/todo_section/ancillary_procedures_details_page.dart'; import 'package:hmg_patient_app_new/presentation/todo_section/widgets/ancillary_orders_list.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; import 'package:hmg_patient_app_new/services/cache_service.dart'; +import 'package:hmg_patient_app_new/services/zoom_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -59,6 +62,8 @@ import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:hmg_patient_app_new/widgets/routes/spring_page_route_builder.dart'; import 'package:provider/provider.dart'; +import '../emergency_services/call_ambulance/widgets/HospitalBottomSheetBody.dart'; + class LandingPage extends StatefulWidget { const LandingPage({super.key}); @@ -80,9 +85,18 @@ class _LandingPageState extends State { late BookAppointmentsViewModel bookAppointmentsViewModel; late EmergencyServicesViewModel emergencyServicesViewModel; late TodoSectionViewModel todoSectionViewModel; + late NotificationsViewModel notificationsViewModel; final SwiperController _controller = SwiperController(); + final ScrollController _horizontalScrollController = ScrollController(); + + @override + void dispose() { + _horizontalScrollController.dispose(); + super.dispose(); + } + @override void initState() { authVM = context.read(); @@ -105,23 +119,27 @@ class _LandingPageState extends State { myAppointmentsViewModel.initAppointmentsViewModel(); myAppointmentsViewModel.getPatientAppointments(true, false); emergencyServicesViewModel.checkPatientERAdvanceBalance(); - myAppointmentsViewModel.getPatientAppointmentQueueDetails(); - if(!appState.isRatedVisible) { - appointmentRatingViewModel.getLastRatingAppointment(onSuccess: (response) { - if (appointmentRatingViewModel.appointmentRatedList.isNotEmpty) { - appointmentRatingViewModel.getAppointmentDetails(appointmentRatingViewModel.appointmentRatedList.last.appointmentNo!, appointmentRatingViewModel.appointmentRatedList.last.projectID!, - onSuccess: ((response) { - appointmentRatingViewModel.setClinicOrDoctor(false); - appointmentRatingViewModel.setTitle("Rate Doctor".needTranslation); - appointmentRatingViewModel.setSubTitle("How was your last visit with doctor?".needTranslation); - openLastRating(); - appState.setRatedVisible(true); - }), - ); - } - }, - ); - } + // myAppointmentsViewModel.getPatientAppointmentQueueDetails(); + notificationsViewModel.initNotificationsViewModel(); + + // Commented as per new requirement to remove rating popup from the app + + // if(!appState.isRatedVisible) { + // appointmentRatingViewModel.getLastRatingAppointment(onSuccess: (response) { + // if (appointmentRatingViewModel.appointmentRatedList.isNotEmpty) { + // appointmentRatingViewModel.getAppointmentDetails(appointmentRatingViewModel.appointmentRatedList.last.appointmentNo!, appointmentRatingViewModel.appointmentRatedList.last.projectID!, + // onSuccess: ((response) { + // appointmentRatingViewModel.setClinicOrDoctor(false); + // appointmentRatingViewModel.setTitle("Rate Doctor".needTranslation); + // appointmentRatingViewModel.setSubTitle("How was your last visit with doctor?".needTranslation); + // openLastRating(); + // appState.setRatedVisible(true); + // }), + // ); + // } + // }, + // ); + // } } }); super.initState(); @@ -135,6 +153,7 @@ class _LandingPageState extends State { immediateLiveCareViewModel = Provider.of(context, listen: false); emergencyServicesViewModel = Provider.of(context, listen: false); todoSectionViewModel = Provider.of(context, listen: false); + notificationsViewModel = Provider.of(context, listen: false); appState = getIt.get(); return PopScope( canPop: false, @@ -177,40 +196,74 @@ class _LandingPageState extends State { fontSize: 14.f, fontWeight: FontWeight.w500, borderRadius: 12.r, - padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), + padding: EdgeInsets.fromLTRB(12.h, 0, 12.h, 0), height: 40.h, ), - Row( - mainAxisSize: MainAxisSize.min, - spacing: 12.h, - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.bell, height: 18.h, width: 18.h).onPress(() { - Navigator.of(context).push( - CustomPageRoute( - page: MedicalFilePage(), - // page: LoginScreen(), - ), - ); - }), - Utils.buildSvgWithAssets(icon: AppAssets.indoor_nav_icon, height: 18.h, width: 18.h).onPress(() { - // Navigator.of(context).push( - // CustomPageRoute( - // page: MedicalFilePage(), - // // page: LoginScreen(), - // ), - // ); - }), - Utils.buildSvgWithAssets(icon: AppAssets.contact_icon, height: 18.h, width: 18.h).onPress(() { - showCommonBottomSheetWithoutHeight( - context, - title: LocaleKeys.contactUs.tr(), - child: ContactUs(), - callBackFunc: () {}, - isFullScreen: false, - ); - }), - ], - ), + Consumer(builder: (context, todoSectionVM, child) { + return Row( + mainAxisSize: MainAxisSize.min, + spacing: 18.h, + children: [ + Stack(children: [ + if (appState.isAuthenticated) + Utils.buildSvgWithAssets(icon: AppAssets.bell, height: 24.h, width: 24.h).onPress(() async { + if (appState.isAuthenticated) { + notificationsViewModel.setNotificationStatusID(2); + notificationsViewModel.getAllNotifications(); + Navigator.of(context).push( + CustomPageRoute( + page: NotificationsListPage(), + // page: LoginScreen(), + ), + ); + } else { + await authVM.onLoginPressed(); + } + }), + (appState.isAuthenticated && (int.parse(todoSectionVM.notificationsCount ?? "0") > 0)) + ? Positioned( + right: 0, + top: 0, + child: Container( + width: 8.w, + height: 8.h, + padding: EdgeInsets.all(4), + decoration: BoxDecoration( + color: AppColors.primaryRedColor, + borderRadius: BorderRadius.circular(20.r), + ), + child: Text( + "", + style: TextStyle( + color: Colors.white, + fontSize: 8.f, + ), + textAlign: TextAlign.center, + ), + ), + ) + : SizedBox.shrink(), + ]), + Utils.buildSvgWithAssets(icon: AppAssets.indoor_nav_icon, height: 24.h, width: 24.w).onPress(() { + openIndoorNavigationBottomSheet(context); + }), + Utils.buildSvgWithAssets(icon: AppAssets.contact_icon, height: 24.h, width: 24.h).onPress(() { + showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.contactUs.tr(), + child: ContactUs(), + callBackFunc: () {}, + isFullScreen: false, + ); + }), + !appState.isAuthenticated + ? Utils.buildSvgWithAssets(icon: AppAssets.changeLanguageHomePageIcon, height: 24.h, width: 24.h).onPress(() { + context.setLocale(appState.isArabic() ? Locale('en', 'US') : Locale('ar', 'SA')); + }) + : SizedBox.shrink() + ], + ); + }), ], ).paddingSymmetrical(24.h, 0.h), !appState.isAuthenticated @@ -234,24 +287,25 @@ class _LandingPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "How are you feeling today?".needTranslation.toText14(isBold: true), - "Check your symptoms with this scale".needTranslation.toText12(fontWeight: FontWeight.w500), + LocaleKeys.howAreYouFeelingToday.tr(context: context).toText14(weight: FontWeight.w600), + LocaleKeys.checkYourSymptomsWithScale.tr(context: context).toText12(fontWeight: FontWeight.w500), SizedBox(height: 14.h), CustomButton( - text: "Check your symptoms".needTranslation, + text: LocaleKeys.checkYourSymptoms.tr(context: context), onPressed: () async { context.navigateWithName(AppRoutes.userInfoSelection); }, + padding: EdgeInsetsGeometry.zero, backgroundColor: Color(0xFF2B353E), borderColor: Color(0xFF2B353E), textColor: AppColors.whiteColor, - fontSize: 14, + fontSize: 14.f, fontWeight: FontWeight.w600, - borderRadius: 12, + borderRadius: 12.r, height: 40.h, ), ], - ) + ).expanded ], ), ), @@ -264,12 +318,12 @@ class _LandingPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Appointments & Visits".toText16(isBold: true), + LocaleKeys.appointmentsAndVisits.tr(context: context).toText16(weight: FontWeight.w600), Row( children: [ - LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor), + LocaleKeys.viewAll.tr(context: context).toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500), SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), + Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 14.h), ], ), ], @@ -310,239 +364,72 @@ class _LandingPageState extends State { isFromHomePage: true, ), ).paddingSymmetrical(24.h, 0.h) - : Swiper( - itemCount: myAppointmentsVM.isMyAppointmentsLoading - ? 3 - : myAppointmentsVM.patientAppointmentsHistoryList.length < 3 - ? myAppointmentsVM.patientAppointmentsHistoryList.length - : 3, - layout: SwiperLayout.STACK, - loop: true, - itemWidth: MediaQuery.of(context).size.width - 48.h, - indicatorLayout: PageIndicatorLayout.COLOR, - axisDirection: AxisDirection.right, - controller: _controller, - itemHeight: 255.h, - pagination: SwiperPagination( - alignment: Alignment.bottomCenter, - margin: EdgeInsets.only(top: 240.h + 8 + 24), - builder: DotSwiperPaginationBuilder(color: Color(0xffD9D9D9), activeColor: AppColors.blackBgColor), - ), - itemBuilder: (BuildContext context, int index) { - return (myAppointmentsVM.isPatientHasQueueAppointment && index == 0) - ? Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 20.h, - hasShadow: false, - side: BorderSide(color: Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus), width: 2.w), - ), - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - AppCustomChipWidget( - labelText: myAppointmentsVM.currentQueueStatus == 0 ? "In Queue".needTranslation : "Your Turn".needTranslation, - backgroundColor: Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus).withValues(alpha: 0.20), - textColor: Utils.getCardBorderColor(myAppointmentsVM.currentQueueStatus), - ), - Utils.buildSvgWithAssets(icon: AppAssets.waiting_icon, width: 24.h, height: 24.h), - ], - ), - SizedBox(height: 8.h), - "Hala ${appState.getAuthenticatedUser()!.firstName}!!!".needTranslation.toText16(isBold: true), - SizedBox(height: 2.h), - "Thank you for your patience, here is your queue number." - .needTranslation - .toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), - SizedBox(height: 8.h), - myAppointmentsVM.currentPatientQueueDetails.queueNo!.toText28(isBold: true), - SizedBox(height: 6.h), - myAppointmentsVM.patientQueueDetailsList.isNotEmpty ? Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - "Serving Now: ".needTranslation.toText14(isBold: true), - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - myAppointmentsVM.patientQueueDetailsList.first.queueNo!.toText12(isBold: true), - SizedBox(width: 8.w), - AppCustomChipWidget( - deleteIcon: myAppointmentsVM.patientQueueDetailsList.first.callType == 1 ? AppAssets.call_for_vitals : AppAssets.call_for_doctor, - labelText: myAppointmentsVM.patientQueueDetailsList.first.callType == 1 ? "Call for vital signs".needTranslation : "Call for Doctor".needTranslation, - iconColor: myAppointmentsVM.patientQueueDetailsList.first.callType == 1 ? AppColors.primaryRedColor : AppColors.successColor, - textColor: myAppointmentsVM.patientQueueDetailsList.first.callType == 1 ? AppColors.primaryRedColor : AppColors.successColor, - iconSize: 14.w, - backgroundColor: myAppointmentsVM.patientQueueDetailsList.first.callType == 1 ? AppColors.primaryRedColor.withValues(alpha: 0.1) : AppColors.successColor.withValues(alpha: 0.1), - labelPadding: EdgeInsetsDirectional.only(start: 8.h, end: -2.h), - ), - ], - ), - ], - ) : SizedBox(height: 12.h), - SizedBox(height: 5.h), - CustomButton( - text: Utils.getCardButtonText(myAppointmentsVM.currentQueueStatus, myAppointmentsVM.currentPatientQueueDetails.roomNo ?? ""), - onPressed: () {}, - backgroundColor: Utils.getCardButtonColor(myAppointmentsVM.currentQueueStatus), - borderColor: Utils.getCardButtonColor(myAppointmentsVM.currentQueueStatus).withValues(alpha: 0.01), - textColor: Utils.getCardButtonTextColor(myAppointmentsVM.currentQueueStatus), - fontSize: 12.f, - fontWeight: FontWeight.w600, - borderRadius: 12.r, - padding: EdgeInsets.symmetric(horizontal: 10.w), - height: 40.h, - iconColor: AppColors.whiteColor, - iconSize: 18.h, - ), - ], - ), - ), - ).onPress(() { - Navigator.of(context).push( - CustomPageRoute( - page: AppointmentQueuePage(), - ), - ); - }) - : (immediateLiveCareVM.patientHasPendingLiveCareRequest && index == 0) - ? Column( - children: [ - SizedBox(height: 12.h), - Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 20.r, - hasShadow: true, - side: BorderSide(color: AppColors.ratingColorYellow, width: 3.h), - ), - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Immediate LiveCare Request".needTranslation.toText16(isBold: true), - SizedBox(height: 10.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - AppCustomChipWidget( - labelText: immediateLiveCareVM.patientLiveCareHistoryList[0].stringCallStatus, - backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.20), - textColor: AppColors.alertColor, - ), - SizedBox(width: 8.w), - AppCustomChipWidget( - icon: AppAssets.appointment_calendar_icon, - labelText: DateUtil.formatDateToDate( - DateUtil.convertStringToDate(immediateLiveCareVM.patientLiveCareHistoryList[0].arrivalTime), false)), - ], - ), - Utils.buildSvgWithAssets(icon: AppAssets.waiting_icon, width: 24.h, height: 24.h), - // Lottie.asset(AppAnimations.pending_loading_animation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 80.h, height: 80.h, fit: BoxFit.cover), - ], - ), - SizedBox(height: 10.h), - "Hala ${appState.getAuthenticatedUser()!.firstName}!!!".needTranslation.toText16(isBold: true), - SizedBox(height: 8.h), - "Your turn is after ${immediateLiveCareVM.patientLiveCareHistoryList[0].patCount} patients.".needTranslation.toText14(isBold: true), - SizedBox(height: 8.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Expected waiting time: ".needTranslation.toText12(isBold: true), - SizedBox(height: 7.h), - ValueListenableBuilder( - valueListenable: immediateLiveCareVM.durationNotifier, - builder: (context, duration, child) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - buildTime(duration), - ], - ); - }, - ), - ], - ), - // CustomButton( - // text: "View Details".needTranslation, - // onPressed: () async { - // Navigator.of(context).push(CustomPageRoute(page: ImmediateLiveCarePendingRequestPage())); - // }, - // backgroundColor: Color(0xffFEE9EA), - // borderColor: Color(0xffFEE9EA), - // textColor: Color(0xffED1C2B), - // fontSize: 14.f, - // fontWeight: FontWeight.w500, - // borderRadius: 12.r, - // padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), - // height: 40.h, - // ), - ], - ), - ), - ).paddingSymmetrical(0.h, 0.h).onPress(() { - Navigator.of(context).push(CustomPageRoute(page: ImmediateLiveCarePendingRequestPage())); - }), - SizedBox(height: 12.h), - ], - ) - : (todoSectionVM.patientAncillaryOrdersList.isNotEmpty && index == 1) - ? AncillaryOrderCard( - order: todoSectionVM.patientAncillaryOrdersList.first, - isLoading: false, - isOrdersList: false, - onCheckIn: () { - log("Check-in for order: ${todoSectionVM.patientAncillaryOrdersList.first.orderNo}"); - }, - onViewDetails: () { - Navigator.of(context).push( - CustomPageRoute( - page: AncillaryOrderDetailsList( - appointmentNoVida: todoSectionVM.patientAncillaryOrdersList.first.appointmentNo ?? 0, - orderNo: todoSectionVM.patientAncillaryOrdersList.first.orderNo ?? 0, - projectID: todoSectionVM.patientAncillaryOrdersList.first.projectID ?? 0, - projectName: todoSectionVM.patientAncillaryOrdersList.first.projectName ?? "", - ), - ), - ); - }, - ) - : Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, - ), - child: AppointmentCard( - patientAppointmentHistoryResponseModel: - myAppointmentsVM.patientAppointmentsHistoryList[immediateLiveCareViewModel.patientHasPendingLiveCareRequest ? --index : index], - myAppointmentsViewModel: myAppointmentsViewModel, - bookAppointmentsViewModel: bookAppointmentsViewModel, - isLoading: false, - isFromHomePage: true, - ), + : isTablet + ? SizedBox( + height: isFoldable ? 290.h : 255.h, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: 3, + shrinkWrap: true, + padding: EdgeInsets.only(left: 16.h, right: 16.h), + itemBuilder: (context, index) { + return SizedBox( + height: 255.h, + width: 250.w, + child: getIndexSwiperCard(index), ); - }, - ) + // return AnimationConfiguration.staggeredList( + // position: index, + // duration: const Duration(milliseconds: 1000), + // child: SlideAnimation( + // horizontalOffset: 100.0, + // child: FadeInAnimation( + // child: SizedBox( + // height: 255.h, + // width: 250.w, + // child: getIndexSwiperCard(index), + // ), + // ), + // ), + // ); + }, + separatorBuilder: (BuildContext cxt, int index) => SizedBox( + width: 10.w, + ), + ), + ) + : Swiper( + itemCount: myAppointmentsVM.isMyAppointmentsLoading + ? 3 + : myAppointmentsVM.patientAppointmentsHistoryList.length < 3 + ? myAppointmentsVM.patientAppointmentsHistoryList.length + : 3, + layout: SwiperLayout.STACK, + loop: true, + itemWidth: MediaQuery.of(context).size.width - 48.h, + indicatorLayout: PageIndicatorLayout.COLOR, + axisDirection: AxisDirection.right, + controller: _controller, + itemHeight: 255.h, + pagination: SwiperPagination( + alignment: Alignment.bottomCenter, + margin: EdgeInsets.only(top: 240.h + 8 + 24), + builder: DotSwiperPaginationBuilder(color: Color(0xffD9D9D9), activeColor: AppColors.blackBgColor), + ), + itemBuilder: (BuildContext context, int index) { + return getIndexSwiperCard(index); + }, + ) : Container( width: double.infinity, decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: Padding( - padding: EdgeInsets.all(12.h), + padding: EdgeInsets.all(16.h), child: Column( children: [ Utils.buildSvgWithAssets(icon: AppAssets.home_calendar_icon, width: 32.h, height: 32.h), SizedBox(height: 12.h), - "You do not have any upcoming appointment. Please book an appointment".needTranslation.toText12(isCenter: true), + LocaleKeys.noUpcomingAppointmentPleaseBook.tr(context: context).toText12(isCenter: true), SizedBox(height: 12.h), CustomButton( text: LocaleKeys.bookAppo.tr(context: context), @@ -591,7 +478,7 @@ class _LandingPageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget( - labelText: "ER Online Check-In Request", + labelText: LocaleKeys.erOnlineCheckInRequest.tr(context: context), backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.10), textColor: AppColors.primaryRedColor, ), @@ -602,7 +489,7 @@ class _LandingPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "You have ER Online Check-In Request".needTranslation.toText12(isBold: true), + LocaleKeys.youHaveEROnlineCheckInRequest.tr(context: context).toText12(isBold: true), Utils.buildSvgWithAssets( icon: AppAssets.forward_arrow_icon_small, iconColor: AppColors.blackColor, @@ -625,16 +512,16 @@ class _LandingPageState extends State { : SizedBox(height: 12.h); }, ), - + SizedBox(height: 24.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Quick Links".needTranslation.toText16(isBold: true), + LocaleKeys.quickLinks.tr(context: context).toText16(weight: FontWeight.w600), Row( children: [ - "View medical file".needTranslation.toText12(color: AppColors.primaryRedColor), + LocaleKeys.viewMedicalFile.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), + Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 14.h), ], ), ], @@ -643,92 +530,121 @@ class _LandingPageState extends State { }), SizedBox(height: 16.h), Container( - height: 121.h, + // height: 121.h, decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), child: Column( children: [ - Expanded( - child: ListView.separated( - scrollDirection: Axis.horizontal, - itemCount: LandingPageData.getLoggedInServiceCardsList.length, - shrinkWrap: true, - padding: EdgeInsets.only(left: 16.h, right: 16.h), - itemBuilder: (context, index) { - return AnimationConfiguration.staggeredList( - position: index, - duration: const Duration(milliseconds: 1000), - child: SlideAnimation( - horizontalOffset: 100.0, - child: FadeInAnimation( - child: SmallServiceCard( - icon: LandingPageData.getLoggedInServiceCardsList[index].icon, - title: LandingPageData.getLoggedInServiceCardsList[index].title, - subtitle: LandingPageData.getLoggedInServiceCardsList[index].subtitle, - iconColor: LandingPageData.getLoggedInServiceCardsList[index].iconColor!, - textColor: LandingPageData.getLoggedInServiceCardsList[index].textColor, - backgroundColor: LandingPageData.getLoggedInServiceCardsList[index].backgroundColor, - isBold: LandingPageData.getLoggedInServiceCardsList[index].isBold, - serviceName: LandingPageData.getLoggedInServiceCardsList[index].serviceName, + SizedBox( + height: 92.h + 32.h - 4.h, + child: RawScrollbar( + controller: _horizontalScrollController, + thumbVisibility: true, + radius: Radius.circular(10.0), + thumbColor: AppColors.primaryRedColor, + trackVisibility: true, + trackColor: Color(0xffD9D9D9), + trackBorderColor: Colors.transparent, + trackRadius: Radius.circular(10.0), + padding: EdgeInsets.only(top: 92.h + 32.h, left: MediaQuery.sizeOf(context).width / 2 - 35, right: MediaQuery.sizeOf(context).width / 2 - 35), + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: LandingPageData.getLoggedInServiceCardsList.length, + shrinkWrap: true, + controller: _horizontalScrollController, + padding: EdgeInsets.only(left: 16.h, right: 16.h, top: 16.h, bottom: 12.h), + itemBuilder: (context, index) { + return AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 1000), + child: SlideAnimation( + horizontalOffset: 100.0, + child: FadeInAnimation( + child: SmallServiceCard( + icon: LandingPageData.getLoggedInServiceCardsList[index].icon, + title: LandingPageData.getLoggedInServiceCardsList[index].title, + subtitle: LandingPageData.getLoggedInServiceCardsList[index].subtitle, + iconColor: LandingPageData.getLoggedInServiceCardsList[index].iconColor!, + textColor: LandingPageData.getLoggedInServiceCardsList[index].textColor, + backgroundColor: LandingPageData.getLoggedInServiceCardsList[index].backgroundColor, + isBold: LandingPageData.getLoggedInServiceCardsList[index].isBold, + serviceName: LandingPageData.getLoggedInServiceCardsList[index].serviceName, + ), ), ), - ), - ); - }, - separatorBuilder: (BuildContext cxt, int index) => 10.width, + ); + }, + separatorBuilder: (BuildContext cxt, int index) => 10.width, + ), ), ), + SizedBox(height: 16.h), ], ), ).paddingSymmetrical(24.h, 0.h), ], ) : Container( - height: 250.h, + // height: 141.h, decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), child: Column( children: [ - Expanded( - child: ListView.separated( - scrollDirection: Axis.horizontal, - itemCount: LandingPageData.getNotLoggedInServiceCardsList.length, - shrinkWrap: true, - padding: EdgeInsets.only(left: 16.h, right: 16.h), - itemBuilder: (context, index) { - return AnimationConfiguration.staggeredList( - position: index, - duration: const Duration(milliseconds: 1000), - child: SlideAnimation( - horizontalOffset: 100.0, - child: FadeInAnimation( - child: SmallServiceCard( - serviceName: LandingPageData.getNotLoggedInServiceCardsList[index].serviceName, - icon: LandingPageData.getNotLoggedInServiceCardsList[index].icon, - title: LandingPageData.getNotLoggedInServiceCardsList[index].title, - subtitle: LandingPageData.getNotLoggedInServiceCardsList[index].subtitle, - iconColor: LandingPageData.getNotLoggedInServiceCardsList[index].iconColor!, - textColor: LandingPageData.getNotLoggedInServiceCardsList[index].textColor, - backgroundColor: LandingPageData.getNotLoggedInServiceCardsList[index].backgroundColor, - isBold: LandingPageData.getNotLoggedInServiceCardsList[index].isBold, + SizedBox( + height: 92.h + 32.h - 4.h, + child: RawScrollbar( + controller: _horizontalScrollController, + thumbVisibility: true, + radius: Radius.circular(10.0), + thumbColor: AppColors.primaryRedColor, + trackVisibility: true, + trackColor: Color(0xffD9D9D9), + trackBorderColor: Colors.transparent, + trackRadius: Radius.circular(10.0), + padding: EdgeInsets.only(top: 92.h + 32.h, left: MediaQuery.sizeOf(context).width / 2 - 35, right: MediaQuery.sizeOf(context).width / 2 - 35), + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: LandingPageData.getNotLoggedInServiceCardsList.length, + shrinkWrap: true, + controller: _horizontalScrollController, + padding: EdgeInsets.only(left: 16.h, right: 16.h, top: 16.h, bottom: 12.h), + // padding: EdgeInsets.zero, + itemBuilder: (context, index) { + return AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 1000), + child: SlideAnimation( + horizontalOffset: 100.0, + child: FadeInAnimation( + child: SmallServiceCard( + serviceName: LandingPageData.getNotLoggedInServiceCardsList[index].serviceName, + icon: LandingPageData.getNotLoggedInServiceCardsList[index].icon, + title: LandingPageData.getNotLoggedInServiceCardsList[index].title, + subtitle: LandingPageData.getNotLoggedInServiceCardsList[index].subtitle, + iconColor: LandingPageData.getNotLoggedInServiceCardsList[index].iconColor!, + textColor: LandingPageData.getNotLoggedInServiceCardsList[index].textColor, + backgroundColor: LandingPageData.getNotLoggedInServiceCardsList[index].backgroundColor, + isBold: LandingPageData.getNotLoggedInServiceCardsList[index].isBold, + ), ), ), - ), - ); - }, - separatorBuilder: (BuildContext cxt, int index) => 0.width, + ); + }, + separatorBuilder: (BuildContext cxt, int index) => 0.width, + ), ), ), + SizedBox(height: 16.h), ], ), ).paddingSymmetrical(24.h, 0.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Services".toText16(isBold: true), + LocaleKeys.services2.tr(context: context).toText18(weight: FontWeight.w600), Row( children: [ - "View all services".toText12(color: AppColors.primaryRedColor), + LocaleKeys.viewAllServices.tr(context: context).toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500), SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), + Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 14.h), ], ).onPress(() { Navigator.of(context).push(CustomPageRoute(page: ServicesPage())); @@ -736,7 +652,7 @@ class _LandingPageState extends State { ], ).paddingSymmetrical(24.w, 0.h), SizedBox( - height: 340.h, + height: 431.h, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: LandingPageData.getServiceCardsList.length, @@ -749,7 +665,7 @@ class _LandingPageState extends State { child: SlideAnimation( horizontalOffset: 100.0, child: FadeInAnimation( - child: LargeServiceCard( + child: FadedLargeServiceCard( serviceCardData: LandingPageData.getServiceCardsList[index], image: LandingPageData.getServiceCardsList[index].icon, title: LandingPageData.getServiceCardsList[index].title, @@ -771,6 +687,356 @@ class _LandingPageState extends State { ); } + // Main card selector based on index and priority + Widget getIndexSwiperCard(int index) { + // Index 0: Priority cards (Queue > LiveCare > Upcoming Appointment > History) + if (index == 0) { + return _buildFirstCardSlot(); + } + // Index 1: Secondary cards based on first card type + if (index == 1) { + return _buildSecondCardSlot(); + } + // Index 2: Tertiary cards + if (index == 2) { + return _buildThirdCardSlot(); + } + return Container(); + } + + // First slot: Shows highest priority card + Widget _buildFirstCardSlot() { + if (myAppointmentsViewModel.isPatientHasQueueAppointment) { + return _buildQueueCard(); + } + + if (immediateLiveCareViewModel.patientHasPendingLiveCareRequest) { + return _buildLiveCareRequestCard(); + } + + if (myAppointmentsViewModel.patientUpcomingAppointmentsHistoryList.isNotEmpty) { + return _buildAppointmentCardWrapper( + myAppointmentsViewModel.patientUpcomingAppointmentsHistoryList.first, + ); + } + + return _buildAppointmentCardWrapper( + myAppointmentsViewModel.patientAppointmentsHistoryList[0], + ); + } + + // Second slot: Shows appointment or ancillary orders + Widget _buildSecondCardSlot() { + final hasQueueOrLiveCare = myAppointmentsViewModel.isPatientHasQueueAppointment || immediateLiveCareViewModel.patientHasPendingLiveCareRequest; + + if (hasQueueOrLiveCare) { + return _buildAppointmentCardWrapper( + myAppointmentsViewModel.patientAppointmentsHistoryList.first, + ); + } + + if (todoSectionViewModel.patientAncillaryOrdersList.isNotEmpty) { + return _buildAncillaryOrderCardWrapper( + todoSectionViewModel.patientAncillaryOrdersList.first, + ); + } + + return _buildAppointmentCardWrapper( + myAppointmentsViewModel.patientAppointmentsHistoryList[1], + ); + } + + // Third slot: Shows ancillary orders or appointment + Widget _buildThirdCardSlot() { + final hasQueueOrLiveCare = myAppointmentsViewModel.isPatientHasQueueAppointment || immediateLiveCareViewModel.patientHasPendingLiveCareRequest; + final hasAncillaryOrders = todoSectionViewModel.patientAncillaryOrdersList.isNotEmpty; + + if (hasQueueOrLiveCare && hasAncillaryOrders) { + return _buildAncillaryOrderCardWrapper( + todoSectionViewModel.patientAncillaryOrdersList.first, + ); + } + + return _buildAppointmentCardWrapper( + myAppointmentsViewModel.patientAppointmentsHistoryList[2], + ); + } + + // Queue Card Widget + Widget _buildQueueCard() { + final currentQueue = myAppointmentsViewModel.currentPatientQueueDetails; + final currentStatus = myAppointmentsViewModel.currentQueueStatus; + + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + side: BorderSide( + color: Utils.getCardBorderColor(currentStatus), + width: 2.w, + ), + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildQueueHeader(currentStatus), + SizedBox(height: 8.h), + _buildQueueGreeting(), + SizedBox(height: 2.h), + LocaleKeys.thankYouForPatience.tr().toText12( + fontWeight: FontWeight.w500, + color: AppColors.textColorLight, + ), + SizedBox(height: 8.h), + currentQueue.queueNo!.toText28(isBold: true), + SizedBox(height: 6.h), + _buildServingNowSection(), + SizedBox(height: 5.h), + _buildQueueActionButton(currentStatus, currentQueue.roomNo ?? ""), + ], + ), + ), + ).onPress(() { + Navigator.of(context).push( + CustomPageRoute(page: AppointmentQueuePage()), + ); + }); + } + + // Queue Card: Header with status chip and icon + Widget _buildQueueHeader(int currentStatus) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + AppCustomChipWidget( + labelText: currentStatus == 0 ? LocaleKeys.inQueue.tr() : LocaleKeys.yourTurn.tr(), + backgroundColor: Utils.getCardBorderColor(currentStatus).withValues(alpha: 0.20), + textColor: Utils.getCardBorderColor(currentStatus), + ), + Utils.buildSvgWithAssets( + icon: AppAssets.waiting_icon, + width: 24.h, + height: 24.h, + ), + ], + ); + } + + // Queue Card: Greeting text + Widget _buildQueueGreeting() { + return LocaleKeys.halaFirstName.tr(namedArgs: {'firstName': appState.getAuthenticatedUser()!.firstName!}).toText16(isBold: true); + } + + // Queue Card: Currently serving section + Widget _buildServingNowSection() { + if (myAppointmentsViewModel.patientQueueDetailsList.isEmpty) { + return SizedBox(height: 12.h); + } + + final servingQueue = myAppointmentsViewModel.patientQueueDetailsList.first; + final isVitalCall = servingQueue.callType == 1; + + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + "${LocaleKeys.servingNow.tr()}: ".toText14(isBold: true), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + servingQueue.queueNo!.toText12(isBold: true), + SizedBox(width: 8.w), + AppCustomChipWidget( + deleteIcon: isVitalCall ? AppAssets.call_for_vitals : AppAssets.call_for_doctor, + labelText: isVitalCall ? LocaleKeys.callForVitalSigns.tr() : LocaleKeys.callForDoctor.tr(), + iconColor: isVitalCall ? AppColors.primaryRedColor : AppColors.successColor, + textColor: isVitalCall ? AppColors.primaryRedColor : AppColors.successColor, + iconSize: 14.w, + backgroundColor: isVitalCall ? AppColors.primaryRedColor.withValues(alpha: 0.1) : AppColors.successColor.withValues(alpha: 0.1), + labelPadding: EdgeInsetsDirectional.only( + start: 8.h, + end: -2.h, + ), + ), + ], + ), + ], + ); + } + + // Queue Card: Action button + Widget _buildQueueActionButton(int currentStatus, String roomNo) { + return CustomButton( + text: Utils.getCardButtonText(currentStatus, roomNo), + onPressed: () {}, + backgroundColor: Utils.getCardButtonColor(currentStatus), + borderColor: Utils.getCardButtonColor(currentStatus).withValues(alpha: 0.01), + textColor: Utils.getCardButtonTextColor(currentStatus), + fontSize: 12.f, + fontWeight: FontWeight.w600, + borderRadius: 12.r, + padding: EdgeInsets.symmetric(horizontal: 10.w), + height: 40.h, + iconColor: AppColors.whiteColor, + iconSize: 18.h, + ); + } + + // LiveCare Request Card Widget + Widget _buildLiveCareRequestCard() { + final liveCareData = immediateLiveCareViewModel.patientLiveCareHistoryList[0]; + + return Column( + children: [ + SizedBox(height: 12.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + hasShadow: true, + side: BorderSide(color: AppColors.ratingColorYellow, width: 3.h), + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.immediateLiveCareRequest.tr(context: context).toText16(isBold: true), + SizedBox(height: 10.h), + _buildLiveCareHeader(liveCareData), + SizedBox(height: 10.h), + _buildLiveCareGreeting(), + SizedBox(height: 8.h), + _buildLiveCareQueueInfo(liveCareData.patCount), + SizedBox(height: 8.h), + _buildLiveCareWaitingTime(), + ], + ), + ), + ).paddingSymmetrical(0.h, 0.h).onPress(() { + Navigator.of(context).push( + CustomPageRoute(page: ImmediateLiveCarePendingRequestPage()), + ); + }), + SizedBox(height: 12.h), + ], + ); + } + + // LiveCare Card: Header with status and date + Widget _buildLiveCareHeader(liveCareData) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + AppCustomChipWidget( + labelText: liveCareData.stringCallStatus, + backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.20), + textColor: AppColors.alertColor, + ), + SizedBox(width: 8.w), + AppCustomChipWidget( + icon: AppAssets.appointment_calendar_icon, + labelText: DateUtil.formatDateToDate( + DateUtil.convertStringToDate(liveCareData.arrivalTime), + false, + ), + ), + ], + ), + Utils.buildSvgWithAssets( + icon: AppAssets.waiting_icon, + width: 24.h, + height: 24.h, + ), + ], + ); + } + + // LiveCare Card: Greeting + Widget _buildLiveCareGreeting() { + return LocaleKeys.halaFirstName.tr( + namedArgs: {'firstName': appState.getAuthenticatedUser()!.firstName!}, + context: context, + ).toText16(isBold: true); + } + + // LiveCare Card: Queue position info + Widget _buildLiveCareQueueInfo(int? patCount) { + return LocaleKeys.yourTurnIsAfterPatients.tr( + namedArgs: {'count': (patCount ?? 0).toString()}, + context: context, + ).toText14(isBold: true); + } + + // LiveCare Card: Waiting time counter + Widget _buildLiveCareWaitingTime() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "${LocaleKeys.waitingTime.tr()}: ".toText12(isBold: true), + SizedBox(height: 7.h), + ValueListenableBuilder( + valueListenable: immediateLiveCareViewModel.durationNotifier, + builder: (context, duration, child) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + buildTime(duration), + ], + ); + }, + ), + ], + ); + } + + // Appointment Card Wrapper (reusable) + Widget _buildAppointmentCardWrapper(appointment) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: AppointmentCard( + patientAppointmentHistoryResponseModel: appointment, + myAppointmentsViewModel: myAppointmentsViewModel, + bookAppointmentsViewModel: bookAppointmentsViewModel, + isLoading: false, + isFromHomePage: true, + ), + ); + } + + // Ancillary Order Card Wrapper (reusable) + Widget _buildAncillaryOrderCardWrapper(order) { + return AncillaryOrderCard( + order: order, + isLoading: false, + isOrdersList: false, + onCheckIn: () { + log("Check-in for order: ${order.orderNo}"); + }, + onViewDetails: () { + Navigator.of(context).push( + CustomPageRoute( + page: AncillaryOrderDetailsList( + appointmentNoVida: order.appointmentNo ?? 0, + orderNo: order.orderNo ?? 0, + projectID: order.projectID ?? 0, + projectName: order.projectName ?? "", + ), + ), + ); + }, + ); + } + void showQuickLogin(BuildContext context) { showCommonBottomSheetWithoutHeight( context, @@ -822,11 +1088,47 @@ class _LandingPageState extends State { isCloseButtonVisible: true, child: StatefulBuilder( builder: (context, setState) { - return RateAppointmentDoctor(); }, ), isFullScreen: false, ); } + + void openIndoorNavigationBottomSheet(BuildContext context) { + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.selectHospital.tr(), + context, + child: ChangeNotifierProvider( + create: (context) => HospitalSelectionBottomSheetViewModel(getIt()), + child: Consumer( + builder: (_, vm, __) => HospitalBottomSheetBody( + searchText: vm.searchController, + displayList: vm.displayList, + onFacilityClicked: (value) { + vm.setSelectedFacility(value); + vm.getDisplayList(); + }, + onHospitalClicked: (hospital) { + Navigator.pop(context); + vm.openPenguin(hospital); + }, + onHospitalSearch: (value) { + vm.searchHospitals(value ?? ""); + }, + selectedFacility: vm.selectedFacility, + hmcCount: vm.hmcCount, + hmgCount: vm.hmgCount, + ), + ), + ), + isFullScreen: false, + isCloseButtonVisible: true, + hasBottomPadding: false, + backgroundColor: AppColors.bottomSheetBgColor, + callBackFunc: () { + context.read().clearSearchText(); + }, + ); + } } diff --git a/lib/presentation/home/navigation_screen.dart b/lib/presentation/home/navigation_screen.dart index 43cc3b9..5cfc8ff 100644 --- a/lib/presentation/home/navigation_screen.dart +++ b/lib/presentation/home/navigation_screen.dart @@ -8,11 +8,8 @@ import 'package:hmg_patient_app_new/presentation/contact_us/feedback_page.dart'; import 'package:hmg_patient_app_new/presentation/hmg_services/services_page.dart'; import 'package:hmg_patient_app_new/presentation/home/landing_page.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/medical_file_page.dart'; -import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection.dart'; -import 'package:hmg_patient_app_new/presentation/todo_section/todo_page.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; import 'package:hmg_patient_app_new/widgets/bottom_navigation/bottom_navigation.dart'; -import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; class LandingNavigation extends StatefulWidget { const LandingNavigation({super.key}); @@ -34,12 +31,12 @@ class _LandingNavigationState extends State { physics: const NeverScrollableScrollPhysics(), children: [ const LandingPage(), - appState.isAuthenticated ? MedicalFilePage() : /* need add feedback page */ FeedbackPage(), + appState.isAuthenticated ? MedicalFilePage(showBackIcon: false) : /* need add feedback page */ FeedbackPage(), SizedBox(), // const ToDoPage(), // appState.isAuthenticated ? UserInfoSelectionScreen() : /* need add news page */ SizedBox(), SizedBox(), - ServicesPage(), + ServicesPage(showBackIcon: false), ], ), bottomNavigationBar: BottomNavigation( @@ -53,11 +50,7 @@ class _LandingNavigationState extends State { } if (_currentIndex == 3) { if (appState.isAuthenticated) { - Navigator.of(context).push( - CustomPageRoute( - page: UserInfoSelectionScreen(), - ), - ); + context.navigateWithName(AppRoutes.userInfoSelection); } else { Utils.openWebView( url: 'https://x.com/HMG', diff --git a/lib/presentation/home/widgets/habib_wallet_card.dart b/lib/presentation/home/widgets/habib_wallet_card.dart index b2649f9..e09b162 100644 --- a/lib/presentation/home/widgets/habib_wallet_card.dart +++ b/lib/presentation/home/widgets/habib_wallet_card.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -5,7 +6,9 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/habib_wallet/habib_wallet_page.dart'; +import 'package:hmg_patient_app_new/presentation/habib_wallet/recharge_wallet_page.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; @@ -21,14 +24,14 @@ class HabibWalletCard extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "My Balance".toText16(isBold: true), - Row( - children: [ - "View all services".toText12(color: AppColors.primaryRedColor), - SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), - ], - ), + LocaleKeys.myBalance.tr(context: context).toText16(weight: FontWeight.w600), + // Row( + // children: [ + // LocaleKeys.viewAllServices.tr(context: context).toText12(color: AppColors.primaryRedColor, weight: FontWeight.w500), + // SizedBox(width: 2.h), + // Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 14.h), + // ], + // ), ], ).paddingSymmetrical(24.h, 0.h), SizedBox(height: 16.h), @@ -45,14 +48,14 @@ class HabibWalletCard extends StatelessWidget { child: ClipRRect(borderRadius: BorderRadius.circular(24.0), child: Utils.buildSvgWithAssets(icon: AppAssets.habib_background_icon, width: 150.h, height: 150.h)), ), Padding( - padding: EdgeInsets.all(14.h), + padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Habib Wallet".toText15(isBold: true), + LocaleKeys.habibWallet.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), Container( height: 40.h, width: 40.h, @@ -92,7 +95,7 @@ class HabibWalletCard extends StatelessWidget { padding: EdgeInsets.symmetric(horizontal: 50.h), child: Row( children: [ - "View details".toText12(color: AppColors.primaryRedColor), + LocaleKeys.viewDetails.tr(context: context).toText12(color: AppColors.primaryRedColor), SizedBox(width: 2.h), Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), ], @@ -113,18 +116,20 @@ class HabibWalletCard extends StatelessWidget { child: Utils.getPaymentMethods(), ), CustomButton( + height: 40.h, icon: AppAssets.recharge_icon, - iconSize: 18.h, - text: "Recharge".needTranslation, - onPressed: () {}, + iconSize: 24.h, backgroundColor: AppColors.infoColor, - borderColor: AppColors.infoColor, textColor: AppColors.whiteColor, - fontSize: 12, - fontWeight: FontWeight.bold, - borderRadius: 12, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 35.h, + text: LocaleKeys.recharge.tr(context: context), + borderWidth: 0.w, + fontWeight: FontWeight.w500, + borderColor: Colors.transparent, + padding: EdgeInsets.fromLTRB(4, 0, 12, 0), + fontSize: 14.f, + onPressed: () { + Navigator.of(context).push(CustomPageRoute(page: RechargeWalletPage())); + }, ), ], ), @@ -132,7 +137,13 @@ class HabibWalletCard extends StatelessWidget { ), ), ]), - ).paddingSymmetrical(24.h, 0.h), + ).paddingSymmetrical(24.h, 0.h).onPress(() { + Navigator.of(context).push( + CustomPageRoute( + page: HabibWalletPage(), + ), + ); + }), ], ); } diff --git a/lib/presentation/home/widgets/large_service_card.dart b/lib/presentation/home/widgets/large_service_card.dart index 5274d5b..e25ed0b 100644 --- a/lib/presentation/home/widgets/large_service_card.dart +++ b/lib/presentation/home/widgets/large_service_card.dart @@ -55,6 +55,7 @@ class LargeServiceCard extends StatelessWidget { right: 0.0, child: Container( height: 180.h, + padding: EdgeInsets.only(bottom: 16.h, top: 16.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, customBorder: BorderRadius.only( @@ -69,7 +70,7 @@ class LargeServiceCard extends StatelessWidget { children: [ Container( height: 48.h, - width: 48.w, + width: 48.h, decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: serviceCardData.backgroundColor, borderRadius: 12.r, @@ -89,19 +90,19 @@ class LargeServiceCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - serviceCardData.title.toText14(isBold: true, color: AppColors.textColor), - SizedBox(width: 6.h), - serviceCardData.subtitle.toText14(weight: FontWeight.w500, color: AppColors.textColorLight), + serviceCardData.title.tr(context: context).toText14(isBold: true, color: AppColors.textColor), + serviceCardData.subtitle.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), ], ), ), ], - ).paddingSymmetrical(16.w, 20.h), + ).paddingSymmetrical(16.w, 0.h).expanded, CustomButton( - text: serviceCardData.isBold ? "Visit Pharmacy Online".needTranslation : LocaleKeys.bookNow.tr(context: context), + text: serviceCardData.isBold ? LocaleKeys.visitPharmacyOnline.tr(context: context) : LocaleKeys.bookNow.tr(context: context), onPressed: () { handleOnTap(); }, + padding: EdgeInsets.zero, backgroundColor: serviceCardData.isBold ? AppColors.successLightColor.withValues(alpha: 0.2) : AppColors.bgRedLightColor, borderColor: serviceCardData.isBold ? AppColors.successLightColor.withValues(alpha: 0.01) : AppColors.bgRedLightColor, textColor: serviceCardData.isBold ? AppColors.successColor : AppColors.primaryRedColor, @@ -146,3 +147,131 @@ class LargeServiceCard extends StatelessWidget { } } } + +class FadedLargeServiceCard extends StatelessWidget { + final ServiceCardData serviceCardData; + final String image; + final String icon; + final String title; + final String subtitle; + + const FadedLargeServiceCard({ + super.key, + required this.serviceCardData, + this.image = "", + this.icon = "", + this.title = "", + this.subtitle = "", + }); + + @override + Widget build(BuildContext context) { + return Container( + height: 411.h, + width: 252.w, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.transparent, borderRadius: 24.r), + child: Column( + children: [ + Stack( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(24.r), + child: Image.asset(serviceCardData.largeCardIcon, fit: BoxFit.cover, width: 520.w, height: 250.h), + ), + Positioned( + top: 0, + left: 0, + right: 0, + height: 250.h, + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24.r), + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + stops: [0.536, 1.0], // 53.6% and 100% + colors: [ + Color(0xFFF8F8F8).withValues(alpha: 0), // Transparent + Color(0xFFF8F8F8), // Solid #F8F8F8 + ], + ), + ), + ), + ), + ], + ), + SizedBox(height: 16.h), + Spacer(), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + height: 32.h, + width: 32.h, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: serviceCardData.backgroundColor, + borderRadius: 30.r, + hasShadow: false, + ), + child: Padding( + padding: EdgeInsets.all(8.h), + child: Utils.buildSvgWithAssets( + icon: serviceCardData.icon, + iconColor: serviceCardData.iconColor, + fit: BoxFit.contain, + ), + ), + ), + SizedBox(width: 12.w), + serviceCardData.title.tr(context: context).toText18(weight: FontWeight.w500, color: AppColors.textColor).expanded, + ], + ), + SizedBox(height: 10.h), + serviceCardData.subtitle.tr(context: context).toText14(weight: FontWeight.w500, color: AppColors.blackBgColor, letterSpacing: 0), + SizedBox(height: 12.h), + CustomButton( + text: serviceCardData.isBold ? "Visit Pharmacy Online".needTranslation : LocaleKeys.bookNow.tr(context: context), + onPressed: () { + handleOnTap(); + }, + padding: EdgeInsets.zero, + backgroundColor: serviceCardData.isBold ? AppColors.successLightColor.withValues(alpha: 0.2) : AppColors.blackBgColor, + borderColor: serviceCardData.isBold ? AppColors.successLightColor.withValues(alpha: 0.01) : AppColors.blackBgColor, + textColor: serviceCardData.isBold ? AppColors.successColor : AppColors.whiteColor, + fontSize: 14.f, + fontWeight: FontWeight.w500, + borderRadius: 10.r, + height: 40.h, + ), + ], + ), + ); + } + + void handleOnTap() { + switch (serviceCardData.serviceName) { + case "livecare": + { + getIt.get().onTabChanged(1); + Navigator.of(getIt.get().navigatorKey.currentContext!).push( + CustomPageRoute( + page: BookAppointmentPage(), + ), + ); + } + case "home_health_care": + { + Navigator.of(getIt().navigatorKey.currentContext!).push( + CustomPageRoute( + page: HhcProceduresPage(), + ), + ); + } + case "pharmacy": + { + Uri uri = Uri.parse(PHARMACY_REDIRECT_URL); + launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + } +} diff --git a/lib/presentation/home/widgets/small_service_card.dart b/lib/presentation/home/widgets/small_service_card.dart index 88365c6..84ef6fa 100644 --- a/lib/presentation/home/widgets/small_service_card.dart +++ b/lib/presentation/home/widgets/small_service_card.dart @@ -1,27 +1,30 @@ -import 'dart:io'; - import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:hmg_patient_app_new/core/utils/live_activty_helper_channel.dart'; -import 'package:hmg_patient_app_new/core/utils/push_notification_handler.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart'; +import 'package:hmg_patient_app_new/features/hospital/hospital_selection_view_model.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/appointments/my_doctors_page.dart'; +import 'package:hmg_patient_app_new/presentation/book_appointment/search_doctor_by_name.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/emergency_services_page.dart'; +import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculators_page.dart'; import 'package:hmg_patient_app_new/presentation/insurance/insurance_home_page.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_orders_page.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/patient_sickleaves_list_page.dart'; +import 'package:hmg_patient_app_new/presentation/parking/paking_page.dart'; import 'package:hmg_patient_app_new/presentation/prescriptions/prescriptions_list_page.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; -import 'package:live_activities/live_activities.dart'; import 'package:provider/provider.dart'; -import '../../../core/common_models/patient_queue.dart'; import '../../../core/utils/utils.dart'; import '../../../theme/colors.dart'; +import '../../emergency_services/call_ambulance/widgets/HospitalBottomSheetBody.dart'; import '../../radiology/radiology_orders_page.dart' show RadiologyOrdersPage; class SmallServiceCard extends StatelessWidget { @@ -48,25 +51,27 @@ class SmallServiceCard extends StatelessWidget { @override Widget build(BuildContext context) { - return Padding( - padding: EdgeInsets.symmetric(horizontal: 0.h, vertical: 12.h), - child: Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: backgroundColor, - borderRadius: 16, - ), - child: Padding( - padding: EdgeInsets.all(12.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Utils.buildSvgWithAssets(icon: icon, iconColor: iconColor, width: 32.h, height: 32.h), - SizedBox(height: 6.h), - title.toText11(color: textColor, isBold: isBold, isCenter: true), - subtitle.toText11(color: textColor, isBold: isBold, isCenter: true), - ], - ), - ), + return Container( + height: 92.h, + width: 92.h, + padding: EdgeInsets.all(4.0), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: backgroundColor, + borderRadius: 16, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets(icon: icon, iconColor: iconColor, width: 32.h, height: 32.h), + SizedBox(height: 6.h), + if (isFoldable || isTablet) ...[ + title.tr(context: context).toText10(color: textColor, weight: FontWeight.w500, isCenter: true, letterSpacing: -0.2, maxlines: 1), + subtitle.tr(context: context).toText10(color: textColor, weight: FontWeight.w500, isCenter: true, letterSpacing: -0.2, maxlines: 1), + ] else ...[ + title.tr(context: context).toText12(color: textColor, fontWeight: FontWeight.w500, isCenter: true, letterSpacing: -0.2, maxLine: 1), + subtitle.tr(context: context).toText12(color: textColor, fontWeight: FontWeight.w500, isCenter: true, letterSpacing: -0.2, maxLine: 1), + ] + ], ), ).onPress(() { switch (serviceName) { @@ -116,8 +121,12 @@ class SmallServiceCard extends StatelessWidget { break; case "emergency": context.read().flushData(); - context.read().getTransportationOrders(showLoader: false,); - context.read().getRRTOrders(showLoader: false,); + context.read().getTransportationOrders( + showLoader: false, + ); + context.read().getRRTOrders( + showLoader: false, + ); Navigator.of(context).push( CustomPageRoute( page: EmergencyServicesPage(), @@ -125,10 +134,83 @@ class SmallServiceCard extends StatelessWidget { ), ); break; + + case "indoor_navigation": + openIndoorNavigationBottomSheet(context); + + case "search_doctor": + Navigator.of(context).push( + CustomPageRoute( + page: SearchDoctorByName(), + ), + ); + break; + case "health_calculators_and_converts": + Navigator.of(context).push( + CustomPageRoute( + page: HealthCalculatorsPage(type: HealthCalConEnum.calculator), + ), + ); + break; + case "health_converters": + Navigator.of(context).push( + CustomPageRoute( + page: HealthCalculatorsPage(type: HealthCalConEnum.converter), + ), + ); + break; + case "parking_guide": + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChangeNotifierProvider( + create: (_) => getIt(), + child: const ParkingPage(), + ), + ), + ); + break; default: // Handle unknown service break; } }); } + + void openIndoorNavigationBottomSheet(BuildContext context) { + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.selectHospital.tr(context: context), + context, + child: ChangeNotifierProvider( + create: (context) => HospitalSelectionBottomSheetViewModel(getIt()), + child: Consumer( + builder: (_, vm, __) => HospitalBottomSheetBody( + searchText: vm.searchController, + displayList: vm.displayList, + onFacilityClicked: (value) { + vm.setSelectedFacility(value); + vm.getDisplayList(); + }, + onHospitalClicked: (hospital) { + Navigator.pop(context); + vm.openPenguin(hospital); + }, + onHospitalSearch: (value) { + vm.searchHospitals(value ?? ""); + }, + selectedFacility: vm.selectedFacility, + hmcCount: vm.hmcCount, + hmgCount: vm.hmgCount, + ), + ), + ), + isFullScreen: false, + isCloseButtonVisible: true, + hasBottomPadding: false, + backgroundColor: AppColors.bottomSheetBgColor, + callBackFunc: () { + context.read().clearSearchText(); + }, + ); + } } diff --git a/lib/presentation/home/widgets/welcome_widget.dart b/lib/presentation/home/widgets/welcome_widget.dart index 8ef0697..1bb17b5 100644 --- a/lib/presentation/home/widgets/welcome_widget.dart +++ b/lib/presentation/home/widgets/welcome_widget.dart @@ -1,7 +1,9 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; class WelcomeWidget extends StatelessWidget { @@ -31,7 +33,7 @@ class WelcomeWidget extends StatelessWidget { spacing: 4.h, mainAxisSize: MainAxisSize.min, children: [ - "Welcome".needTranslation.toText14(color: AppColors.greyTextColor, height: 1, weight: FontWeight.w500), + LocaleKeys.welcome.tr(context: context).toText14(color: AppColors.greyTextColor, height: 1, weight: FontWeight.w500), Row( spacing: 4.h, crossAxisAlignment: CrossAxisAlignment.center, diff --git a/lib/presentation/home_health_care/hhc_order_detail_page.dart b/lib/presentation/home_health_care/hhc_order_detail_page.dart index 92c93d1..7017441 100644 --- a/lib/presentation/home_health_care/hhc_order_detail_page.dart +++ b/lib/presentation/home_health_care/hhc_order_detail_page.dart @@ -10,6 +10,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -121,7 +122,7 @@ class _HhcOrderDetailPageState extends State { Row( children: [ if (!isLoading) ...[ - "Request ID:".needTranslation.toText14( + LocaleKeys.requestID.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -186,7 +187,7 @@ class _HhcOrderDetailPageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any Home Health Care orders yet.".needTranslation, + noDataText: LocaleKeys.dontHaveHHCOrders.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -199,7 +200,7 @@ class _HhcOrderDetailPageState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "HHC Orders".needTranslation, + title: LocaleKeys.hhcOrders.tr(context: context), isLeading: true, child: SingleChildScrollView( child: Column( diff --git a/lib/presentation/home_health_care/hhc_procedures_page.dart b/lib/presentation/home_health_care/hhc_procedures_page.dart index be97a88..ef5dce5 100644 --- a/lib/presentation/home_health_care/hhc_procedures_page.dart +++ b/lib/presentation/home_health_care/hhc_procedures_page.dart @@ -11,6 +11,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_services_resp_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/home_health_care/hhc_order_detail_page.dart'; import 'package:hmg_patient_app_new/presentation/home_health_care/hhc_selection_review_page.dart'; import 'package:hmg_patient_app_new/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart'; @@ -93,7 +94,7 @@ class _HhcProceduresPageState extends State { children: [ Row( children: [ - "Request ID:".needTranslation.toText14(color: AppColors.textColorLight, weight: FontWeight.w500), + LocaleKeys.requestID.tr(context: context).toText14(color: AppColors.textColorLight, weight: FontWeight.w500), SizedBox(width: 4.w), "${order.iD ?? '-'}".toText16(isBold: true), ], @@ -132,7 +133,7 @@ class _HhcProceduresPageState extends State { color: AppColors.primaryRedColor, ), SizedBox(width: 6.w), - "Requested Services".needTranslation.toText14( + LocaleKeys.requestedServices.tr().toText14( weight: FontWeight.w600, color: AppColors.blackColor, ), @@ -209,7 +210,7 @@ class _HhcProceduresPageState extends State { ), SizedBox(width: 8.w), Expanded( - child: "You have a pending order. Please wait for it to be processed.".needTranslation.toText12( + child: LocaleKeys.pendingOrderWait.tr(context: context).toText12( color: AppColors.infoBannerTextColor, fontWeight: FontWeight.w500, ), @@ -223,7 +224,7 @@ class _HhcProceduresPageState extends State { children: [ Expanded( child: CustomButton( - text: "Cancel Order".needTranslation, + text: LocaleKeys.cancelOrder.tr(context: context), onPressed: () => HhcUiSelectionHelper.showCancelConfirmationDialog(context: context, order: order), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -248,7 +249,7 @@ class _HhcProceduresPageState extends State { hasBottomPadding: false, padding: EdgeInsets.only(top: 24.h), context, - title: 'Select Services'.needTranslation, + title: LocaleKeys.selectServices.tr(context: context), isCloseButtonVisible: true, isDismissible: true, callBackFunc: () {}, @@ -257,9 +258,9 @@ class _HhcProceduresPageState extends State { child: Padding( padding: EdgeInsets.all(24.h), child: Text( - 'No services available'.needTranslation, + LocaleKeys.noServicesAvailable.tr(context: context), style: TextStyle( - fontSize: 16.h, + fontSize: 16.f, color: AppColors.greyTextColor, ), ), @@ -300,7 +301,7 @@ class _HhcProceduresPageState extends State { duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, width: 24.w, - height: 24.w, + height: 24.h, decoration: BoxDecoration( color: isSelected ? AppColors.primaryRedColor : Colors.transparent, borderRadius: BorderRadius.circular(5.r), @@ -353,7 +354,7 @@ class _HhcProceduresPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Selected Services".needTranslation.toText12( + LocaleKeys.selectedServices.tr(context: context).toText12( color: AppColors.textColorLight, fontWeight: FontWeight.w600, ), @@ -368,7 +369,7 @@ class _HhcProceduresPageState extends State { SizedBox(height: 16.h), CustomButton( borderWidth: 0, - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () { Navigator.pop(context); _proceedWithSelectedService(); @@ -398,9 +399,9 @@ class _HhcProceduresPageState extends State { bool result = await navigationServices.push( CustomPageRoute( page: MapUtilityScreen( - confirmButtonString: "Submit Request ".needTranslation, - titleString: "Select Location", - subTitleString: "Please select the location".needTranslation, + confirmButtonString: LocaleKeys.submitRequest.tr(context: context), + titleString: LocaleKeys.selectLocation.tr(context: context), + subTitleString: LocaleKeys.pleaseSelectTheLocation.tr(context: context), isGmsAvailable: appState.isGMSAvailable, ), direction: AxisDirection.down), @@ -447,7 +448,7 @@ class _HhcProceduresPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Home Health Care".needTranslation, + title: LocaleKeys.homeHealthCare.tr(context: context), history: () => Navigator.of(context).push(CustomPageRoute(page: HhcOrderDetailPage(), direction: AxisDirection.up)), bottomChild: Consumer( builder: (BuildContext context, HmgServicesViewModel hmgServicesViewModel, Widget? child) { @@ -466,7 +467,7 @@ class _HhcProceduresPageState extends State { padding: EdgeInsets.all(24.w), child: CustomButton( borderWidth: 0, - text: "Create new request".needTranslation, + text: LocaleKeys.createNewRequest.tr(context: context), onPressed: () => _buildServicesListBottomsSheet(hmgServicesViewModel.hhcServicesList), textColor: AppColors.whiteColor, borderRadius: 12.r, @@ -494,7 +495,7 @@ class _HhcProceduresPageState extends State { Center( child: Utils.getNoDataWidget( context, - noDataText: "You have no pending requests.".needTranslation, + noDataText: LocaleKeys.youHaveNoPendingRequests.tr(context: context), ), ), ], diff --git a/lib/presentation/home_health_care/hhc_selection_review_page.dart b/lib/presentation/home_health_care/hhc_selection_review_page.dart index 37410e2..ae2430a 100644 --- a/lib/presentation/home_health_care/hhc_selection_review_page.dart +++ b/lib/presentation/home_health_care/hhc_selection_review_page.dart @@ -50,7 +50,7 @@ class _HhcSelectionReviewPageState extends State { final isArabic = appState.isArabic(); return CollapsingListView( - title: "Summary".needTranslation, + title: LocaleKeys.summary.tr(context: context), bottomChild: _buildBottomButton(), child: SingleChildScrollView( padding: EdgeInsets.all(16.w), @@ -75,7 +75,7 @@ class _HhcSelectionReviewPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Selected Services".needTranslation.toText14( + LocaleKeys.selectedServices.tr(context: context).toText14( weight: FontWeight.w600, color: AppColors.textColor, letterSpacing: -0.4, @@ -86,7 +86,7 @@ class _HhcSelectionReviewPageState extends State { runSpacing: 12.w, children: widget.selectedServices.map((service) { final serviceName = isArabic ? (service.textN ?? service.text ?? '') : (service.text ?? ''); - return AppCustomChipWidget(labelText: serviceName.needTranslation); + return AppCustomChipWidget(labelText: serviceName); }).toList(), ), ], @@ -110,7 +110,7 @@ class _HhcSelectionReviewPageState extends State { if (lat == 0.0 || lng == 0.0) return SizedBox.shrink(); // Get address from geocode response - String address = "Selected Location".needTranslation; + String address = LocaleKeys.selectLocation.tr(context: context); if (geocodeResponse != null && geocodeResponse.results.isNotEmpty) { address = geocodeResponse.results.first.formattedAddress; } @@ -133,7 +133,7 @@ class _HhcSelectionReviewPageState extends State { ), child: CustomButton( borderWidth: 0, - text: "Confirm".needTranslation, + text: LocaleKeys.confirm.tr(context: context), onPressed: () => _handleConfirm(), textColor: AppColors.whiteColor, borderRadius: 12.r, @@ -155,10 +155,10 @@ class _HhcSelectionReviewPageState extends State { padding: EdgeInsets.all(16.w), child: Column( children: [ - Utils.getSuccessWidget(loadingText: "Your request has been successfully submitted.".needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)), Row( children: [ - "Here is your request #: ".needTranslation.toText14( + LocaleKeys.hereIsYourRequestNumber.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -200,7 +200,7 @@ class _HhcSelectionReviewPageState extends State { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to submit this request?".needTranslation, + loadingText: LocaleKeys.confirmSubmitRequest.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); diff --git a/lib/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart b/lib/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart index 688612c..d5310b3 100644 --- a/lib/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart +++ b/lib/presentation/home_health_care/widgets/hhc_ui_selection_helper.dart @@ -25,7 +25,7 @@ class HhcUiSelectionHelper { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to cancel this order?".needTranslation, + loadingText: LocaleKeys.cancelOrderConfirmation.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); @@ -51,7 +51,7 @@ class HhcUiSelectionHelper { padding: EdgeInsets.all(16.w), child: Column( children: [ - Utils.getSuccessWidget(loadingText: "Order has been cancelled successfully".needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.orderCancelledSuccessfully.tr(context: context)), SizedBox(height: 24.h), Row( children: [ diff --git a/lib/presentation/insurance/insurance_approval_details_page.dart b/lib/presentation/insurance/insurance_approval_details_page.dart index 415d66f..a6d8157 100644 --- a/lib/presentation/insurance/insurance_approval_details_page.dart +++ b/lib/presentation/insurance/insurance_approval_details_page.dart @@ -56,7 +56,7 @@ class InsuranceApprovalDetailsPage extends StatelessWidget { AppCustomChipWidget( icon: (!insuranceApprovalResponseModel.isLiveCareAppointment! ? AppAssets.walkin_appointment_icon : AppAssets.small_livecare_icon), iconColor: !insuranceApprovalResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor, - labelText: insuranceApprovalResponseModel.isLiveCareAppointment! ? LocaleKeys.livecare.tr(context: context) : "Walk In".needTranslation, + labelText: insuranceApprovalResponseModel.isLiveCareAppointment! ? LocaleKeys.livecare.tr(context: context) : LocaleKeys.walkin.tr(context: context), backgroundColor: (!insuranceApprovalResponseModel.isLiveCareAppointment! ? AppColors.greyColor : AppColors.successColor), textColor: (!insuranceApprovalResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor), ), @@ -137,7 +137,7 @@ class InsuranceApprovalDetailsPage extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Status:".needTranslation.toText14(isBold: true), + "${LocaleKeys.status.tr(context: context)}: ".toText14(isBold: true), insuranceApprovalResponseModel.apporvalDetails!.status!.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), ], ), diff --git a/lib/presentation/insurance/insurance_approvals_page.dart b/lib/presentation/insurance/insurance_approvals_page.dart index b70c116..52f8b1f 100644 --- a/lib/presentation/insurance/insurance_approvals_page.dart +++ b/lib/presentation/insurance/insurance_approvals_page.dart @@ -95,7 +95,7 @@ class _InsuranceApprovalsPageState extends State { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "You don't have any insurance approvals yet.".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noInsuranceApprovals.tr(context: context)); }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), ), diff --git a/lib/presentation/insurance/insurance_home_page.dart b/lib/presentation/insurance/insurance_home_page.dart index b005e42..519d830 100644 --- a/lib/presentation/insurance/insurance_home_page.dart +++ b/lib/presentation/insurance/insurance_home_page.dart @@ -46,66 +46,63 @@ class _InsuranceHomePageState extends State { Widget build(BuildContext context) { appState = getIt.get(); insuranceViewModel = Provider.of(context, listen: false); - return Scaffold( - backgroundColor: AppColors.bgScaffoldColor, - body: CollapsingListView( - title: "${LocaleKeys.insurance.tr(context: context)} ${LocaleKeys.updateInsurance.tr(context: context)}", - history: () { - insuranceViewModel.setIsInsuranceHistoryLoading(true); - insuranceViewModel.getPatientInsuranceCardHistory(); - showCommonBottomSheetWithoutHeight(context, child: InsuranceHistory(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false); - }, - child: SingleChildScrollView( - child: Consumer(builder: (context, insuranceVM, child) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - insuranceVM.isInsuranceLoading - ? LabResultItemView( - onTap: () {}, - labOrder: null, - index: 0, - isLoading: true, - ).paddingSymmetrical(24.h, 24.h) - : insuranceVM.patientInsuranceList.isNotEmpty - ? Padding( - padding: EdgeInsets.only(top: 24.h), - child: PatientInsuranceCard( - insuranceCardDetailsModel: insuranceVM.patientInsuranceList.first, - isInsuranceExpired: DateTime.now().isAfter(DateUtil.convertStringToDate(insuranceVM.patientInsuranceList.first.cardValidTo))).paddingSymmetrical(24.w, 0.h), - ) - : Padding( - padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.12), - child: Utils.getNoDataWidget( - context, - noDataText: "You don't have insurance registered with HMG.".needTranslation, - callToActionButton: CustomButton( - icon: AppAssets.update_insurance_card_icon, - iconColor: AppColors.successColor, - iconSize: 15.h, - text: "${LocaleKeys.updateInsurance.tr(context: context)} ${LocaleKeys.updateInsuranceSubtitle.tr(context: context)}", - onPressed: () { - insuranceViewModel.setIsInsuranceUpdateDetailsLoading(true); - insuranceViewModel.getPatientInsuranceDetailsForUpdate( - appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString()); - showCommonBottomSheetWithoutHeight(context, - child: PatientInsuranceCardUpdateCard(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false); - }, - backgroundColor: AppColors.bgGreenColor.withOpacity(0.20), - borderColor: AppColors.bgGreenColor.withOpacity(0.0), - textColor: AppColors.bgGreenColor, - fontSize: 14, - fontWeight: FontWeight.w500, - borderRadius: 12, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - ).paddingSymmetrical(64.h, 0.h), - ), + return CollapsingListView( + title: "${LocaleKeys.insurance.tr(context: context)} ${LocaleKeys.updateInsurance.tr(context: context)}", + history: () { + insuranceViewModel.setIsInsuranceHistoryLoading(true); + insuranceViewModel.getPatientInsuranceCardHistory(); + showCommonBottomSheetWithoutHeight(context, child: InsuranceHistory(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false); + }, + child: SingleChildScrollView( + child: Consumer(builder: (context, insuranceVM, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + insuranceVM.isInsuranceLoading + ? LabResultItemView( + onTap: () {}, + labOrder: null, + index: 0, + isLoading: true, + ).paddingSymmetrical(24.h, 24.h) + : insuranceVM.patientInsuranceList.isNotEmpty + ? Padding( + padding: EdgeInsets.only(top: 24.h), + child: PatientInsuranceCard( + insuranceCardDetailsModel: insuranceVM.patientInsuranceList.first, + isInsuranceExpired: DateTime.now().isAfter(DateUtil.convertStringToDate(insuranceVM.patientInsuranceList.first.cardValidTo))) + .paddingSymmetrical(24.w, 0.h), + ) + : Padding( + padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.12), + child: Utils.getNoDataWidget( + context, + noDataText: LocaleKeys.noInsuranceWithHMG.tr(context: context), + callToActionButton: CustomButton( + icon: AppAssets.update_insurance_card_icon, + iconColor: AppColors.successColor, + iconSize: 15.h, + text: "${LocaleKeys.updateInsurance.tr(context: context)} ${LocaleKeys.updateInsuranceSubtitle.tr(context: context)}", + onPressed: () { + insuranceViewModel.setIsInsuranceUpdateDetailsLoading(true); + insuranceViewModel.getPatientInsuranceDetailsForUpdate( + appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString()); + showCommonBottomSheetWithoutHeight(context, child: PatientInsuranceCardUpdateCard(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false); + }, + backgroundColor: AppColors.bgGreenColor.withOpacity(0.20), + borderColor: AppColors.bgGreenColor.withOpacity(0.0), + textColor: AppColors.bgGreenColor, + fontSize: 14, + fontWeight: FontWeight.w500, + borderRadius: 12, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ).paddingSymmetrical(64.h, 0.h), ), - ], - ); - }), - ), + ), + ], + ); + }), ), ); } diff --git a/lib/presentation/insurance/widgets/insurance_approval_card.dart b/lib/presentation/insurance/widgets/insurance_approval_card.dart index ee31538..588f988 100644 --- a/lib/presentation/insurance/widgets/insurance_approval_card.dart +++ b/lib/presentation/insurance/widgets/insurance_approval_card.dart @@ -54,7 +54,7 @@ class InsuranceApprovalCard extends StatelessWidget { ? "Walk In" : insuranceApprovalResponseModel.isLiveCareAppointment! ? LocaleKeys.livecare.tr(context: context) - : "Walk In".needTranslation, + : LocaleKeys.walkin.tr(context: context), backgroundColor: isLoading ? AppColors.greyColor : (!insuranceApprovalResponseModel.isLiveCareAppointment! ? AppColors.greyColor : AppColors.successColor), textColor: isLoading ? AppColors.textColor : (!insuranceApprovalResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor), ).toShimmer2(isShow: isLoading), diff --git a/lib/presentation/insurance/widgets/insurance_history.dart b/lib/presentation/insurance/widgets/insurance_history.dart index 341e234..7219a34 100644 --- a/lib/presentation/insurance/widgets/insurance_history.dart +++ b/lib/presentation/insurance/widgets/insurance_history.dart @@ -111,7 +111,7 @@ class InsuranceHistory extends StatelessWidget { ) : Utils.getNoDataWidget( context, - noDataText: "No insurance update requests found.".needTranslation, + noDataText: LocaleKeys.noInsuranceUpdateRequest.tr(context: context), // isSmallWidget: true, // width: 62, // height: 62, diff --git a/lib/presentation/insurance/widgets/insurance_update_details_card.dart b/lib/presentation/insurance/widgets/insurance_update_details_card.dart index c3bbcd7..c737732 100644 --- a/lib/presentation/insurance/widgets/insurance_update_details_card.dart +++ b/lib/presentation/insurance/widgets/insurance_update_details_card.dart @@ -90,7 +90,7 @@ class PatientInsuranceCardUpdateCard extends StatelessWidget { ], ).paddingSymmetrical(16.h, 16.h), ).paddingSymmetrical(24.h, 0.h) - : Utils.getNoDataWidget(context, noDataText: "No insurance data found...".needTranslation), + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noInsuranceDataFound.tr(context: context)), SizedBox( height: 24.h, ), diff --git a/lib/presentation/insurance/widgets/patient_insurance_card.dart b/lib/presentation/insurance/widgets/patient_insurance_card.dart index fde5811..84fdee4 100644 --- a/lib/presentation/insurance/widgets/patient_insurance_card.dart +++ b/lib/presentation/insurance/widgets/patient_insurance_card.dart @@ -50,12 +50,12 @@ class PatientInsuranceCard extends StatelessWidget { children: [ SizedBox( width: MediaQuery.of(context).size.width * 0.45, child: "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText18(isBold: true)), - "Policy: ${insuranceCardDetailsModel.insurancePolicyNo}".needTranslation.toText12(isBold: true, color: AppColors.lightGrayColor), + LocaleKeys.policyNumber.tr(namedArgs: {'number': insuranceCardDetailsModel.insurancePolicyNo ?? ''}, context: context).toText12(isBold: true, color: AppColors.lightGrayColor), ], ), AppCustomChipWidget( icon: isInsuranceExpired ? AppAssets.cancel_circle_icon : AppAssets.insurance_active_icon, - labelText: isInsuranceExpired ? "Insurance Expired".needTranslation : "Insurance Active".needTranslation, + labelText: isInsuranceExpired ? LocaleKeys.insuranceExpired.tr(context: context) : LocaleKeys.insuranceActive.tr(context: context), iconColor: isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor, textColor: isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor, iconSize: 12, @@ -78,7 +78,7 @@ class PatientInsuranceCard extends StatelessWidget { labelText: "${LocaleKeys.expiryDate.tr(context: context)} ${DateUtil.formatDateToDate(DateUtil.convertStringToDate(insuranceCardDetailsModel.cardValidTo), false)}", labelPadding: EdgeInsetsDirectional.only(start: -4.h, end: 8.h), ), - AppCustomChipWidget(labelText: "Patient Card ID: ${insuranceCardDetailsModel.patientCardID}".needTranslation), + AppCustomChipWidget(labelText: LocaleKeys.patientCardID.tr(namedArgs: {'id': insuranceCardDetailsModel.patientCardID ?? ''}, context: context)), ], ), SizedBox(height: 10.h), diff --git a/lib/presentation/lab/lab_order_by_test.dart b/lib/presentation/lab/lab_order_by_test.dart index 837f482..2e4a96b 100644 --- a/lib/presentation/lab/lab_order_by_test.dart +++ b/lib/presentation/lab/lab_order_by_test.dart @@ -44,7 +44,7 @@ class LabOrderByTest extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget( - richText: '${"Last Tested:".needTranslation} ${DateUtil.formatDateToDate(DateUtil.convertStringToDate(tests!.createdOn), false)}'.toText12(fontWeight: FontWeight.w500), + richText: '${"${LocaleKeys.lastTested.tr(context: context)}:"} ${DateUtil.formatDateToDate(DateUtil.convertStringToDate(tests!.createdOn), false)}'.toText12(fontWeight: FontWeight.w500), backgroundColor: AppColors.greyLightColor, textColor: AppColors.textColor, ), diff --git a/lib/presentation/lab/lab_orders_page.dart b/lib/presentation/lab/lab_orders_page.dart index 90651f1..006280f 100644 --- a/lib/presentation/lab/lab_orders_page.dart +++ b/lib/presentation/lab/lab_orders_page.dart @@ -1 +1 @@ -import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart'; import 'package:hmg_patient_app_new/presentation/lab/search_lab_report.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_toolbar.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/chip/custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; import 'alphabeticScroll.dart'; class LabOrdersPage extends StatefulWidget { const LabOrdersPage({super.key}); @override State createState() => _LabOrdersPageState(); } class _LabOrdersPageState extends State { late LabViewModel labProvider; late DateRangeSelectorRangeViewModel rangeViewModel; late AppState _appState; List?> labSuggestions = []; int? expandedIndex; String? selectedFilterText = ''; int activeIndex = 0; @override void initState() { scheduleMicrotask(() { labProvider.initLabProvider(); }); super.initState(); } @override Widget build(BuildContext context) { labProvider = Provider.of(context, listen: false); rangeViewModel = Provider.of(context); _appState = getIt(); return CollapsingToolbar( title: LocaleKeys.labResults.tr(), search: () async { final lavVM = Provider.of(context, listen: false); if (lavVM.isLabOrdersLoading) { return; } else { String? value = await Navigator.of(context).push( CustomPageRoute( page: SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions), fullScreenDialog: true, direction: AxisDirection.down, ), ); if (value != null) { selectedFilterText = value; lavVM.filterLabReports(value); } } }, child: Consumer( builder: (context, model, child) { return SingleChildScrollView( physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.all(24.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: CustomTabBar( activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ CustomTabBarModel(null, "By Visit".needTranslation), CustomTabBarModel(null, "By Test".needTranslation), // CustomTabBarModel(null, "Completed".needTranslation), ], onTabChange: (index) { activeIndex = index; setState(() {}); }, ), ), ], ), if (activeIndex == 0) Padding( padding: EdgeInsets.symmetric(vertical: 10.h), child: Row( children: [ CustomButton( text: LocaleKeys.byClinic.tr(context: context), onPressed: () { model.setIsSortByClinic(true); }, backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), SizedBox(width: 8.h), CustomButton( text: LocaleKeys.byHospital.tr(context: context), onPressed: () { model.setIsSortByClinic(false); }, backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ], ), ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? // By Visit - show grouped view when available model.isLabOrdersLoading ? ListView.builder( shrinkWrap: true, physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: 5, itemBuilder: (context, index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ), ) : (model.patientLabOrdersViewList.isNotEmpty ? ListView.builder( shrinkWrap: true, physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.patientLabOrdersViewList.length, itemBuilder: (context, index) { final group = model.patientLabOrdersViewList[index]; final isExpanded = expandedIndex == index; return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: AnimatedContainer( duration: Duration(milliseconds: 300), curve: Curves.easeInOut, margin: EdgeInsets.symmetric(vertical: 8.h), decoration: RoundedRectangleBorder() .toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), child: InkWell( onTap: () { setState(() { expandedIndex = isExpanded ? null : index; }); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget(labelText: "${group.length} ${'results'.needTranslation}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), SizedBox(height: 8.h), Text( model.isSortByClinic ? (group.first.clinicDescription ?? 'Unknown') : (group.first.projectName ?? 'Unknown'), style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis, ), ], ), ), AnimatedSwitcher( duration: Duration(milliseconds: 500), switchInCurve: Curves.easeIn, switchOutCurve: Curves.easeOut, transitionBuilder: (Widget child, Animation animation) { return FadeTransition( opacity: animation, child: SizeTransition( sizeFactor: animation, axisAlignment: 0.0, child: child, ), ); }, child: isExpanded ? Container( key: ValueKey(index), padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ...group.map((order) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Image.network( order.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png", width: 24.w, height: 24.h, fit: BoxFit.cover, ).circle(100), SizedBox(width: 8.h), Expanded(child: (order.doctorName ?? order.doctorNameEnglish ?? "").toString().toText14(weight: FontWeight.w500)), ], ), SizedBox(height: 8.h), Wrap( direction: Axis.horizontal, spacing: 4.h, runSpacing: 4.h, children: [ AppCustomChipWidget( labelText: ("Order No: ".needTranslation + order.orderNo!), ), AppCustomChipWidget( labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), ), AppCustomChipWidget( labelText: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), ), ], ), // Row( // children: [ // CustomButton( // text: ("Order No: ".needTranslation + order.orderNo!), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // SizedBox(width: 8.h), // CustomButton( // text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), // SizedBox(height: 8.h), // Row( // children: [ // CustomButton( // text: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), SizedBox(height: 12.h), Row( children: [ Expanded(flex: 2, child: SizedBox()), // Expanded( // flex: 1, // child: Container( // height: 40.h, // width: 40.w, // decoration: RoundedRectangleBorder().toSmoothCornerDecoration( // color: AppColors.textColor, // borderRadius: 12, // ), // child: Padding( // padding: EdgeInsets.all(12.h), // child: Transform.flip( // flipX: _appState.isArabic(), // child: Utils.buildSvgWithAssets( // icon: AppAssets.forward_arrow_icon_small, // iconColor: AppColors.whiteColor, // fit: BoxFit.contain, // ), // ), // ), // ).onPress(() { // model.currentlySelectedPatientOrder = order; // labProvider.getPatientLabResultByHospital(order); // labProvider.getPatientSpecialResult(order); // Navigator.of(context).push( // CustomPageRoute(page: LabResultByClinic(labOrder: order)), // ); // }), // ) Expanded( flex:2, child: CustomButton( icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, text: "View Results".needTranslation, onPressed: () { model.currentlySelectedPatientOrder = order; labProvider.getPatientLabResultByHospital(order); labProvider.getPatientSpecialResult(order); Navigator.of(context).push( CustomPageRoute(page: LabResultByClinic(labOrder: order)), ); }, backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, fontSize: 14, fontWeight: FontWeight.w500, borderRadius: 12, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ) ], ), SizedBox(height: 12.h), Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), SizedBox(height: 12.h), ], ); }).toList(), ], ), ) : SizedBox.shrink(), ), ], ), ), ), ), )); }, ) : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation)) : // By Test or other tabs keep existing behavior (model.isLabOrdersLoading) ? Column( children: List.generate( 5, (index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, )), ) : AlphabeticScroll( alpahbetsAvailable: model.indexedCharacterForUniqueTest, details: model.uniqueTestsList, labViewModel: model, rangeViewModel: rangeViewModel, appState: _appState, ) ], ) ); }, ), ); } Color getLabOrderStatusColor(num status) { switch (status) { case 44: return AppColors.warningColorYellow; case 45: return AppColors.warningColorYellow; case 16: return AppColors.successColor; case 17: return AppColors.successColor; default: return AppColors.greyColor; } } String getLabOrderStatusText(num status) { switch (status) { case 44: return LocaleKeys.resultsPending.tr(context: context); case 45: return LocaleKeys.resultsPending.tr(context: context); case 16: return LocaleKeys.resultsAvailable.tr(context: context); case 17: return LocaleKeys.resultsAvailable.tr(context: context); default: return ""; } } getLabSuggestions(LabViewModel model) { if (model.patientLabOrders.isEmpty) { return []; } return model.patientLabOrders.map((m) => m.testDetails).toList(); } } \ No newline at end of file +import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart'; import 'package:hmg_patient_app_new/presentation/lab/search_lab_report.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_toolbar.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/chip/custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart'; import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; import 'alphabeticScroll.dart'; class LabOrdersPage extends StatefulWidget { const LabOrdersPage({super.key}); @override State createState() => _LabOrdersPageState(); } class _LabOrdersPageState extends State { late LabViewModel labProvider; late DateRangeSelectorRangeViewModel rangeViewModel; late AppState _appState; List?> labSuggestions = []; int? expandedIndex; String? selectedFilterText = ''; int activeIndex = 0; @override void initState() { scheduleMicrotask(() { labProvider.initLabProvider(); }); super.initState(); } @override Widget build(BuildContext context) { labProvider = Provider.of(context, listen: false); rangeViewModel = Provider.of(context); _appState = getIt(); return CollapsingListView( title: LocaleKeys.labResults.tr(context: context), search: () async { final lavVM = Provider.of(context, listen: false); if (lavVM.isLabOrdersLoading) { return; } else { String? value = await Navigator.of(context).push( CustomPageRoute( page: SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions), fullScreenDialog: true, direction: AxisDirection.down, ), ); if (value != null) { selectedFilterText = value; lavVM.filterLabReports(value); } } }, child: Consumer( builder: (context, model, child) { return SingleChildScrollView( physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.all(24.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: CustomTabBar( activeTextColor: Color(0xffED1C2B), activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1), tabs: [ CustomTabBarModel(null, LocaleKeys.byVisit.tr()), CustomTabBarModel(null, LocaleKeys.byTest.tr()), // CustomTabBarModel(null, "Completed".needTranslation), ], onTabChange: (index) { activeIndex = index; setState(() {}); }, ), ), ], ), if (activeIndex == 0) Padding( padding: EdgeInsets.symmetric(vertical: 10.h), child: Row( children: [ CustomButton( text: LocaleKeys.byClinic.tr(context: context), onPressed: () { model.setIsSortByClinic(true); }, backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), SizedBox(width: 8.h), CustomButton( text: LocaleKeys.byHospital.tr(context: context), onPressed: () { model.setIsSortByClinic(false); }, backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, fontSize: 12, fontWeight: FontWeight.w500, borderRadius: 10, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ], ), ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? // By Visit - show grouped view when available model.isLabOrdersLoading ? ListView.builder( shrinkWrap: true, physics: AlwaysScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: 5, itemBuilder: (context, index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ), ) : (model.patientLabOrdersViewList.isNotEmpty ? ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.patientLabOrdersViewList.length, itemBuilder: (context, index) { final group = model.patientLabOrdersViewList[index]; final isExpanded = expandedIndex == index; return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: AnimatedContainer( duration: Duration(milliseconds: 300), curve: Curves.easeInOut, margin: EdgeInsets.symmetric(vertical: 8.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true), child: InkWell( onTap: () { setState(() { expandedIndex = isExpanded ? null : index; }); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(16.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppCustomChipWidget(labelText: "${group.length} ${LocaleKeys.results.tr(context: context)}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), SizedBox(height: 8.h), Text( model.isSortByClinic ? (group.first.clinicDescription ?? 'Unknown') : (group.first.projectName ?? 'Unknown'), style: TextStyle(fontSize: 16.h, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis, ), ], ), ), AnimatedSwitcher( duration: Duration(milliseconds: 500), switchInCurve: Curves.easeIn, switchOutCurve: Curves.easeOut, transitionBuilder: (Widget child, Animation animation) { return FadeTransition( opacity: animation, child: SizeTransition( sizeFactor: animation, axisAlignment: 0.0, child: child, ), ); }, child: isExpanded ? Container( key: ValueKey(index), padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h), child: ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemBuilder: (cxt, index) { PatientLabOrdersResponseModel order = group[index]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Image.network( order.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png", width: 24.w, height: 24.h, fit: BoxFit.cover, ).circle(100), SizedBox(width: 8.h), Expanded(child: (order.doctorName ?? order.doctorNameEnglish ?? "").toString().toText14(weight: FontWeight.w500)), ], ), SizedBox(height: 8.h), Wrap( direction: Axis.horizontal, spacing: 4.h, runSpacing: 4.h, children: [ AppCustomChipWidget( labelText: ("${LocaleKeys.orderNo.tr(context: context)}: ${order.orderNo!}"), ), AppCustomChipWidget( labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), ), AppCustomChipWidget( labelText: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), ), ], ), // Row( // children: [ // CustomButton( // text: ("Order No: ".needTranslation + order.orderNo!), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // SizedBox(width: 8.h), // CustomButton( // text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(order.orderDate ?? ""), false), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), // SizedBox(height: 8.h), // Row( // children: [ // CustomButton( // text: model.isSortByClinic ? (order.clinicDescription ?? "") : (order.projectName ?? ""), // onPressed: () {}, // backgroundColor: AppColors.greyColor, // borderColor: AppColors.greyColor, // textColor: AppColors.blackColor, // fontSize: 10, // fontWeight: FontWeight.w500, // borderRadius: 8, // padding: EdgeInsets.fromLTRB(10, 0, 10, 0), // height: 24.h, // ), // ], // ), SizedBox(height: 12.h), Row( children: [ Expanded(flex: 2, child: SizedBox()), // Expanded( // flex: 1, // child: Container( // height: 40.h, // width: 40.w, // decoration: RoundedRectangleBorder().toSmoothCornerDecoration( // color: AppColors.textColor, // borderRadius: 12, // ), // child: Padding( // padding: EdgeInsets.all(12.h), // child: Transform.flip( // flipX: _appState.isArabic(), // child: Utils.buildSvgWithAssets( // icon: AppAssets.forward_arrow_icon_small, // iconColor: AppColors.whiteColor, // fit: BoxFit.contain, // ), // ), // ), // ).onPress(() { // model.currentlySelectedPatientOrder = order; // labProvider.getPatientLabResultByHospital(order); // labProvider.getPatientSpecialResult(order); // Navigator.of(context).push( // CustomPageRoute(page: LabResultByClinic(labOrder: order)), // ); // }), // ) Expanded( flex: 2, child: CustomButton( icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, text: LocaleKeys.viewResults.tr(context: context), onPressed: () { model.currentlySelectedPatientOrder = order; labProvider.getPatientLabResultByHospital(order); labProvider.getPatientSpecialResult(order); Navigator.of(context).push( CustomPageRoute(page: LabResultByClinic(labOrder: order)), ); }, backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, fontSize: 14, fontWeight: FontWeight.w500, borderRadius: 12, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), height: 40.h, ), ) ], ), // SizedBox(height: 12.h), // Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), // SizedBox(height: 12.h), ], ).paddingOnly(top: 16, bottom: 16); }, separatorBuilder: (cxt, index) => Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h), itemCount: group.length)) : SizedBox.shrink(), ), ], ), ), ), ), )); }, ) : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noLabResults.tr(context: context))) : // By Test or other tabs keep existing behavior (model.isLabOrdersLoading) ? Column( children: List.generate( 5, (index) => LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, )), ) : AlphabeticScroll( alpahbetsAvailable: model.indexedCharacterForUniqueTest, details: model.uniqueTestsList, labViewModel: model, rangeViewModel: rangeViewModel, appState: _appState, ) ], ) ); }, ), ); } Color getLabOrderStatusColor(num status) { switch (status) { case 44: return AppColors.warningColorYellow; case 45: return AppColors.warningColorYellow; case 16: return AppColors.successColor; case 17: return AppColors.successColor; default: return AppColors.greyColor; } } String getLabOrderStatusText(num status) { switch (status) { case 44: return LocaleKeys.resultsPending.tr(context: context); case 45: return LocaleKeys.resultsPending.tr(context: context); case 16: return LocaleKeys.resultsAvailable.tr(context: context); case 17: return LocaleKeys.resultsAvailable.tr(context: context); default: return ""; } } getLabSuggestions(LabViewModel model) { if (model.patientLabOrders.isEmpty) { return []; } return model.patientLabOrders.map((m) => m.testDetails).toList(); } } \ No newline at end of file diff --git a/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart b/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart index ad4a032..50fd1f1 100644 --- a/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart +++ b/lib/presentation/lab/lab_result_via_clinic/LabResultByClinic.dart @@ -89,9 +89,9 @@ class LabResultByClinic extends StatelessWidget { hasShadow: true, ), child: CustomButton( - text: "Download report".needTranslation, + text: LocaleKeys.downloadReport.tr(context: context), onPressed: () async { - LoaderBottomSheet.showLoader(loadingText: "Generating report, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingReport.tr(context: context)); await labViewModel .getLabResultReportPDF( labOrder: labOrder, @@ -114,7 +114,7 @@ class LabResultByClinic extends StatelessWidget { } catch (ex) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation), + child: Utils.getErrorWidget(loadingText: "Cannot open file"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart b/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart index 3f05443..6caa4a5 100644 --- a/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart +++ b/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart'; import 'package:hmg_patient_app_new/features/lab/models/resp_models/lab_result.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/lab_order_result_item.dart'; import 'package:provider/provider.dart' show Selector, Provider, ReadContext; @@ -17,8 +19,7 @@ class LabResultList extends StatelessWidget { builder: (__, list, ___) { if (list.isEmpty && context.read().labSpecialResult.isEmpty) { return Utils.getNoDataWidget(context, - noDataText: "You don't have any lab results yet." - .needTranslation); + noDataText: LocaleKeys.noLabResults.tr(context: context)); } else { return ListView.builder( physics: NeverScrollableScrollPhysics(), diff --git a/lib/presentation/lab/lab_result_via_clinic/lab_order_result_item.dart b/lib/presentation/lab/lab_result_via_clinic/lab_order_result_item.dart index c6841b3..e332066 100644 --- a/lib/presentation/lab/lab_result_via_clinic/lab_order_result_item.dart +++ b/lib/presentation/lab/lab_result_via_clinic/lab_order_result_item.dart @@ -71,7 +71,7 @@ class LabOrderResultItem extends StatelessWidget { child: Visibility( visible: tests?.referanceRange != null, child: Text( - "(Reference range: ${tests?.referanceRange})".needTranslation, + "(${LocaleKeys.referenceRange.tr(context: context)}: ${tests?.referanceRange})", style: TextStyle( fontSize: 12.f, fontWeight: FontWeight.w500, diff --git a/lib/presentation/lab/lab_results/lab_result_details.dart b/lib/presentation/lab/lab_results/lab_result_details.dart index 1d54e06..29e15ee 100644 --- a/lib/presentation/lab/lab_results/lab_result_details.dart +++ b/lib/presentation/lab/lab_results/lab_result_details.dart @@ -32,7 +32,7 @@ class LabResultDetails extends StatelessWidget { @override Widget build(BuildContext context) { return CollapsingListView( - title: 'Lab Result Details'.needTranslation, + title: LocaleKeys.labResultDetails.tr(context: context), child: SingleChildScrollView( child: Column( spacing: 16.h, @@ -74,7 +74,7 @@ class LabResultDetails extends StatelessWidget { .getSeverityText( recentLabResult.calculatedResultFlag ?? "", ) - .tr() + .tr(context: context) .toText10(weight: FontWeight.w500, color: AppColors.greyTextColor), Utils.buildSvgWithAssets( icon: AppAssets.lab_result_indicator, @@ -89,7 +89,7 @@ class LabResultDetails extends StatelessWidget { ], ), SizedBox(height: 4.h), - ("Result of ${recentLabResult.verifiedOn ?? ""}".needTranslation).toText11(weight: FontWeight.w500, color: AppColors.greyTextColor), + ("${LocaleKeys.resultOf.tr(context: context)} ${recentLabResult.verifiedOn ?? ""}").toText11(weight: FontWeight.w500, color: AppColors.greyTextColor), ], ), Row( @@ -116,7 +116,7 @@ class LabResultDetails extends StatelessWidget { Visibility( visible: recentLabResult.referanceRange != null, child: Text( - "Reference range: \n${recentLabResult.referanceRange!.trim()}".needTranslation, + "${LocaleKeys.referenceRange.tr(context: context)}: \n${recentLabResult.referanceRange!.trim()}", style: TextStyle( fontSize: 12.f, fontWeight: FontWeight.w500, @@ -151,8 +151,8 @@ class LabResultDetails extends StatelessWidget { children: [ Text( labmodel.isGraphVisible - ? LocaleKeys.historyFlowchart.tr() - : LocaleKeys.history.tr(), + ? LocaleKeys.historyFlowchart.tr(context: context) + : LocaleKeys.history.tr(context: context), style: TextStyle( fontSize: 16, fontFamily: 'Poppins', @@ -181,7 +181,7 @@ class LabResultDetails extends StatelessWidget { height: 24) .onPress(() { showCommonBottomSheetWithoutHeight( - title: LocaleKeys.setTheDateRange.tr(), + title: LocaleKeys.setTheDateRange.tr(context: context), context, child: DateRangeSelector( onRangeSelected: (start, end) { @@ -261,13 +261,15 @@ class LabResultDetails extends StatelessWidget { leftLabelFormatter: (value) { value = double.parse(value.toStringAsFixed(1)); // return leftLabels(value.toStringAsFixed(2)); - if(value == labmodel.highRefrenceValue) - return leftLabels("High".needTranslation); + if (value == labmodel.highRefrenceValue) { + return leftLabels(LocaleKeys.high.tr()); + } - if(value== labmodel.lowRefenceValue) - return leftLabels("Low".needTranslation); + if (value == labmodel.lowRefenceValue) { + return leftLabels(LocaleKeys.low.tr()); + } - return SizedBox.shrink(); + return SizedBox.shrink(); // } }, graphColor:AppColors.blackColor, @@ -366,8 +368,7 @@ class LabResultDetails extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, spacing: 8.h, children: [ - "What is this result?" - .needTranslation + LocaleKeys.whatIsThisResult.tr(context: context) .toText16(weight: FontWeight.w600, color: AppColors.textColor), testDescription?.toText12( fontWeight: FontWeight.w500, color: AppColors.textColorLight) ?? diff --git a/lib/presentation/medical_file/eye_measurement_details_page.dart b/lib/presentation/medical_file/eye_measurement_details_page.dart index 0662cb1..0822609 100644 --- a/lib/presentation/medical_file/eye_measurement_details_page.dart +++ b/lib/presentation/medical_file/eye_measurement_details_page.dart @@ -96,7 +96,7 @@ class EyeMeasurementDetailsPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.leftEye.tr().needTranslation.toText14(isBold: true), + LocaleKeys.leftEye.tr().toText14(isBold: true), SizedBox(height: 16.h), getRow(LocaleKeys.sphere.tr(), '${patientAppointmentHistoryResponseModel.listHISGetGlassPrescription![0].leftEyeSpherical}', '-'), getRow(LocaleKeys.cylinder.tr(), '${patientAppointmentHistoryResponseModel.listHISGetGlassPrescription![0].leftEyeCylinder}', '-'), @@ -139,7 +139,7 @@ class EyeMeasurementDetailsPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.leftEye.tr().needTranslation.toText14(isBold: true), + LocaleKeys.leftEye.tr().toText14(isBold: true), SizedBox(height: 16.h), getRow(LocaleKeys.brand.tr(), '${patientAppointmentHistoryResponseModel.listHISGetContactLensPrescription![1].brand}', ''), getRow('B.C', '${patientAppointmentHistoryResponseModel.listHISGetContactLensPrescription![1].baseCurve}', ''), diff --git a/lib/presentation/medical_file/eye_measurements_appointments_page.dart b/lib/presentation/medical_file/eye_measurements_appointments_page.dart index 3b82ad4..d8438ba 100644 --- a/lib/presentation/medical_file/eye_measurements_appointments_page.dart +++ b/lib/presentation/medical_file/eye_measurements_appointments_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -7,6 +8,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_card.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -75,7 +77,7 @@ class EyeMeasurementsAppointmentsPage extends StatelessWidget { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "No Ophthalmology appointments found...".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noOphthalmologyAppointments.tr(context: context)); }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), ), diff --git a/lib/presentation/medical_file/medical_file_page.dart b/lib/presentation/medical_file/medical_file_page.dart index 6dde958..a8460ca 100644 --- a/lib/presentation/medical_file/medical_file_page.dart +++ b/lib/presentation/medical_file/medical_file_page.dart @@ -9,12 +9,15 @@ import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/cache_consts.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/size_config.dart'; -import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/active_prescriptions/models/active_prescriptions_response_model.dart'; +import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; @@ -31,10 +34,12 @@ import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_vie import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_view_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/active_medication/active_medication_page.dart'; import 'package:hmg_patient_app_new/presentation/allergies/allergies_list_page.dart'; import 'package:hmg_patient_app_new/presentation/appointments/my_appointments_page.dart'; import 'package:hmg_patient_app_new/presentation/appointments/my_doctors_page.dart'; import 'package:hmg_patient_app_new/presentation/appointments/widgets/ask_doctor_request_type_select.dart'; +import 'package:hmg_patient_app_new/presentation/ask_doctor/ask_doctor_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/book_appointment_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.dart'; @@ -74,11 +79,14 @@ import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:hmg_patient_app_new/widgets/shimmer/common_shimmer_widget.dart'; import 'package:provider/provider.dart'; +import '../../features/active_prescriptions/active_prescriptions_view_model.dart'; import '../prescriptions/prescription_detail_page.dart'; import 'widgets/medical_file_appointment_card.dart'; class MedicalFilePage extends StatefulWidget { - const MedicalFilePage({super.key}); + bool showBackIcon; + + MedicalFilePage({super.key, this.showBackIcon = true}); @override State createState() => _MedicalFilePageState(); @@ -97,6 +105,7 @@ class _MedicalFilePageState extends State { late MonthlyReportViewModel monthlyReportViewModel; final CacheService cacheService = GetIt.instance(); + late ActivePrescriptionsViewModel activePrescriptionsViewModel; int currentIndex = 0; @@ -156,21 +165,21 @@ class _MedicalFilePageState extends State { trailing: Row( children: [ Wrap( - spacing: -8.h, + spacing: -12.h, // runSpacing: 0.h, children: [ Utils.buildImgWithAssets( icon: AppAssets.babyGirlImg, - height: 28.h, - width: 28.w, + height: 32.h, + width: 32.w, border: 1, fit: BoxFit.contain, borderRadius: 50.r, ), Utils.buildImgWithAssets( icon: AppAssets.femaleImg, - height: 28.h, - width: 28.w, + height: 32.h, + width: 32.w, border: 1, borderRadius: 50.r, fit: BoxFit.contain, @@ -178,6 +187,7 @@ class _MedicalFilePageState extends State { Utils.buildImgWithAssets( icon: AppAssets.maleImg, height: 32.h, + width: 32.w, border: 1.5, borderRadius: 50.r, fit: BoxFit.contain, @@ -187,25 +197,26 @@ class _MedicalFilePageState extends State { SizedBox(width: 4.h), Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 22.h, width: 22.w) ], - ).withHorizontalPadding(24.w).onPress(() { + ).onPress(() { DialogService dialogService = getIt.get(); dialogService.showFamilyBottomSheetWithoutH( - label: "Family Files".needTranslation, - message: "This clinic or doctor is only available for the below eligible profiles.".needTranslation, + label: LocaleKeys.familyTitle.tr(context: context), + message: "", + isShowManageButton: true, onSwitchPress: (FamilyFileResponseModelLists profile) { medicalFileViewModel.switchFamilyFiles(responseID: profile.responseId, patientID: profile.patientId, phoneNumber: profile.mobileNumber); }, profiles: medicalFileViewModel.patientFamilyFiles); }), - isLeading: true, - leadingCallback: () { - Navigator.pushAndRemoveUntil( - navigationService.navigatorKey.currentContext!, - CustomPageRoute( - page: LandingNavigation(), - ), - (r) => false); - }, + isLeading: widget.showBackIcon, + // leadingCallback: () { + // Navigator.pushAndRemoveUntil( + // navigationService.navigatorKey.currentContext!, + // CustomPageRoute( + // page: LandingNavigation(), + // ), + // (r) => false); + // }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -241,14 +252,6 @@ class _MedicalFilePageState extends State { icon: AppAssets.file_icon, labelText: "${LocaleKeys.fileno.tr(context: context)}: ${appState.getAuthenticatedUser()!.patientId}", labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w), - onChipTap: () { - navigationService.pushPage( - page: FamilyMedicalScreen( - profiles: medicalFileViewModel.patientFamilyFiles, - onSelect: (FamilyFileResponseModelLists p1) {}, - ), - ); - }, ), AppCustomChipWidget( icon: AppAssets.checkmark_icon, @@ -271,12 +274,12 @@ class _MedicalFilePageState extends State { runSpacing: 4.h, children: [ AppCustomChipWidget( - labelText: "${appState.getAuthenticatedUser()!.age} Years Old", + labelText: LocaleKeys.ageYearsOld.tr(namedArgs: {'age': '${appState.getAuthenticatedUser()!.age}', 'yearsOld': LocaleKeys.yearsOld.tr(context: context)}, context: context), labelPadding: EdgeInsetsDirectional.only(start: 8.w, end: 8.w), ), AppCustomChipWidget( icon: AppAssets.blood_icon, - labelText: "Blood: ${appState.getUserBloodGroup.isEmpty ? "N/A" : appState.getUserBloodGroup}", + labelText: LocaleKeys.bloodGroup.tr(namedArgs: {'bloodType': appState.getUserBloodGroup.isEmpty ? "N/A" : appState.getUserBloodGroup}, context: context), iconColor: AppColors.primaryRedColor, labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w), padding: EdgeInsets.zero, @@ -284,7 +287,7 @@ class _MedicalFilePageState extends State { Consumer(builder: (context, insuranceVM, child) { return AppCustomChipWidget( icon: insuranceVM.isInsuranceExpired ? AppAssets.cancel_circle_icon : AppAssets.insurance_active_icon, - labelText: insuranceVM.isInsuranceExpired ? "Insurance Expired".needTranslation : "Insurance Active".needTranslation, + labelText: insuranceVM.isInsuranceExpired ? LocaleKeys.insuranceExpired.tr(context: context) : LocaleKeys.insuranceActive.tr(context: context), iconColor: insuranceVM.isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor, textColor: insuranceVM.isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor, iconSize: 12.w, @@ -305,55 +308,64 @@ class _MedicalFilePageState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "Vital Signs".needTranslation.toText16(weight: FontWeight.w500, letterSpacing: -0.2), - Row( - children: [ - LocaleKeys.viewAll.tr().toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), - SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), - ], - ), - ], - ).paddingSymmetrical(0.w, 0.h).onPress(() { - Navigator.of(context).push( - CustomPageRoute( - page: VitalSignPage(), - ), - ); - }), + Padding( + padding: EdgeInsets.symmetric(horizontal: 24.w), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + LocaleKeys.vitalSigns.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), + Row( + children: [ + LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + SizedBox(width: 2.h), + Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), + ], + ), + ], + ).paddingSymmetrical(0.w, 0.h).onPress(() { + Navigator.of(context).push( + CustomPageRoute( + page: VitalSignPage(), + ), + ); + }), + ), SizedBox(height: 16.h), // Make this section dynamic-height (no fixed 160.h) LayoutBuilder( builder: (context, constraints) { if (hmgServicesVM.isVitalSignLoading) { - return _buildVitalSignShimmer(); + return Padding( + padding: EdgeInsets.symmetric(horizontal: 24.w), + child: _buildVitalSignShimmer(), + ); } if (hmgServicesVM.vitalSignList.isEmpty) { - return Container( - padding: EdgeInsets.all(16.w), - width: MediaQuery.of(context).size.width, - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 12.r, - hasShadow: false, - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.call_for_vitals, width: 32.h, height: 32.h), - SizedBox(height: 12.h), - "No vital signs recorded yet".needTranslation.toText12(isCenter: true), - ], + return Padding( + padding: EdgeInsets.symmetric(horizontal: 24.w), + child: Container( + padding: EdgeInsets.all(16.w), + width: MediaQuery.of(context).size.width, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 12.r, + hasShadow: false, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets(icon: AppAssets.call_for_vitals, width: 32.h, height: 32.h), + SizedBox(height: 12.h), + LocaleKeys.noVitalSignsRecordedYet.tr(context: context).toText12(isCenter: true), + ], + ), ), ); } // The cards define their own height; measure the first rendered page once _scheduleVitalSignMeasure(); - final double hostHeight = _vitalSignMeasuredHeight ?? (160.h); + final double hostHeight = _vitalSignMeasuredHeight ?? (135.h); return SizedBox( height: hostHeight, @@ -390,9 +402,7 @@ class _MedicalFilePageState extends State { width: hmgServicesVM.vitalSignCurrentPage == index ? 24.w : 8.w, height: 8.h, decoration: BoxDecoration( - color: hmgServicesVM.vitalSignCurrentPage == index - ? AppColors.primaryRedColor - : AppColors.dividerColor, + color: hmgServicesVM.vitalSignCurrentPage == index ? AppColors.primaryRedColor : AppColors.dividerColor, borderRadius: BorderRadius.circular(4.r), ), ), @@ -400,24 +410,24 @@ class _MedicalFilePageState extends State { ), ], ], - ).paddingSymmetrical(24.w, 0.0); + ); }), SizedBox(height: 16.h), - TextInputWidget( - labelText: LocaleKeys.search.tr(context: context), - hintText: "Type any record".needTranslation, - controller: TextEditingController(), - keyboardType: TextInputType.number, - isEnable: true, - prefix: null, - autoFocus: false, - isBorderAllowed: false, - isAllowLeadingIcon: true, - padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8.h), - leadingIcon: AppAssets.search_icon, - hintColor: AppColors.textColor, - ).paddingSymmetrical(24.w, 0.0), + // TextInputWidget( + // labelText: LocaleKeys.search.tr(context: context), + // hintText: "Type any record".needTranslation, + // controller: TextEditingController(), + // keyboardType: TextInputType.number, + // isEnable: true, + // prefix: null, + // autoFocus: false, + // isBorderAllowed: false, + // isAllowLeadingIcon: true, + // padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8.h), + // leadingIcon: AppAssets.search_icon, + // hintColor: AppColors.textColor, + // ).paddingSymmetrical(24.w, 0.0), SizedBox(height: 16.h), // Using CustomExpandableList CustomExpandableList( @@ -426,23 +436,23 @@ class _MedicalFilePageState extends State { itemPadding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 14.h), items: [ ExpandableListItem( - title: "Medical Services".toText18(weight: FontWeight.w600), + title: LocaleKeys.medicalServices.tr(context: context).toText18(weight: FontWeight.w600), children: [ SizedBox(height: 10.h), getSelectedTabData(0), ], ), ExpandableListItem( - title: "Medical Reports".toText18( - weight: FontWeight.w600, - ), + title: LocaleKeys.medicalReports.tr(context: context).toText18( + weight: FontWeight.w600, + ), expandedBackgroundColor: Colors.transparent, children: [ SizedBox(height: 10.h), getSelectedTabData(2), ]), ExpandableListItem( - title: "Insurance & Payments".toText18(weight: FontWeight.w600), + title: LocaleKeys.insuranceAndPayments.tr(context: context).toText18(weight: FontWeight.w600), expandedBackgroundColor: Colors.transparent, children: [ SizedBox(height: 10.h), @@ -450,7 +460,7 @@ class _MedicalFilePageState extends State { ], ), ExpandableListItem( - title: "Tracker & Others".toText18(weight: FontWeight.w600), + title: LocaleKeys.trackerAndOthers.tr(context: context).toText18(weight: FontWeight.w600), expandedBackgroundColor: Colors.transparent, children: [ SizedBox(height: 10.h), @@ -534,7 +544,7 @@ class _MedicalFilePageState extends State { onSuccess: (dynamic respData) async { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( - title: "Pick a Date".needTranslation, + title: LocaleKeys.pickADate.tr(context: context), context, child: AppointmentCalendar(), isFullScreen: false, @@ -564,10 +574,10 @@ class _MedicalFilePageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Appointments & visits".needTranslation.toText16(weight: FontWeight.w500, letterSpacing: -0.2), + LocaleKeys.appointmentsAndVisits.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), Row( children: [ - LocaleKeys.viewAll.tr().toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), SizedBox(width: 2.h), Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), ], @@ -601,7 +611,7 @@ class _MedicalFilePageState extends State { children: [ Utils.buildSvgWithAssets(icon: AppAssets.home_calendar_icon, width: 32.h, height: 32.h), SizedBox(height: 12.h), - "You do not have any appointments. Please book an appointment".needTranslation.toText12(isCenter: true), + LocaleKeys.noUpcomingAppointmentPleaseBook.tr(context: context).toText12(isCenter: true), SizedBox(height: 12.h), CustomButton( text: LocaleKeys.bookAppo.tr(context: context), @@ -631,66 +641,66 @@ class _MedicalFilePageState extends State { scrollDirection: Axis.horizontal, shrinkWrap: true, itemCount: myAppointmentsVM.patientAppointmentsHistoryList.length, + padding: EdgeInsets.zero, itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( - position: index, - duration: const Duration(milliseconds: 500), - child: SlideAnimation( - horizontalOffset: 100.0, - child: FadeInAnimation( - child: AnimatedContainer( - duration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - child: MedicalFileAppointmentCard( - patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index], - myAppointmentsViewModel: myAppointmentsViewModel, - onRescheduleTap: () { - openDoctorScheduleCalendar(myAppointmentsVM.patientAppointmentsHistoryList[index]); - }, - onAskDoctorTap: () async { - LoaderBottomSheet.showLoader(loadingText: "Checking doctor availability...".needTranslation); - await myAppointmentsViewModel.isDoctorAvailable( - projectID: myAppointmentsVM.patientAppointmentsHistoryList[index].projectID, - doctorId: myAppointmentsVM.patientAppointmentsHistoryList[index].doctorID, - clinicId: myAppointmentsVM.patientAppointmentsHistoryList[index].clinicID, - onSuccess: (value) async { - if (value) { - await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) { + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + horizontalOffset: 100.0, + child: FadeInAnimation( + child: AnimatedContainer( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + child: MedicalFileAppointmentCard( + patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index], + myAppointmentsViewModel: myAppointmentsViewModel, + onRescheduleTap: () { + openDoctorScheduleCalendar(myAppointmentsVM.patientAppointmentsHistoryList[index]); + }, + onAskDoctorTap: () async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context)); + await myAppointmentsViewModel.isDoctorAvailable( + projectID: myAppointmentsVM.patientAppointmentsHistoryList[index].projectID, + doctorId: myAppointmentsVM.patientAppointmentsHistoryList[index].doctorID, + clinicId: myAppointmentsVM.patientAppointmentsHistoryList[index].clinicID, + onSuccess: (value) async { + if (value) { + await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + title: LocaleKeys.askDoctor.tr(context: context), + child: AskDoctorRequestTypeSelect( + askDoctorRequestTypeList: myAppointmentsViewModel.askDoctorRequestTypeList, + myAppointmentsViewModel: myAppointmentsViewModel, + patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index], + ), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + } else { LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight( - context, - title: LocaleKeys.askDoctor.tr(context: context), - child: AskDoctorRequestTypeSelect( - askDoctorRequestTypeList: myAppointmentsViewModel.askDoctorRequestTypeList, - myAppointmentsViewModel: myAppointmentsViewModel, - patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index], - ), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - }); - } else { + } + }, + onError: (_) { LoaderBottomSheet.hideLoader(); - print("Doctor is not available"); - } - }, - onError: (_) { - LoaderBottomSheet.hideLoader(); - }, - ); - }, + }, + ); + }, + ), ), ), - ), - )); + )); }, - separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 12.h), + separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 12.w), ), - ).paddingSymmetrical(0.w, 0.h); + ); }), SizedBox(height: 10.h), - "Lab & Radiology".needTranslation.toText16(weight: FontWeight.w500, letterSpacing: -0.2), + LocaleKeys.labAndRadiology.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), SizedBox(height: 16.h), Row( children: [ @@ -713,7 +723,7 @@ class _MedicalFilePageState extends State { Expanded( child: LabRadCard( icon: AppAssets.radiology_icon, - labelText: "${LocaleKeys.radiology.tr(context: context)} Results".needTranslation, + labelText: "${LocaleKeys.radiology.tr(context: context)} ${LocaleKeys.results.tr(context: context)}", // labOrderTests: ["Complete blood count", "Creatinine", "Blood Sugar", // labOrderTests: ["Chest X-ray", "Abdominal Ultrasound", "Dental X-ray"], labOrderTests: [], @@ -729,7 +739,7 @@ class _MedicalFilePageState extends State { ], ).paddingSymmetrical(0.w, 0.h), SizedBox(height: 24.h), - "Active Medications & Prescriptions".needTranslation.toText16(weight: FontWeight.w500, letterSpacing: -0.2), + LocaleKeys.activeMedicationsAndPrescriptions.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), SizedBox(height: 16.h), Consumer(builder: (context, prescriptionVM, child) { return prescriptionVM.isPrescriptionsOrdersLoading @@ -748,110 +758,110 @@ class _MedicalFilePageState extends State { physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( - position: index, - duration: const Duration(milliseconds: 500), - child: SlideAnimation( - verticalOffset: 100.0, - child: FadeInAnimation( - child: Row( - children: [ - Image.network( - prescriptionVM.patientPrescriptionOrders[index].doctorImageURL!, - width: 40.w, - height: 40.h, - fit: BoxFit.cover, - ).circle(100.r), - SizedBox(width: 16.w), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - prescriptionVM.patientPrescriptionOrders[index].doctorName!.toText16(isBold: true), - SizedBox(height: 4.h), - Wrap( - direction: Axis.horizontal, - spacing: 3.w, - runSpacing: 4.w, - children: [ - AppCustomChipWidget(labelText: prescriptionVM.patientPrescriptionOrders[index].clinicDescription!), - AppCustomChipWidget( - icon: AppAssets.doctor_calendar_icon, - labelText: DateUtil.formatDateToDate( - DateUtil.convertStringToDate(prescriptionVM.patientPrescriptionOrders[index].appointmentDate), - false, + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + verticalOffset: 100.0, + child: FadeInAnimation( + child: Row( + children: [ + Image.network( + prescriptionVM.patientPrescriptionOrders[index].doctorImageURL!, + width: 40.w, + height: 40.h, + fit: BoxFit.cover, + ).circle(100.r), + SizedBox(width: 16.w), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + prescriptionVM.patientPrescriptionOrders[index].doctorName!.toText16(isBold: true), + SizedBox(height: 4.h), + Wrap( + direction: Axis.horizontal, + spacing: 3.w, + runSpacing: 4.w, + children: [ + AppCustomChipWidget(labelText: prescriptionVM.patientPrescriptionOrders[index].clinicDescription!), + AppCustomChipWidget( + icon: AppAssets.doctor_calendar_icon, + labelText: DateUtil.formatDateToDate( + DateUtil.convertStringToDate(prescriptionVM.patientPrescriptionOrders[index].appointmentDate), + false, + ), ), - ), - ], - ), - ], + ], + ), + ], + ), ), - ), - // SizedBox(width: 40.h), - Transform.flip( - flipX: appState.isArabic(), - child: Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon_small, width: 15.w, height: 15.h, fit: BoxFit.contain, iconColor: AppColors.textColor)), - ], - ).onPress(() { - prescriptionVM.setPrescriptionsDetailsLoading(); - Navigator.of(context).push( - CustomPageRoute( - page: PrescriptionDetailPage(isFromAppointments: false, prescriptionsResponseModel: prescriptionVM.patientPrescriptionOrders[index]), - ), - ); - }), - ), - )); - }, - separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), - ), - SizedBox(height: 16.h), - const Divider(color: AppColors.dividerColor), - SizedBox(height: 16.h), - Row( - children: [ - Expanded( - child: CustomButton( - text: "All Prescriptions".needTranslation, - onPressed: () { - Navigator.of(context).push( - CustomPageRoute( - page: PrescriptionsListPage(), - ), - ); - }, - backgroundColor: AppColors.secondaryLightRedColor, - borderColor: AppColors.secondaryLightRedColor, - textColor: AppColors.primaryRedColor, - fontSize: 12.f, - fontWeight: FontWeight.w500, - borderRadius: 12.r, - height: 40.h, - icon: AppAssets.requests, - iconColor: AppColors.primaryRedColor, - iconSize: 16.w, - ), + // SizedBox(width: 40.h), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, width: 15.w, height: 15.h, fit: BoxFit.contain, iconColor: AppColors.textColor)), + ], + ).onPress(() { + prescriptionVM.setPrescriptionsDetailsLoading(); + Navigator.of(context).push( + CustomPageRoute( + page: PrescriptionDetailPage(isFromAppointments: false, prescriptionsResponseModel: prescriptionVM.patientPrescriptionOrders[index]), + ), + ); + }), + ), + )); + }, + separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), + ), + SizedBox(height: 16.h), + const Divider(color: AppColors.dividerColor), + SizedBox(height: 16.h), + Row( + children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.allPrescriptions.tr(context: context), + onPressed: () { + Navigator.of(context).push( + CustomPageRoute( + page: PrescriptionsListPage(), + ), + ); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: 12.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 40.h, + icon: AppAssets.requests, + iconColor: AppColors.primaryRedColor, + iconSize: 16.w, ), - SizedBox(width: 6.w), - Expanded( - child: CustomButton( - text: "All Medications".needTranslation, - onPressed: () {}, - backgroundColor: AppColors.secondaryLightRedColor, - borderColor: AppColors.secondaryLightRedColor, - textColor: AppColors.primaryRedColor, - fontSize: 12.f, - fontWeight: FontWeight.w500, - borderRadius: 12.h, - height: 40.h, - icon: AppAssets.all_medications_icon, - iconColor: AppColors.primaryRedColor, - iconSize: 16.h, - ), + ), + SizedBox(width: 6.w), + Expanded( + child: CustomButton( + text: LocaleKeys.allMedications.tr(context: context), + onPressed: () {}, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: 12.f, + fontWeight: FontWeight.w500, + borderRadius: 12.h, + height: 40.h, + icon: AppAssets.all_medications_icon, + iconColor: AppColors.primaryRedColor, + iconSize: 16.h, ), - ], - ), - ], + ), + ], + ), + ], ), ), ).paddingSymmetrical(0.w, 0.h) @@ -863,7 +873,7 @@ class _MedicalFilePageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any prescriptions yet.".needTranslation, + noDataText: LocaleKeys.youDontHaveAnyPrescriptionsYet.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -878,7 +888,7 @@ class _MedicalFilePageState extends State { LocaleKeys.myDoctor.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), Row( children: [ - LocaleKeys.viewAll.tr().toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), + LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), SizedBox(width: 2.w), Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), ], @@ -918,7 +928,7 @@ class _MedicalFilePageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any completed visits yet".needTranslation, + noDataText: LocaleKeys.youDontHaveAnyCompletedVisitsYet.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -932,65 +942,65 @@ class _MedicalFilePageState extends State { shrinkWrap: true, itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( - position: index, - duration: const Duration(milliseconds: 1000), - child: SlideAnimation( - horizontalOffset: 100.0, - child: FadeInAnimation( - child: SizedBox( - // width: 80.w, - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Image.network( - myAppointmentsVM.patientMyDoctorsList[index].doctorImageURL!, - width: 64.w, - height: 64.h, - fit: BoxFit.cover, - ).circle(100).toShimmer2(isShow: false, radius: 50.r), - SizedBox(height: 8.h), - Expanded( - child: (myAppointmentsVM.patientMyDoctorsList[index].doctorName) - .toString() - .toText12(fontWeight: FontWeight.w500, isCenter: true, maxLine: 2) - .toShimmer2(isShow: false), - ), - ], - ), - ).onPress(() async { - bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel( - clinicID: myAppointmentsVM.patientMyDoctorsList[index].clinicID, - projectID: myAppointmentsVM.patientMyDoctorsList[index].projectID, - doctorID: myAppointmentsVM.patientMyDoctorsList[index].doctorID, - )); - LoaderBottomSheet.showLoader(); - await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) { - LoaderBottomSheet.hideLoader(); - Navigator.of(context).push( - CustomPageRoute( - page: DoctorProfilePage(), - ), - ); - }, onError: (err) { - LoaderBottomSheet.hideLoader(); - showCommonBottomSheetWithoutHeight( - context, - child: Utils.getErrorWidget(loadingText: err), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, - ); - }); - }), - ), - )); + position: index, + duration: const Duration(milliseconds: 1000), + child: SlideAnimation( + horizontalOffset: 100.0, + child: FadeInAnimation( + child: SizedBox( + // width: 80.w, + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + myAppointmentsVM.patientMyDoctorsList[index].doctorImageURL!, + width: 64.w, + height: 64.h, + fit: BoxFit.cover, + ).circle(100).toShimmer2(isShow: false, radius: 50.r), + SizedBox(height: 8.h), + Expanded( + child: (myAppointmentsVM.patientMyDoctorsList[index].doctorName) + .toString() + .toText12(fontWeight: FontWeight.w500, isCenter: true, maxLine: 2) + .toShimmer2(isShow: false), + ), + ], + ), + ).onPress(() async { + bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel( + clinicID: myAppointmentsVM.patientMyDoctorsList[index].clinicID, + projectID: myAppointmentsVM.patientMyDoctorsList[index].projectID, + doctorID: myAppointmentsVM.patientMyDoctorsList[index].doctorID, + )); + LoaderBottomSheet.showLoader(); + await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) { + LoaderBottomSheet.hideLoader(); + Navigator.of(context).push( + CustomPageRoute( + page: DoctorProfilePage(), + ), + ); + }, onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + }), + ), + )); }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h), ), ).paddingSymmetrical(0.w, 0); }), SizedBox(height: 24.h), - "Others".needTranslation.toText16(weight: FontWeight.w500, letterSpacing: -0.2), + LocaleKeys.others.tr(context: context).toText16(weight: FontWeight.w500, letterSpacing: -0.2), SizedBox(height: 16.h), GridView( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( @@ -1004,7 +1014,7 @@ class _MedicalFilePageState extends State { shrinkWrap: true, children: [ MedicalFileCard( - label: "Eye Test Results".needTranslation, + label: LocaleKeys.eyeMeasurements.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.eye_result_icon, @@ -1021,7 +1031,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "Allergy Info".needTranslation, + label: "Allergy Information".needTranslation, textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.allergy_info_icon, @@ -1036,7 +1046,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "Vaccine Info".needTranslation, + label: "Vaccine Information".needTranslation, textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.vaccine_info_icon, @@ -1081,7 +1091,7 @@ class _MedicalFilePageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have insurance registered with HMG.".needTranslation, + noDataText: LocaleKeys.noInsuranceWithHMG.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -1121,7 +1131,7 @@ class _MedicalFilePageState extends State { shrinkWrap: true, children: [ MedicalFileCard( - label: "Update Insurance".needTranslation, + label: LocaleKeys.updateInsuranceInfo.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.update_insurance_icon, @@ -1145,7 +1155,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "My Invoices List".needTranslation, + label: LocaleKeys.myInvoicesList.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.invoices_list_icon, @@ -1159,7 +1169,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "Ancillary Orders List".needTranslation, + label: LocaleKeys.ancillaryOrdersList.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.ancillary_orders_list_icon, @@ -1200,7 +1210,7 @@ class _MedicalFilePageState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any sick leaves yet.".needTranslation, + noDataText: LocaleKeys.youDontHaveAnySickLeavesYet.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -1235,7 +1245,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "Medical Reports".needTranslation, + label: LocaleKeys.medicalReports.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.medical_reports_icon, @@ -1251,7 +1261,7 @@ class _MedicalFilePageState extends State { ); }), MedicalFileCard( - label: "Sick Leave Report".needTranslation, + label: LocaleKeys.sickLeaveReport.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.sick_leave_report_icon, @@ -1276,7 +1286,7 @@ class _MedicalFilePageState extends State { children: [ Row( children: [ - "Health Trackers".needTranslation.toText16(weight: FontWeight.w500, color: AppColors.textColor), + LocaleKeys.healthTrackers.tr(context: context).toText16(weight: FontWeight.w500, color: AppColors.textColor), ], ), SizedBox(height: 16.h), @@ -1292,35 +1302,35 @@ class _MedicalFilePageState extends State { shrinkWrap: true, children: [ MedicalFileCard( - label: "Blood Sugar".needTranslation, + label: LocaleKeys.bloodSugar.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.blood_sugar_icon, isLargeText: true, iconSize: 36.w, - ).onPress(() {}), + ).onPress(() => context.navigateWithName(AppRoutes.healthTrackerDetailPage, arguments: HealthTrackerTypeEnum.bloodSugar)), MedicalFileCard( - label: "Blood Pressure".needTranslation, + label: LocaleKeys.bloodPressure.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.lab_result_icon, isLargeText: true, iconSize: 36.w, - ).onPress(() {}), + ).onPress(() => context.navigateWithName(AppRoutes.healthTrackerDetailPage, arguments: HealthTrackerTypeEnum.bloodPressure)), MedicalFileCard( - label: "Weight Tracker".needTranslation, + label: LocaleKeys.weightTracker.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.weight_tracker_icon, isLargeText: true, iconSize: 36.w, - ).onPress(() {}), + ).onPress(() => context.navigateWithName(AppRoutes.healthTrackerDetailPage, arguments: HealthTrackerTypeEnum.weightTracker)), ], ).paddingSymmetrical(0.w, 0.0), SizedBox(height: 16.h), Row( children: [ - "Others".needTranslation.toText16(weight: FontWeight.w500, color: AppColors.textColor), + LocaleKeys.others.tr(context: context).toText16(weight: FontWeight.w500, color: AppColors.textColor), ], ), SizedBox(height: 16.h), @@ -1336,21 +1346,28 @@ class _MedicalFilePageState extends State { shrinkWrap: true, children: [ MedicalFileCard( - label: "Ask Your Doctor".needTranslation, + label: LocaleKeys.askYourDoctor.tr(context: context), textColor: AppColors.blackColor, backgroundColor: AppColors.whiteColor, svgIcon: AppAssets.ask_doctor_medical_file_icon, isLargeText: true, iconSize: 36.w, - ).onPress(() {}), - MedicalFileCard( - label: "Internet Pairing".needTranslation, - textColor: AppColors.blackColor, - backgroundColor: AppColors.whiteColor, - svgIcon: AppAssets.internet_pairing_icon, - isLargeText: true, - iconSize: 36.w, - ).onPress(() {}), + ).onPress(() { + getIt.get().initAskDoctorViewModel(); + Navigator.of(context).push( + CustomPageRoute( + page: AskDoctorPage(), + ), + ); + }), + // MedicalFileCard( + // label: LocaleKeys.internetPairing.tr(context: context), + // textColor: AppColors.blackColor, + // backgroundColor: AppColors.whiteColor, + // svgIcon: AppAssets.internet_pairing_icon, + // isLargeText: true, + // iconSize: 36.w, + // ).onPress(() {}), ], ).paddingSymmetrical(0.w, 0.0), SizedBox(height: 24.h), @@ -1394,23 +1411,23 @@ class _MedicalFilePageState extends State { ).toShimmer(), SizedBox(height: 16.h), // Label shimmer - Container( - width: 70.w, - height: 12.h, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(4.r), - ), - ).toShimmer(), - SizedBox(height: 8.h), + // Container( + // width: 70.w, + // height: 12.h, + // decoration: BoxDecoration( + // borderRadius: BorderRadius.circular(4.r), + // ), + // ).toShimmer(), + // SizedBox(height: 8.h), // Value shimmer (larger) - Container( - width: 60.w, - height: 32.h, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(4.r), - ), - ).toShimmer(), - SizedBox(height: 12.h), + // Container( + // width: 60.w, + // height: 32.h, + // decoration: BoxDecoration( + // borderRadius: BorderRadius.circular(4.r), + // ), + // ).toShimmer(), + // SizedBox(height: 12.h), // Bottom row with chip and arrow Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -1446,62 +1463,65 @@ class _MedicalFilePageState extends State { }) { return [ // Page 1: BMI + Height - Row( - children: [ - Expanded( - child: _buildVitalSignCard( - icon: AppAssets.bmiVital, - label: "BMI", - value: vitalSign.bodyMassIndex?.toString() ?? '--', - unit: '', - status: vitalSign.bodyMassIndex != null ? _getBMIStatus(vitalSign.bodyMassIndex) : null, - onTap: onTap, + Padding( + padding: EdgeInsets.only(left: 24.w), + child: Row( + children: [ + Expanded( + child: _buildVitalSignCard( + icon: AppAssets.bmiVital, + label: LocaleKeys.bmi.tr(context: context), + value: vitalSign.bodyMassIndex?.toString() ?? '--', + unit: '', + status: vitalSign.bodyMassIndex != null ? _getBMIStatus(vitalSign.bodyMassIndex) : null, + onTap: onTap, + ), ), - ), - SizedBox(width: 12.w), - Expanded( - child: _buildVitalSignCard( - icon: AppAssets.heightVital, - label: "Height", - value: vitalSign.heightCm?.toString() ?? '--', - unit: 'cm', - status: null, - onTap: onTap, + SizedBox(width: 12.w), + Expanded( + child: _buildVitalSignCard( + icon: AppAssets.heightVital, + label: LocaleKeys.height.tr(context: context), + value: vitalSign.heightCm?.toString() ?? '--', + unit: 'cm', + status: null, + onTap: onTap, + ), ), - ), - ], + ], + ), ), // Page 2: Weight + Blood Pressure - Row( - children: [ - Expanded( - child: _buildVitalSignCard( - icon: AppAssets.weightVital, - label: "Weight", - value: vitalSign.weightKg?.toString() ?? '--', - unit: 'kg', - status: vitalSign.weightKg != null ? "Normal" : null, - onTap: onTap, - ), - ), - SizedBox(width: 12.w), - Expanded( - child: _buildVitalSignCard( - icon: AppAssets.bloodPressure, - label: "Blood Pressure", - value: vitalSign.bloodPressureLower != null && vitalSign.bloodPressureHigher != null - ? "${vitalSign.bloodPressureHigher}/${vitalSign.bloodPressureLower}" - : '--', - unit: '', - status: _getBloodPressureStatus( - systolic: vitalSign.bloodPressureHigher, - diastolic: vitalSign.bloodPressureLower, + Padding( + padding: EdgeInsets.symmetric(horizontal: 12.w), + child: Row( + children: [ + Expanded( + child: _buildVitalSignCard( + icon: AppAssets.weightVital, + label: LocaleKeys.weight.tr(context: context), + value: vitalSign.weightKg?.toString() ?? '--', + unit: 'kg', + status: vitalSign.weightKg != null ? "Normal" : null, + onTap: onTap, + ), ), - onTap: onTap, - ), - ), - ], - ), + SizedBox(width: 12.w), + Expanded( + child: _buildVitalSignCard( + icon: AppAssets.bloodPressure, + label: LocaleKeys.bloodPressure.tr(context: context), + value: vitalSign.bloodPressureLower != null && vitalSign.bloodPressureHigher != null ? "${vitalSign.bloodPressureHigher}/${vitalSign.bloodPressureLower}" : '--', + unit: '', + status: _getBloodPressureStatus( + systolic: vitalSign.bloodPressureHigher, + diastolic: vitalSign.bloodPressureLower, + ), + onTap: onTap, + ), + ), + ], + )), ]; } @@ -1526,7 +1546,6 @@ class _MedicalFilePageState extends State { return GestureDetector( onTap: onTap, child: Container( - // Same styling used originally for vitals in MedicalFilePage decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, borderRadius: 16.r, @@ -1540,15 +1559,15 @@ class _MedicalFilePageState extends State { Row( children: [ Container( - padding: EdgeInsets.all(10.h), + padding: EdgeInsets.all(8.h), decoration: BoxDecoration( color: scheme.iconBg, borderRadius: BorderRadius.circular(12.r), ), child: Utils.buildSvgWithAssets( icon: icon, - width: 20.w, - height: 20.h, + width: 22.w, + height: 22.h, iconColor: scheme.iconFg, fit: BoxFit.contain, ), @@ -1563,55 +1582,53 @@ class _MedicalFilePageState extends State { ], ), SizedBox(height: 14.h), - Container( - padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 6.h), - decoration: BoxDecoration( + padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.bgScaffoldColor, - borderRadius: BorderRadius.circular(10.r), + borderRadius: 10.r, + hasShadow: false, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - value.toText17( - isBold: true, - color: AppColors.textColor, - ), - if (unit.isNotEmpty) ...[ - SizedBox(width: 3.w), - unit.toText12( - color: AppColors.textColor, - fontWeight: FontWeight.w500, + Flexible( + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: value.toText17( + isBold: true, + color: AppColors.textColor, + ), ), + if (unit.isNotEmpty) ...[ + SizedBox(width: 3.w), + unit.toText12( + color: AppColors.textColor, + fontWeight: FontWeight.w500, + ), + ], ], - ], + ), ), - if (status != null) + if (status != null) ...[ + SizedBox(width: 4.w), AppCustomChipWidget( labelText: status, backgroundColor: scheme.chipBg, textColor: scheme.chipFg, + ), + ] else + AppCustomChipWidget( + labelText: "", + backgroundColor: AppColors.bgScaffoldColor, + textColor: null, ) - else - const SizedBox.shrink(), ], ), ), - SizedBox(height: 8.h), - - Align( - alignment: AlignmentDirectional.centerEnd, - child: Utils.buildSvgWithAssets( - icon: AppAssets.arrow_forward, - width: 18.w, - height: 18.h, - iconColor: AppColors.textColorLight, - fit: BoxFit.contain, - ), - ), ], ), ), @@ -1619,6 +1636,3 @@ class _MedicalFilePageState extends State { ); } } - - - diff --git a/lib/presentation/medical_file/patient_sickleaves_list_page.dart b/lib/presentation/medical_file/patient_sickleaves_list_page.dart index ef5aaeb..93cf17f 100644 --- a/lib/presentation/medical_file/patient_sickleaves_list_page.dart +++ b/lib/presentation/medical_file/patient_sickleaves_list_page.dart @@ -17,6 +17,7 @@ import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; import 'package:open_filex/open_filex.dart'; import 'package:provider/provider.dart'; @@ -197,55 +198,29 @@ class _PatientSickleavesListPageState extends State { ], ), SizedBox(height: 8.h), - Row( + Wrap( + direction: Axis.horizontal, + spacing: 6.h, + runSpacing: 6.h, children: [ - CustomButton( - text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(sickLeave.appointmentDate), false), - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 24.h, + AppCustomChipWidget( + labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(sickLeave.appointmentDate), false), ), - SizedBox(width: 8.h), - CustomButton( - text: model.isSickLeavesSortByClinic ? sickLeave.projectName! : sickLeave.clinicName!, - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 24.h, + AppCustomChipWidget( + labelText: model.isSickLeavesSortByClinic ? sickLeave.projectName! : sickLeave.clinicName!, ), - SizedBox(width: 8.h), - CustomButton( - text: "${sickLeave.sickLeaveDays} Days", - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 24.h, + AppCustomChipWidget( + labelText: "${sickLeave.sickLeaveDays} Days", ), ], ), - SizedBox(height: 8.h), + SizedBox(height: 12.h), Row( children: [ Expanded( flex: 6, child: CustomButton( - text: "Download Report".needTranslation, + text: LocaleKeys.downloadReport.tr(context: context), onPressed: () async { LoaderBottomSheet.showLoader(); await medicalFileViewModel.getPatientSickLeavePDF(sickLeave, appState.getAuthenticatedUser()!).then((val) async { @@ -293,7 +268,7 @@ class _PatientSickleavesListPageState extends State { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "You don't have any sick leaves yet.".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.youDontHaveAnySickLeavesYet.tr(context: context)); }, ).paddingSymmetrical(24.h, 0.h), ], diff --git a/lib/presentation/medical_file/vaccine_list_page.dart b/lib/presentation/medical_file/vaccine_list_page.dart index 777426f..bf02cb7 100644 --- a/lib/presentation/medical_file/vaccine_list_page.dart +++ b/lib/presentation/medical_file/vaccine_list_page.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -40,7 +42,7 @@ class _VaccineListPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Vaccine Info".needTranslation, + title: LocaleKeys.vaccineInfo.tr(context: context), child: SingleChildScrollView( child: Consumer(builder: (context, medicalFileVM, child) { return Column( @@ -170,7 +172,7 @@ class _VaccineListPageState extends State { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "No vaccines data found...".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noDataAvailable.tr(context: context)); }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), ), diff --git a/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart b/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart index fbe79bb..3d3624d 100644 --- a/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart +++ b/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart @@ -183,7 +183,7 @@ class MedicalFileAppointmentCard extends StatelessWidget { iconSize: 16.h, ) : CustomButton( - text: "Rebook".needTranslation, + text: LocaleKeys.rebook.tr(context: context), onPressed: () { onRescheduleTap(); }, diff --git a/lib/presentation/medical_file/widgets/patient_sick_leave_card.dart b/lib/presentation/medical_file/widgets/patient_sick_leave_card.dart index 6f9b8b5..16c05d8 100644 --- a/lib/presentation/medical_file/widgets/patient_sick_leave_card.dart +++ b/lib/presentation/medical_file/widgets/patient_sick_leave_card.dart @@ -94,7 +94,7 @@ class PatientSickLeaveCard extends StatelessWidget { : Expanded( flex: 6, child: CustomButton( - text: "Download Report".needTranslation, + text: LocaleKeys.downloadReport.tr(context: context), onPressed: () async { LoaderBottomSheet.showLoader(); await medicalFileViewModel.getPatientSickLeavePDF(patientSickLeavesResponseModel, _appState.getAuthenticatedUser()!).then((val) async { @@ -106,7 +106,7 @@ class PatientSickLeaveCard extends StatelessWidget { } catch (ex) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation), + child: Utils.getErrorWidget(loadingText: "Cannot open file"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/medical_report/medical_report_request_page.dart b/lib/presentation/medical_report/medical_report_request_page.dart index 8eabcdd..47a2df3 100644 --- a/lib/presentation/medical_report/medical_report_request_page.dart +++ b/lib/presentation/medical_report/medical_report_request_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_card.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -20,7 +22,7 @@ class MedicalReportRequestPage extends StatelessWidget { Widget build(BuildContext context) { medicalFileViewModel = Provider.of(context, listen: false); return CollapsingListView( - title: "Medical Reports".needTranslation, + title: LocaleKeys.medicalReports.tr(context: context), isClose: true, child: Column( children: [ diff --git a/lib/presentation/medical_report/medical_reports_page.dart b/lib/presentation/medical_report/medical_reports_page.dart index f6d7576..87420fd 100644 --- a/lib/presentation/medical_report/medical_reports_page.dart +++ b/lib/presentation/medical_report/medical_reports_page.dart @@ -44,7 +44,7 @@ class _MedicalReportsPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Medical Reports".needTranslation, + title: LocaleKeys.medicalReports.tr(context: context), child: SingleChildScrollView( child: Consumer(builder: (context, medicalFileVM, child) { return Column( @@ -88,7 +88,7 @@ class _MedicalReportsPageState extends State { Row( children: [ CustomButton( - text: "Requested".needTranslation, + text: LocaleKeys.requested.tr(context: context), onPressed: () { setState(() { expandedIndex = null; @@ -300,7 +300,7 @@ class _MedicalReportsPageState extends State { Expanded( flex: 6, child: CustomButton( - text: "Download Report".needTranslation, + text: LocaleKeys.downloadReport.tr(context: context), onPressed: () async { LoaderBottomSheet.showLoader(); await medicalFileViewModel.getPatientMedicalReportPDF(report, appState.getAuthenticatedUser()!).then((val) async { @@ -348,7 +348,7 @@ class _MedicalReportsPageState extends State { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "You don't have any medical reports yet.".needTranslation) + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.youDontHaveAnyMedicalReportsYet.tr(context: context)) .paddingSymmetrical(24.h, 24.h); }, ).paddingSymmetrical(24.h, 0.h), @@ -366,7 +366,7 @@ class _MedicalReportsPageState extends State { hasShadow: true, ), child: CustomButton( - text: "Request medical report".needTranslation, + text: LocaleKeys.requestMedicalReport.tr(context: context), onPressed: () async { LoaderBottomSheet.showLoader(); await medicalFileViewModel.getPatientMedicalReportAppointmentsList(onSuccess: (val) async { @@ -385,7 +385,7 @@ class _MedicalReportsPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "You do not have any appointments to request a medical report.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.youDoNotHaveAnyAppointmentsToRequestMedicalReport.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -414,7 +414,7 @@ class _MedicalReportsPageState extends State { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to request a medical report for this appointment?".needTranslation, + loadingText: LocaleKeys.areYouSureYouWantToRequestMedicalReport.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); @@ -425,7 +425,7 @@ class _MedicalReportsPageState extends State { await medicalFileViewModel.insertRequestForMedicalReport(onSuccess: (val) { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight(context, - child: Utils.getSuccessWidget(loadingText: "Your medical report request has been successfully submitted.".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.yourMedicalReportRequestSubmittedSuccessfully.tr(context: context)), callBackFunc: () { medicalFileViewModel.setIsPatientMedicalReportsLoading(true); medicalFileViewModel.onMedicalReportTabChange(0); diff --git a/lib/presentation/medical_report/widgets/patient_medical_report_card.dart b/lib/presentation/medical_report/widgets/patient_medical_report_card.dart index 413858d..282a2d6 100644 --- a/lib/presentation/medical_report/widgets/patient_medical_report_card.dart +++ b/lib/presentation/medical_report/widgets/patient_medical_report_card.dart @@ -144,7 +144,7 @@ class PatientMedicalReportCard extends StatelessWidget { } catch (ex) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation), + child: Utils.getErrorWidget(loadingText: "Cannot open file"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/monthly_report/monthly_report.dart b/lib/presentation/monthly_report/monthly_report.dart index 1776510..43c7fc1 100644 --- a/lib/presentation/monthly_report/monthly_report.dart +++ b/lib/presentation/monthly_report/monthly_report.dart @@ -80,7 +80,10 @@ class MonthlyReport extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ LocaleKeys.email.tr(context: context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), - "${appState.getAuthenticatedUser()!.emailAddress}".toText16(color: AppColors.textColor, weight: FontWeight.w500), + SizedBox( + width: MediaQuery.of(context).size.width * 0.7, + child: "${appState.getAuthenticatedUser()!.emailAddress}".toText16(color: AppColors.textColor, weight: FontWeight.w500, maxlines: 2), + ), ], ), ], @@ -95,10 +98,7 @@ class MonthlyReport extends StatelessWidget { Utils.buildSvgWithAssets(icon: AppAssets.prescription_remarks_icon, width: 18.w, height: 18.h), SizedBox(width: 9.h), Expanded( - child: - "This monthly health summary report reflects the health indicators and analysis results of the latest visits. Please note that this will be sent automatically from the system and it’s not considered as a official report so no medical decision should be taken based on it" - .needTranslation - .toText10(weight: FontWeight.w500, color: AppColors.greyTextColorLight), + child: LocaleKeys.monthlyHealthSummaryReportDisclaimer.tr(context: context).toText10(weight: FontWeight.w500, color: AppColors.greyTextColorLight), ), ], ), @@ -146,7 +146,7 @@ class MonthlyReport extends StatelessWidget { CustomButton( text: LocaleKeys.save.tr(), onPressed: () async { - LoaderBottomSheet.showLoader(loadingText: "Updating Monthly Report Status...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.updatingMonthlyReportStatus.tr(context: context)); await monthlyReportVM.updatePatientHealthSummaryReport( rSummaryReport: monthlyReportVM.isHealthSummaryEnabled, onSuccess: (response) async { @@ -157,7 +157,7 @@ class MonthlyReport extends StatelessWidget { ); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Monthly Report Status Updated Successfully".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.monthlyReportStatusUpdatedSuccessfully.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/my_family/my_family.dart b/lib/presentation/my_family/my_family.dart index 07f1a4f..bac6f77 100644 --- a/lib/presentation/my_family/my_family.dart +++ b/lib/presentation/my_family/my_family.dart @@ -42,6 +42,8 @@ class _FamilyMedicalScreenState extends State { medicalVM = context.read(); WidgetsBinding.instance.addPostFrameCallback((_) { medicalVM?.onFamilyFileTabChange(0); + medicalVM?.getAllPendingRecordsByResponseId(); + }); } @@ -50,7 +52,7 @@ class _FamilyMedicalScreenState extends State { AppState appState = getIt.get(); return CollapsingListView( - title: "Medical Files".needTranslation, + title: LocaleKeys.familyTitle.tr(context: context), bottomChild: appState.getAuthenticatedUser()!.isParentUser! ? Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( @@ -59,13 +61,13 @@ class _FamilyMedicalScreenState extends State { ), padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 20.h), child: CustomButton( - text: "Add a new family member".needTranslation, + text: LocaleKeys.addANewFamilyMember.tr(context: context), onPressed: () { DialogService dialogService = getIt.get(); medicalVM!.clearAuthValues(); dialogService.showAddFamilyFileSheet( - label: "Add Family Member".needTranslation, - message: "Please fill the below field to add a new family member to your profile".needTranslation, + label: LocaleKeys.addFamilyMember.tr(context: context), + message: LocaleKeys.pleaseFillBelowFieldToAddNewFamilyMember.tr(context: context), onVerificationPress: () { medicalVM!.addFamilyFile(otpTypeEnum: OTPTypeEnum.sms); }); @@ -73,7 +75,7 @@ class _FamilyMedicalScreenState extends State { icon: AppAssets.add_icon, fontSize: 16.f, borderRadius: 12.r, - fontWeight: FontWeight.w500)) + fontWeight: FontWeight.w500)).paddingOnly(bottom: 20.h) : SizedBox(), child: Column( mainAxisSize: MainAxisSize.min, diff --git a/lib/presentation/my_family/widget/family_cards.dart b/lib/presentation/my_family/widget/family_cards.dart index 3621cc3..175cfb1 100644 --- a/lib/presentation/my_family/widget/family_cards.dart +++ b/lib/presentation/my_family/widget/family_cards.dart @@ -54,12 +54,10 @@ class _FamilyCardsState extends State { children: [ Utils.buildSvgWithAssets(icon: AppAssets.alertSquare), SizedBox(width: 8.h), - "Who can view my medical file ?" - .needTranslation - .toText14(color: AppColors.textColor, isUnderLine: true, weight: FontWeight.w500) + LocaleKeys.whoCanViewMyMedicalFile.tr(context: context).toText14(color: AppColors.textColor, isUnderLine: true, weight: FontWeight.w500) .onPress(() { dialogService.showFamilyBottomSheetWithoutHWithChild( - label: "Manage Family".needTranslation, + label: LocaleKeys.manageFiles.tr(context: context), message: "", child: manageFamily(), onOkPressed: () {}, @@ -153,7 +151,7 @@ class _FamilyCardsState extends State { crossAxisCount: 2, crossAxisSpacing: 10.w, mainAxisSpacing: 10.h, - childAspectRatio: widget.isShowDetails ? 0.56.h : 0.65.h, + childAspectRatio: widget.isShowDetails ? 0.56.h : 0.64.h, ), padding: EdgeInsets.only(bottom: 20.h), itemBuilder: (context, index) { @@ -213,7 +211,7 @@ class _FamilyCardsState extends State { onPressed: () { if (canSwitch) widget.onSelect(profile); }, - text: isActive ? "Active".needTranslation : "Switch".needTranslation, + text: isActive ? LocaleKeys.active.tr(context: context) : LocaleKeys.switchLogin.tr(context: context), backgroundColor: isActive || !canSwitch ? Colors.grey.shade200 : AppColors.secondaryLightRedColor, borderColor: isActive || !canSwitch ? Colors.grey.shade200 : AppColors.secondaryLightRedColor, textColor: isActive || !canSwitch ? AppColors.greyTextColor : AppColors.primaryRedColor, @@ -309,7 +307,7 @@ class _FamilyCardsState extends State { height: 30.h, chipType: ChipTypeEnum.alert, backgroundColor: AppColors.lightGrayBGColor, - chipText: "Medical File: ${profile.patientId ?? "N/A".needTranslation}", + chipText: "${LocaleKeys.medicalFile.tr(context: context)}: ${profile.patientId ?? "N/A"}", iconAsset: null, isShowBorder: false, borderRadius: 8.h, @@ -323,7 +321,7 @@ class _FamilyCardsState extends State { : Expanded( child: CustomButton( height: 40.h, - text: LocaleKeys.confirm.tr(), + text: LocaleKeys.acceptLbl.tr(), onPressed: () { navigationService.pop(); widget.onSelect(profile); @@ -331,6 +329,7 @@ class _FamilyCardsState extends State { backgroundColor: AppColors.lightGreenButtonColor, borderColor: AppColors.lightGreenButtonColor, textColor: AppColors.textGreenColor, + borderWidth: 0, icon: null, ), ), @@ -338,7 +337,7 @@ class _FamilyCardsState extends State { Expanded( child: CustomButton( height: 40.h, - text: profile.status == FamilyFileEnum.active.toInt ? LocaleKeys.removeMember.tr() : LocaleKeys.cancel.tr(), + text: profile.status == FamilyFileEnum.active.toInt ? LocaleKeys.removeMember.tr() : LocaleKeys.rejectView.tr(), onPressed: () { navigationService.pop(); widget.onRemove(profile); @@ -364,26 +363,26 @@ class _FamilyCardsState extends State { switch (status) { case FamilyFileEnum.active: if (isRequestFromMySide) { - return "${status.displayName} your request to be your family member".needTranslation; + return LocaleKeys.acceptedYourRequestToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context); } else { - return "can view your file".needTranslation; + return LocaleKeys.canViewYourFile.tr(context: context); } case FamilyFileEnum.pending: if (isRequestFromMySide) { - return "has a request ${status.displayName} to be your family member".needTranslation; + return LocaleKeys.hasARequestPendingToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context); } else { - return "wants to add you as their family member".needTranslation; + return LocaleKeys.wantsToAddYouAsTheirFamilyMember.tr(context: context); } case FamilyFileEnum.rejected: if (isRequestFromMySide) { - return "${status.displayName} your request to be your family member".needTranslation; + return LocaleKeys.rejectedYourRequestToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context); } else { - return "${status.displayName} your family member request".needTranslation; + return LocaleKeys.rejectedYourFamilyMemberRequest.tr(namedArgs: {'status': status.displayName}, context: context); } case FamilyFileEnum.inactive: - return "Inactive".needTranslation; + return LocaleKeys.inactive.tr(context: context); default: - return "N/A".needTranslation; + return LocaleKeys.notAvailable.tr(context: context); } } } diff --git a/lib/presentation/my_family/widget/my_family_sheet.dart b/lib/presentation/my_family/widget/my_family_sheet.dart index d469ab2..50f1b2a 100644 --- a/lib/presentation/my_family/widget/my_family_sheet.dart +++ b/lib/presentation/my_family/widget/my_family_sheet.dart @@ -1,7 +1,9 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/medical_file/models/family_file_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/my_family/widget/family_cards.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -15,8 +17,8 @@ class MyFamilySheet { titleWidget: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - 'Please select a profile'.needTranslation.toText21(isBold: true), - 'switch from the below list of medical file'.needTranslation.toText16(weight: FontWeight.w100, color: AppColors.greyTextColor), + LocaleKeys.selectAProfile.tr(context: context).toText21(isBold: true), + LocaleKeys.switchFamilyFile.tr(context: context).toText16(weight: FontWeight.w100, color: AppColors.greyTextColor), ], ), child: FamilyCards( diff --git a/lib/presentation/my_invoices/my_invoices_details_page.dart b/lib/presentation/my_invoices/my_invoices_details_page.dart index cccd671..a38194f 100644 --- a/lib/presentation/my_invoices/my_invoices_details_page.dart +++ b/lib/presentation/my_invoices/my_invoices_details_page.dart @@ -39,9 +39,9 @@ class _MyInvoicesDetailsPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Invoice Details".needTranslation, + title: LocaleKeys.invoiceDetails.tr(context: context), sendEmail: () async { - LoaderBottomSheet.showLoader(loadingText: "Sending email, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.sendingEmailPleaseWait.tr(context: context)); await myInvoicesViewModel.sendInvoiceEmail( appointmentNo: widget.getInvoiceDetailsResponseModel.appointmentNo!, projectID: widget.getInvoiceDetailsResponseModel.projectID!, @@ -49,7 +49,7 @@ class _MyInvoicesDetailsPageState extends State { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Email sent successfully.".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.emailSentSuccessfullyMessage.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -223,12 +223,12 @@ class _MyInvoicesDetailsPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 24.h), - "Total Balance".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalBalance.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol(widget.getInvoiceDetailsResponseModel.listConsultation!.first.totalShare.toString().toText16(isBold: true), AppColors.blackColor, 13, isSaudiCurrency: true), ], @@ -236,7 +236,7 @@ class _MyInvoicesDetailsPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( widget.getInvoiceDetailsResponseModel.listConsultation!.first.totalVATAmount!.toString().toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, 13, isSaudiCurrency: true), @@ -246,7 +246,7 @@ class _MyInvoicesDetailsPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Discount".needTranslation.toText14(isBold: true), + LocaleKeys.discount.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol(widget.getInvoiceDetailsResponseModel.listConsultation!.first.discountAmount!.toString().toText14(isBold: true, color: AppColors.primaryRedColor), AppColors.primaryRedColor, 13, isSaudiCurrency: true), @@ -255,7 +255,7 @@ class _MyInvoicesDetailsPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Paid".needTranslation.toText14(isBold: true), + LocaleKeys.paid.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol( widget.getInvoiceDetailsResponseModel.listConsultation!.first.grandTotal!.toString().toText14(isBold: true, color: AppColors.textColor), AppColors.textColor, 13, isSaudiCurrency: true), diff --git a/lib/presentation/my_invoices/my_invoices_list.dart b/lib/presentation/my_invoices/my_invoices_list.dart index ef1a9c2..177dde8 100644 --- a/lib/presentation/my_invoices/my_invoices_list.dart +++ b/lib/presentation/my_invoices/my_invoices_list.dart @@ -52,7 +52,7 @@ class _MyInvoicesListState extends State { children: [ SizedBox(height: 24.h), ListView.builder( - itemCount: myInvoicesVM.isInvoicesListLoading ? 4 : myInvoicesVM.allInvoicesList.length, + itemCount: myInvoicesVM.isInvoicesListLoading ? 4 : myInvoicesVM.allInvoicesList.isEmpty ? 1 : myInvoicesVM.allInvoicesList.length, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, padding: EdgeInsetsGeometry.zero, @@ -64,7 +64,7 @@ class _MyInvoicesListState extends State { index: index, isLoading: true, ) - : AnimationConfiguration.staggeredList( + : myInvoicesVM.allInvoicesList.isNotEmpty ? AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( @@ -77,7 +77,7 @@ class _MyInvoicesListState extends State { getInvoicesListResponseModel: myInvoicesVM.allInvoicesList[index], onTap: () async { myInvoicesVM.setInvoiceDetailLoading(); - LoaderBottomSheet.showLoader(loadingText: "Fetching invoice details, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingInvoiceDetails.tr(context: context)); await myInvoicesVM.getInvoiceDetails( appointmentNo: myInvoicesVM.allInvoicesList[index].appointmentNo!, invoiceNo: myInvoicesVM.allInvoicesList[index].invoiceNo!, @@ -105,7 +105,7 @@ class _MyInvoicesListState extends State { ), ), ), - ); + ) : Utils.getNoDataWidget(context); }).paddingSymmetrical(24.w, 0.h), ], ); diff --git a/lib/presentation/my_invoices/widgets/invoice_list_card.dart b/lib/presentation/my_invoices/widgets/invoice_list_card.dart index 27ca79a..4a328c5 100644 --- a/lib/presentation/my_invoices/widgets/invoice_list_card.dart +++ b/lib/presentation/my_invoices/widgets/invoice_list_card.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -41,11 +42,11 @@ class InvoiceListCard extends StatelessWidget { AppCustomChipWidget( icon: AppAssets.walkin_appointment_icon, iconColor: AppColors.textColor, - labelText: 'Walk In'.needTranslation, + labelText: LocaleKeys.walkin.tr(context: context), textColor: AppColors.textColor, ), AppCustomChipWidget( - labelText: 'OutPatient'.needTranslation, + labelText: LocaleKeys.outPatient.tr(context: context), backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.1), textColor: AppColors.primaryRedColor, ), @@ -127,7 +128,7 @@ class InvoiceListCard extends StatelessWidget { ), SizedBox(height: 16.h), CustomButton( - text: "View invoice details".needTranslation, + text: LocaleKeys.viewInvoiceDetails.tr(context: context), onPressed: () { if (onTap != null) { onTap!(); diff --git a/lib/presentation/notifications/notification_details_page.dart b/lib/presentation/notifications/notification_details_page.dart new file mode 100644 index 0000000..949b872 --- /dev/null +++ b/lib/presentation/notifications/notification_details_page.dart @@ -0,0 +1,285 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/notifications/models/resp_models/notification_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:share_plus/share_plus.dart'; + +class NotificationDetailsPage extends StatelessWidget { + final NotificationResponseModel notification; + + const NotificationDetailsPage({ + super.key, + required this.notification, + }); + + @override + Widget build(BuildContext context) { + // Debug logging + print('=== Notification Details ==='); + print('Message: ${notification.message}'); + print('MessageType: ${notification.messageType}'); + print('MessageTypeData: ${notification.messageTypeData}'); + print('VideoURL: ${notification.videoURL}'); + print('========================'); + + return CollapsingListView( + title: LocaleKeys.notificationDetails.tr(), + trailing: IconButton( + icon: Icon( + Icons.share_outlined, + size: 24.h, + color: AppColors.textColor, + ), + onPressed: () { + _shareNotification(); + }, + ), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 24.h), + // Notification content card + _buildNotificationCard(context), + SizedBox(height: 24.h), + ], + ).paddingSymmetrical(24.w, 0.h), + ), + ); + } + + Widget _buildNotificationCard(BuildContext context) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Date and Time row + Row( + children: [ + // Time chip with clock icon + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.access_time, size: 12.w, color: AppColors.textColor), + SizedBox(width: 4.w), + _formatTime(notification.isSentOn).toText10( + weight: FontWeight.w500, + color: AppColors.textColor, + ), + ], + ), + ), + SizedBox(width: 8.w), + // Date chip with calendar icon + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.calendar_today, size: 12.w, color: AppColors.textColor), + SizedBox(width: 4.w), + _formatDate(notification.isSentOn).toText10( + weight: FontWeight.w500, + color: AppColors.textColor, + ), + ], + ), + ), + ], + ), + SizedBox(height: 16.h), + + // Notification message + if (notification.message != null && notification.message!.isNotEmpty) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.messageNotification.tr().toText14( + weight: FontWeight.w600, + color: AppColors.greyTextColor, + ), + SizedBox(height: 8.h), + notification.message!.toText16( + weight: FontWeight.w400, + color: AppColors.textColor, + maxlines: 100, + ), + SizedBox(height: 16.h), + ], + ), + + // Notification image (if MessageType is "image") + if (notification.messageType != null && + notification.messageType!.toLowerCase() == "image") + Builder( + builder: (context) { + // Try to get image URL from videoURL or messageTypeData + String? imageUrl; + + if (notification.videoURL != null && notification.videoURL!.isNotEmpty) { + imageUrl = notification.videoURL; + print('Image URL from videoURL: $imageUrl'); + } else if (notification.messageTypeData != null && notification.messageTypeData!.isNotEmpty) { + imageUrl = notification.messageTypeData; + print('Image URL from messageTypeData: $imageUrl'); + } + + if (imageUrl == null || imageUrl.isEmpty) { + print('No image URL found. videoURL: ${notification.videoURL}, messageTypeData: ${notification.messageTypeData}'); + return SizedBox.shrink(); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.attachedImage.tr().toText14( + weight: FontWeight.w600, + color: AppColors.greyTextColor, + ), + SizedBox(height: 8.h), + ClipRRect( + borderRadius: BorderRadius.circular(12.h), + child: Image.network( + imageUrl, + width: double.infinity, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) { + print('Error loading image: $error'); + print('Image URL: $imageUrl'); + return Container( + height: 200.h, + decoration: BoxDecoration( + color: AppColors.greyColor.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(12.h), + ), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.broken_image_outlined, + size: 48.h, + color: AppColors.greyTextColor, + ), + SizedBox(height: 8.h), + LocaleKeys.failedToLoadImage.tr().toText12( + color: AppColors.greyTextColor, + ), + SizedBox(height: 4.h), + Text( + imageUrl!, + style: TextStyle(fontSize: 8, color: AppColors.greyTextColor), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ); + }, + loadingBuilder: (context, child, loadingProgress) { + if (loadingProgress == null) { + print('Image loaded successfully'); + return child; + } + return Container( + height: 200.h, + decoration: BoxDecoration( + color: AppColors.greyColor.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(12.h), + ), + child: Center( + child: CircularProgressIndicator( + value: loadingProgress.expectedTotalBytes != null + ? loadingProgress.cumulativeBytesLoaded / + loadingProgress.expectedTotalBytes! + : null, + ), + ), + ); + }, + ), + ), + SizedBox(height: 16.h), + ], + ); + }, + ), + + // Additional notification info + if (notification.notificationType != null && notification.notificationType!.isNotEmpty) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.typeNotification.tr().toText14( + weight: FontWeight.w600, + color: AppColors.greyTextColor, + ), + SizedBox(height: 8.h), + notification.notificationType!.toText16( + weight: FontWeight.w400, + color: AppColors.textColor, + ), + ], + ), + ], + ), + ); + } + + void _shareNotification() async { + final String shareText = ''' +${notification.message ?? 'Notification'} + +Time: ${_formatTime(notification.isSentOn)} +Date: ${_formatDate(notification.isSentOn)} +${notification.notificationType != null ? '\nType: ${notification.notificationType}' : ''} + '''.trim(); + + await Share.share(shareText); + } + + String _formatTime(String? dateTimeString) { + if (dateTimeString == null || dateTimeString.isEmpty) return '--'; + try { + final dateTime = DateUtil.convertStringToDate(dateTimeString); + return DateFormat('hh:mm a').format(dateTime); + } catch (e) { + return '--'; + } + } + + String _formatDate(String? dateTimeString) { + if (dateTimeString == null || dateTimeString.isEmpty) return '--'; + try { + final dateTime = DateUtil.convertStringToDate(dateTimeString); + return DateFormat('dd MMM yyyy').format(dateTime); + } catch (e) { + return '--'; + } + } +} + diff --git a/lib/presentation/notifications/notifications_list_page.dart b/lib/presentation/notifications/notifications_list_page.dart new file mode 100644 index 0000000..c5f5d12 --- /dev/null +++ b/lib/presentation/notifications/notifications_list_page.dart @@ -0,0 +1,214 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/int_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/notifications/notifications_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart'; +import 'package:hmg_patient_app_new/presentation/notifications/notification_details_page.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:provider/provider.dart'; +import 'package:intl/intl.dart'; + +class NotificationsListPage extends StatelessWidget { + const NotificationsListPage({super.key}); + + @override + Widget build(BuildContext context) { + return CollapsingListView( + title: LocaleKeys.notifications.tr(context: context), + child: SingleChildScrollView( + child: Consumer(builder: (context, notificationsVM, child) { + return Container( + margin: EdgeInsets.symmetric(vertical: 24.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: false, + ), + child: ListView.builder( + itemCount: notificationsVM.isNotificationsLoading ? 4 : notificationsVM.notificationsList.length, + physics: NeverScrollableScrollPhysics(), + shrinkWrap: true, + padding: EdgeInsetsGeometry.zero, + itemBuilder: (context, index) { + return notificationsVM.isNotificationsLoading + ? LabResultItemView( + onTap: () {}, + labOrder: null, + index: index, + isLoading: true, + ) + : AnimationConfiguration.staggeredList( + position: index, + duration: const Duration(milliseconds: 500), + child: SlideAnimation( + verticalOffset: 100.0, + child: FadeInAnimation( + child: GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => NotificationDetailsPage( + notification: notificationsVM.notificationsList[index], + ), + ), + ); + }, + child: AnimatedContainer( + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + // Message row with red dot for unread + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: notificationsVM.notificationsList[index].message!.toText16( + isBold: (notificationsVM.notificationsList[index].isRead == false), + weight: (notificationsVM.notificationsList[index].isRead == false) + ? FontWeight.w600 + : FontWeight.w400, + ), + ), + SizedBox(width: 8.w), + // Red dot for unread notifications ONLY + if (notificationsVM.notificationsList[index].isRead == false) + Container( + width: 8.w, + height: 8.w, + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + ), + ), + ], + ), + SizedBox(height: 12.h), + // First row: Time and Date chips with arrow + Row( + children: [ + // Time chip with clock icon + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.access_time, size: 12.w, color: AppColors.textColor), + SizedBox(width: 4.w), + _formatTime(notificationsVM.notificationsList[index].isSentOn).toText10( + weight: FontWeight.w500, + color: AppColors.textColor, + ), + ], + ), + ), + SizedBox(width: 8.w), + // Date chip with calendar icon + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.calendar_today, size: 12.w, color: AppColors.textColor), + SizedBox(width: 4.w), + _formatDate(notificationsVM.notificationsList[index].isSentOn).toText10( + weight: FontWeight.w500, + color: AppColors.textColor, + ), + ], + ), + ), + Spacer(), + // Arrow icon + Utils.buildSvgWithAssets( + icon: AppAssets.arrow_forward, + width: 16.w, + height: 16.h, + iconColor: AppColors.greyTextColor, + ), + ], + ), + // Second row: Contains Image chip (if MessageType is "image") + if (notificationsVM.notificationsList[index].messageType != null && + notificationsVM.notificationsList[index].messageType!.toLowerCase() == "image") + Padding( + padding: EdgeInsets.only(top: 8.h), + child: Row( + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h), + decoration: BoxDecoration( + color: AppColors.greyColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.image_outlined, size: 12.w, color: AppColors.textColor), + SizedBox(width: 4.w), + 'Contains Image'.toText10( + weight: FontWeight.w500, + color: AppColors.textColor, + ), + ], + ), + ), + ], + ), + ), + SizedBox(height: 16.h), + 1.divider, + ], + ), + ), + ), + ), + ), + ); + }).paddingSymmetrical(16.w, 0.h), + ).paddingSymmetrical(24.w, 0.h); + }), + ), + ); + } + + String _formatTime(String? dateTimeString) { + if (dateTimeString == null || dateTimeString.isEmpty) return '--'; + try { + final dateTime = DateUtil.convertStringToDate(dateTimeString); + return DateFormat('hh:mm a').format(dateTime); + } catch (e) { + return '--'; + } + } + + String _formatDate(String? dateTimeString) { + if (dateTimeString == null || dateTimeString.isEmpty) return '--'; + try { + final dateTime = DateUtil.convertStringToDate(dateTimeString); + return DateFormat('dd MMM yyyy').format(dateTime); + } catch (e) { + return '--'; + } + } +} diff --git a/lib/presentation/onboarding/onboarding_screen.dart b/lib/presentation/onboarding/onboarding_screen.dart index a40a27b..4855c0c 100644 --- a/lib/presentation/onboarding/onboarding_screen.dart +++ b/lib/presentation/onboarding/onboarding_screen.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -36,7 +38,7 @@ class _OnboardingScreenState extends State { CustomPageRoute( page: LandingNavigation(), ), - (r) => false); + (r) => false); // Navigator.of(context).pushReplacement(FadePage(page: LandingNavigation())); } @@ -67,13 +69,13 @@ class _OnboardingScreenState extends State { children: [ onboardingView( AppAnimations.onboarding_1, - "Booking appointment has never been easy".needTranslation, - "In few clicks find yourself having consultation with the doctor of your choice.".needTranslation, + LocaleKeys.onboardingHeading1.tr(context: context), + LocaleKeys.onboardingBody1.tr(context: context), ), onboardingView( AppAnimations.onboarding_2, - "Access the medical history on finger tips".needTranslation, - "Keep track on your medical history including labs, prescription, insurance, etc".needTranslation, + LocaleKeys.onboardingHeading2.tr(context: context), + LocaleKeys.onboardingBody2.tr(context: context), ), ], onPageChanged: (int index) { @@ -88,15 +90,13 @@ class _OnboardingScreenState extends State { duration: const Duration(milliseconds: 250), height: 6.h, width: selectedIndex == 0 ? 18.w : 6.w, - decoration: BoxDecoration( - color: selectedIndex == 0 ? AppColors.textColor : AppColors.inputLabelTextColor, borderRadius: BorderRadius.circular(30.r)), + decoration: BoxDecoration(color: selectedIndex == 0 ? AppColors.textColor : AppColors.inputLabelTextColor, borderRadius: BorderRadius.circular(30.r)), ), AnimatedContainer( duration: const Duration(milliseconds: 250), height: 6.h, width: selectedIndex == 1 ? 18.w : 6.w, - decoration: BoxDecoration( - color: selectedIndex == 1 ? AppColors.textColor : AppColors.inputLabelTextColor, borderRadius: BorderRadius.circular(30.r)), + decoration: BoxDecoration(color: selectedIndex == 1 ? AppColors.textColor : AppColors.inputLabelTextColor, borderRadius: BorderRadius.circular(30.r)), ), ], ).paddingOnly(left: 24.w, right: 24.w), @@ -107,7 +107,7 @@ class _OnboardingScreenState extends State { transitionBuilder: (child, anim) => FadeTransition(opacity: anim, child: child), child: selectedIndex == 0 ? CustomButton( - text: "Skip".needTranslation, + text: LocaleKeys.skip.tr(context: context), onPressed: () => goToHomePage(), width: 86.w, height: 56.h, @@ -121,7 +121,7 @@ class _OnboardingScreenState extends State { AnimatedContainer( duration: const Duration(milliseconds: 400), curve: Curves.easeInOut, - width: selectedIndex == 0 ? 86.w : MediaQuery.of(context).size.width - 48.w, + width: selectedIndex == 0 ? 56.w : MediaQuery.of(context).size.width - 48.w, margin: EdgeInsets.only(left: 24.w, right: 24.w), decoration: BoxDecoration( color: AppColors.primaryRedColor, @@ -134,15 +134,15 @@ class _OnboardingScreenState extends State { ? CustomButton( icon: getIt.get().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward, iconSize: 32.w, - width: 86.w, + width: 56.w, height: 56.h, - text: "".needTranslation, + text: "", backgroundColor: Colors.transparent, onPressed: () { pageController.animateToPage(1, duration: Duration(milliseconds: 400), curve: Curves.easeInOut); }) : CustomButton( - text: "Get Started".needTranslation, + text: LocaleKeys.getStarted.tr(context: context), fontWeight: FontWeight.w500, fontSize: 16.f, height: 56.h, @@ -153,7 +153,7 @@ class _OnboardingScreenState extends State { ), ), ], - ).paddingOnly(bottom: (isFoldable || isTablet) ? 20.h : 10.h), + ).paddingOnly(bottom: (isFoldable || isTablet) ? 20.h : 32.h), ], ), ), @@ -170,16 +170,11 @@ class _OnboardingScreenState extends State { alignment: Alignment.bottomCenter, child: Transform.flip( flipX: getIt.get().isArabic() ? true : false, - child: Lottie.asset(icon, - repeat: true, - reverse: false, - frameRate: FrameRate(60), - width: MediaQuery.sizeOf(context).width - 50.w, - height: MediaQuery.sizeOf(context).width - 50.w))) + child: Lottie.asset(icon, repeat: true, reverse: false, frameRate: FrameRate(60), width: MediaQuery.sizeOf(context).width - 50.w, height: MediaQuery.sizeOf(context).width - 50.w))) .expanded, Text( heading, - style: TextStyle(fontSize: 36.f, fontWeight: FontWeight.w600, color: AppColors.textColor, letterSpacing: -0.4, height: 1), + style: TextStyle(fontSize: 36.f, fontWeight: FontWeight.w600, color: AppColors.textColor, letterSpacing: -1, height: 1.2), ), Text( body, diff --git a/lib/presentation/parking/paking_page.dart b/lib/presentation/parking/paking_page.dart new file mode 100644 index 0000000..db451b2 --- /dev/null +++ b/lib/presentation/parking/paking_page.dart @@ -0,0 +1,139 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/parking/parking_slot.dart'; +import 'package:provider/provider.dart'; + +import '../../features/qr_parking/qr_parking_view_model.dart'; +import '../../theme/colors.dart'; +import '../../widgets/appbar/app_bar_widget.dart'; +import '../../widgets/buttons/custom_button.dart'; +import '../../widgets/routes/custom_page_route.dart'; + + + +class ParkingPage extends StatefulWidget { + const ParkingPage({super.key}); + + @override + State createState() => _ParkingPageState(); +} + +class _ParkingPageState extends State { + + + Future _readQR(BuildContext context) async { + final vm = context.read(); + final model = await vm.scanAndGetParking(); + if (model == null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(vm.error ?? "Invalid Qr Code")), + ); + return; + } + + Navigator.of(context).push( + CustomPageRoute( + page: ChangeNotifierProvider.value( + value: vm, + child: ParkingSlot(model: model), + ), + ), + ); + } + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) async { + final vm = context.read(); + await vm.getIsSaveParking(); + if (!mounted) return; + + if (vm.isSavePark && vm.qrParkingModel != null) { + Navigator.of(context).push( + CustomPageRoute( + page: ChangeNotifierProvider.value( + value: vm, + child: ParkingSlot(model: vm.qrParkingModel!), + ), + ), + ); + } + }); + } + + @override + Widget build(BuildContext context) { + final vm = context.watch(); + return Scaffold( + backgroundColor: AppColors.scaffoldBgColor, + appBar: CustomAppBar( + onBackPressed: () => Navigator.of(context).pop(), + onLanguageChanged: (_) {}, + hideLogoAndLang: true, + ), + body: Column( + children: [ + Expanded( + child: SingleChildScrollView( + padding: EdgeInsets.symmetric(horizontal: 24.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + LocaleKeys.parking.tr(context: context), + style: TextStyle( + color: AppColors.textColor, + fontSize: 27.f, + fontWeight: FontWeight.w600, + ), + ), + Container( + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), child: LocaleKeys.parkingDescription.tr(context: context).toText12(fontWeight: FontWeight.w500, color: AppColors.textColor)), + ).paddingOnly(top: 16, bottom: 16), + ], + ), + ), + ), + + Container( + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(24.h), + child: CustomButton( + text: LocaleKeys.scanQRCode.tr(context: context), + onPressed: () => _readQR(context), + // always non-null + isDisabled: vm.isLoading, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + fontSize: 18.f, + height: 56.h, + fontWeight: FontWeight.bold, + ), + ), + ), + ], + ), + ); + } +} + + diff --git a/lib/presentation/parking/parking_slot.dart b/lib/presentation/parking/parking_slot.dart new file mode 100644 index 0000000..52ab181 --- /dev/null +++ b/lib/presentation/parking/parking_slot.dart @@ -0,0 +1,238 @@ + + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/qr_parking/models/qr_parking_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import '../../features/qr_parking/qr_parking_view_model.dart'; +import '../../theme/colors.dart'; +import '../../widgets/appbar/app_bar_widget.dart'; +import '../../widgets/buttons/custom_button.dart'; +import '../../widgets/chip/app_custom_chip_widget.dart'; +import 'package:maps_launcher/maps_launcher.dart'; +import 'package:provider/provider.dart'; +import '../../widgets/routes/custom_page_route.dart'; + +class ParkingSlot extends StatefulWidget { + final QrParkingResponseModel model; + + const ParkingSlot({ + super.key, + required this.model, + }); + + @override + State createState() => _ParkingSlotState(); +} + +class _ParkingSlotState extends State { + void _openDirection() { + final lat = widget.model.latitude; + final lng = widget.model.longitude; + + final valid = lat != null && + lng != null && + !(lat == 0.0 && lng == 0.0) && + lat >= -90 && + lat <= 90 && + lng >= -180 && + lng <= 180; + + if (!valid) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Parking location not available")), + ); + return; + } + + MapsLauncher.launchCoordinates(lat, lng); + } + + + Future _resetDirection() async { + final vm = context.read(); + await vm.clearParking(); + final model = await vm.scanAndGetParking(); + if (model == null) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(vm.error ?? "Scan cancelled")), + ); + + Navigator.of(context).pop(); + return; + } + + if (!mounted) return; + Navigator.of(context).pushReplacement( + CustomPageRoute( + page: ChangeNotifierProvider.value( + value: vm, + child: ParkingSlot(model: model), + ), + ), + ); + } + + + DateTime? _parseDotNetDate(String? value) { + if (value == null || value.isEmpty) return null; + + final regExp = RegExp(r'Date\((\d+)([+-]\d+)?\)'); + final match = regExp.firstMatch(value); + if (match == null) return null; + + final milliseconds = int.tryParse(match.group(1)!); + if (milliseconds == null) return null; + + return DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: true).toLocal(); + } + + String _formatPrettyDate(String? value) { + final date = _parseDotNetDate(value); + if (date == null) return '-'; + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ]; + + final day = date.day.toString().padLeft(2, '0'); + final month = months[date.month - 1]; + final year = date.year; + + return "$day $month $year"; // ✅ 15 Dec 2025 + } + + String _formatPrettyTime(String? value) { + final date = _parseDotNetDate(value); + if (date == null) return '-'; + + int hour = date.hour; + final minute = date.minute.toString().padLeft(2, '0'); + + final isPM = hour >= 12; + final period = isPM ? 'PM' : 'AM'; + + hour = hour % 12; + if (hour == 0) hour = 12; + + return "${hour.toString().padLeft(2, '0')}:$minute $period"; // ✅ 03:05 PM + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.scaffoldBgColor, + appBar: CustomAppBar( + onBackPressed: () => Navigator.of(context).pop(), + onLanguageChanged: (_) {}, + hideLogoAndLang: true, + ), + body: LayoutBuilder( + builder: (context, constraints) { + final maxW = constraints.maxWidth; + final contentW = maxW > 600 ? 600.0 : maxW; + + return Align( + alignment: Alignment.topCenter, + child: SizedBox( + width: contentW, + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + width: double.infinity, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + LocaleKeys.parkingSlotDetails.tr(context: context), + style: TextStyle( + fontSize: 16.f, + fontWeight: FontWeight.w600, + color: AppColors.textColor, + ), + ), + SizedBox(height: 16.h), + Wrap( + spacing: 4, + runSpacing: 4, + children: [ + AppCustomChipWidget( + labelText: LocaleKeys.slotNumber.tr(namedArgs: {'code': widget.model.qRParkingCode ?? '-'}, context: context), + ), + AppCustomChipWidget( + labelText: LocaleKeys.basement.tr(namedArgs: {'description': widget.model.floorDescription ?? '-'}, context: context), + ), + AppCustomChipWidget( + labelText: LocaleKeys.parkingDate.tr(namedArgs: {'date': _formatPrettyDate(widget.model.createdOn)}, context: context), + ), + AppCustomChipWidget( + labelText: LocaleKeys.parkedSince.tr(namedArgs: {'time': _formatPrettyTime(widget.model.createdOn)}, context: context), + ), + ], + ), + ], + ), + ), + ), + SizedBox(height: 24.h), + + SizedBox( + width: double.infinity, + height: 48.h, + child: CustomButton( + text: LocaleKeys.getDirections.tr(context: context), + onPressed: _openDirection, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 18, + fontWeight: FontWeight.bold, + borderRadius: 10, + ), + ), + + const Spacer(), + + SizedBox( + width: double.infinity, + height: 48.h, + child: CustomButton( + text: LocaleKeys.resetDirection.tr(context: context), + onPressed: _resetDirection, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 18.f, + fontWeight: FontWeight.bold, + borderRadius: 10.r, + ), + ), + ], + ), + ), + ), + ); + }, + ), + ); + } +} + + + + diff --git a/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart b/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart index 0bedbe2..5a34034 100644 --- a/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart +++ b/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart @@ -118,7 +118,7 @@ class PrescriptionDeliveryOrderSummaryPage extends StatelessWidget { child: CustomButton( text: LocaleKeys.submit.tr(context: context), onPressed: () async { - LoaderBottomSheet.showLoader(loadingText: "Submitting your request..."); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context)); await prescriptionsViewModel.submitPrescriptionDeliveryRequest( latitude: prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lat.toString(), longitude: prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lng.toString(), @@ -129,7 +129,7 @@ class PrescriptionDeliveryOrderSummaryPage extends StatelessWidget { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getSuccessWidget(loadingText: "Request sent successfully.".needTranslation), + child: Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)), callBackFunc: () { Navigator.of(context).pop(); }, diff --git a/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart b/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart index e2ce865..7760fd2 100644 --- a/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart +++ b/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart @@ -88,7 +88,7 @@ class PrescriptionDeliveryOrdersListPage extends StatelessWidget { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "You don't have any prescription orders yet.".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noPrescriptionOrdersYet.tr(context: context)); }, ).paddingSymmetrical(24.h, 0.h), ], diff --git a/lib/presentation/prescriptions/prescription_detail_page.dart b/lib/presentation/prescriptions/prescription_detail_page.dart index 1216c61..796bfdd 100644 --- a/lib/presentation/prescriptions/prescription_detail_page.dart +++ b/lib/presentation/prescriptions/prescription_detail_page.dart @@ -62,7 +62,7 @@ class _PrescriptionDetailPageState extends State { child: CollapsingListView( title: LocaleKeys.prescriptions.tr(context: context), instructions: () async { - LoaderBottomSheet.showLoader(loadingText: "Fetching prescription PDF, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionPDFPleaseWait.tr(context: context)); await prescriptionsViewModel.getPrescriptionInstructionsPDF(widget.prescriptionsResponseModel, onSuccess: (val) { LoaderBottomSheet.hideLoader(); if (prescriptionsViewModel.prescriptionInstructionsPDFLink.isNotEmpty) { @@ -71,7 +71,7 @@ class _PrescriptionDetailPageState extends State { } else { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Unable to fetch PDF".needTranslation), + child: Utils.getErrorWidget(loadingText: "Unable to fetch PDF"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, @@ -136,7 +136,7 @@ class _PrescriptionDetailPageState extends State { AppCustomChipWidget( icon: AppAssets.rating_icon, iconColor: AppColors.ratingColorYellow, - labelText: "Rating: ${widget.prescriptionsResponseModel.decimalDoctorRate}".needTranslation, + labelText: LocaleKeys.ratingValue.tr(namedArgs: {'rating': widget.prescriptionsResponseModel.decimalDoctorRate.toString()}, context: context), ), AppCustomChipWidget( labelText: widget.prescriptionsResponseModel.name!, @@ -145,10 +145,10 @@ class _PrescriptionDetailPageState extends State { ), SizedBox(height: 16.h), CustomButton( - text: "Download Prescription".needTranslation, + text: LocaleKeys.downloadPrescription.tr(context: context), onPressed: () async { - LoaderBottomSheet.showLoader(loadingText: "Fetching prescription PDF, Please wait...".needTranslation); - await prescriptionVM.getPrescriptionPDFBase64(widget.prescriptionsResponseModel).then((val) async { + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionPDFPleaseWait.tr(context: context)); + await prescriptionVM.getPrescriptionPDFBase64(widget.prescriptionsResponseModel, onSuccess: (value) async { LoaderBottomSheet.hideLoader(); if (prescriptionVM.prescriptionPDFBase64Data.isNotEmpty) { String path = await Utils.createFileFromString(prescriptionVM.prescriptionPDFBase64Data, "pdf"); @@ -157,13 +157,22 @@ class _PrescriptionDetailPageState extends State { } catch (ex) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation), + child: Utils.getErrorWidget(loadingText: "Cannot open file"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, ); } } + }, onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); }); }, backgroundColor: AppColors.successColor.withValues(alpha: 0.15), @@ -221,7 +230,7 @@ class _PrescriptionDetailPageState extends State { : LocaleKeys.prescriptionDeliveryError.tr(context: context), onPressed: () async { if (widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported!) { - LoaderBottomSheet.showLoader(loadingText: "Fetching prescription details...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionDetails.tr(context: context)); await prescriptionsViewModel.getPrescriptionDetails(widget.prescriptionsResponseModel, onSuccess: (val) { LoaderBottomSheet.hideLoader(); prescriptionsViewModel.initiatePrescriptionDelivery(); diff --git a/lib/presentation/prescriptions/prescription_item_view.dart b/lib/presentation/prescriptions/prescription_item_view.dart index a2a3e7f..a41b53f 100644 --- a/lib/presentation/prescriptions/prescription_item_view.dart +++ b/lib/presentation/prescriptions/prescription_item_view.dart @@ -10,6 +10,7 @@ import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_mo import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; @@ -56,74 +57,18 @@ class PrescriptionItemView extends StatelessWidget { spacing: 6.h, runSpacing: 6.h, children: [ - Row( - mainAxisSize: MainAxisSize.min, - children: [ - CustomButton( - text: "${LocaleKeys.route.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].route}", - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 30.h, - ).toShimmer2(isShow: isLoading), - ], - ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - CustomButton( - text: "${LocaleKeys.frequency.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].frequency}", - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 30.h, - ).toShimmer2(isShow: isLoading), - ], - ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - CustomButton( - text: "${LocaleKeys.dailyDoses.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].doseDailyQuantity}", - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 30.h, - ).toShimmer2(isShow: isLoading), - ], - ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - CustomButton( - text: "${LocaleKeys.days.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].days}", - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 30.h, - ).toShimmer2(isShow: isLoading), - ], - ), + AppCustomChipWidget( + labelText: "${LocaleKeys.route.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].route}", + ).toShimmer2(isShow: isLoading), + AppCustomChipWidget( + labelText: "${LocaleKeys.frequency.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].frequency}", + ).toShimmer2(isShow: isLoading), + AppCustomChipWidget( + labelText: "${LocaleKeys.dailyDoses.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].doseDailyQuantity}", + ).toShimmer2(isShow: isLoading), + AppCustomChipWidget( + labelText: "${LocaleKeys.days.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].days}", + ).toShimmer2(isShow: isLoading), ], ).paddingSymmetrical(16.h, 0.h), SizedBox(height: 8.h), diff --git a/lib/presentation/prescriptions/prescription_reminder_view.dart b/lib/presentation/prescriptions/prescription_reminder_view.dart index 2f1154f..aab587d 100644 --- a/lib/presentation/prescriptions/prescription_reminder_view.dart +++ b/lib/presentation/prescriptions/prescription_reminder_view.dart @@ -54,7 +54,7 @@ class _PrescriptionReminderViewState extends State { ), child: RadioListTile( title: Text( - "${_options[index]} minutes before".needTranslation, + "${_options[index]} ${LocaleKeys.minute.tr(context: context)}", style: TextStyle( fontSize: 16.h, fontWeight: FontWeight.w500, diff --git a/lib/presentation/prescriptions/prescriptions_list_page.dart b/lib/presentation/prescriptions/prescriptions_list_page.dart index 8b60159..c2d97f8 100644 --- a/lib/presentation/prescriptions/prescriptions_list_page.dart +++ b/lib/presentation/prescriptions/prescriptions_list_page.dart @@ -19,6 +19,7 @@ import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_detail_page.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; @@ -207,32 +208,16 @@ class _PrescriptionsListPageState extends State { ], ), SizedBox(height: 8.h), - Row( + Wrap( + direction: Axis.horizontal, + spacing: 6.h, + runSpacing: 6.h, children: [ - CustomButton( - text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(prescription.appointmentDate), false), - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 24.h, + AppCustomChipWidget( + labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(prescription.appointmentDate), false), ), - SizedBox(width: 8.h), - CustomButton( - text: model.isSortByClinic ? prescription.name! : prescription.clinicDescription!, - onPressed: () {}, - backgroundColor: AppColors.greyColor, - borderColor: AppColors.greyColor, - textColor: AppColors.blackColor, - fontSize: 10, - fontWeight: FontWeight.w500, - borderRadius: 8, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 24.h, + AppCustomChipWidget( + labelText: model.isSortByClinic ? prescription.name! : prescription.clinicDescription!, ), ], ), @@ -247,7 +232,7 @@ class _PrescriptionsListPageState extends State { : LocaleKeys.prescriptionDeliveryError.tr(context: context), onPressed: () async { if (prescription.isHomeMedicineDeliverySupported!) { - LoaderBottomSheet.showLoader(loadingText: "Fetching prescription details...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionDetails.tr(context: context)); await prescriptionsViewModel.getPrescriptionDetails(prescriptionsViewModel.patientPrescriptionOrders[index], onSuccess: (val) { LoaderBottomSheet.hideLoader(); @@ -322,7 +307,7 @@ class _PrescriptionsListPageState extends State { ), ), ) - : Utils.getNoDataWidget(context, noDataText: "You don't have any prescriptions yet.".needTranslation); + : Utils.getNoDataWidget(context, noDataText: LocaleKeys.youDontHaveAnyPrescriptionsYet.tr(context: context)); }, ).paddingSymmetrical(24.h, 0.h), ], diff --git a/lib/presentation/profile_settings/profile_settings.dart b/lib/presentation/profile_settings/profile_settings.dart index e463ae7..a3c2667 100644 --- a/lib/presentation/profile_settings/profile_settings.dart +++ b/lib/presentation/profile_settings/profile_settings.dart @@ -13,6 +13,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/int_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart'; import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; import 'package:hmg_patient_app_new/features/insurance/insurance_view_model.dart'; import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart'; @@ -70,7 +71,7 @@ class ProfileSettingsState extends State { } // Compute and clamp using sensible bounds (uses .h extension) - final double minH = 210.h; + final double minH = 215.h; final double maxH = 380.h; final double computed = (shorter * multiplier); @@ -83,8 +84,10 @@ class ProfileSettingsState extends State { @override Widget build(BuildContext context) { return CollapsingListView( - title: "Profile & Settings".needTranslation, - logout: () {}, + title: LocaleKeys.profileAndSettings.tr(context: context), + logout: () { + context.read().logout(); + }, isClose: true, child: SingleChildScrollView( padding: EdgeInsets.only(top: 24.h, bottom: 24.h), @@ -114,8 +117,8 @@ class ProfileSettingsState extends State { onAddFamilyMemberPress: () { DialogService dialogService = getIt.get(); dialogService.showAddFamilyFileSheet( - label: "Add Family Member".needTranslation, - message: "Please fill the below field to add a new family member to your profile".needTranslation, + label: LocaleKeys.addFamilyMember.tr(context: context), + message: LocaleKeys.pleaseFillBelowFieldToAddNewFamilyMember.tr(context: context), onVerificationPress: () { medicalVm.addFamilyFile(otpTypeEnum: OTPTypeEnum.sms); }); @@ -149,8 +152,8 @@ class ProfileSettingsState extends State { crossAxisAlignment: CrossAxisAlignment.center, children: [ Utils.buildSvgWithAssets(icon: AppAssets.wallet, width: 40.w, height: 40.h), - "Habib Wallet".needTranslation.toText16(weight: FontWeight.w600, maxlines: 2).expanded, - Utils.buildSvgWithAssets(icon: AppAssets.arrow_forward), + LocaleKeys.habibWallet.tr(context: context).toText16(weight: FontWeight.w600, maxlines: 2).expanded, + Utils.buildSvgWithAssets(icon: getIt.get().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward), ], ), Spacer(), @@ -165,7 +168,7 @@ class ProfileSettingsState extends State { iconSize: 22.w, iconColor: AppColors.infoColor, textColor: AppColors.infoColor, - text: "Recharge".needTranslation, + text: LocaleKeys.recharge.tr(context: context), borderWidth: 0.w, fontWeight: FontWeight.w500, borderColor: Colors.transparent, @@ -183,66 +186,54 @@ class ProfileSettingsState extends State { ), ], ), - "Quick Actions" - .needTranslation - .toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1) - .paddingOnly(left: 24.w, right: 24.w), + LocaleKeys.quickActions.tr(context: context).toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w), Container( margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h, bottom: 24.h), padding: EdgeInsets.only(top: 4.h, bottom: 4.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: Column( children: [ - actionItem(AppAssets.language_change, "Language".needTranslation, () { - showCommonBottomSheetWithoutHeight(context, - title: "Application Language".needTranslation, child: AppLanguageChange(), callBackFunc: () {}, isFullScreen: false); - }, trailingLabel: Utils.appState.isArabic() ? "العربية".needTranslation : "English".needTranslation), + actionItem(AppAssets.language_change, LocaleKeys.language.tr(context: context), () { + showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.language.tr(context: context), child: AppLanguageChange(), callBackFunc: () {}, isFullScreen: false); + }, trailingLabel: Utils.appState.isArabic() ? "العربية" : "English"), 1.divider, - actionItem(AppAssets.accessibility, "Accessibility".needTranslation, () {}), + actionItem(AppAssets.bell, LocaleKeys.notificationsSettings.tr(context: context), () {}), 1.divider, - actionItem(AppAssets.bell, "Notifications Settings".needTranslation, () {}), - 1.divider, - actionItem(AppAssets.touch_face_id, "Touch ID / Face ID Services".needTranslation, () {}, switchValue: true), + actionItem(AppAssets.touch_face_id, LocaleKeys.touchIDFaceIDServices.tr(context: context), () {}, switchValue: true), ], ), ), - "Personal Information" - .needTranslation - .toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1) - .paddingOnly(left: 24.w, right: 24.w), + LocaleKeys.personalInformation.tr(context: context).toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w), Container( margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h, bottom: 24.h), padding: EdgeInsets.only(top: 4.h, bottom: 4.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: Column( children: [ - actionItem(AppAssets.email_transparent, "Update Email Address".needTranslation, () {}), - 1.divider, - actionItem(AppAssets.smart_phone_fill, "Phone Number".needTranslation, () {}), - 1.divider, - actionItem(AppAssets.my_address, "My Addresses".needTranslation, () {}), - 1.divider, - actionItem(AppAssets.emergency, "Emergency Contact".needTranslation, () {}), + actionItem(AppAssets.email_transparent, LocaleKeys.updateEmailAddress.tr(context: context), () {}), + // 1.divider, + // actionItem(AppAssets.smart_phone_fill, "Phone Number".needTranslation, () {}), + // 1.divider, + // actionItem(AppAssets.my_address, "My Addresses".needTranslation, () {}), + // 1.divider, + // actionItem(AppAssets.emergency, "Emergency Contact".needTranslation, () {}), ], ), ), - "Help & Support" - .needTranslation - .toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1) - .paddingOnly(left: 24.w, right: 24.w), + LocaleKeys.helpAndSupport.tr(context: context).toText18(weight: FontWeight.w600, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w), Container( margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h), padding: EdgeInsets.only(top: 4.h, bottom: 4.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: Column( children: [ - actionItem(AppAssets.call_fill, "Contact Us".needTranslation, () { + actionItem(AppAssets.call_fill, LocaleKeys.contactUs.tr(context: context), () { launchUrl(Uri.parse("tel://" + "+966 11 525 9999")); }, trailingLabel: "011 525 9999"), 1.divider, - actionItem(AppAssets.permission, "Permissions".needTranslation, () {}, trailingLabel: "Location, Camera"), + actionItem(AppAssets.permission, LocaleKeys.permissions.tr(context: context), () {}, trailingLabel: "Location, Camera"), 1.divider, - actionItem(AppAssets.rate, "Rate Our App".needTranslation, () { + actionItem(AppAssets.rate, LocaleKeys.rateApp.tr(context: context), () { if (Platform.isAndroid) { Utils.openWebView( url: 'https://play.google.com/store/apps/details?id=com.ejada.hmg', @@ -254,13 +245,13 @@ class ProfileSettingsState extends State { } }, isExternalLink: true), 1.divider, - actionItem(AppAssets.privacy_terms, "Privacy Policy".needTranslation, () { + actionItem(AppAssets.privacy_terms, LocaleKeys.privacyPolicy.tr(context: context), () { Utils.openWebView( url: 'https://hmg.com/en/Pages/Privacy.aspx', ); }, isExternalLink: true), 1.divider, - actionItem(AppAssets.privacy_terms, "Terms & Conditions".needTranslation, () { + actionItem(AppAssets.privacy_terms, LocaleKeys.termsConditoins.tr(context: context), () { Utils.openWebView( url: 'https://hmg.com/en/Pages/Terms.aspx', ); @@ -271,7 +262,7 @@ class ProfileSettingsState extends State { CustomButton( height: 56.h, icon: AppAssets.minus, - text: "Deactivate account".needTranslation, + text: LocaleKeys.deactivateAccount.tr(context: context), onPressed: () {}, ).paddingAll(24.w), ], @@ -290,8 +281,7 @@ class ProfileSettingsState extends State { children: [ Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.greyTextColor), label.toText14(weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded, - if (trailingLabel.isNotEmpty) - trailingLabel.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1), + if (trailingLabel.isNotEmpty) trailingLabel.toText14(color: AppColors.greyTextColor, weight: FontWeight.w500, textOverflow: TextOverflow.ellipsis, maxlines: 1), switchValue != null ? Switch( value: switchValue, @@ -355,7 +345,8 @@ class FamilyCardWidget extends StatelessWidget { ), ], ).expanded, - Icon(Icons.qr_code, size: 56.h) + // Icon(Icons.qr_code, size: 56.h) + Image.network("https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${profile.responseId.toString()}", fit: BoxFit.contain, height: 56.h, width: 56.w) ], ), SizedBox(height: 4.h), @@ -366,7 +357,7 @@ class FamilyCardWidget extends StatelessWidget { runSpacing: 4.h, children: [ AppCustomChipWidget( - labelText: "${profile.age} Years Old".needTranslation, + labelText: LocaleKeys.ageYearsOld.tr(namedArgs: {'age': profile.age.toString(), 'yearsOld': LocaleKeys.yearsOld.tr(context: context)}), ), isActive && appState.getAuthenticatedUser()!.bloodGroup != null ? AppCustomChipWidget( @@ -399,17 +390,17 @@ class FamilyCardWidget extends StatelessWidget { if (isLoading) { icon = AppAssets.cancel_circle_icon; - labelText = "Insurance".needTranslation; + labelText = LocaleKeys.insurance.tr(context: context); iconColor = AppColors.primaryRedColor; backgroundColor = AppColors.primaryRedColor; } else if (isExpired) { icon = AppAssets.cancel_circle_icon; - labelText = "Insurance Expired".needTranslation; + labelText = LocaleKeys.insuranceExpired.tr(context: context); iconColor = AppColors.primaryRedColor; backgroundColor = AppColors.primaryRedColor.withValues(alpha: 0.15); } else { icon = AppAssets.insurance_active_icon; - labelText = "Insurance Active".needTranslation; + labelText = LocaleKeys.insuranceActive.tr(context: context); iconColor = AppColors.successColor; backgroundColor = AppColors.successColor.withValues(alpha: 0.15); } @@ -429,8 +420,8 @@ class FamilyCardWidget extends StatelessWidget { ), ), ], - ).paddingOnly(top: 16.h, right: 16.w, left: 16.w, bottom: 12.h), - 1.divider, + ).paddingOnly(top: 16.h, right: 16.w, left: 16.w, bottom: 0.h), + 1.divider.paddingSymmetrical(16.w, 0.h), _buildActionButton(appState), ], ), @@ -454,13 +445,13 @@ class FamilyCardWidget extends StatelessWidget { return CustomButton( icon: canSwitch ? AppAssets.switch_user : AppAssets.add_family, - text: canSwitch ? "Switch Family File".needTranslation : "Add a new family member".needTranslation, + text: canSwitch ? LocaleKeys.switchAccount.tr() : LocaleKeys.addANewFamilyMember.tr(), onPressed: canSwitch ? () => onFamilySwitchPress(profile) : onAddFamilyMemberPress, backgroundColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor, borderColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor, textColor: canSwitch ? AppColors.primaryRedColor : AppColors.whiteColor, iconColor: canSwitch ? AppColors.primaryRedColor : AppColors.whiteColor, - height: isFoldable ? 50.h : 40.h, + height: isFoldable ? 50.h : 45.h, fontSize: 14.f, ).paddingOnly(top: 12.h, right: 16.w, left: 16.w, bottom: 16.h); } @@ -470,7 +461,7 @@ class FamilyCardWidget extends StatelessWidget { return CustomButton( icon: AppAssets.switch_user, - text: canSwitchBack ? "Switch Back To Family File".needTranslation : "Switch".needTranslation, + text: canSwitchBack ? LocaleKeys.switchBackFamilyFile.tr() : LocaleKeys.switchAccount.tr(), backgroundColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200, borderColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200, textColor: canSwitchBack ? AppColors.whiteColor : AppColors.greyTextColor, diff --git a/lib/presentation/profile_settings/widgets/family_card_widget.dart b/lib/presentation/profile_settings/widgets/family_card_widget.dart index eaee4c0..b21c52d 100644 --- a/lib/presentation/profile_settings/widgets/family_card_widget.dart +++ b/lib/presentation/profile_settings/widgets/family_card_widget.dart @@ -73,7 +73,7 @@ class FamilyCardWidget extends StatelessWidget { runSpacing: 4.h, children: [ AppCustomChipWidget( - labelText: "${profile.age} Years Old".needTranslation, + labelText: "${profile.age} ${LocaleKeys.yearsOld.tr(context: context)}", ), isActive && appState.getAuthenticatedUser()!.bloodGroup != null ? AppCustomChipWidget( @@ -106,17 +106,17 @@ class FamilyCardWidget extends StatelessWidget { if (isLoading) { icon = AppAssets.cancel_circle_icon; - labelText = "Insurance".needTranslation; + labelText = LocaleKeys.insurance.tr(context: context); iconColor = AppColors.primaryRedColor; backgroundColor = AppColors.primaryRedColor; } else if (isExpired) { icon = AppAssets.cancel_circle_icon; - labelText = "Insurance Expired".needTranslation; + labelText = LocaleKeys.insuranceExpired.tr(context: context); iconColor = AppColors.primaryRedColor; backgroundColor = AppColors.primaryRedColor.withValues(alpha: 0.15); } else { icon = AppAssets.insurance_active_icon; - labelText = "Insurance Active".needTranslation; + labelText = LocaleKeys.insuranceActive.tr(context: context); iconColor = AppColors.successColor; backgroundColor = AppColors.successColor.withValues(alpha: 0.15); } @@ -161,7 +161,7 @@ class FamilyCardWidget extends StatelessWidget { return CustomButton( icon: canSwitch ? AppAssets.switch_user : AppAssets.add_family, - text: canSwitch ? "Switch Family File".needTranslation : "Add a new family member".needTranslation, + text: canSwitch ? LocaleKeys.switchAccount.tr() : LocaleKeys.addANewFamilyMember.tr(), onPressed: canSwitch ? () => onFamilySwitchPress(profile) : onAddFamilyMemberPress, backgroundColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor, borderColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor, @@ -177,7 +177,7 @@ class FamilyCardWidget extends StatelessWidget { return CustomButton( icon: AppAssets.switch_user, - text: canSwitchBack ? "Switch Back To Family File".needTranslation : "Switch".needTranslation, + text: canSwitchBack ? LocaleKeys.switchBackFamilyFile.tr() : LocaleKeys.switchLogin.tr(), backgroundColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200, borderColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200, textColor: canSwitchBack ? AppColors.whiteColor : AppColors.greyTextColor, diff --git a/lib/presentation/radiology/radiology_orders_page.dart b/lib/presentation/radiology/radiology_orders_page.dart index fb153ea..f9b94e2 100644 --- a/lib/presentation/radiology/radiology_orders_page.dart +++ b/lib/presentation/radiology/radiology_orders_page.dart @@ -35,6 +35,7 @@ class _RadiologyOrdersPageState extends State { late RadiologyViewModel radiologyViewModel; String selectedFilterText = ''; int? expandedIndex; + // Scroll controller to ensure expanded group is visible late ScrollController _scrollController; final Map _groupKeys = {}; @@ -58,128 +59,128 @@ class _RadiologyOrdersPageState extends State { Widget build(BuildContext context) { radiologyViewModel = Provider.of(context); return Scaffold( - backgroundColor: AppColors.bgScaffoldColor, - body: CollapsingListView( - title: LocaleKeys.radiology.tr(context: context), - search: () async { - final lavVM = Provider.of(context, listen: false); - if (lavVM.isLabOrdersLoading) { - return; - } else { - String? value = await Navigator.of(context).push( - CustomPageRoute( - page: SearchRadiologyContent(radiologySuggestionsList: radiologyViewModel.radiologySuggestions), - fullScreenDialog: true, - direction: AxisDirection.down, - ), - ); - if (value != null) { - selectedFilterText = value; - radiologyViewModel.filterRadiologyReports(value); - } + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: LocaleKeys.radiology.tr(context: context), + search: () async { + final lavVM = Provider.of(context, listen: false); + if (lavVM.isLabOrdersLoading) { + return; + } else { + String? value = await Navigator.of(context).push( + CustomPageRoute( + page: SearchRadiologyContent(radiologySuggestionsList: radiologyViewModel.radiologySuggestions), + fullScreenDialog: true, + direction: AxisDirection.down, + ), + ); + if (value != null) { + selectedFilterText = value; + radiologyViewModel.filterRadiologyReports(value); } - }, - child: SingleChildScrollView( - controller: _scrollController, - physics: NeverScrollableScrollPhysics(), - child: Consumer( - builder: (context, model, child) { - // Build grouping lists if we have data and none constructed yet - if (!model.isRadiologyOrdersLoading && model.patientRadiologyOrders.isNotEmpty && model.patientRadiologyOrdersViewList.isEmpty) { - final clinicMap = >{}; - final hospitalMap = >{}; - for (var order in model.patientRadiologyOrders) { - final clinicKey = (order.clinicDescription ?? 'Unknown').trim(); - clinicMap.putIfAbsent(clinicKey, () => []).add(order); - final hospitalKey = (order.projectName ?? order.projectID ?? 'Unknown').toString().trim(); - hospitalMap.putIfAbsent(hospitalKey, () => []).add(order); - } - model.patientRadiologyOrdersByClinic = clinicMap.values.toList(); - model.patientRadiologyOrdersByHospital = hospitalMap.values.toList(); - model.patientRadiologyOrdersViewList = model.isSortByClinic ? model.patientRadiologyOrdersByClinic : model.patientRadiologyOrdersByHospital; + } + }, + child: SingleChildScrollView( + controller: _scrollController, + physics: NeverScrollableScrollPhysics(), + child: Consumer( + builder: (context, model, child) { + // Build grouping lists if we have data and none constructed yet + if (!model.isRadiologyOrdersLoading && model.patientRadiologyOrders.isNotEmpty && model.patientRadiologyOrdersViewList.isEmpty) { + final clinicMap = >{}; + final hospitalMap = >{}; + for (var order in model.patientRadiologyOrders) { + final clinicKey = (order.clinicDescription ?? 'Unknown').trim(); + clinicMap.putIfAbsent(clinicKey, () => []).add(order); + final hospitalKey = (order.projectName ?? order.projectID ?? 'Unknown').toString().trim(); + hospitalMap.putIfAbsent(hospitalKey, () => []).add(order); } + model.patientRadiologyOrdersByClinic = clinicMap.values.toList(); + model.patientRadiologyOrdersByHospital = hospitalMap.values.toList(); + model.patientRadiologyOrdersViewList = model.isSortByClinic ? model.patientRadiologyOrdersByClinic : model.patientRadiologyOrdersByHospital; + } - return Padding( - padding: EdgeInsets.symmetric(horizontal: 24.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Clinic / Hospital toggle - SizedBox(height: 16.h), - Row( - children: [ - CustomButton( - text: LocaleKeys.byClinic.tr(context: context), - onPressed: () { - model.setIsSortByClinic(true); - }, - backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, - borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), - textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, - fontSize: 12, - fontWeight: FontWeight.w500, - borderRadius: 10, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - ), - SizedBox(width: 8.h), - CustomButton( - text: LocaleKeys.byHospital.tr(context: context), - onPressed: () { - model.setIsSortByClinic(false); - }, - backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, - borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, - textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, - fontSize: 12, - fontWeight: FontWeight.w500, - borderRadius: 10, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - ), - ], - ), + return Padding( + padding: EdgeInsets.symmetric(horizontal: 24.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Clinic / Hospital toggle + SizedBox(height: 16.h), + Row( + children: [ + CustomButton( + text: LocaleKeys.byClinic.tr(context: context), + onPressed: () { + model.setIsSortByClinic(true); + }, + backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, + borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2), + textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + SizedBox(width: 8.h), + CustomButton( + text: LocaleKeys.byHospital.tr(context: context), + onPressed: () { + model.setIsSortByClinic(false); + }, + backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, + borderColor: model.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor, + textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor, + fontSize: 12, + fontWeight: FontWeight.w500, + borderRadius: 10, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + ), + ], + ), - SizedBox(height: 8.h), - selectedFilterText.isNotEmpty - ? AppCustomChipWidget( - padding: EdgeInsets.symmetric(horizontal: 5.h), - labelText: selectedFilterText, - deleteIcon: 'assets/images/svg/cross_circle.svg', - backgroundColor: AppColors.alertColor, - textColor: AppColors.whiteColor, - deleteIconColor: AppColors.whiteColor, - deleteIconHasColor: true, - onDeleteTap: () { - setState(() { - selectedFilterText = ''; - model.filterRadiologyReports(''); - }); - }, - // chipType: ChipTypeEnum.alert, - // isSelected: true, - ) - : SizedBox(), + SizedBox(height: 8.h), + selectedFilterText.isNotEmpty + ? AppCustomChipWidget( + padding: EdgeInsets.symmetric(horizontal: 5.h), + labelText: selectedFilterText, + deleteIcon: 'assets/images/svg/cross_circle.svg', + backgroundColor: AppColors.alertColor, + textColor: AppColors.whiteColor, + deleteIconColor: AppColors.whiteColor, + deleteIconHasColor: true, + onDeleteTap: () { + setState(() { + selectedFilterText = ''; + model.filterRadiologyReports(''); + }); + }, + // chipType: ChipTypeEnum.alert, + // isSelected: true, + ) + : SizedBox(), - // Grouped view when available - Builder(builder: (ctx) { - if (model.isRadiologyOrdersLoading) { - return ListView.builder( - shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), - padding: EdgeInsets.zero, - itemCount: 5, - itemBuilder: (context, index) => LabResultItemView( - onTap: () {}, - labOrder: null, - index: index, - isLoading: true, - ), - ); - } + // Grouped view when available + Builder(builder: (ctx) { + if (model.isRadiologyOrdersLoading) { + return ListView.builder( + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + padding: EdgeInsets.zero, + itemCount: 5, + itemBuilder: (context, index) => LabResultItemView( + onTap: () {}, + labOrder: null, + index: index, + isLoading: true, + ), + ); + } if (model.patientRadiologyOrdersViewList.isEmpty) { - return Utils.getNoDataWidget(ctx, noDataText: "You don't have any radiology results yet.".needTranslation); + return Utils.getNoDataWidget(ctx, noDataText: LocaleKeys.youDontHaveRadiologyOrders.tr(context: context)); } return ListView.builder( @@ -239,7 +240,7 @@ class _RadiologyOrdersPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - AppCustomChipWidget(labelText: "${group.length} ${'results'.needTranslation}"), + AppCustomChipWidget(labelText: "${group.length} ${LocaleKeys.results.tr(context: context)}"), Icon(isExpanded ? Icons.expand_less : Icons.expand_more), ], ), @@ -323,7 +324,7 @@ class _RadiologyOrdersPageState extends State { icon: AppAssets.view_report_icon, iconColor: AppColors.primaryRedColor, iconSize: 16.h, - text: "View Results".needTranslation, + text: LocaleKeys.viewResults.tr(context: context), onPressed: () { model.navigationService.push( CustomPageRoute( diff --git a/lib/presentation/radiology/radiology_result_page.dart b/lib/presentation/radiology/radiology_result_page.dart index 1fc2d9f..2328d0e 100644 --- a/lib/presentation/radiology/radiology_result_page.dart +++ b/lib/presentation/radiology/radiology_result_page.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; @@ -10,6 +11,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/radiology/models/resp_models/patient_radiology_response_model.dart'; import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -49,7 +51,7 @@ class _RadiologyResultPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Radiology Result".needTranslation, + title: LocaleKeys.radiologyResult.tr(context: context), child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.h), @@ -72,13 +74,13 @@ class _RadiologyResultPageState extends State { widget.patientRadiologyResponseModel.reportData!.trim().toText12(isBold: true, color: AppColors.textColorLight), SizedBox(height: 16.h), CustomButton( - text: "View Radiology Image".needTranslation, + text: LocaleKeys.viewRadiologyImage.tr(context: context), onPressed: () async { if (radiologyViewModel.radiologyImageURL.isNotEmpty) { Uri uri = Uri.parse(radiologyViewModel.radiologyImageURL); launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: ""); } else { - Utils.showToast("Radiology image not available".needTranslation); + Utils.showToast("Radiology image not available"); } }, backgroundColor: AppColors.primaryRedColor, @@ -111,7 +113,7 @@ class _RadiologyResultPageState extends State { hasShadow: true, ), child: CustomButton( - text: "Download report".needTranslation, + text: LocaleKeys.downloadReport.tr(context: context), onPressed: () async { LoaderBottomSheet.showLoader(); await radiologyViewModel.getRadiologyPDF(patientRadiologyResponseModel: widget.patientRadiologyResponseModel, authenticatedUser: _appState.getAuthenticatedUser()!, onError: (err) { @@ -132,7 +134,7 @@ class _RadiologyResultPageState extends State { } catch (ex) { showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation), + child: Utils.getErrorWidget(loadingText: "Cannot open file"), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/rate_appointment/rate_appointment_clinic.dart b/lib/presentation/rate_appointment/rate_appointment_clinic.dart index 5fb1fa3..e7e29f6 100644 --- a/lib/presentation/rate_appointment/rate_appointment_clinic.dart +++ b/lib/presentation/rate_appointment/rate_appointment_clinic.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -5,6 +6,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/rate_appointment/widget/doctor_row.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -77,9 +79,7 @@ class _RateAppointmentClinicState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - - "Rate Clinic".needTranslation.toText16(isBold: true), - + LocaleKeys.rateClinic.tr(context: context).toText16(isBold: true), SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.center, @@ -147,13 +147,13 @@ class _RateAppointmentClinicState extends State { children: [ Expanded( child: CustomButton( - text: "Back".needTranslation, + text: LocaleKeys.back.tr(context: context), backgroundColor: Color(0xffFEE9EA), borderColor: Color(0xffFEE9EA), textColor: Color(0xffED1C2B), onPressed: () { - appointmentRatingViewModel!.setTitle("Rate Doctor".needTranslation); - appointmentRatingViewModel!.setSubTitle("How was your last visit with doctor?".needTranslation); + appointmentRatingViewModel!.setTitle(LocaleKeys.rateDoctor.tr(context: context)); + appointmentRatingViewModel!.setSubTitle(LocaleKeys.howWasYourLastVisitWithDoctor.tr(context: context)); appointmentRatingViewModel!.setClinicOrDoctor(false); setState(() { @@ -164,7 +164,7 @@ class _RateAppointmentClinicState extends State { SizedBox(width: 10), Expanded( child: CustomButton( - text: "Submit".needTranslation, + text: LocaleKeys.submit.tr(context: context), onPressed: () { submitRating(); diff --git a/lib/presentation/rate_appointment/rate_appointment_doctor.dart b/lib/presentation/rate_appointment/rate_appointment_doctor.dart index ac79744..b9a6c58 100644 --- a/lib/presentation/rate_appointment/rate_appointment_doctor.dart +++ b/lib/presentation/rate_appointment/rate_appointment_doctor.dart @@ -1,9 +1,11 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_view_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/rate_appointment/rate_appointment_clinic.dart'; import 'package:hmg_patient_app_new/presentation/rate_appointment/widget/doctor_row.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -88,9 +90,7 @@ class _RateAppointmentDoctorState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - - "Please rate the doctor".needTranslation.toText16(isBold: true), - + "Please rate the doctor".toText16(isBold: true), SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.center, @@ -142,7 +142,7 @@ class _RateAppointmentDoctorState extends State { maxLines: 4, decoration: InputDecoration.collapsed( - hintText: "Notes".needTranslation, + hintText: LocaleKeys.notes.tr(context: context), hintStyle: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, @@ -172,7 +172,7 @@ class _RateAppointmentDoctorState extends State { children: [ Expanded( child: CustomButton( - text: "Later".needTranslation, + text: "Later", backgroundColor: Color(0xffFEE9EA), borderColor: Color(0xffFEE9EA), textColor: Color(0xffED1C2B), @@ -184,11 +184,11 @@ class _RateAppointmentDoctorState extends State { SizedBox(width: 10), Expanded( child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () { // Set up clinic rating and show clinic rating view - appointmentRatingViewModel!.setTitle("Rate Clinic".needTranslation); - appointmentRatingViewModel!.setSubTitle("How was your appointment?".needTranslation); + appointmentRatingViewModel!.setTitle(LocaleKeys.rateDoctor.tr(context: context),); + appointmentRatingViewModel!.setSubTitle(LocaleKeys.howWasYourLastVisitWithDoctor.tr(context: context),); appointmentRatingViewModel!.setClinicOrDoctor(true); setState(() {}); diff --git a/lib/presentation/smartwatches/smartwatch_home_page.dart b/lib/presentation/smartwatches/smartwatch_home_page.dart new file mode 100644 index 0000000..8fd7909 --- /dev/null +++ b/lib/presentation/smartwatches/smartwatch_home_page.dart @@ -0,0 +1,180 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/smartwatch_health_data/health_provider.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/smartwatches/widgets/supported_watches_list.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:provider/provider.dart'; + +class SmartwatchHomePage extends StatelessWidget { + const SmartwatchHomePage({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: LocaleKeys.smartWatches.tr(), + bottomChild: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: CustomButton( + text: LocaleKeys.supportedSmartWatches.tr(context: context), + onPressed: () { + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.supportedSmartWatches.tr(context: context), + context, + child: SupportedWatchesList(), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }, + backgroundColor: AppColors.infoColor.withAlpha(40), + borderColor: AppColors.infoColor.withAlpha(0), + textColor: AppColors.infoColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 50.h, + icon: AppAssets.ask_doctor_icon, + iconColor: AppColors.infoColor, + iconSize: 18.h, + ).paddingSymmetrical(24.w, 30.h), + ), + child: SingleChildScrollView( + child: Column( + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h), + child: GridView( + padding: EdgeInsets.zero, + shrinkWrap: true, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 16.h, + mainAxisSpacing: 16.w, + mainAxisExtent: 240.h, + ), + children: [ + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: Column( + children: [ + Image.asset("assets/images/png/smartwatches/apple-watch-5.jpg", width: 136.w, height: 136.h).paddingSymmetrical(24.w, 8.h), + "Apple Watch".needTranslation.toText16(isBold: true), + CustomButton( + text: LocaleKeys.select.tr(context: context), + onPressed: () { + context.read().setSelectedWatchType("apple", "assets/images/png/smartwatches/apple-watch-5.jpg"); + }, + backgroundColor: AppColors.primaryRedColor.withAlpha(40), + borderColor: AppColors.primaryRedColor.withAlpha(0), + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 40.h, + ).paddingSymmetrical(16.w, 12.h), + ], + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: Column( + children: [ + Image.asset("assets/images/png/smartwatches/galaxy_watch_8_classic.jpeg", fit: BoxFit.contain, width: 136.w, height: 136.h).paddingSymmetrical(24.w, 8.h), + "Samsung Watch".needTranslation.toText16(isBold: true), + CustomButton( + text: LocaleKeys.select.tr(context: context), + onPressed: () { + context.read().setSelectedWatchType("samsung", "assets/images/png/smartwatches/galaxy_watch_8_classic.jpeg"); + }, + backgroundColor: AppColors.primaryRedColor.withAlpha(40), + borderColor: AppColors.primaryRedColor.withAlpha(0), + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 40.h, + ).paddingSymmetrical(16.w, 12.h), + ], + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: Column( + children: [ + Image.asset("assets/images/png/smartwatches/Huawei_Watch.png", width: 136.w, height: 136.h).paddingSymmetrical(24.w, 8.h), + "Huawei Watch".needTranslation.toText16(isBold: true), + CustomButton( + text: LocaleKeys.select.tr(context: context), + onPressed: () { + context.read().setSelectedWatchType("huawei", "assets/images/png/smartwatches/Huawei_Watch.png"); + }, + backgroundColor: AppColors.primaryRedColor.withAlpha(40), + borderColor: AppColors.primaryRedColor.withAlpha(0), + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 40.h, + ).paddingSymmetrical(16.w, 12.h), + ], + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + ), + child: Column( + children: [ + Image.asset("assets/images/png/smartwatches/Whoop_Watch.png", width: 136.w, height: 136.h).paddingSymmetrical(24.w, 8.h), + "Whoop Watch".needTranslation.toText16(isBold: true), + CustomButton( + text: LocaleKeys.select.tr(context: context), + onPressed: () { + context.read().setSelectedWatchType("whoop", "assets/images/png/smartwatches/Whoop_Watch.png"); + }, + backgroundColor: AppColors.primaryRedColor.withAlpha(40), + borderColor: AppColors.primaryRedColor.withAlpha(0), + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 40.h, + ).paddingSymmetrical(16.w, 12.h), + ], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/smartwatches/smartwatch_instructions_page.dart b/lib/presentation/smartwatches/smartwatch_instructions_page.dart index 7f17f5a..48683d5 100644 --- a/lib/presentation/smartwatches/smartwatch_instructions_page.dart +++ b/lib/presentation/smartwatches/smartwatch_instructions_page.dart @@ -1,19 +1,12 @@ -import 'dart:io'; - import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:health/health.dart'; -import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; -import 'package:hmg_patient_app_new/presentation/smartwatches/health_dashboard/health_dashboard.dart'; -import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; -import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; -import 'package:url_launcher/url_launcher.dart'; class SmartwatchInstructionsPage extends StatelessWidget { const SmartwatchInstructionsPage({super.key}); @@ -22,445 +15,28 @@ class SmartwatchInstructionsPage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, - body: CollapsingListView( - title: LocaleKeys.smartWatches.tr(), - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 24.h), - child: SingleChildScrollView( - child: Platform.isIOS ? getIOSInstructionsUI(context) : getAndroidInstructionsUI(context), - ), - ), - ), - ); - } - - Widget getAndroidInstructionsUI(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Supported Smart Watches".needTranslation.toText20(isBold: true), - SizedBox(height: 16.h), - Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_watch_ultra.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: SizedBox( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Watch Ultra", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_watch_8_classic.jpeg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: SizedBox( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Watch 8 Classic", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], - ), - Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_watch_8.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Watch 8", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_watch_7_classic.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: SizedBox( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Watch 7 Classic", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], - ), - ), - Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_watch_7.webp", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: SizedBox( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Watch 7", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/galaxy_fit_3.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: SizedBox( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Galaxy Fit3", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], - ), - ), - SizedBox(height: 12), - "Please make sure that your Samsung Watch is connected to your Phone, is actively synced & updated.".needTranslation.toText14(isBold: true), - SizedBox(height: 12), - "Before syncing data, please make sure that you have followed the instructions properly.".needTranslation.toText14(isBold: true), - SizedBox(height: 12), - InkWell( - onTap: () { - showInstructionsDialog(context); - }, - child: "View watch instructions".needTranslation.toText12(isBold: true, color: AppColors.textColor, isUnderLine: true)), - SizedBox( - height: 130.h, - ), - CustomButton( - text: LocaleKeys.confirm.tr(context: context), - onPressed: () async { - await Health().getHealthConnectSdkStatus().then((val) { - print('Health Connect SDK Status: $val'); - if (val == HealthConnectSdkStatus.sdkAvailable) { - Navigator.of(context).push( - CustomPageRoute( - page: HealthDashboard(), - ), - ); - } else { - getIt.get().showErrorBottomSheet( - message: "Seems like you do not have Health Connect App installed. Please install it from the Play Store to sync your health data.".needTranslation, - onOkPressed: () { - Navigator.pop(context); - Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata"); - launchUrl(uri, mode: LaunchMode.externalApplication); - }); - return; - } - }); - }, - backgroundColor: AppColors.primaryRedColor, - borderColor: AppColors.primaryRedColor, - textColor: AppColors.whiteColor, - fontSize: 16.f, - fontWeight: FontWeight.w500, - borderRadius: 10.r, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 50.h, - iconColor: AppColors.whiteColor, - iconSize: 18.h, - ), - // DefaultButton( - // LocaleKeys.confirm.tr(context: context), - // () async { - // await Health().getHealthConnectSdkStatus().then((val) { - // print('Health Connect SDK Status: $val'); - // if (val == HealthConnectSdkStatus.sdkAvailable) { - // Navigator.of(context).push( - // FadePage( - // page: HealthDashboard(), // Replace with the actual vital signs page - // // page: HealthApp(), // Replace with the actual vital signs page - // ), - // ); - // } else { - // Utils.showAppDialog(context, LocaleKeys.error.tr(context: context), LocaleKeys.healthConnectNotInstalled.tr(), () { - // Navigator.pop(context); - // Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata"); - // launchUrl(uri, mode: LaunchMode.externalApplication); - // }); - // return; - // } - // }); - // }, - // ) - ], - ); - } - - Widget getIOSInstructionsUI(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - "Supported Smart Watches".needTranslation.toText20(isBold: true), - SizedBox(height: 16.h), - Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/apple-watch-1.jpeg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 5", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), + body: CollapsingListView( + title: "How does it work".needTranslation, + bottomChild: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/apple-watch-2.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 6", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], - ), - Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/apple-watch-3.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 7", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/apple-watch-4.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 8", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], - ), - ), - Container( - margin: EdgeInsets.only(top: 10.0), - child: Row( - children: [ - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/apple-watch-5.jpg", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 9", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - Expanded( - child: Container( - margin: EdgeInsets.only(top: 15.0), - child: Row( - children: [ - Image.asset("assets/images/png/smartwatches/Apple-Watch-6.png", width: 70.0, height: 70.0), - Padding( - padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Container( - width: MediaQuery.of(context).size.width * 0.21, - child: Text("Apple Watch Series 10", overflow: TextOverflow.clip, style: TextStyle(fontSize: 12.0)), - ), - ) - ], - ), - ), - ), - ], + child: CustomButton( + text: LocaleKeys.getStarted.tr(context: context), + onPressed: () { + }, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + height: 50.h, + ).paddingSymmetrical(24.w, 30.h), ), + child: SingleChildScrollView(), ), - SizedBox(height: 12), - "Please make sure that your Apple Watch is connected to your iPhone, is actively synced & updated.".toText14(isBold: true), - SizedBox(height: 12), - "Before syncing data, please make sure that you have followed the instructions properly.".toText14(isBold: true), - SizedBox(height: 12), - InkWell( - onTap: () { - showInstructionsDialog(context); - }, - child: "View watch instructions".toText12(isBold: true, color: AppColors.textColor, isUnderLine: true), - ), - SizedBox( - height: 130.h, - ), - CustomButton( - text: LocaleKeys.confirm.tr(context: context), - onPressed: () async { - Navigator.of(context).push( - CustomPageRoute( - page: HealthDashboard(), - ), - ); - }, - backgroundColor: AppColors.primaryRedColor, - borderColor: AppColors.primaryRedColor, - textColor: AppColors.whiteColor, - fontSize: 16.f, - fontWeight: FontWeight.w500, - borderRadius: 10.r, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 50.h, - iconColor: AppColors.whiteColor, - iconSize: 18.h, - ), - ], ); } - - showInstructionsDialog(BuildContext context) { - showGeneralDialog( - barrierColor: Colors.black.withOpacity(0.5), - transitionBuilder: (context, a1, a2, widget) { - final curvedValue = Curves.easeInOutBack.transform(a1.value) - 1.0; - return Transform( - transform: Matrix4.translationValues(0.0, curvedValue * 200, 0.0), - child: Opacity( - opacity: a1.value, - child: Dialog( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: 350.0, - padding: EdgeInsets.all(21), - color: Colors.white, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "SmartWatch Tracker".toText18(), - IconButton( - icon: Icon( - Icons.close, - color: Color(0xff2E303A), - ), - onPressed: () { - Navigator.pop(context); - }, - ), - ], - ), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (Platform.isIOS - ? "Make sure that you have installed 'Health' App & 'Watch' App from Apple Store." - : "Please make sure that your Samsung Watch is connected to your Phone, is actively synced & updated.") - .needTranslation - .toText14(), - SizedBox(height: 12), - ], - ) - ], - ), - ), - ], - ), - ), - ), - ); - }, - transitionDuration: Duration(milliseconds: 500), - barrierDismissible: true, - barrierLabel: '', - context: context, - pageBuilder: (context, animation1, animation2) { - return SizedBox(); - //Chanbged By Aamir - }); - } } diff --git a/lib/presentation/smartwatches/widgets/health_metric.dart b/lib/presentation/smartwatches/widgets/health_metric.dart index 5375966..43a5746 100644 --- a/lib/presentation/smartwatches/widgets/health_metric.dart +++ b/lib/presentation/smartwatches/widgets/health_metric.dart @@ -1,8 +1,10 @@ import 'dart:io'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:health/health.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; class HealthMetricInfo { @@ -39,7 +41,7 @@ class HealthMetrics { unit: 'BPM', color: AppColors.primaryRedColor, icon: Icons.favorite, - description: "Your heart rate indicates how many times your heart beats per minute".needTranslation, + description: LocaleKeys.heartRateDescription.tr(), minHealthyValue: 60, maxHealthyValue: 100, svgIcon: "assets/images/smartwatches/heartrate_icon.svg"), @@ -51,7 +53,7 @@ class HealthMetrics { // color: Colors.blue, color: Color(0xff3A3558), icon: Icons.air, - description: "Blood oxygen level indicates how much oxygen your red blood cells are carrying".needTranslation, + description: LocaleKeys.bloodOxygenDescription.tr(), minHealthyValue: 95, maxHealthyValue: 100, svgIcon: "assets/images/smartwatches/bloodoxygen_icon.svg"), diff --git a/lib/presentation/smartwatches/widgets/supported_watches_list.dart b/lib/presentation/smartwatches/widgets/supported_watches_list.dart new file mode 100644 index 0000000..839af80 --- /dev/null +++ b/lib/presentation/smartwatches/widgets/supported_watches_list.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; + +class SupportedWatchesList extends StatelessWidget { + const SupportedWatchesList({super.key}); + + @override + Widget build(BuildContext context) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + ), + child: Padding( + padding: EdgeInsets.all(16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + "Apple Watches".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(height: 4.h), + "• Apple Watch Ultra".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Apple Watch 11".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Apple Watch 10".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Apple Watch 9".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Apple Watch 8".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + SizedBox(height: 16.h), + Row( + children: [ + "Samsung Watches".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(height: 4.h), + "• Samsung Watch Ultra".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Galaxy Watch 8".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Galaxy Watch 7".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Galaxy Watch 6".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Galaxy Watch FE".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Galaxy Watch Fit".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + SizedBox(height: 16.h), + Row( + children: [ + "Huawei Watches".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(height: 4.h), + "• Huawei Watch Ultimate Series".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Huawei Watch Series".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Huawei Watch Fit Series".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Huawei Watch Bands".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + SizedBox(height: 16.h), + Row( + children: [ + "Whoop Watches".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(height: 4.h), + "• Whoop 1".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + "• Whoop 2".needTranslation.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/symptoms_checker/organ_selector_screen.dart b/lib/presentation/symptoms_checker/organ_selector_screen.dart index c23b956..9a4a1d9 100644 --- a/lib/presentation/symptoms_checker/organ_selector_screen.dart +++ b/lib/presentation/symptoms_checker/organ_selector_screen.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,13 +7,15 @@ import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; -import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/interactive_body_widget.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; import 'package:provider/provider.dart'; class OrganSelectorPage extends StatefulWidget { @@ -24,25 +27,40 @@ class OrganSelectorPage extends StatefulWidget { class _OrganSelectorPageState extends State { late final AppState _appState; + late final DialogService dialogService; @override void initState() { super.initState(); _appState = getIt.get(); + dialogService = getIt(); } - void _onNextPressed(SymptomsCheckerViewModel viewModel) { + void _onNextPressed(SymptomsCheckerViewModel viewModel) async { if (!viewModel.validateSelection()) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Please select at least one organ'.needTranslation), - backgroundColor: AppColors.errorColor, - ), + dialogService.showErrorBottomSheet( + message: LocaleKeys.noOrgansSelected.tr(context: context), ); return; } + LoaderBottomSheet.showLoader( + loadingText: LocaleKeys.pleaseWait.tr(context: context), + ); - context.navigateWithName(AppRoutes.symptomsSelectorScreen); + final String userName = 'guest_user'; + final String password = '123456'; + + await viewModel.getSymptomsUserDetails( + userName: userName, + password: password, + onSuccess: () { + LoaderBottomSheet.hideLoader(); + context.navigateWithName(AppRoutes.symptomsSelectorPage); + }, + onError: (String error) { + LoaderBottomSheet.hideLoader(); + }, + ); } @override @@ -81,11 +99,11 @@ class _OrganSelectorPageState extends State { flipX: _appState.isArabic(), child: IconButton( icon: Utils.buildSvgWithAssets( - icon: AppAssets.arrow_back, - width: 32.h, - height: 32.h, + icon: AppAssets.forward_top_nav_icon, + width: 24.w, + height: 24.h, ), - padding: const EdgeInsets.only(left: 12), + padding: EdgeInsetsDirectional.only(start: 12, end: 12), onPressed: () => Navigator.pop(context), highlightColor: Colors.transparent, ), @@ -97,7 +115,7 @@ class _OrganSelectorPageState extends State { return Padding( padding: EdgeInsets.symmetric(horizontal: 16.w), child: Text( - "Organ Selector".needTranslation, + LocaleKeys.organSelector.tr(context: context), style: TextStyle( color: AppColors.textColor, fontSize: 22.f, @@ -108,21 +126,32 @@ class _OrganSelectorPageState extends State { } Widget _buildBodyViewer(SymptomsCheckerViewModel viewModel) { - return Padding( - padding: EdgeInsets.fromLTRB(16.h, 16.h, 16.h, 60.h), - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 600), - transitionBuilder: (child, animation) => _build3DFlipTransition(child, animation), - switchInCurve: Curves.easeInOut, - switchOutCurve: Curves.easeInOut, - child: InteractiveBodyWidget( - key: ValueKey(viewModel.currentView), - bodyImageAsset: viewModel.currentView == BodyView.front ? AppAssets.fullBodyFront : AppAssets.fullBodyBack, - organs: viewModel.currentOrgans, - selectedOrganIds: viewModel.selectedOrganIds, - onOrganTap: viewModel.toggleOrganSelection, - isBodyHidden: viewModel.isBodyHidden, - tooltipOrganId: viewModel.tooltipOrganId, + return GestureDetector( + onHorizontalDragEnd: (details) { + // Swipe left or right to toggle view + if (details.primaryVelocity != null) { + if (details.primaryVelocity! < -200 || details.primaryVelocity! > 200) { + viewModel.toggleView(); + } + } + }, + child: Padding( + padding: EdgeInsets.fromLTRB(16.h, 16.h, 16.h, 60.h), + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 600), + transitionBuilder: (child, animation) => _build3DFlipTransition(child, animation), + switchInCurve: Curves.easeInOut, + switchOutCurve: Curves.easeInOut, + child: InteractiveBodyWidget( + key: ValueKey(viewModel.currentView), + bodyImageAsset: viewModel.currentView == BodyView.front ? AppAssets.fullBodyFront : AppAssets.fullBodyBack, + organs: viewModel.currentOrgans, + selectedOrganIds: viewModel.selectedOrganIds, + onOrganTap: viewModel.toggleOrganSelection, + isBodyHidden: viewModel.isBodyHidden, + tooltipOrganId: viewModel.tooltipOrganId, + isArabic: _appState.isArabic(), + ), ), ), ); @@ -152,8 +181,8 @@ class _OrganSelectorPageState extends State { } Widget _buildViewToggleButtons(SymptomsCheckerViewModel viewModel) { - return Positioned( - left: 16.w, + return PositionedDirectional( + start: 16.w, top: 36.h, child: Column( children: [ @@ -234,7 +263,7 @@ class _OrganSelectorPageState extends State { return Padding( padding: EdgeInsets.symmetric(horizontal: 16.w), child: Text( - 'Selected Organs'.needTranslation, + LocaleKeys.selectedOrgans.tr(context: context), style: TextStyle( fontSize: 16.f, fontWeight: FontWeight.w600, @@ -249,7 +278,7 @@ class _OrganSelectorPageState extends State { return Padding( padding: EdgeInsets.symmetric(horizontal: 16.w), child: Text( - 'No organs selected yet'.needTranslation, + LocaleKeys.noOrgansSelected.tr(context: context), style: TextStyle( color: AppColors.greyTextColor, fontSize: 14.f, @@ -258,6 +287,8 @@ class _OrganSelectorPageState extends State { ); } + final isArabic = _appState.isArabic(); + return ConstrainedBox( constraints: BoxConstraints(maxHeight: 150.h), child: SingleChildScrollView( @@ -267,7 +298,7 @@ class _OrganSelectorPageState extends State { runSpacing: 8.h, children: viewModel.selectedOrgans.map((organ) { return AppCustomChipWidget( - labelText: organ.description, + labelText: organ.getLocalizedDescription(isArabic), backgroundColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, deleteIcon: AppAssets.cancel, @@ -286,7 +317,7 @@ class _OrganSelectorPageState extends State { return Padding( padding: EdgeInsets.symmetric(horizontal: 16.w), child: CustomButton( - text: 'Next'.needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () => _onNextPressed(viewModel), isDisabled: viewModel.selectedOrgans.isEmpty, backgroundColor: AppColors.primaryRedColor, @@ -296,8 +327,8 @@ class _OrganSelectorPageState extends State { } Widget _buildExpandCollapseButton(SymptomsCheckerViewModel viewModel) { - return Positioned( - right: 24.w, + return PositionedDirectional( + end: 24.w, top: -24.h, child: GestureDetector( onTap: viewModel.toggleBottomSheet, @@ -314,13 +345,16 @@ class _OrganSelectorPageState extends State { borderRadius: 11.r, ), child: Center( - child: AnimatedRotation( - duration: const Duration(milliseconds: 300), - turns: viewModel.isBottomSheetExpanded ? 0.25 : -0.25, - child: Utils.buildSvgWithAssets( - icon: AppAssets.arrowRight, - width: 25.w, - height: 25.h, + child: Transform.flip( + flipX: _appState.isArabic(), + child: AnimatedRotation( + duration: const Duration(milliseconds: 300), + turns: viewModel.isBottomSheetExpanded ? 0.25 : -0.25, + child: Utils.buildSvgWithAssets( + icon: AppAssets.arrowRight, + width: 25.w, + height: 25.h, + ), ), ), ), diff --git a/lib/presentation/symptoms_checker/possible_conditions_screen.dart b/lib/presentation/symptoms_checker/possible_conditions_screen.dart index 2c99515..8fb0e0f 100644 --- a/lib/presentation/symptoms_checker/possible_conditions_screen.dart +++ b/lib/presentation/symptoms_checker/possible_conditions_screen.dart @@ -3,14 +3,16 @@ import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; -import 'package:hmg_patient_app_new/features/symptoms_checker/models/conditions_model.dart'; -import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/condition_card.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -18,8 +20,8 @@ import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:provider/provider.dart'; import 'package:shimmer/shimmer.dart'; -class PossibleConditionsScreen extends StatelessWidget { - const PossibleConditionsScreen({super.key}); +class PossibleConditionsPage extends StatelessWidget { + const PossibleConditionsPage({super.key}); Widget _buildLoadingShimmer() { return ListView.separated( @@ -44,13 +46,13 @@ class PossibleConditionsScreen extends StatelessWidget { ); } - Widget _buildPredictionsList(List conditions) { + Widget _buildPredictionsList(BuildContext context, List conditions, List symptoms) { if (conditions.isEmpty) { return Center( child: Padding( padding: EdgeInsets.all(24.h), child: Text( - 'No Predictions available'.needTranslation, + LocaleKeys.noPredictionsAvailable.tr(context: context), style: TextStyle( fontSize: 16.h, color: AppColors.greyTextColor, @@ -60,6 +62,8 @@ class PossibleConditionsScreen extends StatelessWidget { ); } + final dialogService = getIt(); + return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -71,22 +75,13 @@ class PossibleConditionsScreen extends StatelessWidget { physics: NeverScrollableScrollPhysics(), separatorBuilder: (context, index) => SizedBox(height: 16.h), itemBuilder: (context, index) { - final conditionModel = conditions[index]; + final condition = conditions[index]; return ConditionCard( - icon: conditionModel.icon, - title: conditionModel.title, - percentage: conditionModel.percentage, - tagText: conditionModel.tagText, - clinic: conditionModel.clinic, - symptoms: conditionModel.symptoms, - description: conditionModel.description, - possibleConditionsSeverityEnum: conditionModel.possibleConditionsSeverityEnum, + condition: condition, + symptoms: symptoms, onActionPressed: () { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('We are not available for a week. May you Rest In Peace :('), - backgroundColor: AppColors.primaryRedColor, - ), + dialogService.showErrorBottomSheet( + message: 'icd10 Code is ${condition.conditionDetails?.icd10Code}. We need to get the clinics mapped against this code.', ); }, ); @@ -102,7 +97,7 @@ class PossibleConditionsScreen extends StatelessWidget { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to restart the organ selection?".needTranslation, + loadingText: LocaleKeys.areYouSureYouWantToExitProgress.tr(context: context), isShowActionButtons: true, onCancelTap: () => Navigator.pop(context), onConfirmTap: () => onConfirm(), @@ -113,47 +108,88 @@ class PossibleConditionsScreen extends StatelessWidget { ); } - _restartOrganSelection(BuildContext context) async { - final symptomsCheckerVm = context.read(); - symptomsCheckerVm.reset(); - context.pop(); - await Future.delayed(Duration(seconds: 1)).whenComplete(() => context.pop()); - } + Widget _buildInfoTile({required PossibleConditionsSeverityEnum severityEnum, required BuildContext context}) { + String title; + String description; + Color dotColor; - _navigateToLandingPage() { - NavigationService navigationService = getIt.get(); - navigationService.replaceAllRoutesAndNavigateToLanding(); - } + switch (severityEnum) { + case PossibleConditionsSeverityEnum.monitorOnly: + title = LocaleKeys.monitor.tr(context: context); + description = LocaleKeys.monitorDescription.tr(context: context); + dotColor = AppColors.chipColorMonitor; + break; + case PossibleConditionsSeverityEnum.seekMedicalAdvice: + title = LocaleKeys.seekMedicalAdvice.tr(context: context); + description = LocaleKeys.seekMedicalAdviceDescription.tr(context: context); + dotColor = AppColors.chipColorSeekMedicalAdvice; + break; + case PossibleConditionsSeverityEnum.emergency: + title = LocaleKeys.emergency.tr(context: context); + description = LocaleKeys.emergencyDescription.tr(context: context); + dotColor = AppColors.chipColorEmergency; + break; + } - _buildTrailingSection(BuildContext context) { return Row( + crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( - height: 40.h, - padding: EdgeInsets.all(8.w), - child: Center( - child: Utils.buildSvgWithAssets( - icon: AppAssets.refreshIcon, - height: 20.h, - width: 20.w, - iconColor: AppColors.textColor, - ), - ), - ).onPress(() => _buildConfirmationBottomSheet(context: context, onConfirm: () => _restartOrganSelection(context))), - Container( - height: 40.h, - padding: EdgeInsets.all(8.w), - child: Center( - child: Utils.buildSvgWithAssets( - icon: AppAssets.homeBorderedIcon, - height: 20.h, - width: 20.w, - iconColor: AppColors.textColor, - ), + height: 14.h, + width: 14.w, + decoration: BoxDecoration(shape: BoxShape.circle, color: dotColor), + ).paddingOnly(top: 3.h), + SizedBox(width: 8.w), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title.toText14(weight: FontWeight.w600, color: AppColors.textColor), + SizedBox(height: 4.h), + description.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + ], ), - ).onPress(() => _buildConfirmationBottomSheet(context: context, onConfirm: () => _navigateToLandingPage())), + ), ], - ).paddingSymmetrical(20.w, 0); + ); + } + + _buildSeverityDetailsBottomsheet({required BuildContext context}) { + return showCommonBottomSheetWithoutHeight( + title: LocaleKeys.colorScience.tr(context: context), + context, + child: Container( + padding: EdgeInsets.all(16.w), + width: double.infinity, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), + child: Column( + children: [ + _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.monitorOnly, context: context), + Divider(color: AppColors.bottomNAVBorder, height: 24.h, thickness: 1), + _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.seekMedicalAdvice, context: context), + Divider(color: AppColors.bottomNAVBorder, height: 24.h, thickness: 1), + _buildInfoTile(severityEnum: PossibleConditionsSeverityEnum.emergency, context: context), + ], + ), + ), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + _buildTrailingSection(BuildContext context) { + return Container( + height: 40.h, + padding: EdgeInsets.all(8.w), + child: Center( + child: Utils.buildSvgWithAssets( + icon: AppAssets.coloredDotsIcon, + height: 20.h, + width: 20.w, + ), + ), + ).onPress(() => _buildSeverityDetailsBottomsheet(context: context)); } @override @@ -161,14 +197,33 @@ class PossibleConditionsScreen extends StatelessWidget { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Possible Conditions".needTranslation, + title: LocaleKeys.possibleConditions.tr(context: context), + leadingCallback: () => _buildConfirmationBottomSheet( + context: context, + onConfirm: () { + context.pop(); + final SymptomsCheckerViewModel symptomsCheckerViewModel = context.read(); + symptomsCheckerViewModel.reset(); // Clear all symptoms checker data + final navigationService = getIt.get(); + navigationService.replaceAllRoutesAndNavigateToLanding(); + }, + ), trailing: _buildTrailingSection(context), child: Consumer( builder: (context, symptomsCheckerViewModel, child) { - if (symptomsCheckerViewModel.isPossibleConditionsLoading || symptomsCheckerViewModel.isPossibleConditionsLoading) { + if (symptomsCheckerViewModel.isPossibleConditionsLoading || symptomsCheckerViewModel.isTriageDiagnosisLoading) { return _buildLoadingShimmer(); } - return _buildPredictionsList(dummyConditions); + // Get conditions directly from ViewModel + final conditions = symptomsCheckerViewModel.currentConditions ?? []; + // Get selected symptoms names for display + final symptoms = symptomsCheckerViewModel + .getAllSelectedSymptoms() + .map((s) => s.commonName ?? s.name ?? '') + .where((name) => name.isNotEmpty) + .take(3) + .toList(); + return _buildPredictionsList(context, conditions, symptoms); }, ), ), diff --git a/lib/presentation/symptoms_checker/risk_factors_screen.dart b/lib/presentation/symptoms_checker/risk_factors_screen.dart index d4ff2cb..484ad2d 100644 --- a/lib/presentation/symptoms_checker/risk_factors_screen.dart +++ b/lib/presentation/symptoms_checker/risk_factors_screen.dart @@ -1,12 +1,17 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -20,9 +25,14 @@ class RiskFactorsScreen extends StatefulWidget { } class _RiskFactorsScreenState extends State { + late DialogService dialogService; + late AppState _appState; + @override void initState() { super.initState(); + dialogService = getIt(); + _appState = getIt(); // Fetch risk factors based on selected symptoms WidgetsBinding.instance.addPostFrameCallback((_) { final viewModel = context.read(); @@ -36,13 +46,10 @@ class _RiskFactorsScreenState extends State { void _onNextPressed(SymptomsCheckerViewModel viewModel) { if (viewModel.hasSelectedRiskFactors) { - context.navigateWithName(AppRoutes.suggestionsScreen); + context.navigateWithName(AppRoutes.suggestionsPage); } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Please select at least one risk before proceeding'.needTranslation), - backgroundColor: AppColors.errorColor, - ), + dialogService.showErrorBottomSheet( + message: LocaleKeys.pleaseSelectAtLeastOneRiskBeforeProceeding.tr(context: context), ); } } @@ -86,6 +93,8 @@ class _RiskFactorsScreenState extends State { } Widget _buildRiskFactorsList(SymptomsCheckerViewModel viewModel) { + final isArabic = _appState.isArabic(); + return Container( key: ValueKey(viewModel.riskFactorsList.length), width: double.infinity, @@ -96,7 +105,7 @@ class _RiskFactorsScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ ...viewModel.riskFactorsList.map((factor) { - return _buildRiskFactorItem(viewModel, factor.id ?? '', factor.getDisplayName()); + return _buildRiskFactorItem(viewModel, factor.id ?? '', factor.getDisplayName(isArabic: isArabic)); }), SizedBox(height: 12.w), Row( @@ -116,14 +125,14 @@ class _RiskFactorsScreenState extends State { fontSize: 13.f, fontWeight: FontWeight.w500, color: AppColors.greyInfoTextColor, + fontFamily: isArabic ? 'GESSTwo' : 'Poppins' ), children: [ TextSpan( - text: "Above you see the most common risk factors. Although /diagnosis may return questions about risk factors, " - .needTranslation, + text: LocaleKeys.aboveYouSeeCommonRiskFactors.tr(context: context), ), TextSpan( - text: "read more".needTranslation, + text: LocaleKeys.readMore.tr(context: context), style: TextStyle( color: AppColors.primaryRedColor, fontWeight: FontWeight.w500, @@ -193,7 +202,7 @@ class _RiskFactorsScreenState extends State { border: Border.all(color: AppColors.bottomNAVBorder, width: 1), ), child: Text( - 'Not Applicable Risk Factor', + 'Not Applicable Risk Factor'.needTranslation, style: TextStyle(fontSize: 14.f, color: AppColors.textColor), ), ).toShimmer2(isShow: true, radius: 24.r); @@ -214,7 +223,7 @@ class _RiskFactorsScreenState extends State { children: [ Expanded( child: CollapsingListView( - title: "Risk Factors".needTranslation, + title: LocaleKeys.riskFactors.tr(context: context), leadingCallback: () => context.pop(), child: viewModel.isRiskFactorsLoading ? _buildLoadingShimmer() @@ -247,7 +256,7 @@ class _RiskFactorsScreenState extends State { Icon(Icons.info_outline, size: 64.h, color: AppColors.greyTextColor), SizedBox(height: 16.h), Text( - 'No risk factors found'.needTranslation, + LocaleKeys.noRiskFactorsFound.tr(context: context), style: TextStyle( fontSize: 18.f, fontWeight: FontWeight.w600, @@ -256,7 +265,7 @@ class _RiskFactorsScreenState extends State { ), SizedBox(height: 8.h), Text( - 'Based on your selected symptoms, no additional risk factors were identified.'.needTranslation, + LocaleKeys.basedOnYourSelectedSymptomsNoRiskFactors.tr(context: context), textAlign: TextAlign.center, style: TextStyle( fontSize: 14.f, @@ -280,7 +289,7 @@ class _RiskFactorsScreenState extends State { children: [ Expanded( child: CustomButton( - text: "Previous".needTranslation, + text: LocaleKeys.previous.tr(context: context), onPressed: _onPreviousPressed, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), borderColor: Colors.transparent, @@ -291,7 +300,7 @@ class _RiskFactorsScreenState extends State { SizedBox(width: 12.w), Expanded( child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () => _onNextPressed(viewModel), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, diff --git a/lib/presentation/symptoms_checker/suggestions_screen.dart b/lib/presentation/symptoms_checker/suggestions_screen.dart index f2aa71e..8d32b7f 100644 --- a/lib/presentation/symptoms_checker/suggestions_screen.dart +++ b/lib/presentation/symptoms_checker/suggestions_screen.dart @@ -1,11 +1,16 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -19,9 +24,14 @@ class SuggestionsScreen extends StatefulWidget { } class _SuggestionsScreenState extends State { + late DialogService dialogService; + late AppState _appState; + @override void initState() { super.initState(); + dialogService = getIt(); + _appState = getIt(); // Initialize symptom groups based on selected organs WidgetsBinding.instance.addPostFrameCallback((_) { final viewModel = context.read(); @@ -38,13 +48,10 @@ class _SuggestionsScreenState extends State { void _onNextPressed(SymptomsCheckerViewModel viewModel) { if (viewModel.hasSelectedSuggestions) { // Navigate to triage screen - context.navigateWithName(AppRoutes.triageScreen); + context.navigateWithName(AppRoutes.triagePage); } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Please select at least one option before proceeding'.needTranslation), - backgroundColor: AppColors.errorColor, - ), + dialogService.showErrorBottomSheet( + message: LocaleKeys.pleaseSelectAtLeastOneOptionBeforeProceeding.tr(), ); } } @@ -88,6 +95,8 @@ class _SuggestionsScreenState extends State { } Widget _buildSuggestionsList(SymptomsCheckerViewModel viewModel) { + final isArabic = _appState.isArabic(); + return Container( key: ValueKey(viewModel.suggestionsList.length), width: double.infinity, @@ -98,7 +107,7 @@ class _SuggestionsScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ ...viewModel.suggestionsList.map((factor) { - return _buildSuggestionItem(viewModel, factor.id ?? '', factor.getDisplayName()); + return _buildSuggestionItem(viewModel, factor.id ?? '', factor.getDisplayName(isArabic: isArabic)); }), SizedBox(height: 12.w), Row( @@ -111,7 +120,7 @@ class _SuggestionsScreenState extends State { ), SizedBox(width: 12.w), Expanded( - child: "This is a list of symptoms suggested by our AI, based on the information gathered so far during the interview".toText12( + child: LocaleKeys.suggestionAIListDescription.tr(context: context).toText12( color: AppColors.greyInfoTextColor, ), ) @@ -190,7 +199,7 @@ class _SuggestionsScreenState extends State { children: [ Expanded( child: CollapsingListView( - title: "Suggestions".needTranslation, + title: LocaleKeys.suggestions.tr(), leadingCallback: () => context.pop(), child: viewModel.isSuggestionsLoading ? _buildLoadingShimmer() @@ -223,7 +232,7 @@ class _SuggestionsScreenState extends State { Icon(Icons.info_outline, size: 64.h, color: AppColors.greyTextColor), SizedBox(height: 16.h), Text( - 'No organs selected'.needTranslation, + LocaleKeys.noOrgansSelected.tr(), style: TextStyle( fontSize: 18.f, fontWeight: FontWeight.w600, @@ -232,7 +241,7 @@ class _SuggestionsScreenState extends State { ), SizedBox(height: 8.h), Text( - 'Please go back and select organs first'.needTranslation, + LocaleKeys.pleaseGoBackAndSelectOrgansFirst.tr(), textAlign: TextAlign.center, style: TextStyle( fontSize: 14.f, @@ -256,7 +265,7 @@ class _SuggestionsScreenState extends State { children: [ Expanded( child: CustomButton( - text: "Previous".needTranslation, + text: LocaleKeys.previous.tr(), onPressed: _onPreviousPressed, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), borderColor: Colors.transparent, @@ -267,7 +276,7 @@ class _SuggestionsScreenState extends State { SizedBox(width: 12.w), Expanded( child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(), onPressed: () => _onNextPressed(viewModel), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, diff --git a/lib/presentation/symptoms_checker/symptoms_selector_screen.dart b/lib/presentation/symptoms_checker/symptoms_selector_screen.dart index 522c5f8..2bfcb62 100644 --- a/lib/presentation/symptoms_checker/symptoms_selector_screen.dart +++ b/lib/presentation/symptoms_checker/symptoms_selector_screen.dart @@ -1,13 +1,16 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; -import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/body_symptom_response_model.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; +import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -15,17 +18,22 @@ import 'package:hmg_patient_app_new/widgets/chip/custom_selectable_chip.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:provider/provider.dart'; -class SymptomsSelectorScreen extends StatefulWidget { - const SymptomsSelectorScreen({super.key}); +class SymptomsSelectorPage extends StatefulWidget { + const SymptomsSelectorPage({super.key}); @override - State createState() => _SymptomsSelectorScreenState(); + State createState() => _SymptomsSelectorPageState(); } -class _SymptomsSelectorScreenState extends State { +class _SymptomsSelectorPageState extends State { + late DialogService dialogService; + late AppState _appState; + @override void initState() { super.initState(); + dialogService = getIt(); + _appState = getIt(); // Initialize symptom groups based on selected organs WidgetsBinding.instance.addPostFrameCallback((_) { final viewModel = context.read(); @@ -36,13 +44,10 @@ class _SymptomsSelectorScreenState extends State { void _onNextPressed(SymptomsCheckerViewModel viewModel) { if (viewModel.hasSelectedSymptoms) { // Navigate to triage screen - context.navigateWithName(AppRoutes.riskFactorsScreen); + context.navigateWithName(AppRoutes.riskFactorsPage); } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Please select at least one symptom before proceeding'.needTranslation), - backgroundColor: AppColors.errorColor, - ), + dialogService.showErrorBottomSheet( + message: LocaleKeys.pleaseSelectAtLeastOneOptionBeforeProceeding.tr(), ); } } @@ -56,7 +61,7 @@ class _SymptomsSelectorScreenState extends State { title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to restart the organ selection?".needTranslation, + loadingText: LocaleKeys.areYouSureYouWantToRestartOrganSelection.tr(), isShowActionButtons: true, onCancelTap: () => Navigator.pop(context), onConfirmTap: () => onConfirm(), @@ -77,13 +82,15 @@ class _SymptomsSelectorScreenState extends State { children: [ Expanded( child: CollapsingListView( - title: "Symptoms Selector".needTranslation, + title: LocaleKeys.symptomsSelector.tr(), leadingCallback: () => _buildConfirmationBottomSheet( context: context, - onConfirm: () => { - context.pop(), - context.pop(), - }), + onConfirm: () { + context.pop(); + viewModel.reset(); // Clear all symptoms checker data + final navigationService = getIt.get(); + navigationService.replaceAllRoutesAndNavigateToLanding(); + }), child: viewModel.isBodySymptomsLoading ? _buildLoadingShimmer() : viewModel.organSymptomsResults.isEmpty @@ -96,10 +103,11 @@ class _SymptomsSelectorScreenState extends State { // Find matching organ ID from selected organs String? organId; String? organName; + final isArabic = _appState.isArabic(); for (var organ in viewModel.selectedOrgans) { if (organ.name == organResult.name) { organId = organ.id; - organName = organ.description; + organName = organ.getLocalizedDescription(isArabic); break; } } @@ -137,6 +145,8 @@ class _SymptomsSelectorScreenState extends State { String organName, List symptoms, ) { + final isArabic = _appState.isArabic(); + return Container( width: double.infinity, margin: EdgeInsets.symmetric(horizontal: 24.w), @@ -150,7 +160,7 @@ class _SymptomsSelectorScreenState extends State { children: [ Expanded( child: Text( - 'Possible symptoms related to "$organName"', + '${LocaleKeys.possibleSymptomsRelatedTo.tr(context: context)} "$organName"', style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), ), ), @@ -162,7 +172,7 @@ class _SymptomsSelectorScreenState extends State { spacing: 8.w, children: symptoms.map((symptom) { final symptomId = symptom.id ?? ''; - final symptomLabel = symptom.getDisplayName(false); // Pass isArabic from AppState if needed + final symptomLabel = symptom.getDisplayName(isArabic); bool isSelected = viewModel.isSymptomSelected(organId, symptomId); return GestureDetector( onTap: () => viewModel.toggleSymptomSelection(organId, symptomId), @@ -250,7 +260,7 @@ class _SymptomsSelectorScreenState extends State { Icon(Icons.info_outline, size: 64.h, color: AppColors.greyTextColor), SizedBox(height: 16.h), Text( - 'No organs selected'.needTranslation, + LocaleKeys.noOrgansSelected.tr(context: context), style: TextStyle( fontSize: 18.f, fontWeight: FontWeight.w600, @@ -259,7 +269,7 @@ class _SymptomsSelectorScreenState extends State { ), SizedBox(height: 8.h), Text( - 'Please go back and select organs first'.needTranslation, + LocaleKeys.pleaseGoBackAndSelectOrgansFirst.tr(), textAlign: TextAlign.center, style: TextStyle( fontSize: 14.f, @@ -283,7 +293,7 @@ class _SymptomsSelectorScreenState extends State { children: [ Expanded( child: CustomButton( - text: "Previous".needTranslation, + text: LocaleKeys.previous.tr(context: context), onPressed: _onPreviousPressed, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), borderColor: Colors.transparent, @@ -294,7 +304,7 @@ class _SymptomsSelectorScreenState extends State { SizedBox(width: 12.w), Expanded( child: CustomButton( - text: "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), onPressed: () => _onNextPressed(viewModel), backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -302,7 +312,7 @@ class _SymptomsSelectorScreenState extends State { fontSize: 16.f, ), ), - ], + ], ), SizedBox(height: 24.h), ], diff --git a/lib/presentation/symptoms_checker/triage_screen.dart b/lib/presentation/symptoms_checker/triage_screen.dart index ff0482e..0811833 100644 --- a/lib/presentation/symptoms_checker/triage_screen.dart +++ b/lib/presentation/symptoms_checker/triage_screen.dart @@ -1,89 +1,218 @@ +import 'dart:developer'; + import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; -import 'package:hmg_patient_app_new/features/symptoms_checker/data/triage_questions_data.dart'; -import 'package:hmg_patient_app_new/features/symptoms_checker/models/triage_question_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/custom_progress_bar.dart'; +import 'package:hmg_patient_app_new/services/dialog_service.dart'; +import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:lottie/lottie.dart'; +import 'package:provider/provider.dart'; -class TriageScreen extends StatefulWidget { - const TriageScreen({super.key}); +class TriagePage extends StatefulWidget { + const TriagePage({super.key}); @override - State createState() => _TriageScreenState(); + State createState() => _TriagePageState(); } -class _TriageScreenState extends State { - late List triageQuestions; - int currentQuestionIndex = 0; +class _TriagePageState extends State { + late SymptomsCheckerViewModel viewModel; + late DialogService dialogService; + late AppState _appState; @override void initState() { super.initState(); - triageQuestions = TriageQuestionsData.getSampleTriageQuestions(); + viewModel = context.read(); + dialogService = getIt.get(); + _appState = getIt.get(); + + // Start triage process when screen loads + WidgetsBinding.instance.addPostFrameCallback((_) { + _startTriage(); + }); } - TriageQuestionModel get currentQuestion => triageQuestions[currentQuestionIndex]; + void _startTriage() { + viewModel.startOrContinueTriage( + onSuccess: () { + _handleTriageResponse(); + }, + onError: (error) { + dialogService.showErrorBottomSheet( + message: error, + onOkPressed: () => context.pop(), + ); + }, + ); + } - bool get isFirstQuestion => currentQuestionIndex == 0; + void _handleTriageResponse() { + // Case 1: Emergency evidence detected + if (viewModel.hasEmergencyEvidence) { + _showEmergencyDialog(); + return; + } - bool get isLastQuestion => currentQuestionIndex == triageQuestions.length - 1; + // Get the highest probability condition + final conditions = viewModel.currentConditions ?? []; + double highestProbability = 0.0; - void _onOptionSelected(int optionIndex) { - setState(() { - currentQuestion.selectOption(optionIndex); - }); + if (conditions.isNotEmpty) { + final sortedConditions = List.from(conditions); + sortedConditions.sort((a, b) => (b.probability ?? 0.0).compareTo(a.probability ?? 0.0)); + highestProbability = (sortedConditions.first.probability ?? 0.0) * 100; + } + + // Case 2: Should stop flag is true OR Case 3: Probability >= 70% OR Case 4: 7 or more questions answered + if (viewModel.shouldStopTriage || highestProbability >= 70.0 || viewModel.triageQuestionCount >= 7) { + // Navigate to results/possible conditions screen + context.navigateWithName(AppRoutes.possibleConditionsPage); + return; + } + + // Continue triage - question is loaded, reset selection for new question + viewModel.resetTriageChoice(); + } + + void _showEmergencyDialog() { + showCommonBottomSheetWithoutHeight( + context, + child: Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.primaryRedColor, + borderRadius: 24.h, + ), + child: Padding( + padding: EdgeInsets.all(24.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "".toText14(), + Utils.buildSvgWithAssets( + icon: AppAssets.cancel_circle_icon, + iconColor: AppColors.whiteColor, + width: 24.h, + height: 24.h, + fit: BoxFit.contain, + ).onPress(() { + Navigator.of(context).pop(); + }), + ], + ), + Lottie.asset(AppAnimations.ambulanceAlert, + repeat: false, reverse: false, frameRate: FrameRate(60), width: 120.h, height: 120.h, fit: BoxFit.contain), + SizedBox(height: 8.h), + LocaleKeys.emergencyTriage.tr(context: context).toText28(color: AppColors.whiteColor, isBold: true), + SizedBox(height: 8.h), + LocaleKeys.emergencyEvidenceDetected.tr(context: context).toText14(color: AppColors.whiteColor, weight: FontWeight.w500), + SizedBox(height: 24.h), + CustomButton( + text: LocaleKeys.confirm.tr(context: context), + onPressed: () { + context.pop(); + context.navigateWithName(AppRoutes.possibleConditionsPage); + }, + backgroundColor: AppColors.whiteColor, + borderColor: AppColors.whiteColor, + textColor: AppColors.primaryRedColor, + icon: AppAssets.checkmark_icon, + iconColor: AppColors.primaryRedColor, + ), + SizedBox(height: 8.h), + ], + ), + ), + ), + isFullScreen: false, + isCloseButtonVisible: false, + hasBottomPadding: false, + backgroundColor: AppColors.primaryRedColor, + callBackFunc: () {}, + ); + } + + bool get isFirstQuestion => viewModel.getTriageEvidence().isEmpty; + + void _onOptionSelectedForItem(String itemId, int choiceIndex) { + viewModel.selectTriageChoiceForItem(itemId, choiceIndex); } void _onPreviousPressed() { - if (!isFirstQuestion) { - setState(() { - currentQuestionIndex--; - }); - } + context.pop(); } void _onNextPressed() { - if (currentQuestion.isAnswered) { - currentQuestion.confirmSelection(); - if (isLastQuestion) { - context.navigateWithName(AppRoutes.possibleConditionsScreen); - } else { - setState(() { - currentQuestionIndex++; - }); - } - } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Please select an option before proceeding'.needTranslation), - backgroundColor: AppColors.errorColor, - ), + final currentQuestion = viewModel.currentTriageQuestion; + if (currentQuestion?.items == null || currentQuestion!.items!.isEmpty) { + dialogService.showErrorBottomSheet( + message: LocaleKeys.noQuestionItemsAvailable.tr(context: context), ); + return; } - } - _buildConfirmationBottomSheet({required BuildContext context, required VoidCallback onConfirm}) { - return showCommonBottomSheetWithoutHeight( - title: LocaleKeys.notice.tr(context: context), - context, - child: Utils.getWarningWidget( - loadingText: "Are you sure you want to restart the organ selection?".needTranslation, - isShowActionButtons: true, - onCancelTap: () => Navigator.pop(context), - onConfirmTap: () => onConfirm(), - ), - callBackFunc: () {}, - isFullScreen: false, - isCloseButtonVisible: true, + // Check if all items have been answered + if (!viewModel.areAllTriageItemsAnswered) { + dialogService.showErrorBottomSheet(message: LocaleKeys.pleaseAnswerAllQuestionsBeforeProceeding.tr(context: context)); + return; + } + + // Collect all evidence from all items + for (var item in currentQuestion.items!) { + final itemId = item.id ?? ""; + if (itemId.isEmpty) continue; + + final selectedChoiceIndex = viewModel.getTriageChoiceForItem(itemId); + if (selectedChoiceIndex == null) continue; + + if (item.choices != null && selectedChoiceIndex < item.choices!.length) { + final selectedChoice = item.choices![selectedChoiceIndex]; + final choiceId = selectedChoice.id ?? ""; + + if (choiceId.isNotEmpty) { + viewModel.addTriageEvidence(itemId, choiceId); + } + } + } + + // Get all evidence: initial symptoms + risk factors + suggestions + triage evidence + List initialEvidenceIds = viewModel.getAllEvidenceIds(); + List> triageEvidence = viewModel.getTriageEvidence(); + + log("initialEvidenceIds: ${initialEvidenceIds.toString()}"); + log("triageEvidence: ${triageEvidence.toString()}"); + + // Call API with updated evidence + viewModel.getDiagnosisForTriage( + age: viewModel.selectedAge!, + gender: viewModel.selectedGender!.toLowerCase() == "male" ? 1 : 2, + evidenceIds: initialEvidenceIds, + triageEvidence: triageEvidence, + language: viewModel.appState.isArabic() ? 'ar' : 'en', + onSuccess: (response) { + _handleTriageResponse(); + }, + onError: (error) { + dialogService.showErrorBottomSheet(message: error); + }, ); } @@ -91,45 +220,139 @@ class _TriageScreenState extends State { Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, - body: Column( - children: [ - Expanded( - child: CollapsingListView( - title: "Triage".needTranslation, - // onLeadingTapped: () => _buildConfirmationBottomSheet( - // context: context, - // onConfirm: () => { - // context.pop(), - // context.pop(), - // }), - - leadingCallback: () => context.pop(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox(height: 16.h), - _buildQuestionCard(), - ], + body: Consumer( + builder: (context, viewModel, child) { + // Show normal question UI + return Column( + children: [ + Expanded( + child: CollapsingListView( + title: LocaleKeys.triage.tr(context: context), + leadingCallback: () => _showConfirmationBeforeExit(context), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + _buildQuestionCard(viewModel), + ], + ), + ), ), + _buildStickyBottomCard(context, viewModel), + ], + ); + }, + ), + ); + } + + Widget _buildLoadingShimmer() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + // Create 2-3 shimmer cards + ...List.generate(1, (index) { + return Padding( + padding: EdgeInsets.only(bottom: 16.h), + child: _buildShimmerCard(), + ); + }), + ], + ); + } + + Widget _buildShimmerCard() { + return Container( + width: double.infinity, + margin: EdgeInsets.symmetric(horizontal: 24.w), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), + padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Shimmer title + Container( + height: 40.h, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(24.r), ), + ).toShimmer2(isShow: true, radius: 24.r), + SizedBox(height: 16.h), + // Shimmer chips + Wrap( + runSpacing: 12.h, + spacing: 8.w, + children: List.generate(4, (index) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h), + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.circular(24.r), + border: Border.all(color: AppColors.bottomNAVBorder, width: 1), + ), + child: Text( + 'Not Applicable Suggestion', + style: TextStyle(fontSize: 14.f, color: AppColors.textColor), + ), + ).toShimmer2(isShow: true, radius: 24.r); + }), ), - _buildStickyBottomCard(context), ], ), ); } - Widget _buildQuestionCard() { + void _showConfirmationBeforeExit(BuildContext context) { + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.notice.tr(context: context), + context, + child: Utils.getWarningWidget( + loadingText: LocaleKeys.areYouSureYouWantToExitProgress.tr(context: context), + isShowActionButtons: true, + onCancelTap: () => Navigator.pop(context), + onConfirmTap: () { + context.pop(); + viewModel.reset(); // Clear all symptoms checker data + final navigationService = getIt.get(); + navigationService.replaceAllRoutesAndNavigateToLanding(); + }, + ), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + Widget _buildQuestionCard(SymptomsCheckerViewModel viewModel) { + if (viewModel.isTriageDiagnosisLoading) { + return _buildLoadingShimmer(); + } + + if (viewModel.currentTriageQuestion == null) { + return Center( + child: LocaleKeys.noQuestionAvailable.tr(context: context).toText16(weight: FontWeight.w500), + ); + } + + final question = viewModel.currentTriageQuestion; + if (question == null || question.items == null || question.items!.isEmpty) { + return SizedBox.shrink(); + } + return AnimatedSwitcher( duration: const Duration(milliseconds: 400), transitionBuilder: (Widget child, Animation animation) { final offsetAnimation = Tween( begin: const Offset(1.0, 0.0), end: Offset.zero, - ).animate(CurvedAnimation( - parent: animation, - curve: Curves.easeInOut, - )); + ).animate( + CurvedAnimation( + parent: animation, + curve: Curves.easeInOut, + ), + ); return SlideTransition( position: offsetAnimation, @@ -140,7 +363,7 @@ class _TriageScreenState extends State { ); }, child: Container( - key: ValueKey(currentQuestionIndex), + key: ValueKey(question.items!.first.id ?? viewModel.getTriageEvidence().length.toString()), width: double.infinity, margin: EdgeInsets.symmetric(horizontal: 24.w), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), @@ -148,11 +371,36 @@ class _TriageScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - currentQuestion.question.toText16(weight: FontWeight.w500), + // Main question text + (question.text ?? "").toText16(weight: FontWeight.w600, color: AppColors.textColor), SizedBox(height: 24.h), - ...List.generate(currentQuestion.options.length, (index) { - bool selected = currentQuestion.selectedOptionIndex == index; - return _buildOptionItem(index, selected, currentQuestion.options[index].text); + + // Show all items with dividers + ...List.generate(question.items!.length, (itemIndex) { + final item = question.items![itemIndex]; + final itemId = item.id ?? ""; + final choices = item.choices ?? []; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Item name (sub-question) + (item.name ?? "").toText14(weight: FontWeight.w600, color: AppColors.textColor), + SizedBox(height: 8.h), + // Choices for this item + ...List.generate(choices.length, (choiceIndex) { + bool selected = viewModel.getTriageChoiceForItem(itemId) == choiceIndex; + return _buildOptionItem(itemId, choiceIndex, selected, choices[choiceIndex].label ?? ""); + }), + + // Add divider between items (but not after the last one) + if (itemIndex < question.items!.length - 1) ...[ + SizedBox(height: 8.h), + Divider(color: AppColors.bottomNAVBorder, thickness: 1), + SizedBox(height: 10.h), + ], + ], + ); }), ], ), @@ -160,9 +408,9 @@ class _TriageScreenState extends State { ); } - Widget _buildOptionItem(int index, bool selected, String optionText) { + Widget _buildOptionItem(String itemId, int choiceIndex, bool selected, String optionText) { return GestureDetector( - onTap: () => _onOptionSelected(index), + onTap: () => _onOptionSelectedForItem(itemId, choiceIndex), child: Container( margin: EdgeInsets.only(bottom: 12.h), child: Row( @@ -181,16 +429,30 @@ class _TriageScreenState extends State { child: selected ? Icon(Icons.check, size: 16.f, color: AppColors.whiteColor) : null, ), SizedBox(width: 12.w), - Expanded(child: optionText.toText14(weight: FontWeight.w500)), + Expanded(child: optionText.toText13(weight: FontWeight.w500)), ], ), ), ); } - Widget _buildStickyBottomCard(BuildContext context) { - final currentScore = TriageQuestionsData.calculateTotalScore(triageQuestions); - final suggestedCondition = TriageQuestionsData.getSuggestedCondition(currentScore); + Widget _buildStickyBottomCard(BuildContext context, SymptomsCheckerViewModel viewModel) { + // Get the top condition with highest probability + final conditions = viewModel.currentConditions ?? []; + final isArabic = _appState.isArabic(); + String suggestedCondition = LocaleKeys.analyzing.tr(context: context); + double probability = 0.0; + + if (conditions.isNotEmpty) { + // Sort by probability descending + final sortedConditions = List.from(conditions); + sortedConditions.sort((a, b) => (b.probability ?? 0.0).compareTo(a.probability ?? 0.0)); + + final topCondition = sortedConditions.first; + suggestedCondition = topCondition.getDisplayName(isArabic: isArabic); + probability = (topCondition.probability ?? 0.0) * 100; // Convert to percentage + } + // final bool isHighConfidence = probability >= 70.0; return Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), @@ -203,60 +465,60 @@ class _TriageScreenState extends State { children: [ RichText( text: TextSpan( - text: "Possible symptom: ".needTranslation, + text: LocaleKeys.possibleSymptom.tr(context: context), style: TextStyle( - color: AppColors.greyTextColor, - fontWeight: FontWeight.w600, - fontSize: 14.f, - ), + color: AppColors.greyTextColor, fontWeight: FontWeight.w600, fontSize: 14.f, fontFamily: isArabic ? 'GESSTwo' : 'Poppins'), children: [ TextSpan( text: suggestedCondition, style: TextStyle( color: AppColors.textColor, fontWeight: FontWeight.w600, - fontSize: 14.f, - ), + fontSize: 14.f, fontFamily: isArabic ? 'GESSTwo' : 'Poppins'), ), ], ), ), SizedBox(height: 16.h), CustomRoundedProgressBar( - percentage: currentScore, + percentage: probability.toInt(), paddingBetween: 5.h, color: AppColors.primaryRedColor, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.17), height: 8.h, titleWidget: RichText( text: TextSpan( - text: "$currentScore% ", + text: "${probability.toStringAsFixed(1)}% ", style: TextStyle( + fontFamily: isArabic ? 'GESSTwo' : 'Poppins', color: AppColors.primaryRedColor, fontWeight: FontWeight.w600, fontSize: 14.f, ), children: [ TextSpan( - text: "- Symptoms checker finding score".needTranslation, + text: LocaleKeys.symptomsCheckerFindingScore.tr(context: context), style: TextStyle( color: AppColors.textColor, fontWeight: FontWeight.w500, fontSize: 13.f, + fontFamily: isArabic ? 'GESSTwo' : 'Poppins', ), ), ], ), ), ), + // Show high confidence message + SizedBox(height: 12.h), Row( children: [ Expanded( child: CustomButton( - text: "Previous".needTranslation, + text: LocaleKeys.previous.tr(context: context), onPressed: isFirstQuestion ? () {} : _onPreviousPressed, - isDisabled: isFirstQuestion, + isDisabled: isFirstQuestion || viewModel.isTriageDiagnosisLoading, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), borderColor: Colors.transparent, textColor: AppColors.primaryRedColor, @@ -266,7 +528,8 @@ class _TriageScreenState extends State { SizedBox(width: 12.w), Expanded( child: CustomButton( - text: isLastQuestion ? "Finish".needTranslation : "Next".needTranslation, + text: LocaleKeys.next.tr(context: context), + isDisabled: viewModel.isTriageDiagnosisLoading, onPressed: _onNextPressed, backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, diff --git a/lib/presentation/symptoms_checker/user_info_selection.dart b/lib/presentation/symptoms_checker/user_info_selection.dart index fd00308..c8d8cde 100644 --- a/lib/presentation/symptoms_checker/user_info_selection.dart +++ b/lib/presentation/symptoms_checker/user_info_selection.dart @@ -1,26 +1,29 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:provider/provider.dart'; -class UserInfoSelectionScreen extends StatefulWidget { - const UserInfoSelectionScreen({super.key}); +class UserInfoSelectionPage extends StatefulWidget { + const UserInfoSelectionPage({super.key}); @override - State createState() => _UserInfoSelectionScreenState(); + State createState() => _UserInfoSelectionPageState(); } -class _UserInfoSelectionScreenState extends State { +class _UserInfoSelectionPageState extends State { @override void initState() { super.initState(); @@ -40,13 +43,10 @@ class _UserInfoSelectionScreenState extends State { if (user == null) return; // Populate gender (gender is int: 1=Male, 2=Female) + // Use internal keys (male/female) for storage if (user.gender != null) { - String genderStr = user.gender == 1 - ? "Male" - : user.gender == 2 - ? "Female" - : "Other"; - viewModel.setGender(genderStr); + String genderKey = user.gender == 1 ? "male" : user.gender == 2 ? "female" : "other"; + viewModel.setGender(genderKey); } if (user.dateofBirth != null && user.dateofBirth!.isNotEmpty) { @@ -81,17 +81,18 @@ class _UserInfoSelectionScreenState extends State { child: Row( children: [ Container( - height: 40.h, - width: 40.h, - margin: EdgeInsets.only(right: 10.h), - padding: EdgeInsets.all(8.h), - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.greyColor), - child: Utils.buildSvgWithAssets(icon: leadingIcon, iconColor: iconColor)), + height: 40.h, + width: 40.h, + margin: EdgeInsetsDirectional.only(end: 10.h), + padding: EdgeInsets.all(8.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.greyColor), + child: Utils.buildSvgWithAssets(icon: leadingIcon, iconColor: iconColor), + ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - title.toText16(weight: FontWeight.w500), - subTitle.toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500), + title.toText14(weight: FontWeight.w500), + subTitle.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500), ], ), ], @@ -106,7 +107,21 @@ class _UserInfoSelectionScreenState extends State { Widget _getDivider() { return Divider( color: AppColors.dividerColor, - ).paddingSymmetrical(0, 16.h); + ).paddingSymmetrical(0, 8.h); + } + + /// Convert internal gender key to localized display string + String _getLocalizedGender(String? genderKey, BuildContext context) { + if (genderKey == null) return LocaleKeys.notSet.tr(context: context); + + final lowerKey = genderKey.toLowerCase(); + if (lowerKey == "male") { + return LocaleKeys.malE.tr(context: context); + } else if (lowerKey == "female") { + return LocaleKeys.femaleGender.tr(context: context); + } else { + return genderKey; // Return as-is if not recognized + } } @override @@ -114,8 +129,25 @@ class _UserInfoSelectionScreenState extends State { AppState appState = getIt.get(); String name = ""; + int? userAgeFromDOB; if (appState.isAuthenticated) { - name = "${appState.getAuthenticatedUser()!.firstName!} ${appState.getAuthenticatedUser()!.lastName!} "; + final user = appState.getAuthenticatedUser(); + name = "${user!.firstName!} ${user.lastName!} "; + + // Calculate age from authenticated user's DOB if available + if (user.dateofBirth != null && user.dateofBirth!.isNotEmpty) { + try { + DateTime dob = DateUtil.convertStringToDate(user.dateofBirth!); + final now = DateTime.now(); + int age = now.year - dob.year; + if (now.month < dob.month || (now.month == dob.month && now.day < dob.day)) { + age--; + } + userAgeFromDOB = age; + } catch (e) { + // If date parsing fails, ignore + } + } } else { name = "Guest"; } @@ -131,20 +163,23 @@ class _UserInfoSelectionScreenState extends State { viewModel.selectedWeight == null; // Get display values - String genderText = viewModel.selectedGender ?? "Not set"; - // Show age calculated from DOB, not the DOB itself - String ageText = viewModel.selectedAge != null ? "${viewModel.selectedAge} Years" : "Not set"; - String heightText = - viewModel.selectedHeight != null ? "${viewModel.selectedHeight!.round()} ${viewModel.isHeightCm ? 'cm' : 'ft'}" : "Not set"; - String weightText = - viewModel.selectedWeight != null ? "${viewModel.selectedWeight!.round()} ${viewModel.isWeightKg ? 'kg' : 'lbs'}" : "Not set"; + String genderText = _getLocalizedGender(viewModel.selectedGender, context); + // Show age calculated from DOB (prefer viewModel's age, fallback to calculated from user's DOB) + int? displayAge = viewModel.selectedAge ?? userAgeFromDOB; + String ageText = displayAge != null ? "$displayAge ${LocaleKeys.years.tr(context: context)}" : LocaleKeys.notSet.tr(context: context); + String heightText = viewModel.selectedHeight != null + ? "${viewModel.selectedHeight!.round()} ${viewModel.isHeightCm ? 'cm' : 'ft'}" + : LocaleKeys.notSet.tr(context: context); + String weightText = viewModel.selectedWeight != null + ? "${viewModel.selectedWeight!.round()} ${viewModel.isWeightKg ? 'kg' : 'lbs'}" + : LocaleKeys.notSet.tr(context: context); return Column( children: [ Expanded( child: CollapsingListView( - title: "Symptoms Checker".needTranslation, - isLeading: Navigator.canPop(context), + title: LocaleKeys.symptomsChecker.tr(context: context), + isLeading: true, child: SingleChildScrollView( child: Column( children: [ @@ -154,15 +189,15 @@ class _UserInfoSelectionScreenState extends State { padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w), child: Column( children: [ - "Hello $name, Is your information up to date?".needTranslation.toText18( - weight: FontWeight.w600, - color: AppColors.textColor, - ), - SizedBox(height: 24.h), + LocaleKeys.helloIsYourInformationUpToDate.tr(namedArgs: {'name': name}).toText16( + weight: FontWeight.w600, + color: AppColors.textColor, + ), + SizedBox(height: 32.h), _buildEditInfoTile( context: context, leadingIcon: AppAssets.genderIcon, - title: "Gender".needTranslation, + title: LocaleKeys.gender.tr(context: context), subTitle: genderText, onTap: () { viewModel.setUserInfoPage(0, isSinglePageEdit: true); @@ -174,7 +209,7 @@ class _UserInfoSelectionScreenState extends State { _buildEditInfoTile( context: context, leadingIcon: AppAssets.calendarGrey, - title: "Age".needTranslation, + title: LocaleKeys.age.tr(context: context), subTitle: ageText, iconColor: AppColors.greyTextColor, onTap: () { @@ -187,7 +222,7 @@ class _UserInfoSelectionScreenState extends State { _buildEditInfoTile( context: context, leadingIcon: AppAssets.rulerIcon, - title: "Height".needTranslation, + title: LocaleKeys.height.tr(context: context), subTitle: heightText, onTap: () { viewModel.setUserInfoPage(2, isSinglePageEdit: true); @@ -199,7 +234,7 @@ class _UserInfoSelectionScreenState extends State { _buildEditInfoTile( context: context, leadingIcon: AppAssets.weightScale, - title: "Weight".needTranslation, + title: LocaleKeys.weight.tr(context: context), subTitle: weightText, onTap: () { viewModel.setUserInfoPage(3, isSinglePageEdit: true); @@ -228,48 +263,48 @@ class _UserInfoSelectionScreenState extends State { decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r), child: SafeArea( top: false, - child: Padding( - padding: EdgeInsets.all(8.h), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Row( - children: [ - Expanded( - child: CustomButton( - text: "No, Edit all".needTranslation, - icon: AppAssets.edit_icon, - iconColor: AppColors.primaryRedColor, - onPressed: () { - context.read().setUserInfoPage(0, isSinglePageEdit: false); - context.navigateWithName(AppRoutes.userInfoFlowManager); - }, - backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), - borderColor: Colors.transparent, - textColor: AppColors.primaryRedColor, - fontSize: 16.f, - ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 24.h), + Row( + children: [ + Expanded( + child: CustomButton( + text: LocaleKeys.noEditAll.tr(context: context), + icon: AppAssets.edit_icon, + iconColor: AppColors.primaryRedColor, + onPressed: () { + context.read().setUserInfoPage(0, isSinglePageEdit: false); + context.navigateWithName(AppRoutes.userInfoFlowManager); + }, + backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), + borderColor: Colors.transparent, + textColor: AppColors.primaryRedColor, + fontSize: 16.f, + iconSize: 20.w, ), - SizedBox(width: 12.w), - Expanded( - child: CustomButton( - text: "Yes, It is".needTranslation, - icon: AppAssets.tickIcon, - iconColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor, - onPressed: hasEmptyFields - ? () {} // Empty function for disabled state - : () => context.navigateWithName(AppRoutes.organSelectorPage), - backgroundColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor, - borderColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor, - textColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor, - fontSize: 16.f, - ), + ), + SizedBox(width: 12.w), + Expanded( + child: CustomButton( + text: LocaleKeys.yesItIs.tr(context: context), + icon: AppAssets.tickIcon, + iconColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor, + onPressed: hasEmptyFields + ? () {} // Empty function for disabled state + : () => context.navigateWithName(AppRoutes.organSelectorPage), + backgroundColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor, + borderColor: hasEmptyFields ? AppColors.greyLightColor : AppColors.primaryRedColor, + textColor: hasEmptyFields ? AppColors.greyTextColor : AppColors.whiteColor, + fontSize: 16.f, + iconSize: 20.w, ), - ], - ), - ], - ).paddingSymmetrical(24.w, 0), - ), + ), + ], + ), + ], + ).paddingSymmetrical(24.w, 0), ), ); } diff --git a/lib/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart b/lib/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart index d73f387..37802a2 100644 --- a/lib/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart +++ b/lib/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart @@ -1,10 +1,10 @@ -import 'dart:developer'; - +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/widgets/custom_date_picker.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -27,7 +27,7 @@ class AgeSelectionPage extends StatelessWidget { builder: (BuildContext context, symptomsViewModel, Widget? child) { return Column( children: [ - "What is your Date of Birth?".needTranslation.toText18(weight: FontWeight.w600, color: AppColors.textColor).paddingAll(24.w), + LocaleKeys.dateOfBirthSymptoms.tr(context: context).toText18(weight: FontWeight.w600, color: AppColors.textColor).paddingAll(24.w), SizedBox(height: 30.h), ThreeColumnDatePicker( enableHaptic: true, @@ -35,7 +35,6 @@ class AgeSelectionPage extends StatelessWidget { initialDate: symptomsViewModel.dateOfBirth ?? DateTime(2000, 1, 1), onDateChanged: (date) { symptomsViewModel.setDateOfBirth(date); - log('DOB saved: $date, Age: ${symptomsViewModel.selectedAge}'); }, ) ], diff --git a/lib/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart b/lib/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart index 85cb6e2..07f44f1 100644 --- a/lib/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart +++ b/lib/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -5,6 +6,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -13,12 +15,16 @@ class GenderSelectionPage extends StatelessWidget { final String? selectedGender; final Function(String) onGenderSelected; - GenderSelectionPage({ + const GenderSelectionPage({ super.key, required this.selectedGender, required this.onGenderSelected, }); + // Internal gender keys (constant, not localized) + static const String maleKey = "male"; + static const String femaleKey = "female"; + _buildGenderOption(String iconPng, String label, bool isSelected) { return Container( height: 160.h, @@ -38,7 +44,27 @@ class GenderSelectionPage extends StatelessWidget { ); } - final genders = ["Male", "Female"]; + /// Check if the selected gender matches the given key + /// Handles both internal keys and localized strings + bool _isGenderSelected(String genderKey, String? currentSelection, BuildContext context) { + if (currentSelection == null) return false; + + final lowerSelection = currentSelection.toLowerCase(); + + if (genderKey == maleKey) { + // Check against internal key, English, and Arabic + return lowerSelection == maleKey || + lowerSelection == "male" || + currentSelection == LocaleKeys.malE.tr(context: context) || + currentSelection == "ذكر"; + } else { + // Check against internal key, English, and Arabic + return lowerSelection == femaleKey || + lowerSelection == "female" || + currentSelection == LocaleKeys.femaleGender.tr(context: context) || + currentSelection == "أنثى"; + } + } @override Widget build(BuildContext context) { @@ -48,22 +74,31 @@ class GenderSelectionPage extends StatelessWidget { builder: (BuildContext context, symptomsViewModel, Widget? child) { return Column( children: [ - "What is your gender?".needTranslation.toText18(weight: FontWeight.w600, color: AppColors.textColor), + LocaleKeys.genderSymptoms.tr(context: context).toText18(weight: FontWeight.w600, color: AppColors.textColor), SizedBox(height: 70.h), Row( children: [ Expanded( child: InkWell( - onTap: () => onGenderSelected(genders[0]), - child: _buildGenderOption(AppAssets.maleIcon, "Male".needTranslation, symptomsViewModel.selectedGender == genders[0]), + onTap: () => onGenderSelected(maleKey), + child: _buildGenderOption( + AppAssets.maleIcon, + LocaleKeys.malE.tr(context: context), + _isGenderSelected(maleKey, symptomsViewModel.selectedGender, context), + ), ), ), SizedBox(width: 16.w), Expanded( - child: InkWell( - onTap: () => onGenderSelected(genders[1]), - child: _buildGenderOption(AppAssets.femaleIcon, "Female".needTranslation, symptomsViewModel.selectedGender == genders[1]), - )) + child: InkWell( + onTap: () => onGenderSelected(femaleKey), + child: _buildGenderOption( + AppAssets.femaleIcon, + LocaleKeys.femaleGender.tr(context: context), + _isGenderSelected(femaleKey, symptomsViewModel.selectedGender, context), + ), + ), + ) ], ), ], diff --git a/lib/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart b/lib/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart index 0744e81..65cf5a5 100644 --- a/lib/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart +++ b/lib/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart @@ -1,10 +1,12 @@ import 'dart:developer'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/widgets/height_scale.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -107,7 +109,7 @@ class HeightSelectionPage extends StatelessWidget { SizedBox(height: 24.h), Center( child: Text( - 'How tall are you?'.needTranslation, + LocaleKeys.heightSymptoms.tr(context: context), style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), ), ), diff --git a/lib/presentation/symptoms_checker/user_info_selection/pages/weight_selection_page.dart b/lib/presentation/symptoms_checker/user_info_selection/pages/weight_selection_page.dart index 1d38a91..8c83796 100644 --- a/lib/presentation/symptoms_checker/user_info_selection/pages/weight_selection_page.dart +++ b/lib/presentation/symptoms_checker/user_info_selection/pages/weight_selection_page.dart @@ -1,10 +1,12 @@ import 'dart:developer'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/widgets/weight_scale.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -113,7 +115,7 @@ class WeightSelectionPage extends StatelessWidget { SizedBox(height: 24.h), Center( child: Text( - 'What is your weight?'.needTranslation, + LocaleKeys.weightSymptoms.tr(context: context), style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), ), ), diff --git a/lib/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart b/lib/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart index 523470e..fdfe228 100644 --- a/lib/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart +++ b/lib/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart @@ -1,10 +1,11 @@ import 'dart:developer'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; -import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/age_selection_page.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/gender_selection_page.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/pages/height_selection_page.dart'; @@ -27,13 +28,15 @@ class _UserInfoFlowManagerState extends State { late PageController _pageController; late SymptomsCheckerViewModel _viewModel; - // Page titles - final List _pageTitles = [ - "Your Gender", - "Your Birth Date", - "Your Height", - "Your Weight", - ]; + // Get localized page titles + List _getPageTitles(BuildContext context) { + return [ + LocaleKeys.genderSymptoms.tr(context: context), + LocaleKeys.dateOfBirthSymptoms.tr(context: context), + LocaleKeys.heightSymptoms.tr(context: context), + LocaleKeys.weightSymptoms.tr(context: context), + ]; + } @override void initState() { @@ -184,10 +187,12 @@ class _UserInfoFlowManagerState extends State { child: isSingleEdit ? // Single page edit mode - show only Save button CustomButton( - text: "Save".needTranslation, - onPressed: _onNext, - backgroundColor: AppColors.primaryRedColor, - borderColor: AppColors.primaryRedColor, + text: LocaleKeys.save.tr(context: context), + isDisabled: !(viewModel.isCurrentUserInfoPageValid), + onPressed: () => viewModel.isCurrentUserInfoPageValid ? _onNext() : () {}, + backgroundColor: + viewModel.isCurrentUserInfoPageValid ? AppColors.primaryRedColor : AppColors.primaryRedColor.withValues(alpha: 0.5), + borderColor: viewModel.isCurrentUserInfoPageValid ? AppColors.primaryRedColor : AppColors.primaryRedColor.withValues(alpha: 0.5), textColor: AppColors.whiteColor, fontSize: 16.f, ) @@ -197,7 +202,7 @@ class _UserInfoFlowManagerState extends State { if (!isFirstPage) ...[ Expanded( child: CustomButton( - text: "Previous".needTranslation, + text: LocaleKeys.previous.tr(context: context), onPressed: _onPrevious, backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.11), borderColor: Colors.transparent, @@ -209,7 +214,7 @@ class _UserInfoFlowManagerState extends State { ], Expanded( child: CustomButton( - text: isLastPage ? "Submit".needTranslation : "Next".needTranslation, + text: isLastPage ? LocaleKeys.submit.tr(context: context) : LocaleKeys.next.tr(context: context), onPressed: _onNext, backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -226,6 +231,8 @@ class _UserInfoFlowManagerState extends State { @override Widget build(BuildContext context) { + final pageTitles = _getPageTitles(context); + return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: Column( @@ -233,7 +240,7 @@ class _UserInfoFlowManagerState extends State { Expanded( child: CollapsingListView( physics: NeverScrollableScrollPhysics(), - title: _pageTitles[_viewModel.userInfoCurrentPage].needTranslation, + title: pageTitles[_viewModel.userInfoCurrentPage], isLeading: true, child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/presentation/symptoms_checker/widgets/condition_card.dart b/lib/presentation/symptoms_checker/widgets/condition_card.dart index 87a8f3d..e48f41e 100644 --- a/lib/presentation/symptoms_checker/widgets/condition_card.dart +++ b/lib/presentation/symptoms_checker/widgets/condition_card.dart @@ -1,42 +1,145 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/symptoms_checker/models/resp_models/triage_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/widgets/custom_progress_bar.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; class ConditionCard extends StatelessWidget { - final IconData icon; - final String title; - final int percentage; - final String tagText; - final String clinic; + final TriageCondition condition; final List symptoms; - final String description; - final String? monitorNote; - final String? appointmentLabel; - final PossibleConditionsSeverityEnum possibleConditionsSeverityEnum; final VoidCallback? onActionPressed; const ConditionCard({ super.key, - required this.icon, - required this.title, - required this.percentage, - required this.tagText, - required this.clinic, + required this.condition, required this.symptoms, - required this.description, - this.monitorNote, - this.appointmentLabel, - required this.possibleConditionsSeverityEnum, this.onActionPressed, }); + /// Get title from condition (localized) + String get title { + final appState = getIt(); + return condition.getDisplayName(isArabic: appState.isArabic()); + } + + /// Get percentage from probability (0-1 to 0-100) + int get percentage => ((condition.probability ?? 0) * 100).toInt(); + + /// Get clinic name from category + String get clinic => condition.conditionDetails?.category?.name ?? ''; + + /// Get description from hint + String get description => condition.conditionDetails?.hint ?? ''; + + /// Get severity enum based on triage level + PossibleConditionsSeverityEnum get severityEnum { + final triageLevel = condition.conditionDetails?.triageLevel; + if (triageLevel != null) { + switch (triageLevel) { + case TriageLevelEnum.emergencyAmbulance: + case TriageLevelEnum.emergency: + return PossibleConditionsSeverityEnum.emergency; + case TriageLevelEnum.consultation24: + case TriageLevelEnum.consultation: + return PossibleConditionsSeverityEnum.seekMedicalAdvice; + case TriageLevelEnum.selfCare: + return PossibleConditionsSeverityEnum.monitorOnly; + } + } + // Default based on probability + if (percentage >= 70) { + return PossibleConditionsSeverityEnum.seekMedicalAdvice; + } else { + return PossibleConditionsSeverityEnum.monitorOnly; + } + } + + /// Get tag text based on triage level + String getTagText(BuildContext context) { + final triageLevel = condition.conditionDetails?.triageLevel; + if (triageLevel != null) { + switch (triageLevel) { + case TriageLevelEnum.emergencyAmbulance: + case TriageLevelEnum.emergency: + return LocaleKeys.emergency.tr(context: context); + case TriageLevelEnum.consultation24: + case TriageLevelEnum.consultation: + return LocaleKeys.seekMedicalAdvice.tr(context: context); + case TriageLevelEnum.selfCare: + return LocaleKeys.monitor.tr(context: context); + } + } + // Default based on probability + if (percentage >= 70) { + return LocaleKeys.seekMedicalAdvice.tr(context: context); + } else { + return LocaleKeys.monitor.tr(context: context); + } + } + + /// Get monitor note if applicable + String? getMonitorNote(BuildContext context) { + if (severityEnum == PossibleConditionsSeverityEnum.monitorOnly) { + return LocaleKeys.noNeedToVisitDoctor.tr(context: context); + } + return null; + } + + /// Get icon based on category name from API + IconData get icon { + final categoryName = condition.conditionDetails?.category?.name?.toLowerCase() ?? ''; + + if (categoryName.contains('cardio') || categoryName.contains('heart')) { + return Icons.favorite; + } else if (categoryName.contains('neuro') || categoryName.contains('brain')) { + return Icons.psychology_alt; + } else if (categoryName.contains('psychiatr') || categoryName.contains('mental')) { + return Icons.psychology; + } else if (categoryName.contains('eye') || categoryName.contains('ophthalmo')) { + return Icons.remove_red_eye; + } else if (categoryName.contains('ent') || categoryName.contains('ear')) { + return Icons.hearing; + } else if (categoryName.contains('derma') || categoryName.contains('skin')) { + return Icons.face; + } else if (categoryName.contains('ortho') || categoryName.contains('bone')) { + return Icons.accessibility_new; + } else if (categoryName.contains('gyneco') || categoryName.contains('obstet')) { + return Icons.pregnant_woman; + } else if (categoryName.contains('pediatr') || categoryName.contains('child')) { + return Icons.child_care; + } else if (categoryName.contains('surg')) { + return Icons.local_hospital; + } else if (categoryName.contains('pulmo') || categoryName.contains('lung') || categoryName.contains('respiratory')) { + return Icons.air; + } else if (categoryName.contains('gastro') || categoryName.contains('digest')) { + return Icons.restaurant; + } else if (categoryName.contains('nephro') || categoryName.contains('kidney')) { + return Icons.water_drop; + } else if (categoryName.contains('hemato') || categoryName.contains('blood')) { + return Icons.bloodtype; + } else if (categoryName.contains('infect') || categoryName.contains('virus')) { + return Icons.coronavirus; + } else if (categoryName.contains('emergency')) { + return Icons.emergency; + } else if (categoryName.contains('geriatr') || categoryName.contains('elder')) { + return Icons.elderly; + } else if (categoryName.contains('internal')) { + return Icons.medical_services; + } + + return Icons.medical_services; + } + Color getChipColorBySeverityEnum(PossibleConditionsSeverityEnum possibleConditionsSeverityEnum) { switch (possibleConditionsSeverityEnum) { case PossibleConditionsSeverityEnum.seekMedicalAdvice: @@ -65,7 +168,7 @@ class ConditionCard extends StatelessWidget { crossAxisAlignment: WrapCrossAlignment.center, children: [ for (int i = 0; i < symptoms.length; i++) ...[ - Text(symptoms[i], style: TextStyle(color: AppColors.greyTextColor, fontWeight: FontWeight.w500, fontSize: 12.f)), + "● ${symptoms[i]}".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), if (i != symptoms.length - 1) Padding( padding: EdgeInsets.symmetric(horizontal: 2.w), @@ -78,9 +181,12 @@ class ConditionCard extends StatelessWidget { @override Widget build(BuildContext context) { + // final monitorNote = getMonitorNote(context); + final tagText = getTagText(context); + return Container( width: double.infinity, - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -88,14 +194,14 @@ class ConditionCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( - width: 48.w, - height: 48.w, + width: 32.w, + height: 32.w, decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: getChipColorBySeverityEnum(possibleConditionsSeverityEnum).withValues(alpha: 0.2), - borderRadius: 12.r, + color: getChipColorBySeverityEnum(severityEnum).withValues(alpha: 0.2), + borderRadius: 8.r, hasShadow: false, ), - child: Icon(icon, color: getChipTextColorBySeverityEnum(possibleConditionsSeverityEnum), size: 24.f), + child: Icon(icon, color: getChipTextColorBySeverityEnum(severityEnum), size: 16.f), ), SizedBox(width: 12.w), Expanded( @@ -106,34 +212,23 @@ class ConditionCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( - child: Text( - title, - style: TextStyle(fontSize: 18.f, fontWeight: FontWeight.w600, color: AppColors.textColor), - overflow: TextOverflow.ellipsis, - ), + child: title.toText18(weight: FontWeight.w600, color: AppColors.textColor), ), AppCustomChipWidget( labelText: tagText, - backgroundColor: getChipColorBySeverityEnum(possibleConditionsSeverityEnum).withValues(alpha: 0.2), - textColor: getChipTextColorBySeverityEnum(possibleConditionsSeverityEnum), + backgroundColor: getChipColorBySeverityEnum(severityEnum).withValues(alpha: 0.2), + textColor: getChipTextColorBySeverityEnum(severityEnum), ), ], ), CustomRoundedProgressBar( percentage: percentage, height: 6.h, - color: getChipColorBySeverityEnum(possibleConditionsSeverityEnum), + color: getChipColorBySeverityEnum(severityEnum), backgroundColor: AppColors.scaffoldBgColor, titleWidget: Row( children: [ - Text( - "$percentage%", - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 12.f, - color: getChipColorBySeverityEnum(possibleConditionsSeverityEnum), - ), - ), + "$percentage%".toText12(fontWeight: FontWeight.bold, color: getChipColorBySeverityEnum(severityEnum)), ], ).paddingSymmetrical(0, 4.h), ), @@ -146,50 +241,42 @@ class ConditionCard extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - clinic, - style: TextStyle( - fontWeight: FontWeight.w600, - fontSize: 14.f, - color: AppColors.textColor, - ), - ), + LocaleKeys.commonSymptom.tr(context: context).toText14(weight: FontWeight.w600, color: AppColors.textColor), _buildSymptomsRow(), SizedBox(height: 16.h), - Text("Description".needTranslation, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.f, color: AppColors.textColor)), + LocaleKeys.description.tr(context: context).toText14(weight: FontWeight.bold, color: AppColors.textColor), SizedBox(height: 2.h), - Text(description, style: TextStyle(color: AppColors.greyTextColor, fontWeight: FontWeight.w500, fontSize: 12.f)), - if (possibleConditionsSeverityEnum == PossibleConditionsSeverityEnum.emergency) + description.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + if (severityEnum != PossibleConditionsSeverityEnum.monitorOnly) CustomButton( - text: appointmentLabel ?? "Book Appointment".needTranslation, + text: LocaleKeys.bookAppointment.tr(context: context), onPressed: () { if (onActionPressed != null) { onActionPressed!(); } }, - backgroundColor: AppColors.lightRedButtonColor, + backgroundColor: AppColors.primaryRedColor, borderColor: Colors.transparent, - textColor: AppColors.primaryRedColor, - fontSize: 16.f, + textColor: AppColors.whiteColor, + fontSize: 14.f, fontWeight: FontWeight.w500, - borderRadius: 12.r, padding: EdgeInsets.symmetric(horizontal: 10.w), - height: 48.h, icon: AppAssets.add_icon, - iconColor: AppColors.primaryRedColor, - iconSize: 18.h, + height: 48.h, + iconColor: AppColors.whiteColor, ).paddingOnly(top: 16.w), - if (monitorNote != null) - Container( - margin: EdgeInsets.only(top: 12.h), - child: AppCustomChipWidget( - labelText: monitorNote!, - backgroundColor: AppColors.whiteColor, - textColor: AppColors.textColor, - padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 8.h), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)), - ), - ), + + // if (monitorNote != null) + // Container( + // margin: EdgeInsets.only(top: 12.h), + // child: AppCustomChipWidget( + // labelText: monitorNote, + // backgroundColor: AppColors.whiteColor, + // textColor: AppColors.textColor, + // padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 8.h), + // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)), + // ), + // ), ], ).paddingAll(16.w), ], diff --git a/lib/presentation/symptoms_checker/widgets/interactive_body_widget.dart b/lib/presentation/symptoms_checker/widgets/interactive_body_widget.dart index 8957fb1..62c38f9 100644 --- a/lib/presentation/symptoms_checker/widgets/interactive_body_widget.dart +++ b/lib/presentation/symptoms_checker/widgets/interactive_body_widget.dart @@ -13,6 +13,7 @@ class InteractiveBodyWidget extends StatefulWidget { final bool isBodyHidden; final Function(String organId) onOrganTap; final String? tooltipOrganId; + final bool isArabic; const InteractiveBodyWidget({ super.key, @@ -22,6 +23,7 @@ class InteractiveBodyWidget extends StatefulWidget { required this.onOrganTap, this.isBodyHidden = false, this.tooltipOrganId, + this.isArabic = false, }); @override @@ -118,7 +120,10 @@ class _InteractiveBodyWidgetState extends State { (organ) { final centerX = organ.position.x * imageConstraints.maxWidth; final centerY = organ.position.y * imageConstraints.maxHeight; - return OrganTooltipWidget(organName: organ.description, position: Offset(centerX, centerY)); + return OrganTooltipWidget( + organName: organ.getLocalizedDescription(widget.isArabic), + position: Offset(centerX, centerY), + ); }, ), ], diff --git a/lib/presentation/symptoms_checker/widgets/selected_organs_section.dart b/lib/presentation/symptoms_checker/widgets/selected_organs_section.dart index c0f1be3..b66ef03 100644 --- a/lib/presentation/symptoms_checker/widgets/selected_organs_section.dart +++ b/lib/presentation/symptoms_checker/widgets/selected_organs_section.dart @@ -1,8 +1,10 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/symptoms_checker/models/organ_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -52,7 +54,7 @@ class _SelectedOrgansSectionState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - 'Selected Organs'.needTranslation, + LocaleKeys.selectedOrgans.tr(context: context), style: TextStyle( fontSize: 16.f, fontWeight: FontWeight.w600, @@ -101,7 +103,7 @@ class _SelectedOrgansSectionState extends State { Padding( padding: EdgeInsets.symmetric(vertical: 8.h), child: Text( - 'No organs selected yet'.needTranslation, + LocaleKeys.noOrgansSelected.tr(context: context), style: TextStyle( color: AppColors.greyTextColor, fontSize: 14.f, diff --git a/lib/presentation/todo_section/ancillary_order_payment_page.dart b/lib/presentation/todo_section/ancillary_order_payment_page.dart index fdfcc04..fe07186 100644 --- a/lib/presentation/todo_section/ancillary_order_payment_page.dart +++ b/lib/presentation/todo_section/ancillary_order_payment_page.dart @@ -83,7 +83,7 @@ class _AncillaryOrderPaymentPageState extends State { children: [ Expanded( child: CollapsingListView( - title: "Select Payment Method".needTranslation, + title: LocaleKeys.selectPaymentMethod.tr(context: context), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -103,9 +103,9 @@ class _AncillaryOrderPaymentPageState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Image.asset(AppAssets.mada, width: 72.h, height: 25.h).toShimmer2(isShow: todoVM.isProcessingPayment), + LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment), SizedBox(height: 16.h), - "Mada".needTranslation.toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment), + LocaleKeys.mada.tr(context: context).toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment), ], ), SizedBox(width: 8.h), @@ -152,7 +152,7 @@ class _AncillaryOrderPaymentPageState extends State { ], ).toShimmer2(isShow: todoVM.isProcessingPayment), SizedBox(height: 16.h), - "Visa or Mastercard".needTranslation.toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment), + LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment), ], ), SizedBox(width: 8.h), @@ -210,14 +210,14 @@ class _AncillaryOrderPaymentPageState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 24.h), - "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h), SizedBox(height: 17.h), // Amount before tax Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "Amount before tax".needTranslation.toText14(isBold: true), + LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true), Utils.getPaymentAmountWithSymbol( amountBeforeTax.toStringAsFixed(2).toText16(isBold: true), AppColors.blackColor, @@ -231,7 +231,7 @@ class _AncillaryOrderPaymentPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor), + LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor), Utils.getPaymentAmountWithSymbol( taxAmount.toStringAsFixed(2).toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, @@ -247,7 +247,7 @@ class _AncillaryOrderPaymentPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "".needTranslation.toText14(isBold: true), + "".toText14(isBold: true), Utils.getPaymentAmountWithSymbol( widget.totalAmount.toStringAsFixed(2).toText24(isBold: true), AppColors.blackColor, @@ -266,7 +266,11 @@ class _AncillaryOrderPaymentPageState extends State { fit: BoxFit.contain, ).paddingSymmetrical(24.h, 0.h).onPress(() { if (!todoSectionViewModel.isProcessingPayment) { - _startApplePay(); + if (Utils.havePrivilege(103)) { + _startApplePay(); + } else { + _openPaymentURL("ApplePay"); + } } }) : SizedBox(height: 12.h), @@ -342,7 +346,7 @@ class _AncillaryOrderPaymentPageState extends State { } void _checkPaymentStatus() { - LoaderBottomSheet.showLoader(loadingText: "Checking payment status, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context)); todoSectionViewModel.checkPaymentStatus( transID: transID, @@ -380,7 +384,7 @@ class _AncillaryOrderPaymentPageState extends State { required String paymentReference, required String paymentMethod, }) { - LoaderBottomSheet.showLoader(loadingText: "Processing payment, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingPaymentPleaseWait.tr(context: context)); final user = appState.getAuthenticatedUser(); @@ -422,7 +426,7 @@ class _AncillaryOrderPaymentPageState extends State { required String advanceNumber, required String paymentReference, }) { - LoaderBottomSheet.showLoader(loadingText: "Finalizing payment, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.finalizingPaymentPleaseWait.tr(context: context)); final user = appState.getAuthenticatedUser(); @@ -446,7 +450,7 @@ class _AncillaryOrderPaymentPageState extends State { } void _autoGenerateInvoice() { - LoaderBottomSheet.showLoader(loadingText: "Generating invoice, Please wait...".needTranslation); + LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingInvoicePleaseWait.tr(context: context)); List selectedProcListAPI = widget.selectedProcedures.map((element) { return { @@ -492,7 +496,7 @@ class _AncillaryOrderPaymentPageState extends State { children: [ Row( children: [ - "Here is your invoice #: ".needTranslation.toText14( + LocaleKeys.hereIsYourInvoiceNumber.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -506,7 +510,7 @@ class _AncillaryOrderPaymentPageState extends State { Expanded( child: CustomButton( height: 56.h, - text: LocaleKeys.ok.tr(), + text: LocaleKeys.ok.tr(context: context), onPressed: () { Navigator.pushAndRemoveUntil( context, @@ -524,8 +528,8 @@ class _AncillaryOrderPaymentPageState extends State { ), ], ), - // title: "Payment Completed Successfully".needTranslation, - titleWidget: Utils.getSuccessWidget(loadingText: "Payment Completed Successfully".needTranslation), + // title: LocaleKeys.paymentCompletedSuccessfully.tr(context: context), + titleWidget: Utils.getSuccessWidget(loadingText: LocaleKeys.paymentCompletedSuccessfully.tr(context: context)), isCloseButtonVisible: false, isDismissible: false, isFullScreen: false, @@ -603,7 +607,7 @@ class _AncillaryOrderPaymentPageState extends State { Navigator.of(context).pop(); showCommonBottomSheetWithoutHeight( context, - child: Utils.getErrorWidget(loadingText: "Failed to initialize Apple Pay. Please try again.".needTranslation), + child: Utils.getErrorWidget(loadingText: LocaleKeys.failedToInitializeApplePay.tr(context: context)), callBackFunc: () {}, isFullScreen: false, isCloseButtonVisible: true, diff --git a/lib/presentation/todo_section/ancillary_procedures_details_page.dart b/lib/presentation/todo_section/ancillary_procedures_details_page.dart index b7515af..eba80cd 100644 --- a/lib/presentation/todo_section/ancillary_procedures_details_page.dart +++ b/lib/presentation/todo_section/ancillary_procedures_details_page.dart @@ -102,14 +102,14 @@ class _AncillaryOrderDetailsListState extends State { String _getApprovalStatusText(AncillaryOrderProcDetail procedure) { if (procedure.isApprovalRequired == false) { - return "Cash"; + return LocaleKeys.cash.tr(context: context); } else { if (procedure.isApprovalCreated == true && procedure.approvalNo != 0) { - return "Approved"; + return LocaleKeys.approved.tr(context: context); } else if (procedure.isApprovalRequired == true && procedure.isApprovalCreated == true && procedure.approvalNo == 0) { - return "Approval Rejected - Please visit receptionist"; + return LocaleKeys.approvalRejectedPleaseVisitReceptionist.tr(context: context); } else { - return "Sent For Approval"; + return LocaleKeys.sentForApproval.tr(context: context); } } } @@ -135,7 +135,7 @@ class _AncillaryOrderDetailsListState extends State { children: [ Expanded( child: CollapsingListView( - title: "Ancillary Order Details".needTranslation, + title: LocaleKeys.ancillaryOrderDetails.tr(context: context), child: viewModel.isAncillaryDetailsProceduresLoading ? _buildLoadingShimmer().paddingSymmetrical(24.w, 0) : viewModel.patientAncillaryOrderProceduresList.isEmpty @@ -153,7 +153,7 @@ class _AncillaryOrderDetailsListState extends State { ), ), ), - if (orderData != null) _buildStickyPaymentButton(orderData), + if (orderData != null && !viewModel.isAncillaryDetailsProceduresLoading) _buildStickyPaymentButton(orderData), ], ); }), @@ -164,6 +164,7 @@ class _AncillaryOrderDetailsListState extends State { return ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.zero, itemCount: 3, itemBuilder: (context, index) { return AncillaryOrderCard( @@ -186,7 +187,7 @@ class _AncillaryOrderDetailsListState extends State { ), child: Utils.getNoDataWidget( context, - noDataText: "No Procedures available for the selected order.".needTranslation, + noDataText: LocaleKeys.noProceduresAvailableForSelectedOrder.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -372,7 +373,7 @@ class _AncillaryOrderDetailsListState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Procedures".needTranslation.toText12( + LocaleKeys.procedures.tr(context: context).toText12( color: AppColors.textColorLight, fontWeight: FontWeight.w600, ), @@ -385,7 +386,7 @@ class _AncillaryOrderDetailsListState extends State { Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ - "Total Amount".needTranslation.toText12( + LocaleKeys.totalAmount.tr(context: context).toText12( color: AppColors.textColorLight, fontWeight: FontWeight.w600, ), @@ -535,7 +536,7 @@ class _AncillaryOrderDetailsListState extends State { // ), if (procedure.isCovered == true) AppCustomChipWidget( - labelText: "Covered".needTranslation, + labelText: LocaleKeys.covered.tr(context: context), backgroundColor: AppColors.successColor.withValues(alpha: 0.1), textColor: AppColors.successColor, ), @@ -551,7 +552,7 @@ class _AncillaryOrderDetailsListState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Price".needTranslation.toText10(color: AppColors.textColorLight), + LocaleKeys.price.tr(context: context).toText10(color: AppColors.textColorLight), SizedBox(height: 4.h), Row( children: [ @@ -570,7 +571,7 @@ class _AncillaryOrderDetailsListState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "VAT (15%)".needTranslation.toText10(color: AppColors.textColorLight), + LocaleKeys.vatPercent.tr(context: context).toText10(color: AppColors.textColorLight), SizedBox(height: 4.h), Row( children: [ @@ -589,7 +590,7 @@ class _AncillaryOrderDetailsListState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Total".needTranslation.toText10(color: AppColors.textColorLight), + LocaleKeys.total.tr(context: context).toText10(color: AppColors.textColorLight), SizedBox(height: 4.h), Row( children: [ @@ -654,9 +655,10 @@ class _AncillaryOrderDetailsListState extends State { CustomButton( borderWidth: 0, backgroundColor: AppColors.infoLightColor, - text: "Proceed to Payment".needTranslation, + text: LocaleKeys.proceedToPayment.tr(context: context), onPressed: () { // Navigate to payment page with selected procedures + todoSectionViewModel.setIsAncillaryOrdersNeedReloading(true); Navigator.of(context).push( CustomPageRoute( page: AncillaryOrderPaymentPage( diff --git a/lib/presentation/todo_section/todo_page.dart b/lib/presentation/todo_section/todo_page.dart index 0d2d806..161ffaf 100644 --- a/lib/presentation/todo_section/todo_page.dart +++ b/lib/presentation/todo_section/todo_page.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:developer'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/todo_section/models/resp_models/ancillary_order_list_response_model.dart'; import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/todo_section/ancillary_procedures_details_page.dart'; import 'package:hmg_patient_app_new/presentation/todo_section/widgets/ancillary_orders_list.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; @@ -61,7 +63,7 @@ class _ToDoPageState extends State { Widget build(BuildContext context) { appState = getIt.get(); return CollapsingListView( - title: "Ancillary Orders".needTranslation, + title: LocaleKeys.ancillaryOrdersList.tr(context: context), isLeading: true, child: SingleChildScrollView( child: Column( diff --git a/lib/presentation/todo_section/widgets/ancillary_orders_list.dart b/lib/presentation/todo_section/widgets/ancillary_orders_list.dart index 78d7e3e..58ee6d4 100644 --- a/lib/presentation/todo_section/widgets/ancillary_orders_list.dart +++ b/lib/presentation/todo_section/widgets/ancillary_orders_list.dart @@ -71,19 +71,12 @@ class AncillaryOrdersList extends StatelessWidget { return Center( child: Padding( padding: EdgeInsets.symmetric(vertical: 40.h), - child: Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 12.r, - hasShadow: false, - ), - child: Utils.getNoDataWidget( - context, - noDataText: "You don't have any ancillary orders yet.".needTranslation, - isSmallWidget: true, - width: 62.w, - height: 62.h, - ), + child: Utils.getNoDataWidget( + context, + noDataText: LocaleKeys.youDontHaveAnyAncillaryOrdersYet.tr(context: context), + isSmallWidget: true, + width: 62.w, + height: 62.h, ), ), ); @@ -145,7 +138,7 @@ class AncillaryOrderCard extends StatelessWidget { if (!isLoading) ...[ Image.network( "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png", - width: 63.w, + width: 63.h, height: 63.h, fit: BoxFit.cover, ).circle(100.r), @@ -177,47 +170,45 @@ class AncillaryOrderCard extends StatelessWidget { labelText: order.projectName ?? '-', ).toShimmer2(isShow: isLoading), // orderNo - // if (order.orderNo != null || isLoading) - // AppCustomChipWidget( - // // icon: AppAssets.calendar, - // labelText: "${"Order# :".needTranslation}${order.orderNo ?? '-'}", - // ).toShimmer2(isShow: isLoading), + if (order.orderNo != null || isLoading) + AppCustomChipWidget( + // icon: AppAssets.calendar, + labelText: "${LocaleKeys.orderNumber.tr(context: context)}${order.orderNo ?? '-'}", + ).toShimmer2(isShow: isLoading), // Appointment Date if (order.appointmentDate != null || isLoading) AppCustomChipWidget( icon: AppAssets.appointment_calendar_icon, - labelText: isLoading ? "Date: Jan 20, 2024" : DateFormat('MMM dd, yyyy').format(order.appointmentDate!).needTranslation, + labelText: isLoading ? "Date: Jan 20, 2024" : DateFormat('MMM dd, yyyy').format(order.appointmentDate!), ).toShimmer2(isShow: isLoading), // Appointment Number if (order.appointmentNo != null || isLoading) AppCustomChipWidget( - labelText: isLoading ? "Appt# : 98765" : "Appt #: ${order.appointmentNo}".needTranslation, + labelText: isLoading ? "Appt# : 98765" : "Appt #: ${order.appointmentNo}", ).toShimmer2(isShow: isLoading), // Invoice Number if (order.invoiceNo != null || isLoading) AppCustomChipWidget( - labelText: isLoading ? "Invoice: 45678" : "Invoice: ${order.invoiceNo}".needTranslation, + labelText: isLoading ? "Invoice: 45678" : LocaleKeys.invoiceWithNumber.tr(namedArgs: {'invoiceNo': '${order.invoiceNo}'}), ).toShimmer2(isShow: isLoading), // Queued Status if (order.isQueued == true || isLoading) AppCustomChipWidget( - labelText: "Queued".needTranslation, + labelText: LocaleKeys.queued.tr(context: context), ).toShimmer2(isShow: isLoading), // Check-in Available Status if (order.isCheckInAllow == true || isLoading) AppCustomChipWidget( - labelText: "Check-in Ready".needTranslation, + labelText: LocaleKeys.checkInReady.tr(context: context), ).toShimmer2(isShow: isLoading), ], ), - - SizedBox(height: 12.h), - + SizedBox(height: 6.h), // Action Buttons Row( children: [ @@ -225,7 +216,7 @@ class AncillaryOrderCard extends StatelessWidget { if (order.isCheckInAllow == true || isLoading) Expanded( child: CustomButton( - text: "Check In".needTranslation, + text: LocaleKeys.checkIn.tr(context: context), onPressed: () { if (isLoading) { return; @@ -236,7 +227,7 @@ class AncillaryOrderCard extends StatelessWidget { backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, textColor: AppColors.whiteColor, - fontSize: 14.f, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, fontWeight: FontWeight.w500, borderRadius: 10.r, padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), @@ -249,7 +240,7 @@ class AncillaryOrderCard extends StatelessWidget { // View Details Button Expanded( child: CustomButton( - text: "View Details".needTranslation, + text: LocaleKeys.viewDetails.tr(context: context), onPressed: () { if (isLoading) { return; @@ -260,7 +251,7 @@ class AncillaryOrderCard extends StatelessWidget { backgroundColor: Color(0xffFEE9EA), borderColor: Color(0xffFEE9EA), textColor: Color(0xffED1C2B), - fontSize: 14.f, + fontSize: (isFoldable || isTablet) ? 12.f : 14.f, fontWeight: FontWeight.w500, borderRadius: 10.r, padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), diff --git a/lib/presentation/todo_section/widgets/ancillary_procedures_list.dart b/lib/presentation/todo_section/widgets/ancillary_procedures_list.dart index ba2f94d..2d99aa0 100644 --- a/lib/presentation/todo_section/widgets/ancillary_procedures_list.dart +++ b/lib/presentation/todo_section/widgets/ancillary_procedures_list.dart @@ -7,6 +7,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/todo_section/models/resp_models/ancillary_order_list_response_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; @@ -73,7 +74,7 @@ class AncillaryProceduresList extends StatelessWidget { ), child: Utils.getNoDataWidget( context, - noDataText: "You don't have any ancillary orders yet.".needTranslation, + noDataText: LocaleKeys.youDontHaveAnyAncillaryOrdersYet.tr(context: context), isSmallWidget: true, width: 62.w, height: 62.h, @@ -118,7 +119,7 @@ class AncillaryOrderCard extends StatelessWidget { children: [ Row( children: [ - "Order #".needTranslation.toText14( + LocaleKeys.orderNumber.tr(context: context).toText14( color: AppColors.textColorLight, weight: FontWeight.w500, ), @@ -181,31 +182,31 @@ class AncillaryOrderCard extends StatelessWidget { AppCustomChipWidget( icon: AppAssets.calendar, labelText: - isLoading ? "Date: Jan 20, 2024" : "Date: ${DateFormat('MMM dd, yyyy').format(order.appointmentDate!)}".needTranslation, + isLoading ? "Date: Jan 20, 2024" : "Date: ${DateFormat('MMM dd, yyyy').format(order.appointmentDate!)}", ).toShimmer2(isShow: isLoading), // Appointment Number if (order.appointmentNo != null || isLoading) AppCustomChipWidget( - labelText: isLoading ? "Appt #: 98765" : "Appt #: ${order.appointmentNo}".needTranslation, + labelText: isLoading ? "Appt #: 98765" : "Appt #: ${order.appointmentNo}", ).toShimmer2(isShow: isLoading), // Invoice Number if (order.invoiceNo != null || isLoading) AppCustomChipWidget( - labelText: isLoading ? "Invoice: 45678" : "Invoice: ${order.invoiceNo}".needTranslation, + labelText: isLoading ? "Invoice: 45678" : LocaleKeys.invoiceWithNumber.tr(namedArgs: {'invoiceNo': '${order.invoiceNo}'}), ).toShimmer2(isShow: isLoading), // Queued Status if (order.isQueued == true || isLoading) AppCustomChipWidget( - labelText: "Queued".needTranslation, + labelText: LocaleKeys.queued.tr(context: context), ).toShimmer2(isShow: isLoading), // Check-in Available Status if (order.isCheckInAllow == true || isLoading) AppCustomChipWidget( - labelText: "Check-in Ready".needTranslation, + labelText: LocaleKeys.checkInReady.tr(context: context), ).toShimmer2(isShow: isLoading), ], ), @@ -219,7 +220,7 @@ class AncillaryOrderCard extends StatelessWidget { if (order.isCheckInAllow == true || isLoading) Expanded( child: CustomButton( - text: "Check In".needTranslation, + text: LocaleKeys.checkIn.tr(context: context), onPressed: () { if (isLoading) { return; @@ -243,7 +244,7 @@ class AncillaryOrderCard extends StatelessWidget { // View Details Button Expanded( child: CustomButton( - text: "View Details".needTranslation, + text: LocaleKeys.viewDetails.tr(context: context), onPressed: () { if (isLoading) { return; diff --git a/lib/presentation/vital_sign/vital_sign_details_page.dart b/lib/presentation/vital_sign/vital_sign_details_page.dart new file mode 100644 index 0000000..980357d --- /dev/null +++ b/lib/presentation/vital_sign/vital_sign_details_page.dart @@ -0,0 +1,740 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/common_models/data_points.dart'; +import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/vital_sign_respo_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/vital_sign_ui_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart'; +import 'package:provider/provider.dart'; + +/// Which vital sign is being shown in the details screen. +enum VitalSignMetric { + bmi, + height, + weight, + bloodPressure, + temperature, + heartRate, + respiratoryRate, +} + +class VitalSignDetailsArgs { + final VitalSignMetric metric; + final String title; + final String icon; + final String unit; + + /// Optional bounds used for graph shading and labels. + final double? low; + final double? high; + + const VitalSignDetailsArgs({ + required this.metric, + required this.title, + required this.icon, + required this.unit, + this.low, + this.high, + }); +} + +class VitalSignDetailsPage extends StatefulWidget { + final VitalSignDetailsArgs args; + + const VitalSignDetailsPage({super.key, required this.args}); + + @override + State createState() => _VitalSignDetailsPageState(); +} + +class _VitalSignDetailsPageState extends State { + bool _isGraphVisible = true; + + VitalSignDetailsArgs get args => widget.args; + + @override + Widget build(BuildContext context) { + return CollapsingListView( + title: LocaleKeys.vitalSignDetails.tr(context: context), + child: Consumer( + builder: (context, viewModel, child) { + final latest = viewModel.vitalSignList.isNotEmpty ? viewModel.vitalSignList.first : null; + + final history = _buildSeries(viewModel.vitalSignList, args); + final latestValueText = _latestValueText(latest); + final status = _statusForLatest(latest); + final scheme = VitalSignUiModel.scheme(status: status, label: args.title); + + return SingleChildScrollView( + child: Column( + spacing: 16.h, + children: [ + _headerCard( + context, + title: args.title, + icon: args.icon, + valueText: latestValueText, + status: status, + scheme: scheme, + latestDate: latest?.vitalSignDate, + ), + _whatIsThisResultCard(context), + _historyCard(context, history: history), + ], + ).paddingAll(24.h), + ); + }, + ), + ); + } + + Widget _headerCard( + BuildContext context, { + required String title, + required String icon, + required String valueText, + required String? status, + required VitalSignUiModel scheme, + required DateTime? latestDate, + }) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8.h, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + title.toText28(isBold: true, color: AppColors.textColor, letterSpacing: -1), + + + ], + ), + SizedBox(height: 8.h), + (latestDate != null + ? LocaleKeys.resultOf.tr(namedArgs: {'date': latestDate.toString().split(' ').first}) + : LocaleKeys.resultOfNoDate.tr(context: context)) + .toText11(weight: FontWeight.w500, color: AppColors.greyTextColor), + ], + ), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: valueText.toText28( + isBold: true, + color: scheme.iconFg, + letterSpacing: -2, + ), + ), + SizedBox(width: 4.h), + if (status != null) + Column( + spacing: 6.h, + children: [ + status.toText10(weight: FontWeight.w500, color: AppColors.greyTextColor), + Utils.buildSvgWithAssets( + icon: AppAssets.lab_result_indicator, + width: 21, + height: 23, + iconColor: scheme.iconFg, + ), + ], + ), + ], + ), + ), + ], + ), + if (args.low != null || args.high != null) + Text( + _referenceText(context), + style: TextStyle( + fontSize: 12.f, + fontWeight: FontWeight.w500, + fontFamily: 'Poppins', + color: AppColors.greyTextColor, + ), + softWrap: true, + ), + ], + ), + ); + } + + String _referenceText(BuildContext context) { + if (args.low != null && args.high != null) { + return LocaleKeys.referenceRangeBetween.tr(namedArgs: { + 'low': args.low.toString(), + 'high': args.high.toString(), + 'unit': args.unit ?? '' + }); + } + if (args.low != null) { + return LocaleKeys.referenceRangeMin.tr(namedArgs: { + 'low': args.low.toString(), + 'unit': args.unit ?? '' + }); + } + if (args.high != null) { + return LocaleKeys.referenceRangeMax.tr(namedArgs: { + 'high': args.high.toString(), + 'unit': args.unit ?? '' + }); + } + return ''; + } + + Widget _whatIsThisResultCard(BuildContext context) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8.h, + children: [ + LocaleKeys.whatIsThisResult.tr(context: context).toText16(weight: FontWeight.w600, color: AppColors.textColor), + _descriptionText(context).toText12(fontWeight: FontWeight.w500, color: AppColors.textColorLight), + ], + ), + ); + } + + Widget _historyCard(BuildContext context, {required List history}) { + // For blood pressure, we need both systolic and diastolic series + List? secondaryHistory; + if (args.metric == VitalSignMetric.bloodPressure) { + secondaryHistory = _buildBloodPressureDiastolicSeries( + context.read().vitalSignList, + ); + } + + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + height: _isGraphVisible + ? 260.h + : (history.length < 3) + ? (history.length * 64) + 80.h + : 260.h, + padding: EdgeInsets.all(15.h), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + _isGraphVisible ? LocaleKeys.historyFlowchart.tr(context: context) : LocaleKeys.history.tr(context: context), + style: TextStyle( + fontSize: 16, + fontFamily: 'Poppins', + fontWeight: FontWeight.w600, + color: AppColors.textColor, + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 24.h, + height: 24.h, + alignment: Alignment.center, + child: InkWell( + onTap: () { + setState(() { + _isGraphVisible = !_isGraphVisible; + }); + }, + child: Utils.buildSvgWithAssets( + icon: _isGraphVisible ? AppAssets.ic_list : AppAssets.ic_graph, + width: 24.h, + height: 24.h, + ), + ), + ), + // SizedBox(width: 16.h), + // Container( + // width: 24.h, + // height: 24.h, + // alignment: Alignment.center, + // child: Utils.buildSvgWithAssets( + // icon: AppAssets.ic_date_filter, + // width: 24.h, + // height: 24.h, + // ), + // ), + ], + ), + ], + ).paddingOnly(bottom: _isGraphVisible ? 16.h : 24.h), + + if (history.isEmpty) + Utils.getNoDataWidget(context, noDataText: LocaleKeys.noHistoryAvailable.tr(context: context), isSmallWidget: true) + else if (_isGraphVisible) + _buildHistoryGraph(history, secondaryHistory: secondaryHistory) + else + _buildHistoryList(context, history), + ], + ), + ); + } + + Widget _buildHistoryGraph(List history, {List? secondaryHistory}) { + final minY = _minY(history, secondaryHistory: secondaryHistory); + final maxY = _maxY(history, secondaryHistory: secondaryHistory); + final scheme = VitalSignUiModel.scheme(status: _statusForLatest(null), label: args.title); + + return CustomGraph( + dataPoints: history, + secondaryDataPoints: secondaryHistory, + makeGraphBasedOnActualValue: true, + leftLabelReservedSize: 40, + showGridLines: true, + showShadow: true, + leftLabelInterval: _leftInterval(history, secondaryHistory: secondaryHistory), + maxY: maxY, + minY: minY, + maxX: history.length.toDouble() - .75, + horizontalInterval: _leftInterval(history, secondaryHistory: secondaryHistory), + leftLabelFormatter: (value) { + // Show only numeric labels at regular intervals + return _axisLabel(value.toStringAsFixed(0)); + }, + getDrawingHorizontalLine: (value) { + // Draw reference lines for high/low bounds + if (args.high != null && (value - args.high!).abs() < 0.1) { + return FlLine( + color: AppColors.bgGreenColor.withOpacity(0.2), + strokeWidth: 1, + dashArray: [5, 5], + ); + } + if (args.low != null && (value - args.low!).abs() < 0.1) { + return FlLine( + color: AppColors.bgGreenColor.withOpacity(0.2), + strokeWidth: 1, + dashArray: [5, 5], + ); + } + // Draw grid lines at intervals + return FlLine( + color: AppColors.bgGreenColor.withOpacity(0.2), + strokeWidth: 1, + dashArray: [5, 5], + ); + }, + graphColor: AppColors.bgGreenColor, + secondaryGraphColor: AppColors.blueColor, + graphShadowColor: AppColors.lightGreenColor.withOpacity(.4), + graphGridColor: scheme.iconFg, + bottomLabelFormatter: (value, data) { + if (data.isEmpty) return const SizedBox.shrink(); + if (value == 0) return _bottomLabel(data[value.toInt()].label); + if (value == data.length - 1) return _bottomLabel(data[value.toInt()].label, isLast: true); + if (value == ((data.length - 1) / 2)) return _bottomLabel(data[value.toInt()].label); + return const SizedBox.shrink(); + }, + rangeAnnotations: _rangeAnnotations(history, secondaryHistory: secondaryHistory), + minX: (history.length == 1) ? null : -.2, + scrollDirection: Axis.horizontal, + height: 180.h, + ); + } + + + Widget _buildHistoryList(BuildContext context, List history) { + final items = history.reversed.toList(); + final height = items.length < 3 ? items.length * 64.0 : 180.h; + + // Get diastolic values if this is blood pressure + List? secondaryItems; + if (args.metric == VitalSignMetric.bloodPressure) { + final viewModel = context.read(); + final secondaryHistory = _buildBloodPressureDiastolicSeries(viewModel.vitalSignList); + secondaryItems = secondaryHistory.reversed.toList(); + } + + return SizedBox( + height: height, + child: ListView.separated( + padding: EdgeInsets.zero, + itemCount: items.length, + separatorBuilder: (_, __) => Divider( + color: AppColors.borderOnlyColor.withValues(alpha: 0.1), + height: 1, + ), + itemBuilder: (context, index) { + final dp = items[index]; + + // Build the value text based on metric type + String valueText; + if (args.metric == VitalSignMetric.bloodPressure && secondaryItems != null && index < secondaryItems.length) { + // Show systolic/diastolic for blood pressure + final diastolic = secondaryItems[index]; + valueText = '${dp.actualValue}/${diastolic.actualValue} ${dp.unitOfMeasurement ?? ''}'; + } else { + // Show single value for other metrics + valueText = '${dp.actualValue} ${dp.unitOfMeasurement ?? ''}'; + } + + return Padding( + padding: EdgeInsets.symmetric(vertical: 12.h), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + dp.displayTime.toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500), + valueText.toText12( + color: AppColors.textColor, + fontWeight: FontWeight.w600, + ), + ], + ), + ); + }, + ), + ); + } + + double _minY(List points, {List? secondaryHistory}) { + // IMPORTANT: y-axis uses actual numeric values (from actualValue). + final values = points.map((e) => double.tryParse(e.actualValue) ?? 0).toList(); + + // Include secondary data points if provided (for blood pressure) + if (secondaryHistory != null && secondaryHistory.isNotEmpty) { + values.addAll(secondaryHistory.map((e) => double.tryParse(e.actualValue) ?? 0)); + } + + final min = values.reduce((a, b) => a < b ? a : b); + final double boundLow = args.low ?? min; + return (min < boundLow ? min : boundLow) - 1; + } + + double _maxY(List points, {List? secondaryHistory}) { + // IMPORTANT: y-axis uses actual numeric values (from actualValue). + final values = points.map((e) => double.tryParse(e.actualValue) ?? 0).toList(); + + // Include secondary data points if provided (for blood pressure) + if (secondaryHistory != null && secondaryHistory.isNotEmpty) { + values.addAll(secondaryHistory.map((e) => double.tryParse(e.actualValue) ?? 0)); + } + + final max = values.reduce((a, b) => a > b ? a : b); + final double boundHigh = args.high ?? max; + return (max > boundHigh ? max : boundHigh) + 1; + } + + double _leftInterval(List points, {List? secondaryHistory}) { + // Keep it stable; graph will mostly show just two labels. + final range = (_maxY(points, secondaryHistory: secondaryHistory) - _minY(points, secondaryHistory: secondaryHistory)).abs(); + if (range <= 0) return 1; + return (range / 4).clamp(1, 20); + } + + RangeAnnotations? _rangeAnnotations(List points, {List? secondaryHistory}) { + if (args.low == null && args.high == null) return null; + + final minY = _minY(points, secondaryHistory: secondaryHistory); + final maxY = _maxY(points, secondaryHistory: secondaryHistory); + + final List ranges = []; + + if (args.low != null) { + ranges.add( + HorizontalRangeAnnotation( + y1: minY, + y2: args.low!, + color: AppColors.highAndLow.withOpacity(0.05), + ), + ); + } + + if (args.low != null && args.high != null) { + ranges.add( + HorizontalRangeAnnotation( + y1: args.low!, + y2: args.high!, + color: AppColors.bgGreenColor.withOpacity(0.05), + ), + ); + } + + if (args.high != null) { + ranges.add( + HorizontalRangeAnnotation( + y1: args.high!, + y2: maxY, + color: AppColors.criticalLowAndHigh.withOpacity(0.05), + ), + ); + } + + return RangeAnnotations(horizontalRangeAnnotations: ranges); + } + + List _buildSeries(List vitals, VitalSignDetailsArgs args) { + final List points = []; + + // Build a chronological series (oldest -> newest), skipping null/zero values. + final sorted = List.from(vitals); + sorted.sort((a, b) { + final ad = a.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0); + final bd = b.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0); + return ad.compareTo(bd); + }); + + double? metricValue(VitalSignResModel v) { + switch (args.metric) { + case VitalSignMetric.bmi: + return _toDouble(v.bodyMassIndex); + case VitalSignMetric.height: + return _toDouble(v.heightCm); + case VitalSignMetric.weight: + return _toDouble(v.weightKg); + case VitalSignMetric.temperature: + return _toDouble(v.temperatureCelcius); + case VitalSignMetric.heartRate: + return _toDouble(v.heartRate ?? v.pulseBeatPerMinute); + case VitalSignMetric.respiratoryRate: + return _toDouble(v.respirationBeatPerMinute); + case VitalSignMetric.bloodPressure: + // Graph systolic for primary series + return _toDouble(v.bloodPressureHigher); + } + } + + const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + + double index = 0; + for (final v in sorted) { + final mv = metricValue(v); + if (mv == null) continue; + if (mv == 0) continue; + + final dt = v.vitalSignDate ?? DateTime.now(); + final label = '${monthNames[dt.month - 1]}, ${dt.year}'; + + points.add( + DataPoint( + value: index, + label: label, + actualValue: mv.toStringAsFixed(0), + time: dt, + displayTime: '${dt.day}/${dt.month}/${dt.year}', + unitOfMeasurement: args.unit, + ), + ); + index += 1; + } + + return points; + } + + /// Build diastolic blood pressure series for dual-line graph + List _buildBloodPressureDiastolicSeries(List vitals) { + final List points = []; + + // Build a chronological series (oldest -> newest), skipping null/zero values. + final sorted = List.from(vitals); + sorted.sort((a, b) { + final ad = a.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0); + final bd = b.vitalSignDate ?? DateTime.fromMillisecondsSinceEpoch(0); + return ad.compareTo(bd); + }); + + const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + + double index = 0; + for (final v in sorted) { + final diastolic = _toDouble(v.bloodPressureLower); + if (diastolic == null) continue; + if (diastolic == 0) continue; + + final dt = v.vitalSignDate ?? DateTime.now(); + final label = '${monthNames[dt.month - 1]}, ${dt.year}'; + + points.add( + DataPoint( + value: index, + label: label, + actualValue: diastolic.toStringAsFixed(0), + time: dt, + displayTime: '${dt.day}/${dt.month}/${dt.year}', + unitOfMeasurement: args.unit, + ), + ); + index += 1; + } + + return points; + } + + double? _toDouble(dynamic v) { + if (v == null) return null; + if (v is num) return v.toDouble(); + return double.tryParse(v.toString()); + } + + String _latestValueText(VitalSignResModel? latest) { + if (latest == null) return '--'; + + switch (args.metric) { + case VitalSignMetric.bmi: + final v = _toDouble(latest.bodyMassIndex); + return v == null ? '--' : v.toStringAsFixed(0); + case VitalSignMetric.height: + final v = _toDouble(latest.heightCm); + return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}'; + case VitalSignMetric.weight: + final v = _toDouble(latest.weightKg); + return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}'; + case VitalSignMetric.temperature: + final v = _toDouble(latest.temperatureCelcius); + return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}'; + case VitalSignMetric.heartRate: + final v = _toDouble(latest.heartRate ?? latest.pulseBeatPerMinute); + return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}'; + case VitalSignMetric.respiratoryRate: + final v = _toDouble(latest.respirationBeatPerMinute); + return v == null ? '--' : '${v.toStringAsFixed(0)} ${args.unit}'; + case VitalSignMetric.bloodPressure: + final s = _toDouble(latest.bloodPressureHigher); + final d = _toDouble(latest.bloodPressureLower); + if (s == null || d == null) return '--'; + return '${s.toStringAsFixed(0)}/${d.toStringAsFixed(0)}'; + } + } + + String? _statusForLatest(VitalSignResModel? latest) { + if (latest == null) return null; + + switch (args.metric) { + case VitalSignMetric.bmi: + return VitalSignUiModel.bmiStatus(latest.bodyMassIndex); + case VitalSignMetric.bloodPressure: + return VitalSignUiModel.bloodPressureStatus(systolic: latest.bloodPressureHigher, diastolic: latest.bloodPressureLower); + case VitalSignMetric.height: + return null; + case VitalSignMetric.weight: + return latest.weightKg != null ? 'Normal' : null; + case VitalSignMetric.temperature: + return null; + case VitalSignMetric.heartRate: + return (latest.heartRate ?? latest.pulseBeatPerMinute) != null ? 'Normal' : null; + case VitalSignMetric.respiratoryRate: + return latest.respirationBeatPerMinute != null ? 'Normal' : null; + } + } + + String _descriptionText(BuildContext context) { + switch (args.metric) { + case VitalSignMetric.bmi: + return LocaleKeys.bmiDescription.tr(context: context); + case VitalSignMetric.height: + return LocaleKeys.heightDescription.tr(context: context); + case VitalSignMetric.weight: + return LocaleKeys.weightDescription.tr(context: context); + case VitalSignMetric.bloodPressure: + return LocaleKeys.bloodPressureDescription.tr(context: context); + case VitalSignMetric.temperature: + return LocaleKeys.temperatureDescription.tr(context: context); + case VitalSignMetric.heartRate: + return LocaleKeys.heartRateDescriptionVital.tr(context: context); + case VitalSignMetric.respiratoryRate: + return LocaleKeys.respiratoryRateDescription.tr(context: context); + } + } + + String _nextStepsText(BuildContext context) { + switch (args.metric) { + case VitalSignMetric.bmi: + return LocaleKeys.bmiAdvice.tr(context: context); + case VitalSignMetric.height: + return LocaleKeys.heightAdvice.tr(context: context); + case VitalSignMetric.weight: + return LocaleKeys.weightAdvice.tr(context: context); + case VitalSignMetric.bloodPressure: + return LocaleKeys.bloodPressureAdvice.tr(context: context); + case VitalSignMetric.temperature: + return LocaleKeys.temperatureAdvice.tr(context: context); + case VitalSignMetric.heartRate: + return LocaleKeys.heartRateAdvice.tr(context: context); + case VitalSignMetric.respiratoryRate: + return LocaleKeys.respiratoryRateAdvice.tr(context: context); + } + } + + Widget _nextStepsCard(BuildContext context) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.whatShouldIDoNext.tr(context: context).toText16(weight: FontWeight.w600), + SizedBox(height: 8.h), + _nextStepsText(context).toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w500, maxLine: 10), + ], + ), + ); + } + + Widget _axisLabel(String value) { + return Text( + value, + style: TextStyle( + fontWeight: FontWeight.w600, + fontFamily: 'Poppins', + fontSize: 8.f, + color: AppColors.textColor, + ), + ); + } + + Widget _bottomLabel(String label, {bool isLast = false}) { + return Padding( + padding: EdgeInsets.only( + top: 8.0, + right: isLast ? 16.h : 0, + ), + child: label.toText8(fontWeight: FontWeight.w500), + ); + } + +} diff --git a/lib/presentation/vital_sign/vital_sign_page.dart b/lib/presentation/vital_sign/vital_sign_page.dart index bd25641..e457023 100644 --- a/lib/presentation/vital_sign/vital_sign_page.dart +++ b/lib/presentation/vital_sign/vital_sign_page.dart @@ -1,5 +1,6 @@ import 'dart:ui'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; @@ -8,10 +9,13 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/vital_sign_respo_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/vital_sign_ui_model.dart'; +import 'package:hmg_patient_app_new/presentation/vital_sign/vital_sign_details_page.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; class VitalSignPage extends StatefulWidget { @@ -22,6 +26,13 @@ class VitalSignPage extends StatefulWidget { } class _VitalSignPageState extends State { + void _openDetails(VitalSignDetailsArgs args) { + Navigator.of(context).push( + CustomPageRoute( + page: VitalSignDetailsPage(args: args), + ), + ); + } @override void initState() { @@ -33,7 +44,7 @@ class _VitalSignPageState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: 'Vital Signs', + title: LocaleKeys.vitalSigns.tr(context: context), child: Consumer( builder: (context, viewModel, child) { @@ -61,40 +72,61 @@ class _VitalSignPageState extends State { // BMI Card _buildVitalSignCard( icon: AppAssets.bmiVital, - label: 'BMI', + label: LocaleKeys.bmi.tr(context: context), value: latestVitalSign?.bodyMassIndex?.toString() ?? '--', unit: '', status: VitalSignUiModel.bmiStatus(latestVitalSign?.bodyMassIndex), - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.bmi, + title: LocaleKeys.bmi.tr(context: context), + icon: AppAssets.bmiVital, + unit: '', + ), + ), ), SizedBox(height: 16.h), // Height Card _buildVitalSignCard( icon: AppAssets.heightVital, - label: 'Height', + label: LocaleKeys.height.tr(context: context), value: latestVitalSign?.heightCm?.toString() ?? '--', unit: 'cm', status: null, - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.height, + title: LocaleKeys.height.tr(context: context), + icon: AppAssets.heightVital, + unit: 'cm', + ), + ), ), SizedBox(height: 16.h), // Weight Card _buildVitalSignCard( icon: AppAssets.weightVital, - label: 'Weight', + label: LocaleKeys.weight.tr(context: context), value: latestVitalSign?.weightKg?.toString() ?? '--', unit: 'kg', status: (latestVitalSign?.weightKg != null) ? 'Normal' : null, - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.weight, + title: LocaleKeys.height.tr(context: context), + icon: AppAssets.weightVital, + unit: 'kg', + ), + ), ), SizedBox(height: 16.h), // Blood Pressure Card _buildVitalSignCard( icon: AppAssets.bloodPressure, - label: 'Blood Pressure', + label: LocaleKeys.bloodPressure.tr(context: context), value: latestVitalSign != null && latestVitalSign.bloodPressureHigher != null && latestVitalSign.bloodPressureLower != null @@ -105,18 +137,36 @@ class _VitalSignPageState extends State { systolic: latestVitalSign?.bloodPressureHigher, diastolic: latestVitalSign?.bloodPressureLower, ), - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.bloodPressure, + title: LocaleKeys.bloodPressure.tr(context: context), + icon: AppAssets.bloodPressure, + unit: 'mmHg', + low: 90, + high: 140, + ), + ), ), SizedBox(height: 16.h), // Temperature Card _buildVitalSignCard( icon: AppAssets.temperature, - label: 'Temperature', + label: LocaleKeys.temperature.tr(context: context), value: latestVitalSign?.temperatureCelcius?.toString() ?? '--', unit: '°C', status: null, - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.temperature, + title: LocaleKeys.temperature.tr(context: context), + icon: AppAssets.temperature, + unit: '°C', + low: 36.1, + high: 37.2, + ), + ), ), ], ), @@ -130,7 +180,7 @@ class _VitalSignPageState extends State { children: [ // Body anatomy image with Heart Rate card overlaid at bottom SizedBox( - height: 480.h, + height: 420.h, width: double.infinity, child: Stack( clipBehavior: Clip.none, @@ -148,7 +198,7 @@ class _VitalSignPageState extends State { Align( alignment: Alignment.bottomCenter, child: SizedBox( - height: 420.h, + height: 460.h, child: ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: Container( @@ -178,26 +228,44 @@ class _VitalSignPageState extends State { bottom: 12.h, child: _buildVitalSignCard( icon: AppAssets.heart, - label: 'Heart Rate', + label: LocaleKeys.heart.tr(context: context), value: latestVitalSign?.heartRate?.toString() ?? latestVitalSign?.pulseBeatPerMinute?.toString() ?? '--', unit: 'bpm', status: 'Normal', - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.heartRate, + title: LocaleKeys.heart.tr(context: context), + icon: AppAssets.heart, + unit: 'bpm', + low: 60, + high: 100, + ), + ), ), ), ], ), ), - SizedBox(height: 12.h), + SizedBox(height: 12.h), // Respiratory rate Card _buildVitalSignCard( icon: AppAssets.respRate, - label: 'Respiratory rate', - value: latestVitalSign?.respirationBeatPerMinute?.toString() ?? '--', + label: LocaleKeys.respirationRate.tr(context: context), + value: latestVitalSign?.respirationBeatPerMinute?.toString() ?? '--', unit: 'bpm', status: 'Normal', - onTap: () {}, + onTap: () => _openDetails( + VitalSignDetailsArgs( + metric: VitalSignMetric.respiratoryRate, + title: LocaleKeys.respirationRate.tr(context: context), + icon: AppAssets.respRate, + unit: 'bpm', + low: 12, + high: 20, + ), + ), ), ], ), @@ -242,15 +310,15 @@ class _VitalSignPageState extends State { Row( children: [ Container( - padding: EdgeInsets.all(10.h), + padding: EdgeInsets.all(8.h), decoration: BoxDecoration( color: scheme.iconBg, borderRadius: BorderRadius.circular(12.r), ), child: Utils.buildSvgWithAssets( icon: icon, - width: 20.w, - height: 20.h, + width: 22.w, + height: 22.h, iconColor: scheme.iconFg, fit: BoxFit.contain, ), @@ -266,10 +334,15 @@ class _VitalSignPageState extends State { ), SizedBox(height: 14.h), Container( - padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 6.h), - decoration: BoxDecoration( + padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h), + // decoration: BoxDecoration( + // color: AppColors.bgScaffoldColor, + // borderRadius: BorderRadius.circular(10.r), + // ), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.bgScaffoldColor, - borderRadius: BorderRadius.circular(10.r), + borderRadius: 10.r, + hasShadow: false, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -295,23 +368,24 @@ class _VitalSignPageState extends State { labelText: status, backgroundColor: scheme.chipBg, textColor: scheme.chipFg, + ) else const SizedBox.shrink(), ], ), ), - SizedBox(height: 8.h), - Align( - alignment: AlignmentDirectional.centerEnd, - child: Utils.buildSvgWithAssets( - icon: AppAssets.arrow_forward, - width: 18.w, - height: 18.h, - iconColor: AppColors.textColorLight, - fit: BoxFit.contain, - ), - ), + // SizedBox(height: 8.h), + // Align( + // alignment: AlignmentDirectional.centerEnd, + // child: Utils.buildSvgWithAssets( + // icon: AppAssets.arrow_forward, + // width: 18.w, + // height: 18.h, + // iconColor: AppColors.textColorLight, + // fit: BoxFit.contain, + // ), + // ), ], ), ), diff --git a/lib/presentation/water_monitor/water_consumption_screen.dart b/lib/presentation/water_monitor/water_consumption_page.dart similarity index 93% rename from lib/presentation/water_monitor/water_consumption_screen.dart rename to lib/presentation/water_monitor/water_consumption_page.dart index 5d08bcd..54dace5 100644 --- a/lib/presentation/water_monitor/water_consumption_screen.dart +++ b/lib/presentation/water_monitor/water_consumption_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -9,6 +10,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/hydration_tips_widget.dart'; import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_intake_summary_widget.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; @@ -21,14 +23,14 @@ import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart'; import 'package:provider/provider.dart'; import 'package:shimmer/shimmer.dart'; -class WaterConsumptionScreen extends StatefulWidget { - const WaterConsumptionScreen({super.key}); +class WaterConsumptionPage extends StatefulWidget { + const WaterConsumptionPage({super.key}); @override - State createState() => _WaterConsumptionScreenState(); + State createState() => _WaterConsumptionPageState(); } -class _WaterConsumptionScreenState extends State { +class _WaterConsumptionPageState extends State { @override void initState() { super.initState(); @@ -98,37 +100,14 @@ class _WaterConsumptionScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - "History".needTranslation.toText16(isBold: true), Row( children: [ - InkWell( - onTap: () => viewModel.setGraphView(!viewModel.isGraphView), - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 300), - transitionBuilder: (Widget child, Animation animation) { - return FadeTransition( - opacity: animation, - child: ScaleTransition( - scale: animation, - child: child, - ), - ); - }, - child: Container( - key: ValueKey(viewModel.isGraphView), - child: Utils.buildSvgWithAssets( - icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon, - height: 24.h, - width: 24.h, - ), - ), - ), - ), + LocaleKeys.history.tr(context: context).toText16(isBold: true), SizedBox(width: 8.w), InkWell( onTap: () => _showHistoryDurationBottomsheet(context, viewModel), child: Container( - padding: EdgeInsets.symmetric(vertical: 6.h, horizontal: 6.h), + padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 6.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( backgroundColor: AppColors.greyColor, borderRadius: 8.r, @@ -137,13 +116,36 @@ class _WaterConsumptionScreenState extends State { child: Row( children: [ viewModel.selectedDurationFilter.toText12(fontWeight: FontWeight.w500), - Utils.buildSvgWithAssets(icon: AppAssets.arrow_down), + Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 16.h), ], ), ), ) ], ), + InkWell( + onTap: () => viewModel.setGraphView(!viewModel.isGraphView), + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + transitionBuilder: (Widget child, Animation animation) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + child: child, + ), + ); + }, + child: Container( + key: ValueKey(viewModel.isGraphView), + child: Utils.buildSvgWithAssets( + icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon, + height: 24.h, + width: 24.h, + ), + ), + ), + ), ], ), if (!viewModel.isGraphView) _buildHistoryListView(viewModel) else ...[SizedBox(height: 16.h), _buildHistoryGraph()] @@ -604,7 +606,7 @@ class _WaterConsumptionScreenState extends State { final dialogService = getIt.get(); dialogService.showFamilyBottomSheetWithoutHWithChild( - label: title.needTranslation, + label: title, message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -634,7 +636,7 @@ class _WaterConsumptionScreenState extends State { void _showHistoryDurationBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Duration".needTranslation, + title: LocaleKeys.selectDuration.tr(context: context), items: viewModel.durationFilters, selectedValue: viewModel.selectedDurationFilter, onSelected: viewModel.setFilterDuration, @@ -655,10 +657,10 @@ class _WaterConsumptionScreenState extends State { /// Show confirmation bottom sheet before cancelling reminders void _showCancelReminderConfirmation(WaterMonitorViewModel viewModel) { showCommonBottomSheetWithoutHeight( - title: 'Notice'.needTranslation, + title: LocaleKeys.notice.tr(context: context), context, child: Utils.getWarningWidget( - loadingText: "Are you sure you want to cancel all water reminders?".needTranslation, + loadingText: LocaleKeys.areYouSureYouWantToCancelAllWaterReminders.tr(context: context), isShowActionButtons: true, onCancelTap: () { Navigator.pop(context); @@ -694,7 +696,7 @@ class _WaterConsumptionScreenState extends State { /// Show bottom sheet with scheduled reminder times void _showReminderScheduledDialog(List times) { showCommonBottomSheetWithoutHeight( - title: 'Reminders Set!'.needTranslation, + title: LocaleKeys.remindersSet.tr(context: context), context, isCloseButtonVisible: false, isDismissible: false, @@ -703,7 +705,7 @@ class _WaterConsumptionScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Utils.getSuccessWidget(loadingText: 'Daily water reminders scheduled at:'.needTranslation), + Utils.getSuccessWidget(loadingText: LocaleKeys.dailyWaterRemindersScheduledAt.tr(context: context)), SizedBox(height: 16.h), Wrap( spacing: 8.w, @@ -728,7 +730,7 @@ class _WaterConsumptionScreenState extends State { Expanded( child: CustomButton( height: 56.h, - text: 'OK'.needTranslation, + text: LocaleKeys.ok.tr(context: context), onPressed: () => Navigator.of(context).pop(), textColor: AppColors.whiteColor, ), @@ -792,7 +794,7 @@ class _WaterConsumptionScreenState extends State { return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "Water Consumption".needTranslation, + title: LocaleKeys.waterConsumption.tr(context: context), bottomChild: Consumer( builder: (context, viewModel, child) { return Container( @@ -804,7 +806,7 @@ class _WaterConsumptionScreenState extends State { child: Padding( padding: EdgeInsets.all(24.w), child: CustomButton( - text: viewModel.isWaterReminderEnabled ? "Cancel Reminders".needTranslation : "Set Reminder".needTranslation, + text: viewModel.isWaterReminderEnabled ? LocaleKeys.cancelReminder.tr(context: context) : LocaleKeys.setReminder.tr(context: context), textColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor : AppColors.successColor, backgroundColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor.withValues(alpha: 0.1) : AppColors.successLightBgColor, onPressed: () => _handleReminderButtonTap(viewModel), diff --git a/lib/presentation/water_monitor/water_monitor_settings_screen.dart b/lib/presentation/water_monitor/water_monitor_settings_page.dart similarity index 84% rename from lib/presentation/water_monitor/water_monitor_settings_screen.dart rename to lib/presentation/water_monitor/water_monitor_settings_page.dart index 1b783ca..a3c82c0 100644 --- a/lib/presentation/water_monitor/water_monitor_settings_screen.dart +++ b/lib/presentation/water_monitor/water_monitor_settings_page.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,20 +7,30 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/services/dialog_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:provider/provider.dart'; -class WaterMonitorSettingsScreen extends StatefulWidget { - const WaterMonitorSettingsScreen({super.key}); +class WaterMonitorSettingsPage extends StatefulWidget { + const WaterMonitorSettingsPage({super.key}); @override - State createState() => _WaterMonitorSettingsScreenState(); + State createState() => _WaterMonitorSettingsPageState(); } -class _WaterMonitorSettingsScreenState extends State { +class _WaterMonitorSettingsPageState extends State { + late DialogService dialogService; + + @override + void initState() { + super.initState(); + dialogService = getIt.get(); + } + // No need to call initialize() here since it's already called in water_consumption_screen // The ViewModel is shared via Provider, so data is already loaded @@ -59,10 +70,8 @@ class _WaterMonitorSettingsScreenState extends State required Function(String) onSelected, bool useUpperCase = false, }) { - final dialogService = getIt.get(); - dialogService.showFamilyBottomSheetWithoutHWithChild( - label: title.needTranslation, + label: title, message: "", child: Container( padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h), @@ -92,7 +101,7 @@ class _WaterMonitorSettingsScreenState extends State void _showGenderSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Gender".needTranslation, + title: LocaleKeys.selectGender.tr(context: context), items: viewModel.genderOptions, selectedValue: viewModel.selectedGender, onSelected: viewModel.setGender, @@ -102,7 +111,7 @@ class _WaterMonitorSettingsScreenState extends State void _showHeightUnitSelectionBottomSheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Unit".needTranslation, + title: LocaleKeys.selectUnit.tr(context: context), items: viewModel.heightUnits, selectedValue: viewModel.selectedHeightUnit, onSelected: viewModel.setHeightUnit, @@ -113,7 +122,7 @@ class _WaterMonitorSettingsScreenState extends State void _showWeightUnitSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Unit".needTranslation, + title: LocaleKeys.selectUnit.tr(context: context), items: viewModel.weightUnits, selectedValue: viewModel.selectedWeightUnit, onSelected: viewModel.setWeightUnit, @@ -124,7 +133,7 @@ class _WaterMonitorSettingsScreenState extends State void _showActivityLevelSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Activity Level".needTranslation, + title: LocaleKeys.selectActivityLevel.tr(context: context), items: viewModel.activityLevels, selectedValue: viewModel.selectedActivityLevel, onSelected: viewModel.setActivityLevel, @@ -134,7 +143,7 @@ class _WaterMonitorSettingsScreenState extends State void _showNumberOfRemindersSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) { _showSelectionBottomSheet( context: context, - title: "Select Number of Reminders".needTranslation, + title: LocaleKeys.selectNumberOfReminders.tr(context: context), items: viewModel.reminderOptions, selectedValue: viewModel.selectedNumberOfReminders, onSelected: viewModel.setNumberOfReminders, @@ -249,7 +258,7 @@ class _WaterMonitorSettingsScreenState extends State return Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( - title: "H20 Settings".needTranslation, + title: LocaleKeys.h2oSettings.tr(context: context), bottomChild: Container( decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.whiteColor, @@ -259,13 +268,24 @@ class _WaterMonitorSettingsScreenState extends State child: Padding( padding: EdgeInsets.all(24.w), child: CustomButton( - text: "Save".needTranslation, + text: LocaleKeys.save.tr(context: context), onPressed: () async { final success = await viewModel.saveSettings(); if (!success && viewModel.validationError != null) { - _showSnackBar(context, viewModel.validationError!); + dialogService.showErrorBottomSheet( + message: viewModel.validationError!, + ); } else if (success) { - _showSnackBar(context, "Settings saved successfully"); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getSuccessWidget( + loadingText: LocaleKeys.settingsSavedSuccessfully.tr(context: context), + ), + callBackFunc: () {}, + isCloseButtonVisible: false, + isDismissible: true, + isFullScreen: false, + ); } }, borderRadius: 12.r, @@ -281,18 +301,18 @@ class _WaterMonitorSettingsScreenState extends State children: [ _buildSettingsRow( icon: AppAssets.profileIcon, - label: "Your Name".needTranslation, + label: LocaleKeys.yourName.tr(context: context), inputField: _buildTextField(viewModel.nameController, 'Guest'), ), _buildSettingsRow( icon: AppAssets.genderIcon, - label: "Select Gender".needTranslation, + label: LocaleKeys.selectGender.tr(context: context), value: viewModel.selectedGender, onRowTap: () => _showGenderSelectionBottomsheet(context, viewModel), ), _buildSettingsRow( icon: AppAssets.calendarGrey, - label: "Age (11-120) yrs".needTranslation, + label: LocaleKeys.ageYears.tr(context: context), inputField: _buildTextField( viewModel.ageController, '20', @@ -301,7 +321,7 @@ class _WaterMonitorSettingsScreenState extends State ), _buildSettingsRow( icon: AppAssets.heightIcon, - label: "Height".needTranslation, + label: LocaleKeys.height.tr(context: context), inputField: _buildTextField( viewModel.heightController, '175', @@ -312,7 +332,7 @@ class _WaterMonitorSettingsScreenState extends State ), _buildSettingsRow( icon: AppAssets.weightScaleIcon, - label: "Weight".needTranslation, + label: LocaleKeys.weight.tr(context: context), inputField: _buildTextField( viewModel.weightController, '75', @@ -323,13 +343,13 @@ class _WaterMonitorSettingsScreenState extends State ), _buildSettingsRow( icon: AppAssets.dumbellIcon, - label: "Activity Level".needTranslation, + label: LocaleKeys.activityLevel.tr(context: context), value: viewModel.selectedActivityLevel, onRowTap: () => _showActivityLevelSelectionBottomsheet(context, viewModel), ), _buildSettingsRow( icon: AppAssets.notificationIconGrey, - label: "Number of reminders in a day".needTranslation, + label: LocaleKeys.numberOfRemindersInADay.tr(context: context), value: viewModel.selectedNumberOfReminders, onRowTap: () => _showNumberOfRemindersSelectionBottomsheet(context, viewModel), showDivider: false, @@ -340,16 +360,4 @@ class _WaterMonitorSettingsScreenState extends State ), ); } - - // Show snackbar for validation errors and success messages - void _showSnackBar(BuildContext context, String message) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(message), - duration: const Duration(seconds: 3), - behavior: SnackBarBehavior.floating, - backgroundColor: message.contains('successfully') ? Colors.green : AppColors.errorColor, - ), - ); - } } diff --git a/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart b/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart index 4ffa30d..4ee6170 100644 --- a/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart +++ b/lib/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -7,6 +8,7 @@ import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/water_monitor/models/water_cup_model.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; @@ -143,7 +145,7 @@ class SwitchCupBottomSheet extends StatelessWidget { child: Center(child: Utils.buildSvgWithAssets(icon: AppAssets.cupAdd, height: 30.h, width: 42.w)), ), SizedBox(height: 4.h), - 'Add'.needTranslation.toText10(weight: FontWeight.w500), + LocaleKeys.add.tr(context: context).toText10(weight: FontWeight.w500), ], ), ); @@ -157,7 +159,7 @@ void showCustomizeCupBottomSheet(BuildContext context, {WaterCupModel? cupToEdit titleWidget: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "Customize your drink cup".needTranslation.toText20(weight: FontWeight.w600), + LocaleKeys.customizeDrinkCup.tr(context: context).toText20(weight: FontWeight.w600), ], ), child: CustomizeCupBottomSheet(cupToEdit: cupToEdit), @@ -294,7 +296,7 @@ class _CustomizeCupBottomSheetState extends State { SizedBox(height: 24.h), CustomButton( - text: 'Select'.needTranslation, + text: LocaleKeys.select.tr(context: context), onPressed: () { final newCup = WaterCupModel( id: widget.cupToEdit?.id ?? Uuid().v4(), diff --git a/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart b/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart index df55886..7c49550 100644 --- a/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart +++ b/lib/presentation/water_monitor/widgets/hydration_tips_widget.dart @@ -1,9 +1,11 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; class HydrationTipsWidget extends StatelessWidget { @@ -30,26 +32,26 @@ class HydrationTipsWidget extends StatelessWidget { height: 24.h, ), SizedBox(width: 8.w), - "Tips to stay hydrated".needTranslation.toText16(isBold: true), + LocaleKeys.tipsToStayHydrated.tr(context: context).toText16(isBold: true), ], ), SizedBox(height: 8.h), - " • ${"Drink before you feel thirsty"}".needTranslation.toText12( + " • ${LocaleKeys.drinkBeforeYouFeelThirsty.tr(context: context)}".toText12( fontWeight: FontWeight.w500, color: AppColors.textColorLight, ), SizedBox(height: 4.h), - " • ${"Keep a refillable bottle next to you"}".needTranslation.toText12( + " • ${LocaleKeys.keepRefillableBottleNextToYou.tr(context: context)}".toText12( fontWeight: FontWeight.w500, color: AppColors.textColorLight, ), SizedBox(height: 4.h), - " • ${"Track your daily intake to stay motivated"}".needTranslation.toText12( + " • ${LocaleKeys.trackYourDailyIntakeToStayMotivated.tr(context: context)}".toText12( fontWeight: FontWeight.w500, color: AppColors.textColorLight, ), SizedBox(height: 4.h), - " • ${"Choose sparkling water instead of soda"}".needTranslation.toText12( + " • ${LocaleKeys.chooseSparklingWaterInsteadOfSoda.tr(context: context)}".toText12( fontWeight: FontWeight.w500, color: AppColors.textColorLight, ), diff --git a/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart b/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart index 6546f77..115dd21 100644 --- a/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart +++ b/lib/presentation/water_monitor/widgets/water_action_buttons_widget.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -6,6 +7,7 @@ import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/cup_bottomsheet_widgets.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:provider/provider.dart'; @@ -18,23 +20,29 @@ class WaterActionButtonsWidget extends StatelessWidget { return Consumer(builder: (context, vm, _) { final cupAmount = vm.selectedCupCapacityMl; final isGoalAchieved = vm.progressPercent >= 100 || vm.nextDrinkTime.toLowerCase().contains('goal achieved'); + final isDisabled = vm.isLoading || isGoalAchieved; return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - InkWell( - onTap: () async { - if (cupAmount > 0) { - await vm.undoUserActivity(); - } - }, - child: Utils.buildSvgWithAssets( - icon: AppAssets.minimizeIcon, - height: 20.h, - width: 20.h, - iconColor: AppColors.textColor, + Opacity( + opacity: vm.isLoading ? 0.4 : 1.0, + child: InkWell( + onTap: vm.isLoading + ? null + : () async { + if (cupAmount > 0) { + await vm.undoUserActivity(); + } + }, + child: Utils.buildSvgWithAssets( + icon: AppAssets.minimizeIcon, + height: 20.h, + width: 20.h, + iconColor: AppColors.textColor, + ), ), ), Container( @@ -51,9 +59,9 @@ class WaterActionButtonsWidget extends StatelessWidget { ), ), Opacity( - opacity: isGoalAchieved ? 0.4 : 1.0, + opacity: isDisabled ? 0.4 : 1.0, child: InkWell( - onTap: isGoalAchieved + onTap: isDisabled ? null : () async { if (cupAmount > 0) { @@ -77,19 +85,19 @@ class WaterActionButtonsWidget extends StatelessWidget { context: context, onTap: () => showSwitchCupBottomSheet(context), overlayWidget: AppAssets.refreshIcon, - title: "Switch Cup".needTranslation, + title: LocaleKeys.switchCup.tr(context: context), icon: Utils.buildSvgWithAssets(icon: AppAssets.glassIcon, height: 24.w, width: 24.w), ), _buildActionButton( context: context, onTap: () async {}, - title: "Plain Water".needTranslation, + title: LocaleKeys.plainWater.tr(context: context), icon: Utils.buildSvgWithAssets(icon: AppAssets.glassIcon, height: 24.w, width: 24.w), ), _buildActionButton( context: context, - onTap: () => context.navigateWithName(AppRoutes.waterMonitorSettingsScreen), - title: "Settings".needTranslation, + onTap: () => context.navigateWithName(AppRoutes.waterMonitorSettingsPage), + title: LocaleKeys.settings.tr(context: context), icon: Icon( Icons.settings, color: AppColors.blueColor, diff --git a/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart b/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart index 137f6a3..ec796ab 100644 --- a/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart +++ b/lib/presentation/water_monitor/widgets/water_intake_summary_widget.dart @@ -1,7 +1,9 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_action_buttons_widget.dart'; import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_bottle_widget.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -51,7 +53,6 @@ class WaterIntakeSummaryWidget extends StatelessWidget { if (!vm.nextDrinkTime.toLowerCase().contains('goal achieved')) // Show "Tomorrow" if nextDrinkTime contains "tomorrow", otherwise "Next Drink Time" (vm.nextDrinkTime.toLowerCase().contains('tomorrow') ? "Tomorrow" : "Next Drink Time") - .needTranslation .toText18(weight: FontWeight.w600, color: AppColors.textColor), // Extract only time if "tomorrow" is present, otherwise show as is @@ -61,14 +62,17 @@ class WaterIntakeSummaryWidget extends StatelessWidget { .toText32(weight: FontWeight.w600, color: AppColors.blueColor), SizedBox(height: 12.h), - _buildStatusColumn(title: "Your Goal".needTranslation, subTitle: "${goalMl}ml"), - SizedBox(height: 8.h), - _buildStatusColumn(title: "Remaining".needTranslation, subTitle: "${remaining}ml"), - SizedBox(height: 8.h), - _buildStatusColumn(title: "Completed".needTranslation, subTitle: completedPercent, subTitleColor: AppColors.successColor), - SizedBox(height: 8.h), + Row( + children: [ + _buildStatusColumn(title: LocaleKeys.yourGoal.tr(context: context), subTitle: "${goalMl}ml"), + SizedBox(width: 16.w), + _buildStatusColumn(title: LocaleKeys.remaining.tr(context: context), subTitle: "${remaining}ml"), + SizedBox(width: 16.w), + _buildStatusColumn(title: LocaleKeys.completed.tr(context: context), subTitle: completedPercent, subTitleColor: AppColors.successColor), + ], + ), _buildStatusColumn( - title: "Hydration Status".needTranslation, + title: LocaleKeys.hydrationStatus.tr(context: context), subTitle: vm.hydrationStatus, subTitleColor: vm.hydrationStatusColor, ), diff --git a/lib/routes/app_routes.dart b/lib/routes/app_routes.dart index 9fd4b1a..bb74479 100644 --- a/lib/routes/app_routes.dart +++ b/lib/routes/app_routes.dart @@ -5,14 +5,20 @@ import 'package:hmg_patient_app_new/presentation/authentication/register.dart'; import 'package:hmg_patient_app_new/presentation/authentication/register_step2.dart'; import 'package:hmg_patient_app_new/presentation/blood_donation/blood_donation_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/book_appointment_page.dart'; +import 'package:hmg_patient_app_new/presentation/child_vaccine/my_child_vaccine_page.dart'; import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/comprehensive_checkup_page.dart'; +import 'package:hmg_patient_app_new/presentation/covid19test/covid19_landing_page.dart'; import 'package:hmg_patient_app_new/presentation/e_referral/new_e_referral.dart'; +import 'package:hmg_patient_app_new/presentation/emergency_services/emergency_services_page.dart'; import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculators_page.dart'; +import 'package:hmg_patient_app_new/presentation/health_trackers/add_health_tracker_entry_page.dart'; +import 'package:hmg_patient_app_new/presentation/health_trackers/health_tracker_detail_page.dart'; +import 'package:hmg_patient_app_new/presentation/health_trackers/health_trackers_page.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; import 'package:hmg_patient_app_new/presentation/home_health_care/hhc_procedures_page.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/medical_file_page.dart'; import 'package:hmg_patient_app_new/presentation/smartwatches/huawei_health_example.dart'; -import 'package:hmg_patient_app_new/presentation/smartwatches/smartwatch_instructions_page.dart'; +import 'package:hmg_patient_app_new/presentation/smartwatches/smartwatch_home_page.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/organ_selector_screen.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/possible_conditions_screen.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/risk_factors_screen.dart'; @@ -23,11 +29,17 @@ import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_sele import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/user_info_flow_manager.dart'; import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.dart'; import 'package:hmg_patient_app_new/presentation/vital_sign/vital_sign_page.dart'; -import 'package:hmg_patient_app_new/presentation/water_monitor/water_consumption_screen.dart'; -import 'package:hmg_patient_app_new/presentation/water_monitor/water_monitor_settings_screen.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/water_consumption_page.dart'; +import 'package:hmg_patient_app_new/presentation/water_monitor/water_monitor_settings_page.dart'; import 'package:hmg_patient_app_new/splashPage.dart'; +import 'package:provider/provider.dart'; -import '../presentation/covid19test/covid19_landing_page.dart'; +import '../core/dependencies.dart'; +import '../features/monthly_reports/monthly_reports_repo.dart'; +import '../features/monthly_reports/monthly_reports_view_model.dart'; +import '../features/qr_parking/qr_parking_view_model.dart'; +import '../presentation/parking/paking_page.dart'; +import '../services/error_handler_service.dart'; class AppRoutes { static const String initialRoute = '/initialRoute'; @@ -43,28 +55,38 @@ class AppRoutes { static const String homeHealthCarePage = '/homeHealthCarePage'; static const String zoomCallPage = '/zoomCallPage'; static const String bloodDonationPage = '/bloodDonationPage'; + static const String myChildVaccine = '/myChildVaccine'; static const String smartWatches = '/smartWatches'; static const String huaweiHealthExample = '/huaweiHealthExample'; static const String covid19Test = '/covid19Test'; static const String vitalSign = '/vitalSign'; + //appointments static const String bookAppointmentPage = '/bookAppointmentPage'; // Water Monitor - static const String waterConsumptionScreen = '/waterConsumptionScreen'; - static const String waterMonitorSettingsScreen = '/waterMonitorSettingsScreen'; + static const String waterConsumptionPage = '/waterConsumptionScreen'; + static const String waterMonitorSettingsPage = '/waterMonitorSettingsScreen'; // Symptoms Checker static const String organSelectorPage = '/organSelectorPage'; - static const String symptomsSelectorScreen = '/symptomsCheckerScreen'; - static const String suggestionsScreen = '/suggestionsScreen'; - static const String riskFactorsScreen = '/riskFactorsScreen'; - static const String possibleConditionsScreen = '/possibleConditionsScreen'; - static const String triageScreen = '/triageProgressScreen'; - - //UserInfoSelection + static const String symptomsSelectorPage = '/symptomsCheckerScreen'; + static const String suggestionsPage = '/suggestionsScreen'; + static const String riskFactorsPage = '/riskFactorsScreen'; + static const String possibleConditionsPage = '/possibleConditionsScreen'; + static const String triagePage = '/triageProgressScreen'; static const String userInfoSelection = '/userInfoSelection'; static const String userInfoFlowManager = '/userInfoFlowManager'; + static const String monthlyReports = '/monthlyReportsPage'; + static const String qrParking = '/qrParkingPage'; + + // Health Trackers + static const String healthTrackersPage = '/healthTrackersListScreen'; + static const String addHealthTrackerEntryPage = '/addHealthTrackerEntryPage'; + static const String healthTrackerDetailPage = '/healthTrackerDetailPage'; + + // Emergency Services + static const String emergencyServicesPage = '/emergencyServicesPage'; static Map get routes => { initialRoute: (context) => SplashPage(), @@ -78,23 +100,47 @@ class AppRoutes { comprehensiveCheckupPage: (context) => ComprehensiveCheckupPage(), homeHealthCarePage: (context) => HhcProceduresPage(), organSelectorPage: (context) => OrganSelectorPage(), - symptomsSelectorScreen: (context) => SymptomsSelectorScreen(), - riskFactorsScreen: (context) => RiskFactorsScreen(), - suggestionsScreen: (context) => SuggestionsScreen(), - possibleConditionsScreen: (context) => PossibleConditionsScreen(), - triageScreen: (context) => TriageScreen(), + symptomsSelectorPage: (context) => SymptomsSelectorPage(), + riskFactorsPage: (context) => RiskFactorsScreen(), + suggestionsPage: (context) => SuggestionsScreen(), + possibleConditionsPage: (context) => PossibleConditionsPage(), + triagePage: (context) => TriagePage(), bloodDonationPage: (context) => BloodDonationPage(), + myChildVaccine: (context) => MyChildVaccinePage(), bookAppointmentPage: (context) => BookAppointmentPage(), - userInfoSelection: (context) => UserInfoSelectionScreen(), + userInfoSelection: (context) => UserInfoSelectionPage(), userInfoFlowManager: (context) => UserInfoFlowManager(), - smartWatches: (context) => SmartwatchInstructionsPage(), + smartWatches: (context) => SmartwatchHomePage(), huaweiHealthExample: (context) => HuaweiHealthExample(), covid19Test: (context) => Covid19LandingPage(), - // - waterConsumptionScreen: (context) => WaterConsumptionScreen(), - waterMonitorSettingsScreen: (context) => WaterMonitorSettingsScreen(), + waterConsumptionPage: (context) => WaterConsumptionPage(), + waterMonitorSettingsPage: (context) => WaterMonitorSettingsPage(), healthCalculatorsPage: (context) => HealthCalculatorsPage(type: HealthCalConEnum.calculator), healthConvertersPage: (context) => HealthCalculatorsPage(type: HealthCalConEnum.converter), - vitalSign: (context) => VitalSignPage() + healthTrackersPage: (context) => HealthTrackersPage(), + vitalSign: (context) => VitalSignPage(), + emergencyServicesPage: (context) => EmergencyServicesPage(), + addHealthTrackerEntryPage: (context) { + final args = ModalRoute.of(context)?.settings.arguments as HealthTrackerTypeEnum?; + return AddHealthTrackerEntryPage( + trackerType: args ?? HealthTrackerTypeEnum.bloodSugar, + ); + }, + healthTrackerDetailPage: (context) { + final args = ModalRoute.of(context)?.settings.arguments as HealthTrackerTypeEnum?; + return HealthTrackerDetailPage( + trackerType: args ?? HealthTrackerTypeEnum.bloodSugar, + ); + }, + monthlyReports: (context) => ChangeNotifierProvider( + create: (_) => MonthlyReportsViewModel( + monthlyReportsRepo: getIt(), + errorHandlerService: getIt(), + ), + ), + qrParking: (context) => ChangeNotifierProvider( + create: (_) => getIt(), + child: const ParkingPage(), + ) }; } diff --git a/lib/services/dialog_service.dart b/lib/services/dialog_service.dart index 497a009..b185d89 100644 --- a/lib/services/dialog_service.dart +++ b/lib/services/dialog_service.dart @@ -2,10 +2,12 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/features/medical_file/models/family_file_response_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/my_family/my_family.dart'; import 'package:hmg_patient_app_new/presentation/my_family/widget/family_cards.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -14,6 +16,8 @@ import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; import 'package:hmg_patient_app_new/widgets/family_files/family_file_add_widget.dart'; +import '../widgets/medication_reminder/reminder_timer_dialog.dart'; + abstract class DialogService { Future showErrorBottomSheet({String title = "", required String message, Function()? onOkPressed, Function()? onCancelPressed}); @@ -21,18 +25,22 @@ abstract class DialogService { Future showCommonBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}); + Future showSuccessBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}); + Future showFamilyBottomSheetWithoutH( {String? label, required String message, required Function(FamilyFileResponseModelLists response) onSwitchPress, - required List profiles}); + required List profiles, + bool isShowManageButton = false}); - Future showFamilyBottomSheetWithoutHWithChild( - {String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}); + Future showFamilyBottomSheetWithoutHWithChild({String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}); Future showPhoneNumberPickerSheet({String? label, String? message, required Function() onSMSPress, required Function() onWhatsappPress}); Future showAddFamilyFileSheet({String? label, String? message, required Function() onVerificationPress}); + + Future showReminderBottomSheetWithoutHWithChild({String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}); // TODO : Need to be Fixed showPhoneNumberPickerSheet ( From Login ADn Signup Bottom Sheet Move Here } @@ -62,18 +70,16 @@ class DialogServiceImp implements DialogService { message: message, showCancel: onCancelPressed != null ? true : false, onOkPressed: () { - print('ok button is pressed'); if (onOkPressed != null) { - print('onOkPressed is not null'); onOkPressed(); - }else { + } else { Navigator.pop(context); } }, onCancelPressed: () { if (onCancelPressed != null) { onCancelPressed(); - }else { + } else { Navigator.pop(context); } }, @@ -119,12 +125,25 @@ class DialogServiceImp implements DialogService { ); } + @override + Future showSuccessBottomSheetWithoutH({String? label, required String message, required Function() onOkPressed, Function()? onCancelPressed}) async { + final context = navigationService.navigatorKey.currentContext; + if (context == null) return; + showCommonBottomSheetWithoutHeight( + context, + title: label ?? "", + child: Utils.getSuccessWidget(loadingText: message.needTranslation), + callBackFunc: () {}, + ); + } + @override Future showFamilyBottomSheetWithoutH( {String? label, required String message, required Function(FamilyFileResponseModelLists response) onSwitchPress, - required List profiles}) async { + required List profiles, + bool isShowManageButton = false}) async { final context = navigationService.navigatorKey.currentContext; if (context == null) return; showCommonBottomSheetWithoutHeight(context, @@ -133,7 +152,7 @@ class DialogServiceImp implements DialogService { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ - (message).toText16(isBold: false, color: AppColors.textColor), + if (message != null) (message).toText16(isBold: false, color: AppColors.textColor), SizedBox(height: 24.h), FamilyCards( profiles: profiles, @@ -143,14 +162,41 @@ class DialogServiceImp implements DialogService { onRemove: (FamilyFileResponseModelLists profile) {}, isShowDetails: false, ), + SizedBox(height: isShowManageButton ? 15.h : 24.h), + if (isShowManageButton) + CustomButton( + text: LocaleKeys.manageFiles.tr(context: context), + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedBorderColor, + height: 48.h, + onPressed: () { + navigationService.pushPage( + page: FamilyMedicalScreen( + profiles: profiles, + onSelect: (FamilyFileResponseModelLists p1) {}, + ), + ); + }) ], ), callBackFunc: () {}); } @override - Future showFamilyBottomSheetWithoutHWithChild( - {String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}) async { + Future showFamilyBottomSheetWithoutHWithChild({String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}) async { + final context = navigationService.navigatorKey.currentContext; + if (context == null) return; + showCommonBottomSheetWithoutHeight( + context, + title: label ?? "", + child: child ?? SizedBox(), + callBackFunc: () {}, + ); + } + + @override + Future showReminderBottomSheetWithoutHWithChild({String? label, required String message, Widget? child, required Function() onOkPressed, Function()? onCancelPressed}) async { final context = navigationService.navigatorKey.currentContext; if (context == null) return; showCommonBottomSheetWithoutHeight( @@ -166,9 +212,7 @@ class DialogServiceImp implements DialogService { final context = navigationService.navigatorKey.currentContext; if (context == null) return; showCommonBottomSheetWithoutHeight(context, - title: label ?? "", - child: showPhoneNumberPickerWidget(context: context, message: message, onSMSPress: onSMSPress, onWhatsappPress: onWhatsappPress), - callBackFunc: () {}); + title: label ?? "", child: showPhoneNumberPickerWidget(context: context, message: message, onSMSPress: onSMSPress, onWhatsappPress: onWhatsappPress), callBackFunc: () {}); } @override @@ -195,7 +239,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), onPressed: () { Navigator.of(context).pop(); }, @@ -209,7 +253,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin SizedBox(width: 10.h), Expanded( child: CustomButton( - text: LocaleKeys.confirm.tr(), + text: LocaleKeys.confirm.tr(context: context), onPressed: onOkPressed, backgroundColor: AppColors.bgGreenColor, borderColor: AppColors.bgGreenColor, @@ -223,7 +267,7 @@ Widget exceptionBottomSheetWidget({required BuildContext context, required Strin Padding( padding: EdgeInsets.only(bottom: 10.h), child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), onPressed: (onCancelPressed == null) ? () { context.pop(); @@ -248,7 +292,7 @@ Widget showPhoneNumberPickerWidget({required BuildContext context, String? messa Padding( padding: EdgeInsets.only(bottom: 10.h), child: CustomButton( - text: LocaleKeys.sendOTPSMS.tr(), + text: LocaleKeys.sendOTPSMS.tr(context: context), onPressed: onSMSPress, backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedBorderColor, @@ -262,14 +306,14 @@ Widget showPhoneNumberPickerWidget({required BuildContext context, String? messa children: [ Padding( padding: EdgeInsets.symmetric(horizontal: 8.h), - child: LocaleKeys.oR.tr().toText16(color: AppColors.textColor), + child: LocaleKeys.oR.tr(context: context).toText16(color: AppColors.textColor), ), ], ), Padding( padding: EdgeInsets.only(bottom: 10.h, top: 10.h), child: CustomButton( - text: LocaleKeys.sendOTPWHATSAPP.tr(), + text: LocaleKeys.sendOTPWHATSAPP.tr(context: context), onPressed: onWhatsappPress, backgroundColor: Colors.white, borderColor: AppColors.borderOnlyColor, diff --git a/lib/services/livecare_permission_service.dart b/lib/services/livecare_permission_service.dart new file mode 100644 index 0000000..a9a5d29 --- /dev/null +++ b/lib/services/livecare_permission_service.dart @@ -0,0 +1,92 @@ +import 'dart:async'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:permission_handler/permission_handler.dart'; + +class LiveCarePermissionService { + LiveCarePermissionService._(); + + static final LiveCarePermissionService instance = LiveCarePermissionService._(); + + // Guard to prevent concurrent permission requests + Completer>? _ongoingRequest; + + /// Requests camera, microphone and notification permissions together and + /// returns the final map of permission statuses. + /// This method does NOT show any dialogs — UI decisions must be done by caller. + Future> requestCameraMicAndNotification(BuildContext context) async { + if (_ongoingRequest != null) { + return _ongoingRequest!.future; + } + + _ongoingRequest = Completer>(); + final completer = _ongoingRequest!; + + final permissions = [ + Permission.camera, + Permission.microphone, + Permission.notification, + ]; + + try { + final statuses = await permissions.request(); + + // Ensure all requested keys exist in the returned map (some platforms may omit) + final result = {}; + for (final p in permissions) { + result[p] = statuses[p] ?? await p.status; + } + + if (!completer.isCompleted) completer.complete(result); + return completer.future; + } catch (e) { + if (!completer.isCompleted) completer.complete({}); + return completer.future; + } finally { + _ongoingRequest = null; + } + } + + /// Show an "open settings" dialog (kept as helper for the UI layer). + Future showOpenSettingsDialog(BuildContext context, {required String title, required String message}) async { + return showCommonBottomSheetWithoutHeight( + title: title, + context, + child: Utils.getWarningWidget( + loadingText: message, + isShowActionButtons: true, + onCancelTap: () { + Navigator.of(context).pop(); + }, + onConfirmTap: () async { + openAppSettings(); + Navigator.of(context).pop(); + }), + isFullScreen: false, + isCloseButtonVisible: true, + callBackFunc: () {}, + ); + // return showDialog( + // context: context, + // builder: (c) => ConfirmDialog( + // title: '$title Permission', + // message: message, + // onTap: () { + // openAppSettings(); + // Navigator.of(c).pop(); + // }, + // okTitle: LocaleKeys.ok.tr(context: c), + // ), + // ); + } + + String friendlyName(Permission permission) { + if (permission == Permission.camera) return 'Camera'; + if (permission == Permission.microphone) return 'Microphone'; + if (permission == Permission.notification) return 'Notifications'; + return permission.toString(); + } +} diff --git a/lib/services/zoom_service.dart b/lib/services/zoom_service.dart new file mode 100644 index 0000000..9af543d --- /dev/null +++ b/lib/services/zoom_service.dart @@ -0,0 +1,33 @@ +// lib/services/zoom_service.dart +import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; + +class ZoomService { + static final ZoomService _instance = ZoomService._internal(); + factory ZoomService() => _instance; + ZoomService._internal(); + + ZoomVideoSdk? _zoom; + bool _isInitialized = false; + + Future initializeZoomSDK() async { + if (_isInitialized) return; + + try { + _zoom = ZoomVideoSdk(); + InitConfig initConfig = InitConfig( + domain: "zoom.us", + enableLog: true, // Enable for debugging + ); + + await _zoom!.initSdk(initConfig); + _isInitialized = true; + print("Zoom SDK initialized successfully"); + } catch (e) { + print("Error initializing Zoom SDK: $e"); + rethrow; + } + } + + ZoomVideoSdk? get zoom => _zoom; + bool get isInitialized => _isInitialized; +} \ No newline at end of file diff --git a/lib/splashPage.dart b/lib/splashPage.dart index 5a07123..49680a2 100644 --- a/lib/splashPage.dart +++ b/lib/splashPage.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_callkit_incoming/entities/call_event.dart'; import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; -// import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -19,6 +19,7 @@ import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_scr import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:hmg_patient_app_new/services/navigation_service.dart'; import 'package:hmg_patient_app_new/services/notification_service.dart'; +import 'package:hmg_patient_app_new/services/zoom_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart'; import 'package:lottie/lottie.dart'; @@ -26,6 +27,7 @@ import 'package:lottie/lottie.dart'; import 'core/cache_consts.dart'; import 'core/utils/push_notification_handler.dart'; + class SplashPage extends StatefulWidget { const SplashPage({super.key}); @@ -50,11 +52,11 @@ class _SplashScreenState extends State { bool isAppOpenedFromCall = getIt.get().getBool(key: CacheConst.isAppOpenedFromCall) ?? false; // Initialize NotificationService using dependency injection - // final notificationService = getIt.get(); - // await notificationService.initialize(onNotificationClick: (payload) { - // // Handle notification click here - // }); - + final notificationService = getIt.get(); + await notificationService.initialize(onNotificationClick: (payload) { + // Handle notification click here + }); + ZoomService().initializeZoomSDK(); if (isAppOpenedFromCall) { navigateToTeleConsult(); } else { @@ -84,14 +86,14 @@ class _SplashScreenState extends State { Navigator.of(GetIt.instance().navigatorKey.currentContext!) .pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: LandingNavigation()))); - // Navigator.pushReplacementNamed( - // // context, - // GetIt.instance().navigatorKey.currentContext!, - // AppRoutes.zoomCallPage, - // // arguments: CallArguments(appointmentID, "111", "Patient", "40", "1", true, 1), - // arguments: CallArguments(roomID, "123", "Patient", "40", "0", true, 1), - // // arguments: CallArguments("SmallDailyStandup9875", "123", "Patient", "40", "0", false, int.parse(widget.incomingCallData!.appointmentNo!)), - // ); + Navigator.pushReplacementNamed( + // context, + GetIt.instance().navigatorKey.currentContext!, + AppRoutes.zoomCallPage, + // arguments: CallArguments(appointmentID, "111", "Patient", "40", "1", true, 1), + arguments: CallArguments(roomID, "123", "Patient", "40", "0", true, 1), + // arguments: CallArguments("SmallDailyStandup9875", "123", "Patient", "40", "0", false, int.parse(widget.incomingCallData!.appointmentNo!)), + ); } Future listenerEvent() async { diff --git a/lib/theme/colors.dart b/lib/theme/colors.dart index c631f5b..d56178b 100644 --- a/lib/theme/colors.dart +++ b/lib/theme/colors.dart @@ -2,111 +2,115 @@ import 'package:flutter/material.dart'; class AppColors { static const transparent = Colors.transparent; - static const mainPurple = Color(0xFF7954F7); + static const mainPurple = Color(0xFF7954F7); // #7954F7 - static const scaffoldBgColor = Color(0xFFF8F8F8); - static const bottomSheetBgColor = Color(0xFFF8F8FA); - static const lightGreyEFColor = Color(0xffeaeaff); - static const greyF7Color = Color(0xffF7F7F7); - static const greyInfoTextColor = Color(0xff777777); - static const lightGrayColor = Color(0xff808080); - static const greyTextColorLight = Color(0xFFA2A2A2); + static const scaffoldBgColor = Color(0xFFF8F8F8); // #F8F8F8 + static const bottomSheetBgColor = Color(0xFFF8F8FA); // #F8F8FA + static const lightGreyEFColor = Color(0xffeaeaff); // #EAEAFF + static const greyF7Color = Color(0xffF7F7F7); // #F7F7F7 + static const greyInfoTextColor = Color(0xff777777); // #777777 + static const lightGrayColor = Color(0xff808080); // #808080 + static const greyTextColorLight = Color(0xFFA2A2A2); // #A2A2A2 // New UI Colors - static const whiteColor = Color(0xFFffffff); - static const Color bgScaffoldColor = Color(0xffF8F8F8); - static const Color primaryRedColor = Color(0xFFED1C2B); - static const Color primaryRedBorderColor = Color(0xFFED1C2B); - static const Color secondaryLightRedColor = Color(0xFFFEE9EA); - static const Color secondaryLightRedBorderColor = Color(0xFFFEE9EA); - static const Color bgRedLightColor = Color(0xFFFEE9EA); - static const Color bgGreenColor = Color(0xFF18C273); - static const Color textColor = Color(0xFF2E3039); - static const Color borderGrayColor = Color(0x332E3039); - static const Color textColorLight = Color(0xFF5E5E5E); - static const Color borderOnlyColor = Color(0xFF2E3039); - static const Color chipBorderColorOpacity20 = Color(0x332E3039); - static const Color dividerColor = Color(0x40D2D2D2); - static const Color warningColorYellow = Color(0xFFF4A308); - static const Color blackBgColor = Color(0xFF2E3039); - static const blackColor = textColor; - static const Color inputLabelTextColor = Color(0xff898A8D); - static const Color greyTextColor = Color(0xFF8F9AA3); - static const Color lightGrayBGColor = Color(0x142E3039); - static const Color checkBoxBorderColor = Color(0xffD2D2D2); - - static const Color pharmacyBGColor = Color(0xFF359846); - - static const lightGreenColor = Color(0xFF0ccedde); - static const textGreenColor = Color(0xFF18C273); - static const Color ratingColorYellow = Color(0xFFFFAF15); - static const Color spacerLineColor = Color(0x2E30391A); + static const whiteColor = Color(0xFFffffff); // #FFFFFF + static const Color bgScaffoldColor = Color(0xffF8F8F8); // #F8F8F8 + static const Color primaryRedColor = Color(0xFFED1C2B); // #ED1C2B + static const Color primaryRedBorderColor = Color(0xFFED1C2B); // #ED1C2B + static const Color secondaryLightRedColor = Color(0xFFFEE9EA); // #FEE9EA + static const Color secondaryLightRedBorderColor = Color(0xFFFEE9EA); // #FEE9EA + static const Color bgRedLightColor = Color(0xFFFEE9EA); // #FEE9EA + static const Color bgGreenColor = Color(0xFF18C273); // #18C273 + static const Color textColor = Color(0xFF2E3039); // #2E3039 + static const Color borderGrayColor = Color(0x332E3039); // #2E3039 (20% opacity) + static const Color textColorLight = Color(0xFF5E5E5E); // #5E5E5E + static const Color borderOnlyColor = Color(0xFF2E3039); // #2E3039 + static const Color chipBorderColorOpacity20 = Color(0x332E3039); // #2E3039 (20% opacity) + static const Color dividerColor = Color(0x40D2D2D2); // #D2D2D2 (25% opacity) + static const Color warningColorYellow = Color(0xFFF4A308); // #F4A308 + static const Color blackBgColor = Color(0xFF2E3039); // #2E3039 + static const blackColor = textColor; // #2E3039 + static const Color inputLabelTextColor = Color(0xff898A8D); // #898A8D + static const Color greyTextColor = Color(0xFF8F9AA3); // #8F9AA3 + static const Color lightGrayBGColor = Color(0x142E3039); // #2E3039 (8% opacity) + static const Color checkBoxBorderColor = Color(0xffD2D2D2); // #D2D2D2 + + static const Color pharmacyBGColor = Color(0xFF359846); // #359846 + + static const lightGreenColor = Color(0xFF0ccedde); // #0CCEDDE + static const textGreenColor = Color(0xFF18C273); // #18C273 + static const Color ratingColorYellow = Color(0xFFFFAF15); // #FFAF15 + static const Color spacerLineColor = Color(0x2E30391A); // #2E3039 (10% opacity) //Chips - static const Color successColor = Color(0xff18C273); - static const Color successLightBgColor = Color(0xffDDF6EA); - static const Color errorColor = Color(0xFFED1C2B); - static const Color alertColor = Color(0xFFD48D05); - static const Color infoColor = Color(0xFF0B85F7); - static const Color warningColor = Color(0xFFFFCC00); - static const Color greyColor = Color(0xFFEFEFF0); - static const Color chipPrimaryRedBorderColor = Color(0xFFED1C2B); - static const Color chipSecondaryLightRedColor = Color(0xFFFEE9EA); - - static const Color successLightColor = Color(0xFF18C273); - static const Color errorLightColor = Color(0xFFED1C2B); - static const Color alertLightColor = Color(0xFFD48D05); - static const Color infoLightColor = Color(0xFF0B85F7); - static const Color warningLightColor = Color(0xFFFFCC00); - static const Color greyLightColor = Color(0xFFEFEFF0); - static const Color thumbColor = Color(0xFF18C273); - static const Color switchBackgroundColor = Color(0x2618C273); - - static const Color bottomNAVBorder = Color(0xFFEEEEEE); - - static const Color quickLoginColor = Color(0xFF666666); - - static const Color tooltipTextColor = Color(0xFF414D55); - static const Color graphGridColor = Color(0x4D18C273); - static const Color criticalLowAndHigh = Color(0xFFED1C2B); - static const Color highAndLow = Color(0xFFFFAF15); - static const Color labelTextColor = Color(0xFF838383); - static const Color calenderTextColor = Color(0xFFD0D0D0); - static const Color lightGreenButtonColor = Color(0x2618C273); - - static const Color lightRedButtonColor = Color(0x1AED1C2B); + static const Color successColor = Color(0xff18C273); // #18C273 + static const Color successLightBgColor = Color(0xffDDF6EA); // #DDF6EA + static const Color errorColor = Color(0xFFED1C2B); // #ED1C2B + static const Color alertColor = Color(0xFFD48D05); // #D48D05 + static const Color infoColor = Color(0xFF0B85F7); // #0B85F7 + static const Color warningColor = Color(0xFFFFCC00); // #FFCC00 + static const Color greyColor = Color(0xFFEFEFF0); // #EFEFF0 + static const Color chipPrimaryRedBorderColor = Color(0xFFED1C2B); // #ED1C2B + static const Color chipSecondaryLightRedColor = Color(0xFFFEE9EA); // #FEE9EA + // static const Color chipSecondaryLightRedColor = Color(0xFFFF9E15); // #FEE9EA + + static const Color successLightColor = Color(0xFF18C273); // #18C273 + static const Color errorLightColor = Color(0xFFED1C2B); // #ED1C2B + static const Color alertLightColor = Color(0xFFD48D05); // #D48D05 + static const Color infoLightColor = Color(0xFF0B85F7); // #0B85F7 + static const Color warningLightColor = Color(0xFFFFCC00); // #FFCC00 + static const Color greyLightColor = Color(0xFFEFEFF0); // #EFEFF0 + static const Color thumbColor = Color(0xFF18C273); // #18C273 + static const Color switchBackgroundColor = Color(0x2618C273); // #18C273 (15% opacity) + + static const Color bottomNAVBorder = Color(0xFFEEEEEE); // #EEEEEE + + static const Color quickLoginColor = Color(0xFF666666); // #666666 + + static const Color tooltipTextColor = Color(0xFF414D55); // #414D55 + static const Color graphGridColor = Color(0x4D18C273); // #18C273 (30% opacity) + static const Color criticalLowAndHigh = Color(0xFFED1C2B); // #ED1C2B + static const Color highAndLow = Color(0xFFFFAF15); // #FFAF15 + static const Color labelTextColor = Color(0xFF838383); // #838383 + static const Color calenderTextColor = Color(0xFFD0D0D0); // #D0D0D0 + static const Color lightGreenButtonColor = Color(0x2618C273); // #18C273 (15% opacity) + + static const Color lightRedButtonColor = Color(0x1AED1C2B); // #ED1C2B (10% opacity) // Status Colors - static const Color statusPendingColor = Color(0xffCC9B14); - static const Color statusProcessingColor = Color(0xff2E303A); - static const Color statusCompletedColor = Color(0xff359846); - static const Color statusRejectedColor = Color(0xffD02127); + static const Color statusPendingColor = Color(0xffCC9B14); // #CC9B14 + static const Color statusProcessingColor = Color(0xff2E303A); // #2E303A + static const Color statusCompletedColor = Color(0xff359846); // #359846 + static const Color statusRejectedColor = Color(0xffD02127); // #D02127 // Info Banner Colors - static const Color infoBannerBgColor = Color(0xFFFFF4E6); - static const Color infoBannerBorderColor = Color(0xFFFFE5B4); - static const Color infoBannerIconColor = Color(0xFFCC9B14); - static const Color infoBannerTextColor = Color(0xFF856404); + static const Color infoBannerBgColor = Color(0xFFFFF4E6); // #FFF4E6 + static const Color infoBannerBorderColor = Color(0xFFFFE5B4); // #FFE5B4 + static const Color infoBannerIconColor = Color(0xFFCC9B14); // #CC9B14 + static const Color infoBannerTextColor = Color(0xFF856404); // #856404 // SymptomsChecker - static const Color chipColorSeekMedicalAdvice = Color(0xFFFFAF15); - static const Color chipTextColorSeekMedicalAdvice = Color(0xFFAB7103); - static const Color chipColorMonitor = Color(0xFF18C273); - static const Color chipColorEmergency = Color(0xFFED1C2B); + static const Color chipColorSeekMedicalAdvice = Color(0xFFFFAF15); // #FFAF15 + static const Color chipTextColorSeekMedicalAdvice = Color(0xFFD48D05); // #AB7103 + static const Color chipColorMonitor = Color(0xFF18C273); // #18C273 + static const Color chipColorEmergency = Color(0xFFED1C2B); // #ED1C2B // Services Page Colors - static const Color eReferralCardColor = Color(0xFFFF8012); - static const Color bloodDonationCardColor = Color(0xFFFF5662); - static const Color bookAppointment = Color(0xFF415364); + static const Color eReferralCardColor = Color(0xFFFF8012); // #FF8012 + static const Color bloodDonationCardColor = Color(0xFFFF5662); // #FF5662 + static const Color myChildVaccineCardColor = Color(0xFFFF2D78); // #FF5662 + static const Color bookAppointment = Color(0xFF415364); // #415364 // Water Monitor - static const Color blueColor = Color(0xFF4EB5FF); - static const Color blueGradientColorOne = Color(0xFFF1F7FD); - static const Color blueGradientColorTwo = Color(0xFFD9EFFF); + static const Color blueColor = Color(0xFF4EB5FF); // #4EB5FF + static const Color blueGradientColorOne = Color(0xFFF1F7FD); // #F1F7FD + static const Color blueGradientColorTwo = Color(0xFFD9EFFF); // #D9EFFF // Shimmer - static const Color shimmerBaseColor = Color(0xFFE0E0E0); - static const Color shimmerHighlightColor = Color(0xFFF5F5F5); - static const Color covid29Color = Color(0xff2563EB); + static const Color shimmerBaseColor = Color(0xFFE0E0E0); // #E0E0E0 + static const Color shimmerHighlightColor = Color(0xFFF5F5F5); // #F5F5F5 + static const Color covid29Color = Color(0xff2563EB); // #2563EB + static const Color lightGreyTextColor = Color(0xFF959595); + static const Color labelColorYellow = Color(0xFFFBCB6E); } diff --git a/lib/widgets/app_language_change.dart b/lib/widgets/app_language_change.dart index de9cda5..c94195a 100644 --- a/lib/widgets/app_language_change.dart +++ b/lib/widgets/app_language_change.dart @@ -41,14 +41,14 @@ class _AppLanguageChangeState extends State { decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true), child: Column( children: [ - languageItem("English".needTranslation, "en"), + languageItem("English", "en"), 1.divider, - languageItem("العربية".needTranslation, "ar"), + languageItem("العربية", "ar"), ], ), ), CustomButton( - text: LocaleKeys.save.tr(), + text: LocaleKeys.save.tr(context: context), onPressed: () { context.setLocale(selectedValue == 'en' ? Locale('en', 'US') : Locale('ar', 'SA')).then((val) { Navigator.pop(context); diff --git a/lib/widgets/appbar/app_bar_widget.dart b/lib/widgets/appbar/app_bar_widget.dart index b3bc3eb..942a93f 100644 --- a/lib/widgets/appbar/app_bar_widget.dart +++ b/lib/widgets/appbar/app_bar_widget.dart @@ -42,15 +42,15 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { ? RotatedBox( quarterTurns: 90, child: Utils.buildSvgWithAssets( - icon: AppAssets.arrow_back, - width: 32.w, - height: 32.h, + icon: AppAssets.forward_top_nav_icon, + width: 24.w, + height: 24.h, ), ) : Utils.buildSvgWithAssets( - icon: AppAssets.arrow_back, - width: 32.w, - height: 32.h, + icon: AppAssets.forward_top_nav_icon, + width: 24.w, + height: 24.h, ), ), ), diff --git a/lib/widgets/appbar/collapsing_list_view.dart b/lib/widgets/appbar/collapsing_list_view.dart index 5409fcf..575de03 100644 --- a/lib/widgets/appbar/collapsing_list_view.dart +++ b/lib/widgets/appbar/collapsing_list_view.dart @@ -1,4 +1,4 @@ - +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -8,6 +8,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/route_extensions.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import '../../core/dependencies.dart'; @@ -22,6 +23,7 @@ class CollapsingListView extends StatelessWidget { VoidCallback? instructions; VoidCallback? requests; VoidCallback? sendEmail; + VoidCallback? doctorResponse; Widget? bottomChild; Widget? trailing; bool isClose; @@ -42,6 +44,7 @@ class CollapsingListView extends StatelessWidget { this.instructions, this.requests, this.sendEmail, + this.doctorResponse, this.isLeading = true, this.trailing, this.leadingCallback, @@ -62,60 +65,65 @@ class CollapsingListView extends StatelessWidget { controller: _controller, slivers: [ SliverAppBar( - automaticallyImplyLeading: isLeading, - pinned: true, - // toolbarHeight: isLeading ? 24.h : kToolbarHeight, - leadingWidth: isLeading ? null : double.infinity, - systemOverlayStyle: SystemUiOverlayStyle(statusBarBrightness: Brightness.light), - surfaceTintColor: Colors.transparent, - backgroundColor: AppColors.bgScaffoldColor, - bottom: isLeading - ? ScrollAnimatedTitle( - title: title, - showBack: true, - controller: _controller, - search: search, - report: report, - logout: logout, - history: history, - instructions: instructions, - requests: requests, - sendEmail: sendEmail, - bottomChild: bottomChild, - trailing: trailing, - ) - : null, - leading: isLeading - ? Transform.flip( + automaticallyImplyLeading: isLeading, + pinned: true, + toolbarHeight: 40.h, + leadingWidth: isLeading ? 40.w + 32.w : double.infinity, + systemOverlayStyle: SystemUiOverlayStyle(statusBarBrightness: Brightness.light), + surfaceTintColor: Colors.transparent, + backgroundColor: AppColors.bgScaffoldColor, + bottom: + // isLeading + // ? + ScrollAnimatedTitle( + title: title, + showBack: true, + controller: _controller, + search: search, + report: report, + logout: logout, + history: history, + instructions: instructions, + requests: requests, + sendEmail: sendEmail, doctorResponse: doctorResponse, + bottomChild: bottomChild, + trailing: trailing, + ), + // : null, + leading: Visibility( + visible: isLeading, + child: Container( + height: 32.h, + width: 32.w, + alignment: appState.isArabic() ? Alignment.centerRight : Alignment.centerLeft, + margin: EdgeInsets.fromLTRB(24.w, 0, 24.w, 0), + child: Transform.flip( flipX: appState.isArabic(), - child: IconButton( - icon: Utils.buildSvgWithAssets(icon: isClose ? AppAssets.closeBottomNav : AppAssets.arrow_back, width: 24.h, height: 24.h), - padding: EdgeInsets.only(left: 12), - onPressed: () { - if (leadingCallback != null) { - leadingCallback!(); - } else { - context.pop(); - } - }, - highlightColor: Colors.transparent, - ), - ) - : ScrollAnimatedTitle( - title: title, - showBack: false, - controller: _controller, - search: search, - report: report, - logout: logout, - history: history, - instructions: instructions, - requests: requests, - sendEmail: sendEmail, - bottomChild: bottomChild, - trailing: trailing, + child: Utils.buildSvgWithAssets(icon: isClose ? AppAssets.close_bottom_nav_trans : AppAssets.arrow_back_new, width: 24.h, height: 24.h), ), - ), + ).onPress(() { + if (leadingCallback != null) { + leadingCallback!(); + } else { + context.pop(); + } + }), + ) + // : ScrollAnimatedTitle( + // title: title, + // showBack: false, + // controller: _controller, + // search: search, + // report: report, + // logout: logout, + // history: history, + // instructions: instructions, + // requests: requests, + // sendEmail: sendEmail, + // bottomChild: bottomChild, + // trailing: trailing, + // ), + ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) => child, @@ -186,6 +194,7 @@ class ScrollAnimatedTitle extends StatefulWidget implements PreferredSizeWidget VoidCallback? instructions; VoidCallback? requests; VoidCallback? sendEmail; + VoidCallback? doctorResponse; Widget? bottomChild; Widget? trailing; @@ -201,12 +210,13 @@ class ScrollAnimatedTitle extends StatefulWidget implements PreferredSizeWidget this.instructions, this.requests, this.sendEmail, + this.doctorResponse, this.bottomChild, this.trailing, }); @override - Size get preferredSize => const Size.fromHeight(50); + Size get preferredSize => const Size.fromHeight(56.0); @override State createState() => _ScrollAnimatedTitleState(); @@ -250,11 +260,12 @@ class _ScrollAnimatedTitleState extends State { @override Widget build(BuildContext context) { - final isRtl = Directionality.of(context) == TextDirection.rtl; + final isRtl = Directionality.of(context) == TextDirection.RTL; return Container( - height: (widget.preferredSize.height - _fontSize / 2).h, + // height: (widget.preferredSize.height - _fontSize / 2).h, + height: 56.h, alignment: isRtl ? (widget.showBack ? Alignment.topRight : Alignment.centerRight) : (widget.showBack ? Alignment.topLeft : Alignment.centerLeft), - padding: EdgeInsets.fromLTRB(24, 0, 24, 0), + padding: EdgeInsets.fromLTRB(24.w, 0, 24.w, 0), child: Row( spacing: 4.h, children: [ @@ -263,18 +274,19 @@ class _ScrollAnimatedTitleState extends State { maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( - fontSize: _fontSize, + fontSize: _fontSize.f, fontWeight: FontWeight.bold, - letterSpacing: -1.0, + letterSpacing: -0.5, ), ).expanded, ...[ - if (widget.logout != null) actionButton(context, t, title: "Logout".needTranslation, icon: AppAssets.logout).onPress(widget.logout!), - if (widget.report != null) actionButton(context, t, title: "Feedback".needTranslation, icon: AppAssets.report_icon).onPress(widget.report!), - if (widget.history != null) actionButton(context, t, title: "History".needTranslation, icon: AppAssets.insurance_history_icon).onPress(widget.history!), - if (widget.instructions != null) actionButton(context, t, title: "Instructions".needTranslation, icon: AppAssets.requests).onPress(widget.instructions!), - if (widget.requests != null) actionButton(context, t, title: "Requests".needTranslation, icon: AppAssets.insurance_history_icon).onPress(widget.requests!), - if (widget.sendEmail != null) actionButton(context, t, title: "Send Email".needTranslation, icon: AppAssets.email).onPress(widget.sendEmail!), + if (widget.logout != null) actionButton(context, t, title: LocaleKeys.logout.tr(context: context), icon: AppAssets.logout).onPress(widget.logout!), + if (widget.report != null) actionButton(context, t, title: LocaleKeys.feedback.tr(context: context), icon: AppAssets.report_icon).onPress(widget.report!), + if (widget.history != null) actionButton(context, t, title: LocaleKeys.history.tr(context: context), icon: AppAssets.insurance_history_icon).onPress(widget.history!), + if (widget.instructions != null) actionButton(context, t, title: LocaleKeys.instructions.tr(context: context), icon: AppAssets.requests).onPress(widget.instructions!), + if (widget.requests != null) actionButton(context, t, title: LocaleKeys.requests.tr(context: context), icon: AppAssets.insurance_history_icon).onPress(widget.requests!), + if (widget.sendEmail != null) actionButton(context, t, title: LocaleKeys.sendEmail.tr(context: context), icon: AppAssets.email).onPress(widget.sendEmail!), + if (widget.doctorResponse != null) actionButton(context, t, title: LocaleKeys.doctorResponses.tr(context: context), icon: AppAssets.doctorResponseIcon).onPress(widget.doctorResponse!), if (widget.search != null) Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(widget.search!), if (widget.trailing != null) widget.trailing!, ] @@ -287,7 +299,7 @@ class _ScrollAnimatedTitleState extends State { return AnimatedSize( duration: Duration(milliseconds: 150), child: Container( - height: 36.h + (4.h * t), + height: 40.h, padding: EdgeInsets.all(8.w), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: AppColors.secondaryLightRedColor, @@ -299,7 +311,7 @@ class _ScrollAnimatedTitleState extends State { mainAxisSize: MainAxisSize.min, spacing: 8.h, children: [ - Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor), + Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w), if (t >= .5) Text( title, diff --git a/lib/widgets/appbar/collapsing_toolbar.dart b/lib/widgets/appbar/collapsing_toolbar.dart index 87cf15a..8bf1e4b 100644 --- a/lib/widgets/appbar/collapsing_toolbar.dart +++ b/lib/widgets/appbar/collapsing_toolbar.dart @@ -1,5 +1,6 @@ import 'dart:ui'; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; @@ -8,6 +9,7 @@ import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import '../../core/dependencies.dart'; @@ -140,11 +142,11 @@ class _CollapsingToolbarState extends State { color: AppColors.blackColor, letterSpacing: -0.5), ).expanded, - if (widget.logout != null) actionButton(context, t, title: "Logout".needTranslation, icon: AppAssets.logout).onPress(widget.logout!), - if (widget.report != null) actionButton(context, t, title: "Report".needTranslation, icon: AppAssets.report_icon).onPress(widget.report!), - if (widget.history != null) actionButton(context, t, title: "History".needTranslation, icon: AppAssets.insurance_history_icon).onPress(widget.history!), - if (widget.instructions != null) actionButton(context, t, title: "Instructions".needTranslation, icon: AppAssets.requests).onPress(widget.instructions!), - if (widget.requests != null) actionButton(context, t, title: "Requests".needTranslation, icon: AppAssets.insurance_history_icon).onPress(widget.requests!), + if (widget.logout != null) actionButton(context, t, title: LocaleKeys.logout.tr(context: context), icon: AppAssets.logout).onPress(widget.logout!), + if (widget.report != null) actionButton(context, t, title: LocaleKeys.report.tr(context: context), icon: AppAssets.report_icon).onPress(widget.report!), + if (widget.history != null) actionButton(context, t, title: LocaleKeys.history.tr(context: context), icon: AppAssets.insurance_history_icon).onPress(widget.history!), + if (widget.instructions != null) actionButton(context, t, title: LocaleKeys.instructions.tr(context: context), icon: AppAssets.requests).onPress(widget.instructions!), + if (widget.requests != null) actionButton(context, t, title: LocaleKeys.requests.tr(context: context), icon: AppAssets.insurance_history_icon).onPress(widget.requests!), if (widget.search != null) Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(widget.search!).paddingOnly(right: 24), if (widget.trailing != null) widget.trailing!, ], diff --git a/lib/widgets/bottom_navigation/bottom_navigation.dart b/lib/widgets/bottom_navigation/bottom_navigation.dart index 2da1d44..bbe8d81 100644 --- a/lib/widgets/bottom_navigation/bottom_navigation.dart +++ b/lib/widgets/bottom_navigation/bottom_navigation.dart @@ -6,6 +6,7 @@ import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -19,26 +20,28 @@ class BottomNavigation extends StatelessWidget { Widget build(BuildContext context) { AppState appState = getIt.get(); final items = [ - BottomNavItem(icon: AppAssets.homeBottom, label: LocaleKeys.home.tr(context: context)), + BottomNavItem(icon: AppAssets.homeBottom, fillIcon: AppAssets.homeBottomFill, label: LocaleKeys.home.tr(context: context)), appState.isAuthenticated - ? BottomNavItem(icon: AppAssets.myFilesBottom, label: LocaleKeys.medicalFile.tr(context: context)) - : BottomNavItem(icon: AppAssets.feedback, label: LocaleKeys.feedback.tr()), + ? BottomNavItem(icon: AppAssets.myFilesBottom, fillIcon: AppAssets.myFilesBottomFill, label: LocaleKeys.medicalFile.tr(context: context)) + : BottomNavItem(icon: AppAssets.feedback, fillIcon: AppAssets.feedbackFill, label: LocaleKeys.feedback.tr()), BottomNavItem( icon: AppAssets.bookAppoBottom, + fillIcon: AppAssets.bookAppoBottom, label: LocaleKeys.appointment.tr(context: context), - iconSize: 27, + iconSize: 32, isSpecial: true, ), appState.isAuthenticated // ? BottomNavItem(icon: AppAssets.toDoBottom, label: LocaleKeys.todoList.tr(context: context)) - ? BottomNavItem(icon: AppAssets.symptomCheckerBottomIcon, label: "Symptoms") - : BottomNavItem(icon: AppAssets.news, label: LocaleKeys.news.tr()), - BottomNavItem(icon: AppAssets.servicesBottom, label: LocaleKeys.services2.tr(context: context)), + ? BottomNavItem(icon: AppAssets.symptomCheckerBottomIcon, fillIcon: AppAssets.symptomCheckerBottomFillIcon, label: "Symptoms") + : BottomNavItem(icon: AppAssets.news, fillIcon: AppAssets.newsFill, label: LocaleKeys.news.tr()), + BottomNavItem(icon: AppAssets.servicesBottom, fillIcon: AppAssets.servicesBottomFill, label: LocaleKeys.services2.tr(context: context)), ]; return Container( decoration: _containerDecoration, padding: _containerPadding, + // height: 84.h, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: List.generate( @@ -55,28 +58,33 @@ class BottomNavigation extends StatelessWidget { return GestureDetector( onTap: () => onTap(index), behavior: HitTestBehavior.opaque, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Center( - child: Utils.buildSvgWithAssets( - icon: item.icon, + child: SizedBox( + height: 56.h, + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets( + icon: isSelected ? item.fillIcon : item.icon, height: item.iconSize.h, width: item.iconSize.w, // iconColor: isSelected ? Colors.black87 : Colors.black87, ), - ), - const SizedBox(height: 10), - item.label.toText11(weight: FontWeight.w500), - SizedBox(height: item.isSpecial ? 5 : 0) - ], + // const SizedBox(height: 10), + SizedBox(height: item.isSpecial ? 0 : 8.h), + item.label.toText11(weight: FontWeight.w500), + // SizedBox(height: item.isSpecial ? 5 : 0) + ], + ), ), - ); + ).expanded; } } class BottomNavItem { final String icon; + final String fillIcon; final String label; final double iconSize; final bool isSpecial; @@ -84,6 +92,7 @@ class BottomNavItem { const BottomNavItem({ required this.icon, + required this.fillIcon, required this.label, this.iconSize = 24, this.isSpecial = false, diff --git a/lib/widgets/buttons/custom_button.dart b/lib/widgets/buttons/custom_button.dart index 08d281f..8500ce8 100644 --- a/lib/widgets/buttons/custom_button.dart +++ b/lib/widgets/buttons/custom_button.dart @@ -75,25 +75,22 @@ class CustomButton extends StatelessWidget { children: [ if (icon != null) Padding( - padding: text.isNotEmpty ? EdgeInsets.only(right: 8.w, left: 8.w) : EdgeInsets.zero, + padding: text.isNotEmpty ? EdgeInsets.only(right: 4.w, left: 4.w) : EdgeInsets.zero, child: Utils.buildSvgWithAssets(icon: icon!, iconColor: iconColor, isDisabled: isDisabled, width: iconS, height: iconS), ), - Visibility( - visible: text.isNotEmpty, - child: Padding( - padding: EdgeInsets.only(top: 0), - child: Text( - text, - overflow: textOverflow, - style: context.dynamicTextStyle( - fontSize: fontS, - color: isDisabled ? AppColors.greyTextColor : textColor, - letterSpacing: 0, - fontWeight: fontWeight, - ), + if (text.isNotEmpty) + Text( + text, + overflow: textOverflow ?? TextOverflow.ellipsis, + maxLines: 1, + textAlign: TextAlign.center, + style: context.dynamicTextStyle( + fontSize: fontS, + color: isDisabled ? AppColors.greyTextColor : textColor, + letterSpacing: 0, + fontWeight: fontWeight, ), ), - ), ], ), )); diff --git a/lib/widgets/common_bottom_sheet.dart b/lib/widgets/common_bottom_sheet.dart index 6ff5cc5..fb51f28 100644 --- a/lib/widgets/common_bottom_sheet.dart +++ b/lib/widgets/common_bottom_sheet.dart @@ -1,5 +1,6 @@ import 'dart:io' show Platform; +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -7,14 +8,14 @@ import 'package:hmg_patient_app_new/core/utils/calender_utils_new.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_reminder_view.dart'; import 'package:hmg_patient_app_new/services/permission_service.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:permission_handler/permission_handler.dart'; - -class BottomSheetUtils{ - showReminderBottomSheet(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted, +class BottomSheetUtils { + showReminderBottomSheet(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted, {required Function() onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool isMultiAllowed = false}) async { if (Platform.isAndroid) { if (await PermissionService.isCalendarPermissionEnabled()) { @@ -40,13 +41,13 @@ class BottomSheetUtils{ Future _showReminderBottomSheet(BuildContext providedContext, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted, {required Function onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool? isMultiAllowed}) async { - showCommonBottomSheetWithoutHeight(providedContext, title: "Set the timer of reminder".needTranslation, child: PrescriptionReminderView( + showCommonBottomSheetWithoutHeight(providedContext, title: LocaleKeys.setTimerOfReminder.tr(context: providedContext), child: PrescriptionReminderView( setReminder: (int value) async { if (!isMultiAllowed!) { if (onMultiDateSuccess == null) { - CalenderUtilsNew calendarUtils = CalenderUtilsNew.instance; + CalenderUtilsNew calendarUtils = CalenderUtilsNew.instance; await calendarUtils.createOrUpdateEvent( - title: title ?? "You have appointment with Dr. ".needTranslation + doctorName, + title: title ?? LocaleKeys.youHaveAppointmentWithDr.tr(context: providedContext) + doctorName, description: description ?? "At " + appoDateFormatted + " " + appoTimeFormatted, scheduleDateTime: dateTime, eventId: eventId, @@ -60,6 +61,7 @@ class BottomSheetUtils{ ), callBackFunc: () {}, isFullScreen: false); } } + void showCommonBottomSheet(BuildContext context, {required Widget child, Function(String?)? callBackFunc, @@ -108,7 +110,7 @@ class ButtonSheetContent extends StatelessWidget { @override Widget build(BuildContext context) { return Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 20.h, @@ -127,9 +129,7 @@ class ButtonSheetContent extends StatelessWidget { // Close button isCloseButtonVisible && isFullScreen - ? Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ + ? Row(mainAxisAlignment: MainAxisAlignment.end, children: [ Padding( padding: EdgeInsets.symmetric( horizontal: 16, @@ -168,7 +168,7 @@ void showCommonBottomSheetWithoutHeight( Widget? titleWidget, bool useSafeArea = false, bool hasBottomPadding = true, - EdgeInsets? padding, + EdgeInsets? padding, Color backgroundColor = AppColors.bottomSheetBgColor, VoidCallback? onCloseClicked, }) { @@ -177,10 +177,8 @@ void showCommonBottomSheetWithoutHeight( duration: Duration(milliseconds: 500), reverseDuration: Duration(milliseconds: 300), ), - constraints: BoxConstraints( - - maxWidth: MediaQuery.sizeOf(context).width//MediaQuery.of(context).size.width, // Full width - ), + constraints: BoxConstraints(maxWidth: MediaQuery.sizeOf(context).width //MediaQuery.of(context).size.width, // Full width + ), context: context, isScrollControlled: true, showDragHandle: false, @@ -201,46 +199,48 @@ void showCommonBottomSheetWithoutHeight( physics: ClampingScrollPhysics(), child: isCloseButtonVisible ? Container( - padding: padding ?? const EdgeInsets.only( - left: 24, - top: 24, - right: 24, - bottom: 12, - ), - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.bottomSheetBgColor, - borderRadius: 24.h, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: padding != null? EdgeInsets.symmetric(horizontal: 24.w): EdgeInsets.zero, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + padding: padding ?? + const EdgeInsets.only( + left: 24, + top: 24, + right: 24, + bottom: 12, + ), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.bottomSheetBgColor, + borderRadius: 24.h, + ), + child: Column( + mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ - titleWidget ?? - Expanded( - child: title.toText20(weight: FontWeight.w600), - ), - if (isCloseButtonVisible) ...[ - Utils.buildSvgWithAssets( - icon: AppAssets.close_bottom_sheet_icon, - iconColor: Color(0xff2B353E), - ).onPress(() { - onCloseClicked?.call(); - Navigator.of(context).pop(); - }),], + Padding( + padding: padding != null ? EdgeInsets.symmetric(horizontal: 24.w) : EdgeInsets.zero, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + titleWidget ?? + Expanded( + child: title.toText20(weight: FontWeight.w600), + ), + if (isCloseButtonVisible) ...[ + Utils.buildSvgWithAssets( + icon: AppAssets.close_bottom_sheet_icon, + iconColor: Color(0xff2B353E), + ).onPress(() { + onCloseClicked?.call(); + Navigator.of(context).pop(); + }), + ], + ], + ), + ), + isCloseButtonVisible ? SizedBox(height: 16.h) : SizedBox.shrink(), + child, ], ), - ), - isCloseButtonVisible ? SizedBox(height: 16.h) : SizedBox.shrink(), - child, - ], - ), - ) + ) : child, ), ), diff --git a/lib/widgets/countdown_timer.dart b/lib/widgets/countdown_timer.dart index 165a833..1722ebf 100644 --- a/lib/widgets/countdown_timer.dart +++ b/lib/widgets/countdown_timer.dart @@ -1,6 +1,8 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; Widget buildTime(Duration duration, {bool isHomePage = false}) { String twoDigits(int n) => n.toString().padLeft(2, '0'); @@ -11,9 +13,9 @@ Widget buildTime(Duration duration, {bool isHomePage = false}) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - buildTimeColumn(hours, "Hours".needTranslation), - buildTimeColumn(minutes, "Mins".needTranslation), - buildTimeColumn(seconds, "Secs".needTranslation, isLast: true), + buildTimeColumn(hours, LocaleKeys.hours.tr()), + buildTimeColumn(minutes, LocaleKeys.mins.tr()), + buildTimeColumn(seconds, LocaleKeys.secs.tr(), isLast: true), ], ); } diff --git a/lib/widgets/date_range_selector/date_range_calender.dart b/lib/widgets/date_range_selector/date_range_calender.dart index debc069..89725f3 100644 --- a/lib/widgets/date_range_selector/date_range_calender.dart +++ b/lib/widgets/date_range_selector/date_range_calender.dart @@ -71,7 +71,7 @@ class _DateRangeSelectorState extends State { children: [ fromDateComponent(), Text( - LocaleKeys.to.tr(), + LocaleKeys.to.tr(context: context), style: TextStyle( color: AppColors.calenderTextColor, fontSize: 14.h, @@ -168,7 +168,7 @@ class _DateRangeSelectorState extends State { children: [ Expanded( child: CustomButton( - text: LocaleKeys.cancel.tr(), + text: LocaleKeys.cancel.tr(context: context), onPressed: () { _calendarController.selectedRange = null; _calendarController.selectedDate = null; @@ -192,7 +192,7 @@ class _DateRangeSelectorState extends State { ), Expanded( child: CustomButton( - text: LocaleKeys.search.tr(), + text: LocaleKeys.search.tr(context: context), onPressed: () { Navigator.of(context).pop(); widget.onRangeSelected(model.fromDate, model.toDate); @@ -216,7 +216,7 @@ class _DateRangeSelectorState extends State { fromDateComponent() { return Consumer( builder: (_, model, __) { - return displayDate(LocaleKeys.startDate.tr(), + return displayDate(LocaleKeys.startDate.tr(context: context), model.getDateString(model.fromDate), model.fromDate == null); }, ); @@ -225,7 +225,7 @@ class _DateRangeSelectorState extends State { toDateComponent() { return Consumer( builder: (_, model, __) { - return displayDate(LocaleKeys.endDate.tr(), + return displayDate(LocaleKeys.endDate.tr(context: context), model.getDateString(model.toDate), model.toDate == null); }, ); @@ -270,7 +270,7 @@ class _DateRangeSelectorState extends State { spacing: 8.h, children: [ AppCustomChipWidget( - labelText: "This Week".needTranslation, + labelText: LocaleKeys.thisWeek.tr(context: context), backgroundColor: model.currentlySelectedRange == Range.WEEKLY ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor, @@ -288,7 +288,7 @@ class _DateRangeSelectorState extends State { model.calculateDatesFromRange(); }), AppCustomChipWidget( - labelText: "Last Month".needTranslation, + labelText: LocaleKeys.lastMonth.tr(context: context), backgroundColor: model.currentlySelectedRange == Range.LAST_MONTH ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor, @@ -306,7 +306,7 @@ class _DateRangeSelectorState extends State { model.calculateDatesFromRange(); }), AppCustomChipWidget( - labelText: "Last 6 Months".needTranslation, + labelText: LocaleKeys.lastSixMonths.tr(context: context), backgroundColor: model.currentlySelectedRange == Range.LAST_6MONTH ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.whiteColor, diff --git a/lib/widgets/expandable_list_widget.dart b/lib/widgets/expandable_list_widget.dart index b948299..db4e398 100644 --- a/lib/widgets/expandable_list_widget.dart +++ b/lib/widgets/expandable_list_widget.dart @@ -282,9 +282,9 @@ class ExpandableListTheme { dividerColor: dividerColor ?? Colors.grey.shade300, defaultTrailingIcon: defaultTrailingIcon ?? Icon(Icons.keyboard_arrow_down, color: Colors.black, size: 24), - itemPadding: itemPadding ?? const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), - contentPadding: contentPadding ?? const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 16.0), - leadingSpacing: leadingSpacing ?? 12.0, + itemPadding: itemPadding ?? EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h), + contentPadding: contentPadding ?? EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16.h), + leadingSpacing: leadingSpacing ?? 12.w, ); } } diff --git a/lib/widgets/family_files/family_file_add_widget.dart b/lib/widgets/family_files/family_file_add_widget.dart index 4840ba7..abc529b 100644 --- a/lib/widgets/family_files/family_file_add_widget.dart +++ b/lib/widgets/family_files/family_file_add_widget.dart @@ -77,7 +77,7 @@ class FamilyFileAddWidget extends StatelessWidget { ), SizedBox(height: 20.h), CustomButton( - text: "Verify the member".needTranslation, + text: LocaleKeys.pleaseVerify.tr(context: context), onPressed: () { FocusScope.of(context).unfocus(); if (ValidationUtils.isValidatedIdAndPhoneWithCountryValidation( diff --git a/lib/widgets/graph/custom_graph.dart b/lib/widgets/graph/custom_graph.dart index 1f5d806..f114521 100644 --- a/lib/widgets/graph/custom_graph.dart +++ b/lib/widgets/graph/custom_graph.dart @@ -11,6 +11,7 @@ import 'package:hmg_patient_app_new/theme/colors.dart'; /// /// **Parameters:** /// - [dataPoints]: List of `DataPoint` objects to plot. +/// - [secondaryDataPoints]: Optional list for a second line (e.g., diastolic in blood pressure). /// - [leftLabelFormatter]: Function to build left axis labels. /// - [bottomLabelFormatter]: Function to build bottom axis labels. /// - [width]: Optional width of the chart. @@ -18,6 +19,7 @@ import 'package:hmg_patient_app_new/theme/colors.dart'; /// - [maxY], [maxX], [minX]: Axis bounds. /// - [spotColor]: Color of the touched spot marker. /// - [graphColor]: Color of the line. +/// - [secondaryGraphColor]: Color of the secondary line. /// - [graphShadowColor]: Color of the area below the line. /// - [graphGridColor]: Color of the grid lines. /// - [bottomLabelColor]: Color of bottom axis labels. @@ -43,6 +45,7 @@ import 'package:hmg_patient_app_new/theme/colors.dart'; /// ) class CustomGraph extends StatelessWidget { final List dataPoints; + final List? secondaryDataPoints; // For dual-line graphs (e.g., blood pressure) final double? width; final double height; final double? maxY; @@ -50,6 +53,7 @@ class CustomGraph extends StatelessWidget { final double? minX; final Color spotColor; final Color graphColor; + final Color? secondaryGraphColor; // Color for secondary line final Color graphShadowColor; final Color graphGridColor; final Color bottomLabelColor; @@ -79,6 +83,7 @@ class CustomGraph extends StatelessWidget { const CustomGraph( {super.key, required this.dataPoints, + this.secondaryDataPoints, required this.leftLabelFormatter, this.width, required this.scrollDirection, @@ -89,6 +94,7 @@ class CustomGraph extends StatelessWidget { this.isFullScreeGraph = false, this.spotColor = AppColors.bgGreenColor, this.graphColor = AppColors.bgGreenColor, + this.secondaryGraphColor, this.graphShadowColor = AppColors.graphGridColor, this.graphGridColor = AppColors.graphGridColor, this.bottomLabelColor = AppColors.textColor, @@ -124,9 +130,23 @@ class CustomGraph extends StatelessWidget { minX: minX, lineTouchData: LineTouchData( getTouchLineEnd: (_, __) => 0, + handleBuiltInTouches: true, + touchCallback: (FlTouchEvent event, LineTouchResponse? touchResponse) { + // Let fl_chart handle the touch + }, getTouchedSpotIndicator: (barData, indicators) { - // Only show custom marker for touched spot + // Show custom marker for touched spot with correct color per line return indicators.map((int index) { + // Determine which line is being touched based on barData + Color dotColor = spotColor; + if (secondaryDataPoints != null && barData.spots.length > 0) { + // Check if this is the secondary line by comparing the first spot's color + final gradient = barData.gradient; + if (gradient != null && gradient.colors.isNotEmpty) { + dotColor = gradient.colors.first; + } + } + return TouchedSpotIndicatorData( FlLine(color: Colors.transparent), FlDotData( @@ -134,7 +154,7 @@ class CustomGraph extends StatelessWidget { getDotPainter: (spot, percent, barData, idx) { return FlDotCirclePainter( radius: 8, - color: spotColor, + color: dotColor, strokeWidth: 2, strokeColor: Colors.white, ); @@ -148,17 +168,18 @@ class CustomGraph extends StatelessWidget { getTooltipColor: (_) => Colors.white, getTooltipItems: (touchedSpots) { if (touchedSpots.isEmpty) return []; - // Only show tooltip for the first touched spot, hide others + // Show tooltip for each touched line return touchedSpots.map((spot) { - if (spot == touchedSpots.first) { - final dataPoint = dataPoints[spot.x.toInt()]; + // Determine which dataset this spot belongs to + final isSecondary = secondaryDataPoints != null && spot.barIndex == 1; + final dataPoint = isSecondary + ? secondaryDataPoints![spot.x.toInt()] + : dataPoints[spot.x.toInt()]; - return LineTooltipItem( - '${dataPoint.actualValue} ${dataPoint.unitOfMeasurement ?? ""} - ${dataPoint.displayTime}', - TextStyle(color: Colors.black, fontSize: 12.f, fontWeight: FontWeight.w500), - ); - } - return null; // hides the rest + return LineTooltipItem( + '${dataPoint.actualValue} ${dataPoint.unitOfMeasurement ?? ""} - ${dataPoint.displayTime}', + TextStyle(color: Colors.black, fontSize: 12.f, fontWeight: FontWeight.w500), + ); }).toList(); }, ), @@ -225,7 +246,7 @@ class CustomGraph extends StatelessWidget { return FlSpot(entry.key.toDouble(), value); }).toList(); - var data = [ + var data = [ LineChartBarData( spots: allSpots, isCurved: true, @@ -254,6 +275,31 @@ class CustomGraph extends StatelessWidget { ) ]; + // Add secondary line if provided (for dual-line graphs like blood pressure) + if (secondaryDataPoints != null && secondaryDataPoints!.isNotEmpty) { + final List secondarySpots = secondaryDataPoints!.asMap().entries.map((entry) { + double value = (makeGraphBasedOnActualValue) ? double.tryParse(entry.value.actualValue) ?? 0.0 : entry.value.value; + return FlSpot(entry.key.toDouble(), value); + }).toList(); + + data.add( + LineChartBarData( + spots: secondarySpots, + isCurved: true, + isStrokeCapRound: true, + isStrokeJoinRound: true, + barWidth: 2, + gradient: LinearGradient( + colors: [secondaryGraphColor ?? AppColors.blueColor, secondaryGraphColor ?? AppColors.blueColor], + begin: Alignment.centerLeft, + end: Alignment.centerRight, + ), + dotData: FlDotData(show: showLinePoints), + belowBarData: BarAreaData(show: false), + ), + ); + } + return data; } } diff --git a/lib/widgets/input_widget.dart b/lib/widgets/input_widget.dart index 94ed9f8..cf1b132 100644 --- a/lib/widgets/input_widget.dart +++ b/lib/widgets/input_widget.dart @@ -3,17 +3,14 @@ import 'package:hijri_gregorian_calendar/hijri_gregorian_calendar.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/dropdown/country_dropdown_widget.dart'; - -import '../core/dependencies.dart'; - -// TODO: Import AppColors if bgRedColor is defined there -// import 'package:hmg_patient_app_new/core/ui_utils/app_colors.dart'; +import 'package:hmg_patient_app_new/widgets/time_picker_widget.dart'; class TextInputWidget extends StatelessWidget { final String labelText; @@ -49,6 +46,7 @@ class TextInputWidget extends StatelessWidget { final int maxLines; final Color? hintColor; final bool? isHideSwitcher; + final bool? isArrowTrailing; // final List countryList; // final Function(Country)? onCountryChange; @@ -87,6 +85,7 @@ class TextInputWidget extends StatelessWidget { this.minLines = 3, this.maxLines = 6, this.isHideSwitcher, + this.isArrowTrailing, // this.countryList = const [], // this.onCountryChange, }); @@ -126,7 +125,7 @@ class TextInputWidget extends StatelessWidget { children: [ Container( padding: padding, - height: isMultiline ? null : 64.h, + // height: isMultiline ? null : 64.h, alignment: Alignment.center, decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: Colors.white, @@ -154,10 +153,18 @@ class TextInputWidget extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildLabelText(labelColor).paddingOnly(right: (appState.getLanguageCode() == "ar" ? 10 : 0)), + _buildLabelText(labelColor).paddingOnly( + right: (appState.getLanguageCode() == "ar" ? 10 : 0), + left: (appState.getLanguageCode() == "en" ? 10 : 0), + ), Row( children: [ - Expanded(child: _buildTextField(context)), + Expanded( + child: _buildTextField(context).paddingOnly( + right: (appState.getLanguageCode() == "ar" ? 10 : 0), + left: (appState.getLanguageCode() == "en" ? 10 : 0), + ), + ) ], ), ], @@ -167,7 +174,8 @@ class TextInputWidget extends StatelessWidget { ], ), ), - if (selectionType == SelectionTypeEnum.calendar) _buildTrailingIcon(context), + if (selectionType == SelectionTypeEnum.calendar) _buildTrailingIcon(context, isArrowTrailing: isArrowTrailing ?? false), + if (selectionType == SelectionTypeEnum.time) _buildTimePickerIcon(context, isArrowTrailing: isArrowTrailing ?? false), if (selectionType == SelectionTypeEnum.search) _buildTrailingIconForSearch(context), ], ), @@ -191,7 +199,7 @@ class TextInputWidget extends StatelessWidget { return Container( height: 40.h, width: 40.h, - margin: EdgeInsets.only(right: 10.h), + // margin: EdgeInsets.symmetric(horizontal: 10.w), padding: EdgeInsets.all(8.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration( borderRadius: 12.r, @@ -200,11 +208,11 @@ class TextInputWidget extends StatelessWidget { child: Utils.buildSvgWithAssets(icon: leadingIcon!)); } - Widget _buildTrailingIcon(BuildContext context) { + Widget _buildTrailingIcon(BuildContext context, {bool isArrowTrailing = false}) { final AppState appState = getIt.get(); return Container( height: 40.h, - width: 40.h, + width: 40.w, margin: EdgeInsets.zero, padding: EdgeInsets.all(8.h), decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.whiteColor), @@ -233,7 +241,47 @@ class TextInputWidget extends StatelessWidget { onChange!(picked.toString()); } }, - child: Utils.buildSvgWithAssets(icon: AppAssets.calendar), + child: Utils.buildSvgWithAssets(icon: isArrowTrailing ? AppAssets.arrow_down : AppAssets.calendar), + ), + ); + } + + Widget _buildTimePickerIcon(BuildContext context, {bool isArrowTrailing = false}) { + return Container( + height: 40.h, + width: 40.h, + margin: EdgeInsets.zero, + padding: EdgeInsets.all(8.h), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + borderRadius: 12.r, + color: AppColors.whiteColor, + ), + child: GestureDetector( + onTap: () async { + // Parse existing time if available + TimeOfDay? initialTime; + if (controller?.text.isNotEmpty ?? false) { + initialTime = TimePickerWidget.parseTime(controller!.text); + } + + final picked = await TimePickerWidget.show( + context, + initialTime: initialTime, + use24HourFormat: false, // You can make this configurable if needed + onTimeSelected: (time) { + if (onChange != null) { + final formattedTime = TimePickerWidget.formatTime(time); + onChange!(formattedTime); + } + }, + ); + + // Update controller if time was picked + if (picked != null && controller != null) { + controller!.text = TimePickerWidget.formatTime(picked); + } + }, + child: Utils.buildSvgWithAssets(icon: isArrowTrailing ? AppAssets.arrow_down : AppAssets.alarm_clock_icon), ), ); } diff --git a/lib/widgets/map/location_map_widget.dart b/lib/widgets/map/location_map_widget.dart index c0eb431..2a1ea65 100644 --- a/lib/widgets/map/location_map_widget.dart +++ b/lib/widgets/map/location_map_widget.dart @@ -1,9 +1,11 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; import 'package:maps_launcher/maps_launcher.dart'; @@ -154,7 +156,7 @@ class LocationMapWidget extends StatelessWidget { child: SizedBox( width: MediaQuery.of(context).size.width * 0.785, child: CustomButton( - text: "Get Directions".needTranslation, + text: LocaleKeys.getDirections.tr(context: context), onPressed: onDirectionsTap ?? _defaultLaunchDirections, backgroundColor: AppColors.textColor.withValues(alpha: 0.8), borderColor: AppColors.textColor.withValues(alpha: 0.01), diff --git a/lib/widgets/map/map_utility_screen.dart b/lib/widgets/map/map_utility_screen.dart index 19823da..cb3eb8e 100644 --- a/lib/widgets/map/map_utility_screen.dart +++ b/lib/widgets/map/map_utility_screen.dart @@ -1,3 +1,4 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/app_assets.dart'; import 'package:hmg_patient_app_new/core/app_export.dart'; @@ -5,6 +6,7 @@ import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; import 'package:hmg_patient_app_new/features/location/location_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/emergency_services/widgets/location_input_bottom_sheet.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; @@ -126,14 +128,14 @@ class MapUtilityScreen extends StatelessWidget { weight: FontWeight.w600, color: AppColors.textColor, ), - subTitleString.needTranslation.toText12( + subTitleString.toText12( fontWeight: FontWeight.w500, color: AppColors.greyTextColor, ) ], ), CustomButton( - text: confirmButtonString.needTranslation, + text: confirmButtonString, onPressed: () { if (onSubmitted != null) { onSubmitted!(); @@ -172,8 +174,8 @@ class MapUtilityScreen extends StatelessWidget { return SizedBox( width: MediaQuery.sizeOf(context).width, child: TextInputWidget( - labelText: "Enter Pickup Location Manually".needTranslation, - hintText: "Enter Pickup Location".needTranslation, + labelText: LocaleKeys.enterPickupLocationManually.tr(context: context), + hintText: LocaleKeys.enterPickupLocation.tr(context: context), controller: TextEditingController( text: vm.geocodeResponse?.results.first.formattedAddress ?? vm.selectedPrediction?.description, ), @@ -203,7 +205,7 @@ class MapUtilityScreen extends StatelessWidget { openLocationInputBottomSheet(BuildContext context) { context.read().flushSearchPredictions(); showCommonBottomSheetWithoutHeight( - title: "".needTranslation, + title: "", context, child: SizedBox( height: MediaQuery.sizeOf(context).height * .8, diff --git a/lib/widgets/medication_reminder/reminder_timer_dialog.dart b/lib/widgets/medication_reminder/reminder_timer_dialog.dart new file mode 100644 index 0000000..62dbd96 --- /dev/null +++ b/lib/widgets/medication_reminder/reminder_timer_dialog.dart @@ -0,0 +1,155 @@ +// import 'package:easy_localization/easy_localization.dart'; +// import 'package:flutter/material.dart'; +// import 'package:hmg_patient_app_new/extensions/widget_extensions.dart'; +// +// import '../../generated/locale_keys.g.dart'; +// import '../../theme/colors.dart'; +// +// class ReminderTimerDialog extends StatefulWidget { +// final Function()? onSetReminderPress; +// final String message; +// +// const ReminderTimerDialog(this.onSetReminderPress, this.message, {super.key}); +// +// +// @override +// State createState() => _ReminderTimerDialogState(); +// } +// +// class _ReminderTimerDialogState extends State { +// final List options = ["Morning", "Afternoon", "Evening", "Midnight"]; +// final List selectedTimes = ["Morning"]; // Default selection +// +// +// @override +// Widget build(BuildContext context) { +// return // +// Column( +// children: [ +// Container( +// decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24, +// hasShadow: true,), +// child: Column( +// mainAxisSize: MainAxisSize.min, +// crossAxisAlignment: CrossAxisAlignment.start, +// // Checkboxes list +// children: options.map((time) => buildCircleCheckbox(time)).toList(), +// ).paddingAll(16), +// ), +// const SizedBox(height: 25), +// // Buttons Row +// Row( +// children: [ +// Expanded( +// child: ElevatedButton.icon( +// onPressed: () => Navigator.pop(context), +// icon: const Icon(Icons.close, color: AppColors.errorColor), +// label: Text( +// LocaleKeys.cancel.tr(), +// style: TextStyle( +// color: AppColors.errorColor, +// fontWeight: FontWeight.w500, +// fontSize: 14 +// ), +// ), +// style: ElevatedButton.styleFrom( +// backgroundColor: AppColors.secondaryLightRedColor, +// elevation: 0, +// padding: const EdgeInsets.symmetric(vertical: 14), +// shape: RoundedRectangleBorder( +// borderRadius: BorderRadius.circular(12), +// ), +// ), +// ), +// ), +// const SizedBox(width: 12), +// Expanded( +// child: ElevatedButton.icon( +// onPressed: () { +// Navigator.pop(context, selectedTimes); +// }, +// icon: const Icon(Icons.notifications_rounded), +// label: Text( +// LocaleKeys.setReminder.tr(), +// style: TextStyle( +// fontWeight: FontWeight.w500, +// fontSize: 14 +// ), +// ), +// style: ElevatedButton.styleFrom( +// backgroundColor: AppColors.successColor, +// foregroundColor: AppColors.whiteColor, +// elevation: 0, +// padding: const EdgeInsets.symmetric(vertical: 14), +// shape: RoundedRectangleBorder( +// borderRadius: BorderRadius.circular(12), +// ), +// ), +// ), +// ), +// ], +// ), +// const SizedBox(height: 30), +// ], +// ); +// } +// +// Widget buildCircleCheckbox(String label) { +// final bool isSelected = selectedTimes.contains(label); +// return InkWell( +// onTap: () { +// setState(() { +// if (isSelected) { +// selectedTimes.remove(label); +// } else { +// selectedTimes.add(label); +// } +// }); +// }, +// borderRadius: BorderRadius.circular(25), +// child: Padding( +// padding: const EdgeInsets.symmetric(vertical: 8.0), +// child: Row( +// children: [ +// // Custom circle checkbox +// Container( +// width: 15, +// height: 15, +// decoration: BoxDecoration( +// shape: BoxShape.circle, +// border: Border.all( +// color: isSelected ? AppColors.spacerLineColor: AppColors.spacerLineColor, +// width: 1, +// ), +// color: isSelected ? AppColors.errorColor: AppColors.transparent, +// ), +// ), +// const SizedBox(width: 12), +// // Label text +// Text( +// label, +// style: const TextStyle(fontSize: 16, color: Colors.black87), +// ), +// ], +// ), +// ), +// ); +// } +// +// +// void showCircleCheckboxDialog(BuildContext context) async { +// final selected = await showDialog>( +// context: context, +// builder: (context) => const ReminderTimerDialog(), +// ); +// +// if (selected != null && selected.isNotEmpty) { +// ScaffoldMessenger.of(context).showSnackBar( +// SnackBar(content: Text('Reminders set for: ${selected.join(', ')}')), +// ); +// } +// } +// } +// +// +// diff --git a/lib/widgets/time_picker_widget.dart b/lib/widgets/time_picker_widget.dart new file mode 100644 index 0000000..bc996de --- /dev/null +++ b/lib/widgets/time_picker_widget.dart @@ -0,0 +1,350 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; + +/// A reusable time picker widget that can be used anywhere in the app +/// Shows a bottom sheet with iOS-style time picker +class TimePickerWidget { + /// Shows a time picker bottom sheet + /// + /// [context] - BuildContext for showing the bottom sheet + /// [initialTime] - Initial time to display (defaults to current time) + /// [use24HourFormat] - Whether to use 24-hour format (defaults to false) + /// [onTimeSelected] - Callback when time is selected + /// + /// Returns the selected TimeOfDay or null if cancelled + static Future show( + BuildContext context, { + TimeOfDay? initialTime, + bool use24HourFormat = false, + bool displaySelectedTime = false, + Function(TimeOfDay)? onTimeSelected, + }) async { + final selectedTime = initialTime ?? TimeOfDay.now(); + + final result = await showModalBottomSheet( + context: context, + backgroundColor: Colors.transparent, + isScrollControlled: true, + builder: (BuildContext context) { + return _TimePickerBottomSheet( + initialTime: selectedTime, + use24HourFormat: use24HourFormat, + displaySelectedTime: displaySelectedTime, + onTimeChanged: (time) { + // Time is being changed in real-time + }, + ); + }, + ); + + if (result != null && onTimeSelected != null) { + onTimeSelected(result); + } + + return result; + } + + /// Formats TimeOfDay to string (HH:mm format) + static String formatTime(TimeOfDay time, {bool use24HourFormat = false}) { + if (use24HourFormat) { + return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}'; + } else { + final hour = time.hourOfPeriod == 0 ? 12 : time.hourOfPeriod; + final period = time.period == DayPeriod.am ? 'AM' : 'PM'; + return '${hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')} $period'; + } + } + + /// Parses time string to TimeOfDay + static TimeOfDay? parseTime(String timeString) { + try { + final parts = timeString.split(':'); + if (parts.length == 2) { + final hour = int.parse(parts[0]); + final minute = int.parse(parts[1].split(' ')[0]); + return TimeOfDay(hour: hour, minute: minute); + } + } catch (e) { + return null; + } + return null; + } +} + +class _TimePickerBottomSheet extends StatefulWidget { + final TimeOfDay initialTime; + final bool use24HourFormat; + final bool displaySelectedTime; + final Function(TimeOfDay) onTimeChanged; + + const _TimePickerBottomSheet({ + required this.initialTime, + required this.use24HourFormat, + required this.displaySelectedTime, + required this.onTimeChanged, + }); + + @override + State<_TimePickerBottomSheet> createState() => _TimePickerBottomSheetState(); +} + +class _TimePickerBottomSheetState extends State<_TimePickerBottomSheet> { + late int selectedHour; + late int selectedMinute; + late DayPeriod selectedPeriod; + + @override + void initState() { + super.initState(); + selectedHour = widget.use24HourFormat ? widget.initialTime.hour : widget.initialTime.hourOfPeriod; + if (selectedHour == 0 && !widget.use24HourFormat) selectedHour = 12; + selectedMinute = widget.initialTime.minute; + selectedPeriod = widget.initialTime.period; + } + + TimeOfDay _getCurrentTime() { + if (widget.use24HourFormat) { + return TimeOfDay(hour: selectedHour, minute: selectedMinute); + } else { + int hour = selectedHour; + if (selectedPeriod == DayPeriod.pm && hour != 12) { + hour += 12; + } else if (selectedPeriod == DayPeriod.am && hour == 12) { + hour = 0; + } + return TimeOfDay(hour: hour, minute: selectedMinute); + } + } + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: AppColors.whiteColor, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(20.r), + topRight: Radius.circular(20.r), + ), + ), + child: SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Header + Container( + padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h), + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: AppColors.dividerColor, + width: 1, + ), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + LocaleKeys.selectTime.tr(context: context).toText18( + weight: FontWeight.w600, + color: AppColors.textColor, + ), + GestureDetector( + onTap: () => Navigator.pop(context), + child: Utils.buildSvgWithAssets( + icon: AppAssets.cancel, + width: 24.h, + height: 24.h, + iconColor: AppColors.textColor, + ), + ), + ], + ), + ), + + // Time Picker + SizedBox( + height: 250.h, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // Hour Picker + Expanded( + child: CupertinoPicker( + scrollController: FixedExtentScrollController( + initialItem: widget.use24HourFormat ? selectedHour : (selectedHour - 1), + ), + itemExtent: 50.h, + onSelectedItemChanged: (index) { + setState(() { + if (widget.use24HourFormat) { + selectedHour = index; + } else { + selectedHour = index + 1; + } + widget.onTimeChanged(_getCurrentTime()); + }); + }, + children: List.generate( + widget.use24HourFormat ? 24 : 12, + (index) { + final hour = widget.use24HourFormat ? index : index + 1; + return Center( + child: Text( + hour.toString().padLeft(2, '0'), + style: TextStyle( + fontSize: 24.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ), + ); + }, + ), + ), + ), + + // Separator + Text( + ':', + style: TextStyle( + fontSize: 24.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ), + + // Minute Picker + Expanded( + child: CupertinoPicker( + scrollController: FixedExtentScrollController( + initialItem: selectedMinute, + ), + itemExtent: 50.h, + onSelectedItemChanged: (index) { + setState(() { + selectedMinute = index; + widget.onTimeChanged(_getCurrentTime()); + }); + }, + children: List.generate( + 60, + (index) => Center( + child: Text( + index.toString().padLeft(2, '0'), + style: TextStyle( + fontSize: 24.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ), + ), + ), + ), + ), + + // AM/PM Picker (only for 12-hour format) + if (!widget.use24HourFormat) + Expanded( + child: CupertinoPicker( + scrollController: FixedExtentScrollController( + initialItem: selectedPeriod == DayPeriod.am ? 0 : 1, + ), + itemExtent: 50.h, + onSelectedItemChanged: (index) { + setState(() { + selectedPeriod = index == 0 ? DayPeriod.am : DayPeriod.pm; + widget.onTimeChanged(_getCurrentTime()); + }); + }, + children: [ + Center( + child: Text( + 'AM', + style: TextStyle( + fontSize: 24.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ), + ), + Center( + child: Text( + 'PM', + style: TextStyle( + fontSize: 24.f, + fontWeight: FontWeight.w500, + color: AppColors.textColor, + ), + ), + ), + ], + ), + ), + ], + ), + ), + + if (widget.displaySelectedTime) + // Current Time Display + Container( + margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h), + padding: EdgeInsets.symmetric(vertical: 12.h), + decoration: BoxDecoration( + color: AppColors.lightGrayBGColor, + borderRadius: BorderRadius.circular(12.r), + ), + child: Center( + child: TimePickerWidget.formatTime( + _getCurrentTime(), + use24HourFormat: widget.use24HourFormat, + ).toText20( + weight: FontWeight.w600, + color: AppColors.textColor, + ), + ), + ), + + // Action Buttons + Padding( + padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h), + child: Row( + children: [ + Expanded( + child: CustomButton( + height: 56.h, + text: LocaleKeys.cancel.tr(context: context), + onPressed: () => Navigator.pop(context), + textColor: AppColors.textColor, + backgroundColor: AppColors.greyColor, + borderColor: AppColors.greyColor, + ), + ), + SizedBox(width: 12.w), + Expanded( + child: CustomButton( + height: 56.h, + text: LocaleKeys.confirm.tr(context: context), + onPressed: () { + Navigator.pop(context, _getCurrentTime()); + }, + textColor: AppColors.whiteColor, + backgroundColor: AppColors.primaryRedColor, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/time_picker_widget_usage_example.dart b/lib/widgets/time_picker_widget_usage_example.dart new file mode 100644 index 0000000..9ff6c35 --- /dev/null +++ b/lib/widgets/time_picker_widget_usage_example.dart @@ -0,0 +1,165 @@ +// Example usage of TimePickerWidget +// +// This file demonstrates how to use the TimePickerWidget in your Flutter app. +// The TimePickerWidget is a reusable component that shows a bottom sheet with +// an iOS-style time picker. + +// ============================================================================ +// EXAMPLE 1: Using with TextInputWidget +// ============================================================================ +/* +TextInputWidget( + labelText: "Appointment Time", + hintText: "Select time", + controller: timeController, + selectionType: SelectionTypeEnum.time, + isReadOnly: true, + onChange: (value) { + print("Selected time: $value"); + }, +) +*/ + +// ============================================================================ +// EXAMPLE 2: Direct usage with custom button +// ============================================================================ +/* +ElevatedButton( + onPressed: () async { + final selectedTime = await TimePickerWidget.show( + context, + initialTime: TimeOfDay.now(), + use24HourFormat: false, + onTimeSelected: (time) { + print("Time selected: ${TimePickerWidget.formatTime(time)}"); + }, + ); + + if (selectedTime != null) { + print("Final time: ${TimePickerWidget.formatTime(selectedTime)}"); + } + }, + child: Text("Pick Time"), +) +*/ + +// ============================================================================ +// EXAMPLE 3: Using with 24-hour format +// ============================================================================ +/* +TextInputWidget( + labelText: "Meeting Time", + hintText: "Select time (24h)", + controller: timeController, + selectionType: SelectionTypeEnum.time, + isReadOnly: true, + onChange: (value) { + // The value will be formatted as "14:30" for 2:30 PM in 24h format + print("Selected time (24h): $value"); + }, +) + +// Or programmatically: +final time = await TimePickerWidget.show( + context, + use24HourFormat: true, // Enable 24-hour format +); +*/ + +// ============================================================================ +// EXAMPLE 4: Parsing and formatting times +// ============================================================================ +/* +// Parse time string to TimeOfDay +String timeString = "02:30 PM"; +TimeOfDay? parsedTime = TimePickerWidget.parseTime(timeString); + +// Format TimeOfDay to string +TimeOfDay time = TimeOfDay(hour: 14, minute: 30); +String formatted12h = TimePickerWidget.formatTime(time); // "02:30 PM" +String formatted24h = TimePickerWidget.formatTime(time, use24HourFormat: true); // "14:30" +*/ + +// ============================================================================ +// EXAMPLE 5: Complete form example with date and time +// ============================================================================ +/* +class AppointmentForm extends StatefulWidget { + @override + _AppointmentFormState createState() => _AppointmentFormState(); +} + +class _AppointmentFormState extends State { + final TextEditingController dateController = TextEditingController(); + final TextEditingController timeController = TextEditingController(); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + // Date picker + TextInputWidget( + labelText: "Appointment Date", + hintText: "Select date", + controller: dateController, + selectionType: SelectionTypeEnum.calendar, + isReadOnly: true, + onChange: (value) { + print("Date selected: $value"); + }, + ), + + SizedBox(height: 16), + + // Time picker + TextInputWidget( + labelText: "Appointment Time", + hintText: "Select time", + controller: timeController, + selectionType: SelectionTypeEnum.time, + isReadOnly: true, + onChange: (value) { + print("Time selected: $value"); + }, + ), + ], + ); + } +} +*/ + +// ============================================================================ +// Features: +// ============================================================================ +// ✅ iOS-style cupertino picker (works on both iOS and Android) +// ✅ Support for 12-hour format (with AM/PM) +// ✅ Support for 24-hour format +// ✅ Beautiful bottom sheet UI matching app design +// ✅ Real-time preview of selected time +// ✅ Confirm/Cancel buttons +// ✅ Easy integration with TextInputWidget +// ✅ Parse and format time utilities +// ✅ Fully customizable and reusable + +// ============================================================================ +// API Reference: +// ============================================================================ +// TimePickerWidget.show() - Shows the time picker bottom sheet +// Parameters: +// - context: BuildContext (required) +// - initialTime: TimeOfDay? (optional, defaults to current time) +// - use24HourFormat: bool (optional, defaults to false) +// - onTimeSelected: Function(TimeOfDay)? (optional callback) +// Returns: Future +// +// TimePickerWidget.formatTime() - Formats TimeOfDay to string +// Parameters: +// - time: TimeOfDay (required) +// - use24HourFormat: bool (optional, defaults to false) +// Returns: String (e.g., "02:30 PM" or "14:30") +// +// TimePickerWidget.parseTime() - Parses time string to TimeOfDay +// Parameters: +// - timeString: String (required, e.g., "02:30 PM") +// Returns: TimeOfDay? + diff --git a/pubspec.yaml b/pubspec.yaml index 64f160b..d472bd5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -43,7 +43,7 @@ dependencies: lottie: ^3.3.1 flutter_ios_voip_kit_karmm: ^0.8.0 image_picker: ^1.2.0 - file_picker: ^10.3.2 + file_picker: 10.3.8 local_auth: ^2.3.0 share_plus: ^11.1.0 device_calendar_plus: ^0.3.1 @@ -61,7 +61,7 @@ dependencies: geolocator: ^14.0.2 dropdown_search: ^6.0.2 google_maps_flutter: ^2.13.1 -# flutter_zoom_videosdk: 2.1.10 + flutter_zoom_videosdk: 2.1.10 dart_jsonwebtoken: ^3.2.0 dartz: ^0.10.1 equatable: ^2.0.7 @@ -77,12 +77,13 @@ dependencies: amazon_payfort: ^1.1.4 network_info_plus: ^6.1.4 flutter_nfc_kit: ^3.6.0 -# barcode_scan2: ^4.5.1 + barcode_scan2: ^4.6.0 keyboard_actions: ^4.2.0 path_provider: ^2.0.8 open_filex: ^4.7.0 flutter_swiper_view: ^1.1.8 flutter_callkit_incoming: ^3.0.0 +# device_preview: ^1.3.1 location: ^8.0.1 gms_check: ^1.0.4 @@ -116,6 +117,7 @@ flutter: - assets/images/png/body_parts/female/ - assets/images/svg/ - assets/images/png/ + - assets/images/clinicIcons/ - assets/images/png/zoom/ - assets/images/png/smartwatches/ - assets/animations/