diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index ab7b2ca..9c1827a 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -69,4 +69,7 @@ # Penguin classes -keep class com.peng.pennavmap.models.** { *; } --keep class com.peng.pennavmap.db.** { *; } \ No newline at end of file +-keep class com.peng.pennavmap.db.** { *; } + +-keep class com.hiennv.flutter_callkit_incoming.** { *; } +-keepattributes Signature, Annotation, InnerClasses, EnclosingMethod \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6a1c47e..4f7ef74 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -30,9 +30,6 @@ - @@ -91,6 +88,12 @@ + + + + + + @@ -115,6 +118,7 @@ function configurationCacheProblems() { return ( // begin-report-data -{"diagnostics":[{"locations":[{"pluginId":"dev.flutter.flutter-gradle-plugin"}],"problem":[{"text":"The CopyProcessingSpec.setFileMode(Integer) method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The CopyProcessingSpec.setFileMode(Integer) method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#unix_file_permissions_deprecated","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-copyprocessingspec-setfilemode-integer-method-has-been-deprecated","displayName":"The CopyProcessingSpec.setFileMode(Integer) method has been deprecated."}],"solutions":[[{"text":"Please use the filePermissions(Action) method instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/audio_session-0.1.25/android/build.gradle'","line":2},{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/audio_session-0.1.25/android/build.gradle'","line":2}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('checkAllWarnings = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('warningsAsErrors = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/connectivity_plus-6.1.5/android/build.gradle'","line":1},{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/connectivity_plus-6.1.5/android/build.gradle'","line":1}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/connectivity_plus-6.1.5/android/build.gradle'","line":2},{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/connectivity_plus-6.1.5/android/build.gradle'","line":2}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('compileSdk = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('minSdk = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/git/device_calendar-5ea5ed9e2bb499c0633383b53103f2920b634755/android/build.gradle'","line":1},{"path":"build file '/Users/haroonirshad/.pub-cache/git/device_calendar-5ea5ed9e2bb499c0633383b53103f2920b634755/android/build.gradle'","line":1}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/git/device_calendar-5ea5ed9e2bb499c0633383b53103f2920b634755/android/build.gradle'","line":2},{"path":"build file '/Users/haroonirshad/.pub-cache/git/device_calendar-5ea5ed9e2bb499c0633383b53103f2920b634755/android/build.gradle'","line":2}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/device_info_plus-11.5.0/android/build.gradle'","line":1},{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/device_info_plus-11.5.0/android/build.gradle'","line":1}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = ') instead."}]]},{"locations":[{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/device_info_plus-11.5.0/android/build.gradle'","line":2},{"path":"build file '/Users/haroonirshad/.pub-cache/hosted/pub.dev/device_info_plus-11.5.0/android/build.gradle'","line":2}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('compileSdk = ') instead."}]]},{"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('namespace = ') instead."}]]}],"problemsReport":{"totalProblemCount":16,"buildName":"android","requestedTasks":"assembleDebug","documentationLink":"https://docs.gradle.org/8.12/userguide/problems-report.html","documentationLinkCaption":"Problem report","summaries":[{"problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"count":24}]}} +{"diagnostics":[{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":9},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":9}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":1},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":1}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('group = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":2},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":2}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('version = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"locations":[{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22},{"path":"build file '/Users/cloud/.pub-cache/hosted/pub.dev/amazon_payfort-1.1.4/android/build.gradle'","line":22}],"problem":[{"text":"Space-assignment syntax in Groovy DSL has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 10.0."}],"contextualLabel":"Space-assignment syntax in Groovy DSL has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#groovy_space_assignment_syntax","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"solutions":[[{"text":"Use assignment ('url = ') instead."}]]},{"problem":[{"text":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Provider.forUseAtConfigurationTime method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_7.html#for_use_at_configuration_time_deprecation","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-provider-foruseatconfigurationtime-method-has-been-deprecated","displayName":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"solutions":[[{"text":"Simply remove the call."}]]},{"problem":[{"text":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Provider.forUseAtConfigurationTime method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_7.html#for_use_at_configuration_time_deprecation","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-provider-foruseatconfigurationtime-method-has-been-deprecated","displayName":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"solutions":[[{"text":"Simply remove the call."}]]},{"problem":[{"text":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Provider.forUseAtConfigurationTime method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_7.html#for_use_at_configuration_time_deprecation","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-provider-foruseatconfigurationtime-method-has-been-deprecated","displayName":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"solutions":[[{"text":"Simply remove the call."}]]},{"problem":[{"text":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Provider.forUseAtConfigurationTime method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_7.html#for_use_at_configuration_time_deprecation","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-provider-foruseatconfigurationtime-method-has-been-deprecated","displayName":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"solutions":[[{"text":"Simply remove the call."}]]},{"problem":[{"text":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Provider.forUseAtConfigurationTime method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_7.html#for_use_at_configuration_time_deprecation","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-provider-foruseatconfigurationtime-method-has-been-deprecated","displayName":"The Provider.forUseAtConfigurationTime method has been deprecated."}],"solutions":[[{"text":"Simply remove the call."}]]},{"locations":[{"pluginId":"com.google.protobuf"}],"problem":[{"text":"The Configuration.fileCollection(Dependency...) method has been deprecated."}],"severity":"WARNING","problemDetails":[{"text":"This is scheduled to be removed in Gradle 9.0."}],"contextualLabel":"The Configuration.fileCollection(Dependency...) method has been deprecated.","documentationLink":"https://docs.gradle.org/8.12/userguide/upgrading_version_8.html#deprecate_filtered_configuration_file_and_filecollection_methods","problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"the-configuration-filecollection-dependency-method-has-been-deprecated","displayName":"The Configuration.fileCollection(Dependency...) method has been deprecated."}],"solutions":[[{"text":"Use Configuration.getIncoming().artifactView(Action) with a componentFilter instead."}]]}],"problemsReport":{"totalProblemCount":21,"buildName":"android","requestedTasks":"assembleDebug","documentationLink":"https://docs.gradle.org/8.12/userguide/problems-report.html","documentationLinkCaption":"Problem report","summaries":[{"problemId":[{"name":"deprecation","displayName":"Deprecation"},{"name":"space-assignment-syntax-in-groovy-dsl","displayName":"Space-assignment syntax in Groovy DSL has been deprecated."}],"count":48}]}} // end-report-data );} diff --git a/assets/images/png/zoom/chat-send@2x.png b/assets/images/png/zoom/chat-send@2x.png new file mode 100644 index 0000000..73e7cd3 Binary files /dev/null and b/assets/images/png/zoom/chat-send@2x.png differ diff --git a/assets/images/png/zoom/chat-send@3x.png b/assets/images/png/zoom/chat-send@3x.png new file mode 100644 index 0000000..2c18a6b Binary files /dev/null and b/assets/images/png/zoom/chat-send@3x.png differ diff --git a/assets/images/png/zoom/default-avatar.png b/assets/images/png/zoom/default-avatar.png new file mode 100644 index 0000000..c5fd1e7 Binary files /dev/null and b/assets/images/png/zoom/default-avatar.png differ diff --git a/assets/images/png/zoom/hamburger@2x.png b/assets/images/png/zoom/hamburger@2x.png new file mode 100644 index 0000000..9b490c2 Binary files /dev/null and b/assets/images/png/zoom/hamburger@2x.png differ diff --git a/assets/images/png/zoom/hamburger@3x.png b/assets/images/png/zoom/hamburger@3x.png new file mode 100644 index 0000000..434601f Binary files /dev/null and b/assets/images/png/zoom/hamburger@3x.png differ diff --git a/assets/images/png/zoom/index.ts b/assets/images/png/zoom/index.ts new file mode 100644 index 0000000..fce1d50 --- /dev/null +++ b/assets/images/png/zoom/index.ts @@ -0,0 +1,22 @@ +export const icons = { + chatSend: require('./chat-send.png'), + defaultAvatar: require('./default-avatar.png'), + locked: require('./locked.png'), + more: require('./more.png'), + mute: require('./mute.png'), + muted: require('./muted.png'), + shareOn: require('./share-on.png'), + shareOff: require('./share-off.png'), + speakerOn: require('./speaker-on.png'), + speakerOff: require('./speaker-off.png'), + switchCamera: require('./switch-camera.png'), + hamburger: require('./hamburger.png'), + questionBalloon: require('./question-ballon.png'), + talking: require('./talking.png'), + unmute: require('./unmute.png'), + unlocked: require('./unlocked.png'), + videoOn: require('./video-on.png'), + videoOff: require('./video-off.png'), +}; + +export type IconTypes = keyof typeof icons; diff --git a/assets/images/png/zoom/locked@2x.png b/assets/images/png/zoom/locked@2x.png new file mode 100644 index 0000000..c6d9806 Binary files /dev/null and b/assets/images/png/zoom/locked@2x.png differ diff --git a/assets/images/png/zoom/locked@3x.png b/assets/images/png/zoom/locked@3x.png new file mode 100644 index 0000000..170f6e2 Binary files /dev/null and b/assets/images/png/zoom/locked@3x.png differ diff --git a/assets/images/png/zoom/more@2x.png b/assets/images/png/zoom/more@2x.png new file mode 100644 index 0000000..e98bc18 Binary files /dev/null and b/assets/images/png/zoom/more@2x.png differ diff --git a/assets/images/png/zoom/more@3x.png b/assets/images/png/zoom/more@3x.png new file mode 100644 index 0000000..e69710c Binary files /dev/null and b/assets/images/png/zoom/more@3x.png differ diff --git a/assets/images/png/zoom/mute@2x.png b/assets/images/png/zoom/mute@2x.png new file mode 100644 index 0000000..65b555a Binary files /dev/null and b/assets/images/png/zoom/mute@2x.png differ diff --git a/assets/images/png/zoom/mute@3x.png b/assets/images/png/zoom/mute@3x.png new file mode 100644 index 0000000..da7b29c Binary files /dev/null and b/assets/images/png/zoom/mute@3x.png differ diff --git a/assets/images/png/zoom/muted@2x.png b/assets/images/png/zoom/muted@2x.png new file mode 100644 index 0000000..3504363 Binary files /dev/null and b/assets/images/png/zoom/muted@2x.png differ diff --git a/assets/images/png/zoom/muted@3x.png b/assets/images/png/zoom/muted@3x.png new file mode 100644 index 0000000..808ef3e Binary files /dev/null and b/assets/images/png/zoom/muted@3x.png differ diff --git a/assets/images/png/zoom/question-ballon@2x.png b/assets/images/png/zoom/question-ballon@2x.png new file mode 100644 index 0000000..ba79fd3 Binary files /dev/null and b/assets/images/png/zoom/question-ballon@2x.png differ diff --git a/assets/images/png/zoom/question-ballon@3x.png b/assets/images/png/zoom/question-ballon@3x.png new file mode 100644 index 0000000..019c69d Binary files /dev/null and b/assets/images/png/zoom/question-ballon@3x.png differ diff --git a/assets/images/png/zoom/share-off@2x.png b/assets/images/png/zoom/share-off@2x.png new file mode 100644 index 0000000..1dba94c Binary files /dev/null and b/assets/images/png/zoom/share-off@2x.png differ diff --git a/assets/images/png/zoom/share-off@3x.png b/assets/images/png/zoom/share-off@3x.png new file mode 100644 index 0000000..46989fe Binary files /dev/null and b/assets/images/png/zoom/share-off@3x.png differ diff --git a/assets/images/png/zoom/share-on@2x.png b/assets/images/png/zoom/share-on@2x.png new file mode 100644 index 0000000..285118e Binary files /dev/null and b/assets/images/png/zoom/share-on@2x.png differ diff --git a/assets/images/png/zoom/share-on@3x.png b/assets/images/png/zoom/share-on@3x.png new file mode 100644 index 0000000..9ed5713 Binary files /dev/null and b/assets/images/png/zoom/share-on@3x.png differ diff --git a/assets/images/png/zoom/speaker-off.png b/assets/images/png/zoom/speaker-off.png new file mode 100644 index 0000000..9763a5a Binary files /dev/null and b/assets/images/png/zoom/speaker-off.png differ diff --git a/assets/images/png/zoom/speaker-on.png b/assets/images/png/zoom/speaker-on.png new file mode 100644 index 0000000..f3355ba Binary files /dev/null and b/assets/images/png/zoom/speaker-on.png differ diff --git a/assets/images/png/zoom/switch-camera.png b/assets/images/png/zoom/switch-camera.png new file mode 100644 index 0000000..5927b7b Binary files /dev/null and b/assets/images/png/zoom/switch-camera.png differ diff --git a/assets/images/png/zoom/talking@2x.png b/assets/images/png/zoom/talking@2x.png new file mode 100644 index 0000000..676d61d Binary files /dev/null and b/assets/images/png/zoom/talking@2x.png differ diff --git a/assets/images/png/zoom/talking@3x.png b/assets/images/png/zoom/talking@3x.png new file mode 100644 index 0000000..7028a35 Binary files /dev/null and b/assets/images/png/zoom/talking@3x.png differ diff --git a/assets/images/png/zoom/unlocked@2x.png b/assets/images/png/zoom/unlocked@2x.png new file mode 100644 index 0000000..aa5403e Binary files /dev/null and b/assets/images/png/zoom/unlocked@2x.png differ diff --git a/assets/images/png/zoom/unlocked@3x.png b/assets/images/png/zoom/unlocked@3x.png new file mode 100644 index 0000000..25f9390 Binary files /dev/null and b/assets/images/png/zoom/unlocked@3x.png differ diff --git a/assets/images/png/zoom/unmute@2x.png b/assets/images/png/zoom/unmute@2x.png new file mode 100644 index 0000000..4c6d239 Binary files /dev/null and b/assets/images/png/zoom/unmute@2x.png differ diff --git a/assets/images/png/zoom/unmute@3x.png b/assets/images/png/zoom/unmute@3x.png new file mode 100644 index 0000000..dad68fa Binary files /dev/null and b/assets/images/png/zoom/unmute@3x.png differ diff --git a/assets/images/png/zoom/video-off@2x.png b/assets/images/png/zoom/video-off@2x.png new file mode 100644 index 0000000..3e209dd Binary files /dev/null and b/assets/images/png/zoom/video-off@2x.png differ diff --git a/assets/images/png/zoom/video-off@3x.png b/assets/images/png/zoom/video-off@3x.png new file mode 100644 index 0000000..0667405 Binary files /dev/null and b/assets/images/png/zoom/video-off@3x.png differ diff --git a/assets/images/png/zoom/video-on@2x.png b/assets/images/png/zoom/video-on@2x.png new file mode 100644 index 0000000..cdd8544 Binary files /dev/null and b/assets/images/png/zoom/video-on@2x.png differ diff --git a/assets/images/png/zoom/video-on@3x.png b/assets/images/png/zoom/video-on@3x.png new file mode 100644 index 0000000..03e6976 Binary files /dev/null and b/assets/images/png/zoom/video-on@3x.png differ diff --git a/assets/images/svg/doctor_profile_rating_icon.svg b/assets/images/svg/doctor_profile_rating_icon.svg new file mode 100644 index 0000000..f658411 --- /dev/null +++ b/assets/images/svg/doctor_profile_rating_icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/svg/doctor_profile_reviews_icon.svg b/assets/images/svg/doctor_profile_reviews_icon.svg new file mode 100644 index 0000000..9ef9f71 --- /dev/null +++ b/assets/images/svg/doctor_profile_reviews_icon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/images/svg/waitingAppo.svg b/assets/images/svg/waitingAppo.svg new file mode 100644 index 0000000..c9bd009 --- /dev/null +++ b/assets/images/svg/waitingAppo.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index d36b1fa..08f3422 100644 --- a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,122 +1,128 @@ { "images" : [ { - "size" : "20x20", - "idiom" : "iphone", "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" }, { - "size" : "20x20", - "idiom" : "iphone", "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" }, { - "size" : "29x29", - "idiom" : "iphone", "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" + "idiom" : "iphone", + "scale" : "1x", + "size" : "29x29" }, { - "size" : "29x29", - "idiom" : "iphone", "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" }, { - "size" : "29x29", - "idiom" : "iphone", "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" }, { - "size" : "40x40", - "idiom" : "iphone", "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" }, { - "size" : "40x40", - "idiom" : "iphone", "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" }, { - "size" : "60x60", - "idiom" : "iphone", "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" }, { - "size" : "60x60", - "idiom" : "iphone", "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" }, { - "size" : "20x20", - "idiom" : "ipad", "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" }, { - "size" : "20x20", - "idiom" : "ipad", "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" }, { - "size" : "29x29", - "idiom" : "ipad", "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" }, { - "size" : "29x29", - "idiom" : "ipad", "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" }, { - "size" : "40x40", - "idiom" : "ipad", "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" }, { - "size" : "40x40", - "idiom" : "ipad", "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" }, { - "size" : "76x76", - "idiom" : "ipad", "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" }, { - "size" : "76x76", - "idiom" : "ipad", "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" }, { - "size" : "83.5x83.5", - "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" }, { - "size" : "1024x1024", + "filename" : "icon 1.jpg", "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" + "scale" : "1x", + "size" : "1024x1024" + }, + { + "filename" : "Icon-App-76x76@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "size" : "76x76" } ], "info" : { - "version" : 1, - "author" : "xcode" + "author" : "xcode", + "version" : 1 } } diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png deleted file mode 100644 index dc9ada4..0000000 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and /dev/null differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 7353c41..0e65243 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 797d452..2e4c796 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index 6ed2d93..59435c7 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cd7b00..20855aa 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index fe73094..11d35da 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index 321773c..93523cb 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 797d452..2e4c796 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index 502f463..00bb8db 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index 0ec3034..3eaa1fb 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index 0ec3034..3eaa1fb 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index e9f5fea..fd80aa4 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index 84ac32a..39c7958 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 8953cba..47a96a4 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index 0467bf1..8c4ca7b 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/lib/core/api/api_client.dart b/lib/core/api/api_client.dart index aa534f6..888f704 100644 --- a/lib/core/api/api_client.dart +++ b/lib/core/api/api_client.dart @@ -175,8 +175,7 @@ class ApiClientImp implements ApiClient { } // body['TokenID'] = "@dm!n"; - // body['PatientID'] = 4772429; - // body['PatientID'] = 1231755; + // body['PatientID'] = 1018977; // body['PatientTypeID'] = 1; // // body['PatientOutSA'] = 0; @@ -184,9 +183,6 @@ class ApiClientImp implements ApiClient { } body.removeWhere((key, value) => value == null); - log("uri: ${Uri.parse(url.trim())}"); - - log("body: ${json.encode(body)}"); final bool networkStatus = await Utils.checkConnection(bypassConnectionCheck: bypassConnectionCheck); @@ -204,7 +200,7 @@ class ApiClientImp implements ApiClient { final int statusCode = response.statusCode; log("uri: ${Uri.parse(url.trim())}"); log("body: ${json.encode(body)}"); - log("response.body: ${response.body}"); + // log("response.body: ${response.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 f5aa29d..d9906e0 100644 --- a/lib/core/api_consts.dart +++ b/lib/core/api_consts.dart @@ -14,8 +14,8 @@ var PACKAGES_ORDERS = '/api/orders'; var PACKAGES_ORDER_HISTORY = '/api/orders/items'; var PACKAGES_TAMARA_OPT = '/api/orders/paymentoptions/tamara'; // var BASE_URL = 'http://10.50.100.198:2018/'; -// var BASE_URL = 'https://uat.hmgwebservices.com/'; -var BASE_URL = 'https://hmgwebservices.com/'; +var BASE_URL = 'https://uat.hmgwebservices.com/'; +// var BASE_URL = 'https://hmgwebservices.com/'; // var BASE_URL = 'http://10.201.204.103/'; // var BASE_URL = 'https://orash.cloudsolutions.com.sa/'; // var BASE_URL = 'https://vidauat.cloudsolutions.com.sa/'; @@ -178,8 +178,12 @@ var DELETE_CHILD_REQUEST = 'Services/Community.svc/REST/DeleteBaby'; var GET_TABLE_REQUEST = 'Services/Community.svc/REST/CreateVaccinationTable'; ///BloodDenote +/// +/// use get all cities from the e-referral, already calling this api there don't use multiple same api calls var GET_CITIES_REQUEST = 'Services/Lists.svc/REST/GetAllCities'; - +/// +/// +/// ///BloodDetails var GET_BLOOD_REQUEST = 'services/PatientVarification.svc/REST/BloodDonation_GetBloodGroupDetails'; @@ -440,12 +444,7 @@ var H2O_UPDATE_USER_DETAIL = "Services/H2ORemainder.svc/REST/H2O_UpdateUserDetai var H2O_UNDO_USER_ACTIVITY = "Services/H2ORemainder.svc/REST/H2o_UndoUserActivity"; //E_Referral Services -var GET_ALL_RELATIONSHIP_TYPES = "Services/Patients.svc/REST/GetAllRelationshipTypes"; -var SEND_ACTIVATION_CODE_FOR_E_REFERRAL = 'Services/Authentication.svc/REST/SendActivationCodeForEReferral'; -var CHECK_ACTIVATION_CODE_FOR_E_REFERRAL = 'Services/Authentication.svc/REST/CheckActivationCodeForEReferral'; -var GET_ALL_CITIES = 'services/Lists.svc/rest/GetAllCities'; -var CREATE_E_REFERRAL = "Services/Patients.svc/REST/CreateEReferral"; -var GET_E_REFERRALS = "Services/Patients.svc/REST/GetEReferrals"; + // Encillary Orders @@ -744,7 +743,7 @@ class ApiConsts { baseUrl = "https://uat.hmgwebservices.com/"; payFortEnvironment = FortEnvironment.test; applePayMerchantId = "merchant.com.hmgwebservices.uat"; - SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx'; + SERVICE_URL = 'https://uat.hmgwebservices.com/HMGPayment/pages/SendPayFortRequest.aspx'; TAMARA_URL = "https://epharmacy.hmg.com/tamara/Home/Checkout"; GET_TAMARA_INSTALLMENTS_URL = "https://epharmacy.hmg.com/tamara/Home/getinstallments"; GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; @@ -754,7 +753,7 @@ class ApiConsts { baseUrl = "https://uat.hmgwebservices.com/"; payFortEnvironment = FortEnvironment.test; applePayMerchantId = "merchant.com.hmgwebservices.uat"; - SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx'; + SERVICE_URL = 'https://uat.hmgwebservices.com/HMGPayment/pages/SendPayFortRequest.aspx'; TAMARA_URL = "https://epharmacy.hmg.com/tamara/Home/Checkout"; GET_TAMARA_INSTALLMENTS_URL = "https://epharmacy.hmg.com/tamara/Home/getinstallments"; GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; @@ -774,7 +773,7 @@ class ApiConsts { baseUrl = "https://uat.hmgwebservices.com/"; payFortEnvironment = FortEnvironment.test; applePayMerchantId = "merchant.com.hmgwebservices.uat"; - SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx'; + SERVICE_URL = 'https://uat.hmgwebservices.com/HMGPayment/pages/SendPayFortRequest.aspx'; TAMARA_URL = "https://epharmacy.hmg.com/tamara/Home/Checkout"; GET_TAMARA_INSTALLMENTS_URL = "https://epharmacy.hmg.com/tamara/Home/getinstallments"; GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; @@ -784,7 +783,7 @@ class ApiConsts { baseUrl = "https://uat.hmgwebservices.com/"; payFortEnvironment = FortEnvironment.test; applePayMerchantId = "merchant.com.hmgwebservices.uat"; - SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx'; + SERVICE_URL = 'https://uat.hmgwebservices.com/HMGPayment/pages/SendPayFortRequest.aspx'; TAMARA_URL = "https://epharmacy.hmg.com/tamara/Home/Checkout"; GET_TAMARA_INSTALLMENTS_URL = "https://epharmacy.hmg.com/tamara/Home/getinstallments"; GET_TAMARA_PAYMENT_STATUS = 'https://epharmacy.hmg.com/tamara/api/OnlineTamara/order_status?orderid='; @@ -845,8 +844,19 @@ class ApiConsts { static final String updateHHCOrder = 'api/hhc/update'; static final String addHHCOrder = 'api/HHC/add'; + + //E-REFERRAL SERVICES + + static final getAllRelationshipTypes = "Services/Patients.svc/REST/GetAllRelationshipTypes"; + static final sendActivationCodeForEReferral = 'Services/Authentication.svc/REST/SendActivationCodeForEReferral'; + static final checkActivationCodeForEReferral = 'Services/Authentication.svc/REST/CheckActivationCodeForEReferral'; + static final getAllCities = 'services/Lists.svc/rest/GetAllCities'; + static final createEReferral = "Services/Patients.svc/REST/CreateEReferral"; + static final getEReferrals = "Services/Patients.svc/REST/GetEReferrals"; + + // ************ static values for Api **************** - static final double appVersionID = 19.3; + static final double appVersionID = 50.3; static final int appChannelId = 3; static final String appIpAddress = "10.20.10.20"; static final String appGeneralId = "Cs2020@2016\$2958"; diff --git a/lib/core/app_assets.dart b/lib/core/app_assets.dart index ab2bfb2..db2ca46 100644 --- a/lib/core/app_assets.dart +++ b/lib/core/app_assets.dart @@ -175,6 +175,9 @@ class AppAssets { static const String comprehensiveCheckup = '$svgBasePath/comprehensive_checkup.svg'; static const String all_payment_method = '$svgBasePath/all_payment_method.svg'; static const String ic_rrt_vehicle = '$svgBasePath/ic_rrt_vehicle.svg'; + static const String doctor_profile_rating_icon = '$svgBasePath/doctor_profile_rating_icon.svg'; + static const String doctor_profile_reviews_icon = '$svgBasePath/doctor_profile_reviews_icon.svg'; + static const String waiting_appointment_icon = '$svgBasePath/waitingAppo.svg'; //bottom navigation// static const String homeBottom = '$svgBasePath/home_bottom.svg'; diff --git a/lib/core/cache_consts.dart b/lib/core/cache_consts.dart index 66b38d4..bcbb185 100644 --- a/lib/core/cache_consts.dart +++ b/lib/core/cache_consts.dart @@ -74,4 +74,7 @@ class CacheConst { static const String patientOccupationList = 'patient-occupation-list'; static const String hasEnabledQuickLogin = 'has-enabled-quick-login'; static const String quickLoginEnabled = 'quick-login-enabled'; + + static const String zoomRoomID = 'zoom-room-id'; + static String isAppOpenedFromCall = "is_app_opened_from_call"; } diff --git a/lib/core/dependencies.dart b/lib/core/dependencies.dart index 58c4a66..88b1f6f 100644 --- a/lib/core/dependencies.dart +++ b/lib/core/dependencies.dart @@ -126,7 +126,7 @@ class AppDependencies { () => RadiologyViewModel(radiologyRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt()), ); - getIt.registerLazySingleton(() => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt())); + getIt.registerLazySingleton(() => PrescriptionsViewModel(prescriptionsRepo: getIt(), errorHandlerService: getIt(), navServices: getIt())); getIt.registerLazySingleton(() => InsuranceViewModel(insuranceRepo: getIt(), errorHandlerService: getIt())); @@ -217,5 +217,17 @@ class AppDependencies { ); getIt.registerLazySingleton(() => SymptomsCheckerViewModel()); + getIt.registerLazySingleton( + () => HmgServicesViewModel(bookAppointmentsRepo: getIt(), hmgServicesRepo: getIt(), errorHandlerService: getIt(), navigationService: getIt()), + ); + + // Screen-specific VMs → Factory + // getIt.registerFactory( + // () => BookAppointmentsViewModel( + // bookAppointmentsRepo: getIt(), + // dialogService: getIt(), + // errorHandlerService: getIt(), + // ), + // ); } } diff --git a/lib/core/utils/calendar_utils.dart b/lib/core/utils/calendar_utils.dart deleted file mode 100644 index 2068db9..0000000 --- a/lib/core/utils/calendar_utils.dart +++ /dev/null @@ -1,316 +0,0 @@ -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".needTranslation, 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. ".needTranslation + 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 - ); - - 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 new file mode 100644 index 0000000..05448b1 --- /dev/null +++ b/lib/core/utils/calender_utils_new.dart @@ -0,0 +1,178 @@ +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; + +class CalenderUtilsNew { + final DeviceCalendar calender = DeviceCalendar.instance; + List writableCalender = []; + + CalenderUtilsNew._instance() { + getCalenders(); + } + + static final CalenderUtilsNew instance = CalenderUtilsNew._instance(); + + Future getCalenders() async { + CalendarPermissionStatus result = await DeviceCalendar.instance.hasPermissions(); + if (result != CalendarPermissionStatus.granted) await DeviceCalendar.instance.requestPermissions(); + var calenders = await calender.listCalendars(); + calenders.forEach((calender) { + if (!calender.readOnly) { + writableCalender.add(calender); + } + }); + } + + FutureOr createOrUpdateEvent({required String title, required String description, required String location, DateTime? scheduleDateTime, String? eventId, int? reminderMinutes}) async { + if (writableCalender.isEmpty) { + await getCalenders(); + } + var writableCalendars = writableCalender.first; + String eventResult = ""; + CalendarPermissionStatus result = await DeviceCalendar.instance.hasPermissions(); + if (result != CalendarPermissionStatus.granted) await DeviceCalendar.instance.requestPermissions(); + print(result); + + // String eventId = await getEventIdIfEventExist(title!.split("#").last); + // if (eventId.isEmpty) { + eventResult = await DeviceCalendar.instance.createEvent( + calendarId: writableCalendars!.id, + title: title, + description: description, + startDate: scheduleDateTime!, + endDate: scheduleDateTime!.add(Duration(minutes: 30)), + reminderMinutes: reminderMinutes); + return eventResult.isNotEmpty; + // } + + // await DeviceCalendar.instance.updateEvent( + // eventId: eventId, + // title: title, + // description: description, + // startDate: scheduleDateTime!, + // endDate: scheduleDateTime!.add(Duration(minutes: 30)), + // ); + + // return eventId.isNotEmpty; + } + + FutureOr createMultipleEvents( + {required int reminderMinutes, + int? frequencyNumber, + required int days, + required String orderDate, + required String itemDescriptionN, + required String route, + Function(String)? onFailure, + String? prescriptionNumber}) async { + DateTime currentDay = DateTime.now(); + DateTime actualDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 8, 0); + print("the frequency is $frequencyNumber"); + frequencyNumber ??= 2; //Some time frequency number is null so by default will be 2 + int interval = calculateIntervalAsPerFrequency(frequencyNumber); + // int remainingDays = days - (Jiffy.parseFromDateTime(DateTime.now()).diff(Jiffy.parseFromDateTime(DateUtil.convertStringToDate(orderDate)), unit: Unit.day) as int); + Duration difference = (actualDate.difference(DateUtil.convertStringToDate(orderDate))); + int remainingDays = 5; + // if (remainingDays.isNegative) { + // onFailure?.call("Prescription date has been already passed you can not add a reminder for this prescription."); + // return false; + // } + + bool statusOfOperation = false; + + for (int i = 0; i < remainingDays; i++) { + //event for number of days. + for (int j = 0; j < frequencyNumber; j++) { + statusOfOperation = await createOrUpdateEvent( + title: "$itemDescriptionN} Medication about to due for prescription , #$prescriptionNumber", + description: "$itemDescriptionN $frequencyNumber $route ", + scheduleDateTime: actualDate, + location: '', + //event id with varitions + reminderMinutes: reminderMinutes); + if (!statusOfOperation) return false; + + actualDate = actualDate.add(Duration(hours: interval)); + // if (actualDate.difference(currentDay).inDays == 1) break; + } + // actualDate = actualDate.add(Duration(days: 1)); + } + + return statusOfOperation; + } + + int calculateIntervalAsPerFrequency(int frequencyNumber) { + return 24 ~/ frequencyNumber; + } + + FutureOr> getEvents() async { + var availableCalender = writableCalender.first; + DateTime startEventsDate = Jiffy.parseFromDateTime(DateTime.now()).subtract(days: 30).dateTime; + DateTime endEventsDate = Jiffy.parseFromDateTime(DateTime.now()).add(days: 120).dateTime; + return await calender.listEvents(startEventsDate, endEventsDate, calendarIds: [availableCalender.id]); + } + + FutureOr checkIfEventExist(String admissionId) async { + if (writableCalender.isEmpty) { + await getCalenders(); + } + List events = await getEvents(); + if (events.isEmpty) return false; + for (var event in events) { + List title = event.title!.split("#"); + + if (title.contains(admissionId)) return true; + } + return false; + } + + FutureOr getEventIdIfEventExist(String admissionId) async { + if (writableCalender.isEmpty) { + await getCalenders(); + } + List events = await getEvents(); + if (events.isEmpty) return ""; + for (var event in events) { + List title = event.title!.split("#"); + if (title.contains(admissionId)) return event.eventId; + } + return ""; + } + + FutureOr checkAndRemove({required String id}) async { + if (writableCalender.isEmpty) { + await getCalenders(); + } + List events = await getEvents(); + if (events.isEmpty) return false; + for (var event in events) { + List title = event.title!.split("#"); + + if (title.contains(id)) { + calender.deleteEvent(eventId: event.eventId); + return true; + } + } + return false; + } + + FutureOr checkAndRemoveMultipleItems({required String id}) async { + if (writableCalender.isEmpty) { + await getCalenders(); + } + List events = await getEvents(); + if (events.isEmpty) return false; + bool statusOfOperation = false; + for (var event in events) { + List title = event.title.split("#"); + + if (title.contains(id)) { + calender.deleteEvent(eventId: event.eventId); + statusOfOperation = true; + } + } + return statusOfOperation; + } +} diff --git a/lib/core/utils/date_util.dart b/lib/core/utils/date_util.dart index a918706..a42a44d 100644 --- a/lib/core/utils/date_util.dart +++ b/lib/core/utils/date_util.dart @@ -17,8 +17,7 @@ class DateUtil { final endIndex = date.indexOf(end, startIndex + start.length); return DateTime.fromMillisecondsSinceEpoch(int.parse( date.substring(startIndex + start.length, endIndex), - )) - ; + )); } static DateTime convertStringToDateSaudiTimezone(String date, int projectId) { @@ -370,6 +369,29 @@ class DateUtil { } } + static String getDateStringForNearestSlot(String date) { + DateTime dateObj = DateUtil.convertStringToDate(date); + return DateUtil.getWeekDay(dateObj.weekday) + + ", " + + dateObj.day.toString() + + " " + + DateUtil.getMonth(dateObj.month) + + " " + + dateObj.year.toString() + + " " + + dateObj.hour.toString() + + ":" + + getMinute(dateObj); + } + + static String getMinute(DateTime dateObj) { + if (dateObj.minute == 0) { + return dateObj.minute.toString() + "0"; + } else { + return dateObj.minute.toString(); + } + } + static String getMonthDayYearLangDateFormatted(DateTime dateTime, String lang) { if (dateTime != null) { return lang == 'en' diff --git a/lib/core/utils/jwt.dart b/lib/core/utils/jwt.dart new file mode 100644 index 0000000..f82c4e1 --- /dev/null +++ b/lib/core/utils/jwt.dart @@ -0,0 +1,38 @@ +import 'dart:math'; + +import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; +import 'package:hmg_patient_app_new/core/utils/zoom_config.dart'; + +String makeId(int length) { + String result = ""; + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + int charactersLength = characters.length; + for (var i = 0; i < length; i++) { + result += characters[Random().nextInt(charactersLength)]; + } + return result; +} + +String generateJwt(String sessionName, String roleType) { + try { + var iat = DateTime.now(); + var exp = DateTime.now().add(Duration(days: 2)); + final jwt = JWT( + { + 'app_key': configs["ZOOM_SDK_KEY"], + 'version': 1, + 'user_identity': makeId(10), + 'iat': (iat.millisecondsSinceEpoch / 1000).round(), + 'exp': (exp.millisecondsSinceEpoch / 1000).round(), + 'tpc': sessionName, + 'role_type': int.parse(roleType), + 'cloud_recording_option': 1, + }, + ); + var token = jwt.sign(SecretKey(configs["ZOOM_SDK_SECRET"])); + return token; + } catch (e) { + print(e); + return ''; + } +} diff --git a/lib/core/utils/push_notification_handler.dart b/lib/core/utils/push_notification_handler.dart index 2e0d7c3..ee05335 100644 --- a/lib/core/utils/push_notification_handler.dart +++ b/lib/core/utils/push_notification_handler.dart @@ -8,14 +8,22 @@ import 'package:firebase_messaging/firebase_messaging.dart' as fir; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_callkit_incoming/entities/android_params.dart'; +import 'package:flutter_callkit_incoming/entities/call_kit_params.dart'; +import 'package:flutter_callkit_incoming/entities/ios_params.dart'; +import 'package:flutter_callkit_incoming/entities/notification_params.dart'; +import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_ios_voip_kit_karmm/call_state_type.dart'; import 'package:flutter_ios_voip_kit_karmm/flutter_ios_voip_kit.dart'; // import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/core/utils/local_notifications.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; +import 'package:hmg_patient_app_new/services/cache_service.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:uuid/uuid.dart'; import '../cache_consts.dart'; @@ -36,16 +44,83 @@ Future backgroundMessageHandler(dynamic message) async { callPage(String sessionID, String token) async {} _incomingCall(Map data) async { + print('the value of the _incomingCall remote message is $data'); + // LandingPage.incomingCallData = IncomingCallData.fromJson(data); // var dataItem = await AppSharedPreferences().getObject('call_data'); // if(dataItem != null ) return; // to stop repeated attempt to invoke the call // if (LandingPage.isOpenCallPage == false) { // LandingPage.isOpenCallPage = true; + + String roomID = data['session_id'] ?? ''; + + // GetIt.instance().saveString(key: CacheConst.zoomRoomID, value: roomID); + // GetIt.instance().saveBool(key: CacheConst.isAppOpenedFromCall, value: true); + + Utils.saveStringFromPrefs(CacheConst.zoomRoomID, roomID); + Utils.saveBoolFromPrefs(CacheConst.isAppOpenedFromCall, true); + WidgetsFlutterBinding.ensureInitialized(); - // var _currentUuid = Uuid().v4(); - // await FlutterCallkitIncoming.showCallkitIncoming(callKitParams); - // } - // LandingPage.isOpenCallPage = false; + + var _currentUuid = Uuid().v4(); + CallKitParams callKitParams = CallKitParams( + id: _currentUuid, + nameCaller: "Dr Al Habib", + appName: 'Dr Al Habib', + avatar: 'https://play-lh.googleusercontent.com/FBNNpxb7m6eM6wtW7MV1Ffp6OXOGLI38q47zcvP29OCYA1yhYH5mZzl5itZi0TgOyZpG', + // handle: LandingPage.incomingCallData.name, + type: 1, + textAccept: 'Accept', + textDecline: 'Decline', + missedCallNotification: NotificationParams( + showNotification: true, + isShowCallback: false, + subtitle: 'Missed call', + callbackText: '', + ), + callingNotification: const NotificationParams( + showNotification: false, + isShowCallback: true, + subtitle: 'Calling...', + callbackText: 'Hang Up', + ), + duration: 30000, + extra: {'userId': '1a2b3c4d'}, + headers: {'apiKey': 'Abc@123!', 'platform': 'flutter'}, + android: const AndroidParams( + isImportant: true, + isShowFullLockedScreen: true, + isCustomNotification: true, + isShowLogo: false, + logoUrl: "https://play-lh.googleusercontent.com/FBNNpxb7m6eM6wtW7MV1Ffp6OXOGLI38q47zcvP29OCYA1yhYH5mZzl5itZi0TgOyZpG", + ringtonePath: 'system_ringtone_default', + backgroundColor: '#ED1C2B', + backgroundUrl: 'https://saudipedia.com/en/saudipediaen/uploads/images/2024/08/02/97358.jpg', + actionColor: '#4CAF50', + textColor: '#000000', + incomingCallNotificationChannelName: "Incoming Call", + missedCallNotificationChannelName: "Missed Call", + isShowCallID: false), + ios: IOSParams( + iconName: 'Meena Health', + handleType: 'generic', + supportsVideo: true, + maximumCallGroups: 2, + maximumCallsPerCallGroup: 1, + audioSessionMode: 'default', + audioSessionActive: true, + audioSessionPreferredSampleRate: 44100.0, + audioSessionPreferredIOBufferDuration: 0.005, + supportsDTMF: true, + supportsHolding: true, + supportsGrouping: false, + supportsUngrouping: false, + ringtonePath: 'system_ringtone_default', + ), + ); + FlutterCallkitIncoming.unsilenceEvents(); + await FlutterCallkitIncoming.showCallkitIncoming(callKitParams); + await Future.delayed(Duration(milliseconds: 500)); } @@ -224,7 +299,9 @@ class PushNotificationHandler { print('🎈 example: onDidAcceptIncomingCall $uuid - $callerId'); await voIPKit.acceptIncomingCall(callerState: CallStateType.calling); await voIPKit.callConnected(); - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(Duration(seconds: 2)).then((val) async { + await voIPKit.endCall(); + }); // Navigator.pushNamed( // locator().navigatorKey.currentContext!, @@ -232,8 +309,6 @@ class PushNotificationHandler { // arguments: CallArguments("hoover-dam", "123", "Patient", "40", "1", false), // ); - await voIPKit.endCall(); - // Navigator.pushNamed(navigatorKey.currentContext!, VIDEO_CALL_SCREEN, // arguments: VideoArgus( // reservationId: int.parse(callerId), token: null, isVideo: true)); diff --git a/lib/core/utils/utils.dart b/lib/core/utils/utils.dart index 9fdd947..b43c55e 100644 --- a/lib/core/utils/utils.dart +++ b/lib/core/utils/utils.dart @@ -8,6 +8,7 @@ import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:crypto/crypto.dart' as crypto; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:google_api_availability/google_api_availability.dart'; @@ -29,6 +30,7 @@ import 'package:hmg_patient_app_new/widgets/loading_dialog.dart'; import 'package:lottie/lottie.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:url_launcher/url_launcher.dart'; class Utils { static AppState appState = getIt.get(); @@ -805,7 +807,11 @@ class Utils { static Future checkConnection({bool bypassConnectionCheck = false}) async { if (bypassConnectionCheck) return true; List connectivityResult = await (Connectivity().checkConnectivity()); - if (connectivityResult.contains(ConnectivityResult.mobile) || connectivityResult.contains(ConnectivityResult.wifi)) { + if (connectivityResult.contains(ConnectivityResult.mobile) || + connectivityResult.contains(ConnectivityResult.wifi) || + connectivityResult.contains(ConnectivityResult.ethernet) || + connectivityResult.contains(ConnectivityResult.bluetooth) || + connectivityResult.contains(ConnectivityResult.vpn)) { return true; } else { return false; @@ -865,4 +871,8 @@ class Utils { } return isHavePrivilege; } + static void openWebView({ required String url}) { + Uri uri = Uri.parse(url); + launchUrl(uri, mode: LaunchMode.inAppBrowserView); + } } diff --git a/lib/core/utils/validation_utils.dart b/lib/core/utils/validation_utils.dart index 7e38300..abba447 100644 --- a/lib/core/utils/validation_utils.dart +++ b/lib/core/utils/validation_utils.dart @@ -101,8 +101,7 @@ class ValidationUtils { return regex.hasMatch(id); } - static bool validateUaeRegistration( - {String? name, GenderTypeEnum? gender, NationalityCountries? country, MaritalStatusTypeEnum? maritalStatus, required Function() onOkPress}) { + static bool validateUaeRegistration({String? name, GenderTypeEnum? gender, NationalityCountries? country, MaritalStatusTypeEnum? maritalStatus, required Function() onOkPress}) { if (name == null || name.isEmpty) { _dialogService.showExceptionBottomSheet(message: LocaleKeys.pleaseEnterAValidName.tr(), onOkPressed: onOkPress); return false; @@ -141,8 +140,7 @@ class ValidationUtils { return true; } - static bool isValidatedIdAndPhoneWithCountryValidation( - {String? nationalId, String? phoneNumber, required Function() onOkPress, CountryEnum? selectedCountry}) { + static bool isValidatedIdAndPhoneWithCountryValidation({String? nationalId, String? phoneNumber, required Function() onOkPress, CountryEnum? selectedCountry}) { bool isCorrectID = true; if (nationalId == null || nationalId.isEmpty) { _dialogService.showExceptionBottomSheet(message: LocaleKeys.pleaseEnterAnationalID.tr(), onOkPressed: onOkPress); @@ -171,4 +169,10 @@ class ValidationUtils { } return isCorrectID; } -} + + static bool isNullOrEmpty(String? value) { + return value == null || value + .trim() + .isEmpty; + } +} \ No newline at end of file diff --git a/lib/core/utils/zoom_config.dart b/lib/core/utils/zoom_config.dart new file mode 100644 index 0000000..09370c0 --- /dev/null +++ b/lib/core/utils/zoom_config.dart @@ -0,0 +1,4 @@ +const Map configs = { + 'ZOOM_SDK_KEY': 'b9T74nhfTg-ioP9urm970A', + 'ZOOM_SDK_SECRET': 'KOzmjBNXQ1f4IPHpnngfL29uZvJMufSy2Fk8', +}; diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 250453d..c2a4a87 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -301,14 +301,14 @@ extension EmailValidator on String { fontWeight: weight ?? (isBold ? FontWeight.bold : FontWeight.normal)), ); - Widget toText28({Color? color, bool isBold = false, double? height, bool isCenter = false}) => Text( + Widget toText28({Color? color, bool isBold = false, double? height, bool isCenter = false, double? letterSpacing}) => Text( this, textAlign: isCenter ? TextAlign.center : null, style: TextStyle( height: height ?? 23 / 28, color: color ?? AppColors.blackColor, fontSize: 28.f, - letterSpacing: -1, + letterSpacing: letterSpacing ?? -1, fontWeight: isBold ? FontWeight.bold : FontWeight.normal), ); diff --git a/lib/features/authentication/authentication_repo.dart b/lib/features/authentication/authentication_repo.dart index d566996..6ecf4b1 100644 --- a/lib/features/authentication/authentication_repo.dart +++ b/lib/features/authentication/authentication_repo.dart @@ -265,6 +265,12 @@ class AuthenticationRepoImp implements AuthenticationRepo { newRequest.isDentalAllowedBackend = false; newRequest.forRegisteration = newRequest.isRegister ?? false; newRequest.isRegister = false; + //silent login case removed token and login token + if(newRequest.logInTokenID.isEmpty && newRequest.isSilentLogin == true) { + newRequest.logInTokenID = null; + newRequest.deviceToken = null; + } + } Map familyRequest = {}; diff --git a/lib/features/book_appointments/book_appointments_repo.dart b/lib/features/book_appointments/book_appointments_repo.dart index 8aafc9b..3683d57 100644 --- a/lib/features/book_appointments/book_appointments_repo.dart +++ b/lib/features/book_appointments/book_appointments_repo.dart @@ -14,6 +14,7 @@ import 'package:hmg_patient_app_new/features/book_appointments/models/resp_model import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_patient_dental_plan_response_model.dart'; 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/models/resp_models/patient_appointment_share_response_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; import 'models/resp_models/laser_body_parts.dart'; @@ -84,6 +85,22 @@ abstract class BookAppointmentsRepo { Future>>> getLaserClinics(int laserCategoryID, int projectID, int languageID, {Function(dynamic)? onSuccess, Function(String)? onError}); + + Future>> checkScannedNFCAndQRCode(String nfcCode, int projectId, {Function(dynamic)? onSuccess, Function(String)? onError}); + + Future>> getPatientShareWalkInAppointment({required int projectID, required int clinicID, required int doctorID}); + + Future>> insertSpecificAppointmentForWalkIn( + {required int docID, + required int clinicID, + required int projectID, + required String selectedTime, + required String selectedDate, + required int initialSlotDuration, + required int genderID, + required int userAge, + Function(dynamic)? onSuccess, + Function(String)? onError}); } class BookAppointmentsRepoImp implements BookAppointmentsRepo { @@ -848,4 +865,144 @@ class BookAppointmentsRepoImp implements BookAppointmentsRepo { return Left(UnknownFailure(e.toString())); } } + + @override + Future> checkScannedNFCAndQRCode(String nfcCode, int projectId, {Function(dynamic)? onSuccess, Function(String)? onError}) async { + Map mapDevice = {"NFC_Code": nfcCode, "ProjectID": projectId}; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + CHECK_SCANNED_NFC_QR_CODE, + body: mapDevice, + 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())); + } + } + + @override + Future>> getPatientShareWalkInAppointment({required int projectID, required int clinicID, required int doctorID}) async { + Map mapRequest = {"ProjectID": projectID, "ClinicID": clinicID, "DoctorID": doctorID}; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + GET_PATIENT_SHARE_FOR_WALKIN_APPOINTMENT, + body: mapRequest, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final list = response['OnlineCheckInAppointmentsWalkInModel']; + if (list == null || list.isEmpty) { + throw Exception("patient share list is empty"); + } + + final patientShareObj = PatientAppointmentShareResponseModel.fromJson(list); + patientShareObj.isCash = response["IsCash"]; + patientShareObj.isEligible = response["IsEligible"]; + patientShareObj.isInsured = response["IsInsured"]; + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: patientShareObj, + ); + } 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> insertSpecificAppointmentForWalkIn( + {required int docID, + required int clinicID, + required int projectID, + required String selectedTime, + required String selectedDate, + required int initialSlotDuration, + required int genderID, + required int userAge, + Function(dynamic)? onSuccess, + Function(String)? onError}) async { + Map mapDevice = { + "IsForLiveCare": true, + "ProjectID": projectID, + "ClinicID": clinicID, + "DoctorID": docID, + "StartTime": selectedTime, + "SelectedTime": selectedTime, + "EndTime": selectedTime, + "InitialSlotDuration": initialSlotDuration, + "StrAppointmentDate": selectedDate, + "IsVirtual": false, + "BookedBy": 102, + "VisitType": 1, + "VisitFor": 1, + "GenderID": genderID, + "Age": userAge + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + INSERT_WALKIN_APPOINTMENT, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + final appointmentNo = response['AppointmentNo']; + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: response["ErrorEndUserMessage"], + 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/book_appointments/book_appointments_view_model.dart b/lib/features/book_appointments/book_appointments_view_model.dart index a50b683..2413827 100644 --- a/lib/features/book_appointments/book_appointments_view_model.dart +++ b/lib/features/book_appointments/book_appointments_view_model.dart @@ -24,6 +24,7 @@ import 'package:hmg_patient_app_new/features/book_appointments/models/timeslots. 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/patient_appointment_history_response_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_share_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/home/navigation_screen.dart'; @@ -112,6 +113,15 @@ class BookAppointmentsViewModel extends ChangeNotifier { String? selectedClinicForFilters; bool applyFilters = false; + bool isWaitingAppointmentAvailable = false; + + bool isWaitingAppointmentSelected = false; + int waitingAppointmentProjectID = 0; + DoctorsListResponseModel? waitingAppointmentDoctor; + String waitingAppointmentNFCCode = ""; + + PatientAppointmentShareResponseModel? patientWalkInAppointmentShareResponseModel; + ///variables for laser clinic List femaleLaserCategory = [ LaserCategoryType(1, 'bodyString'), @@ -171,11 +181,32 @@ class BookAppointmentsViewModel extends ChangeNotifier { dentalChiefComplaintsList.clear(); isContinueDentalPlan = false; isChiefComplaintsListLoading = true; + isWaitingAppointmentSelected = false; bodyTypes = [maleLaserCategory, femaleLaserCategory]; // getLocation(); notifyListeners(); } + setIsWaitingAppointmentSelected(bool isWaitingAppointmentSelected) { + this.isWaitingAppointmentSelected = isWaitingAppointmentSelected; + notifyListeners(); + } + + setWaitingAppointmentDoctor(DoctorsListResponseModel waitingAppointmentDoctor) { + this.waitingAppointmentDoctor = waitingAppointmentDoctor; + notifyListeners(); + } + + setWaitingAppointmentNFCCode(String waitingAppointmentNFCCode) { + this.waitingAppointmentNFCCode = waitingAppointmentNFCCode; + notifyListeners(); + } + + setWaitingAppointmentProjectID(int projectID) { + waitingAppointmentProjectID = projectID; + notifyListeners(); + } + setIsDoctorsListLoading(bool value) { if (value) { doctorsList.clear(); @@ -337,22 +368,20 @@ class BookAppointmentsViewModel extends ChangeNotifier { //TODO: Make the API dynamic with parameters for ProjectID, isNearest, languageID, doctorId, doctorName Future getDoctorsList( - {int projectID = 0, - bool isNearest = false, - int doctorId = 0, + {int projectID = 0, bool isNearest = true, int doctorId = 0, String doctorName = "", Function(dynamic)? onSuccess, Function(String)? onError}) async { doctorsList.clear(); projectID = currentlySelectedHospitalFromRegionFlow != null ? int.parse(currentlySelectedHospitalFromRegionFlow!) : projectID; - final result = await bookAppointmentsRepo.getDoctorsList(selectedClinic.clinicID ?? 0, projectID, isNearest, doctorId, doctorName, - isContinueDentalPlan: isContinueDentalPlan); + final result = + await bookAppointmentsRepo.getDoctorsList(selectedClinic.clinicID ?? 0, projectID, doctorName.isNotEmpty ? false : isNearest, doctorId, doctorName, isContinueDentalPlan: isContinueDentalPlan); result.fold( (failure) async { isDoctorsListLoading = false; + if (onError != null) onError("No doctors found for the search criteria".needTranslation); - onError!("No doctors found for the search criteria".needTranslation); notifyListeners(); }, (apiResponse) { @@ -468,6 +497,9 @@ class BookAppointmentsViewModel extends ChangeNotifier { } initialSlotDuration = apiResponse.data["InitialSlotDuration"]; freeSlotsResponse = apiResponse.data['FreeTimeSlots']; + // isWaitingAppointmentAvailable = apiResponse.data["IsAllowToBookWaitingAppointment"]; + isWaitingAppointmentAvailable = true; + freeSlotsResponse.forEach((element) { // date = (isLiveCareSchedule != null && isLiveCareSchedule) // ? DateUtil.convertStringToDate(element) @@ -1165,4 +1197,95 @@ class BookAppointmentsViewModel extends ChangeNotifier { laserBodyPartsList = []; duration = 0; } + + Future checkScannedNFCAndQRCode(String nfcCode, int projectId, {Function(dynamic)? onSuccess, Function(String)? onError}) async { + final result = await bookAppointmentsRepo.checkScannedNFCAndQRCode(nfcCode, projectId); + + result.fold( + (failure) async { + onError!("Invalid verification point scanned.".needTranslation); + }, + (apiResponse) { + // if (apiResponse.data['returnValue'] == 0) { + // onError!("Invalid verification point scanned.".needTranslation); + // } else if (apiResponse.data['returnValue'] == 1) { + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + // } + }, + ); + } + + Future getWalkInPatientShareAppointment({Function(dynamic)? onSuccess, Function(String)? onError}) async { + final result = await bookAppointmentsRepo.getPatientShareWalkInAppointment(projectID: waitingAppointmentProjectID, clinicID: selectedDoctor.clinicID!, doctorID: selectedDoctor.doctorID!); + + result.fold( + (failure) async { + if (onError != null) { + onError(failure.message); + } + // await errorHandlerService.handleError( + // failure: failure, + // onOkPressed: () { + // onError!(failure.message); + // }); + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + onError!(apiResponse.errorMessage!); + // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); + } else if (apiResponse.messageStatus == 1) { + patientWalkInAppointmentShareResponseModel = apiResponse.data!; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } + + Future insertSpecificAppointmentForWalkIn({Function(dynamic p1)? onSuccess, Function(dynamic p1)? onError}) async { + _appState = getIt(); + final result = await bookAppointmentsRepo.insertSpecificAppointmentForWalkIn( + docID: selectedDoctor.doctorID!, + clinicID: selectedDoctor.clinicID!, + projectID: selectedDoctor.projectID!, + selectedDate: selectedAppointmentDate, + selectedTime: selectedAppointmentTime, + initialSlotDuration: initialSlotDuration, + genderID: _appState.getAuthenticatedUser()!.gender!, + userAge: _appState.getAuthenticatedUser()!.age!, + onError: onError); + + result.fold( + (failure) async { + print(failure); + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + LoadingUtils.hideFullScreenLoader(); + showCommonBottomSheetWithoutHeight( + title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!), + navigationService.navigatorKey.currentContext!, + child: Utils.getErrorWidget(loadingText: apiResponse.errorMessage), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } else if (apiResponse.messageStatus == 1) { + if (apiResponse.data == null || apiResponse.data!.isEmpty) { + onError!("Unexpected Error Occurred".needTranslation); + return; + } + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } } diff --git a/lib/features/emergency_services/emergency_services_view_model.dart b/lib/features/emergency_services/emergency_services_view_model.dart index 0f264c5..400eb04 100644 --- a/lib/features/emergency_services/emergency_services_view_model.dart +++ b/lib/features/emergency_services/emergency_services_view_model.dart @@ -1042,8 +1042,8 @@ class EmergencyServicesViewModel extends ChangeNotifier { bool result = await navServices.push( CustomPageRoute( page: MapUtilityScreen( - confirmButtonString: "Submit Request ".needTranslation, - titleString: "Select Location", + confirmButtonString: "Submit Request".needTranslation, + titleString: "Select Location".needTranslation, subTitleString: "Please select the location".needTranslation, isGmsAvailable: appState.isGMSAvailable, ), diff --git a/lib/features/hmg_services/hmg_services_repo.dart b/lib/features/hmg_services/hmg_services_repo.dart index 254d309..4103569 100644 --- a/lib/features/hmg_services/hmg_services_repo.dart +++ b/lib/features/hmg_services/hmg_services_repo.dart @@ -5,12 +5,21 @@ 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/hmg_services/models/req_models/check_activation_e_referral_req_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/cmc_create_new_order_req_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/order_update_req_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/search_e_referral_req_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_all_cities_resp_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/features/my_appointments/models/resp_models/hospital_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; +import 'package:provider/provider.dart'; + +import 'models/req_models/create_e_referral_model.dart'; +import 'models/req_models/send_activation_code_ereferral_req_model.dart'; +import 'models/resq_models/relationship_type_resp_mode.dart'; +import 'models/resq_models/search_e_referral_resp_model.dart'; abstract class HmgServicesRepo { Future>>> getAllComprehensiveCheckupOrders(); @@ -38,6 +47,21 @@ abstract class HmgServicesRepo { required int orderServiceID, required List services, }); + + Future>>> getRelationshipTypes(); + + Future>>> getAllCities(); + + Future>> sendEReferralActivationCode(SendActivationCodeForEReferralRequestModel requestModel); + + Future>> checkEReferralActivationCode(CheckActivationCodeForEReferralRequestModel requestModel); + + Future>> createEReferral(CreateEReferralRequestModel requestModel); + + + Future>>> searchEReferral(SearchEReferralRequestModel requestModel); + + } class HmgServicesRepoImp implements HmgServicesRepo { @@ -519,4 +543,278 @@ class HmgServicesRepoImp implements HmgServicesRepo { return Left(UnknownFailure(e.toString())); } } + + + /*e-referral functions*/ + + + @override + Future>>> getRelationshipTypes() async { + Map requestBody = {}; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getAllRelationshipTypes, + body: requestBody, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + List relationshipList = []; + + if (response['List_EReferralResult'] != null && response['List_EReferralResult'] is List) { + final servicesList = response['List_EReferralResult'] as List; + + for (var serviceJson in servicesList) { + if (serviceJson is Map) { + relationshipList.add(GetAllRelationshipTypeResponseModel.fromJson(serviceJson)); + } + } + } + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: relationshipList, + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in getAllCmcServices: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>>> getAllCities() async { + Map requestBody = {}; + + try { + GenericApiModel>? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getAllCities, + body: requestBody, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + List citiesList = []; + + if (response['ListCities'] != null && response['ListCities'] is List) { + final servicesList = response['ListCities'] as List; + + for (var serviceJson in servicesList) { + if (serviceJson is Map) { + citiesList.add(GetAllCitiesResponseModel.fromJson(serviceJson)); + } + } + } + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: citiesList, + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in getAllCmcServices: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + + + @override + Future>> sendEReferralActivationCode(SendActivationCodeForEReferralRequestModel requestModel) async { + GenericApiModel? apiResponse; + try { + + Failure? failure; + await apiClient.post( + ApiConsts.sendActivationCodeForEReferral, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + + + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response['LogInTokenID'] as String, + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in getAllCmcServices: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + + @override + Future>> createEReferral(CreateEReferralRequestModel requestModel) async { + GenericApiModel? apiResponse; + try { + Failure? failure; + await apiClient.post( + ApiConsts.createEReferral, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response['ReferralNumber'].toString(), + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in getAllCmcServices: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + + + @override + Future>> checkEReferralActivationCode(CheckActivationCodeForEReferralRequestModel requestModel) async { + GenericApiModel? apiResponse; + try { + Failure? failure; + await apiClient.post( + ApiConsts.checkActivationCodeForEReferral, + body: requestModel.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: response['IsAuthenticated'].toString(), + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in getAllCmcServices: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + + + + @override + Future>>> searchEReferral(SearchEReferralRequestModel requestBody) async { + + + try { + GenericApiModel>? apiResponse; + Failure? failure; + + await apiClient.post( + ApiConsts.getEReferrals, + body: requestBody.toJson(), + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + loggerService.logError("EReferral Services API Failed: $error, Status: $statusCode"); + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + List searchReferral = []; + + if (response['List_EReferrals'] != null && response['List_EReferrals'] is List) { + final servicesList = response['List_EReferrals'] as List; + + for (var serviceJson in servicesList) { + if (serviceJson is Map) { + searchReferral.add(SearchEReferralResponseModel.fromJson(serviceJson)); + } + } + } + + apiResponse = GenericApiModel>( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: errorMessage, + data: searchReferral, + ); + } catch (e) { + loggerService.logError("Error parsing E-Referral services: ${e.toString()}"); + failure = DataParsingFailure(e.toString()); + } + }, + ); + + if (failure != null) return Left(failure!); + if (apiResponse == null) return Left(ServerFailure("Unknown error")); + return Right(apiResponse!); + } catch (e) { + log("Unknown error in Search Referral: ${e.toString()}"); + return Left(UnknownFailure(e.toString())); + } + } + } diff --git a/lib/features/hmg_services/hmg_services_view_model.dart b/lib/features/hmg_services/hmg_services_view_model.dart index 24b7fff..81cd060 100644 --- a/lib/features/hmg_services/hmg_services_view_model.dart +++ b/lib/features/hmg_services/hmg_services_view_model.dart @@ -1,19 +1,31 @@ import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_repo.dart'; import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_repo.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/cmc_create_new_order_req_model.dart'; import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/order_update_req_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/search_e_referral_req_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_all_cities_resp_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/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart'; import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; import 'package:hmg_patient_app_new/services/error_handler_service.dart'; +import 'package:hmg_patient_app_new/services/navigation_service.dart'; + +import 'models/req_models/check_activation_e_referral_req_model.dart'; +import 'models/resq_models/relationship_type_resp_mode.dart'; class HmgServicesViewModel extends ChangeNotifier { final HmgServicesRepo hmgServicesRepo; final BookAppointmentsRepo bookAppointmentsRepo; final ErrorHandlerService errorHandlerService; + final NavigationService navigationService; + HmgServicesViewModel({required this.bookAppointmentsRepo, required this.hmgServicesRepo, required this.errorHandlerService, required this.navigationService}); - HmgServicesViewModel({required this.bookAppointmentsRepo, required this.hmgServicesRepo, required this.errorHandlerService}); bool isCmcOrdersLoading = false; bool isCmcServicesLoading = false; @@ -41,6 +53,12 @@ class HmgServicesViewModel extends ChangeNotifier { // HHC order creation state (no hospital selection needed for home healthcare) GetCMCServicesResponseModel? selectedServiceForHhcOrder; + + List relationTypes =[]; + List getAllCitiesList =[]; + List searchReferralList =[]; + + Future getOrdersList() async {} // HHC multiple services selection List selectedHhcServices = []; @@ -512,4 +530,262 @@ class HmgServicesViewModel extends ChangeNotifier { selectedHhcServices.clear(); notifyListeners(); } + + /*e-referral functions*/ + + Future getRelationshipType({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + notifyListeners(); + final result = await hmgServicesRepo.getRelationshipTypes(); + + result.fold( + (failure) async { + + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + + if (apiResponse.messageStatus == 1) { + relationTypes = apiResponse.data ?? []; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + + Future getAllCities({ + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + notifyListeners(); + final result = await hmgServicesRepo.getAllCities(); + + result.fold( + (failure) async { + + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + + if (apiResponse.messageStatus == 1) { + getAllCitiesList = apiResponse.data ?? []; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + Future eReferralSendActivationCode({ + required SendActivationCodeForEReferralRequestModel requestModel, + Function(GenericApiModel)? onSuccess, + Function(String)? onError, + }) async { + + notifyListeners(); + + final result = await hmgServicesRepo.sendEReferralActivationCode(requestModel); + + result.fold( + (failure) async { + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + if (apiResponse.messageStatus == 1) { + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + Future checkEReferralActivationCode({ + required CheckActivationCodeForEReferralRequestModel requestModel, + Function(GenericApiModel)? onSuccess, + Function(String)? onError, + }) async { + + notifyListeners(); + + final result = await hmgServicesRepo.checkEReferralActivationCode(requestModel); + + result.fold( + (failure) async { + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + if (apiResponse.messageStatus == 1) { + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + + Future createEReferral({ + required CreateEReferralRequestModel requestModel, + Function(GenericApiModel)? onSuccess, + Function(String)? onError, + }) async { + + notifyListeners(); + + final result = await hmgServicesRepo.createEReferral(requestModel); + + result.fold( + (failure) async { + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + if (apiResponse.messageStatus == 1) { + + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + + + Future searchEReferral({ + required SearchEReferralRequestModel requestModel, + Function(dynamic)? onSuccess, + Function(String)? onError, + }) async { + + notifyListeners(); + + final result = await hmgServicesRepo.searchEReferral(requestModel); + + result.fold( + (failure) async { + + notifyListeners(); + await errorHandlerService.handleError(failure: failure); + if (onError != null) { + onError(failure.toString()); + } + }, + (apiResponse) { + + if (apiResponse.messageStatus == 1) { + searchReferralList = apiResponse.data ?? []; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } else { + notifyListeners(); + if (onError != null) { + onError(apiResponse.errorMessage ?? 'Unknown error'); + } + } + }, + ); + } + + Future navigateToOTPScreen( + {required OTPTypeEnum otpTypeEnum, + required String phoneNumber, + required String loginToken, + required Function onSuccess, + }) async { + + navigationService.pushToOtpScreen( + phoneNumber: phoneNumber, + isFormFamilyFile: false, + checkActivationCode: (int activationCode) async { + + checkEReferralActivationCode( + requestModel: CheckActivationCodeForEReferralRequestModel( + logInTokenID: loginToken, + activationCode: activationCode.toString(), + ), + onSuccess: (GenericApiModel response) { + onSuccess(); + }, + onError: (String errorMessage) { + print(errorMessage); + }, + ); + }, + onResendOTPPressed: (String phoneNumber) async { + // await sendActivationCode( + // otpTypeEnum: otpTypeEnum, + // phoneNumber: phoneNumberController.text, + // nationalIdOrFileNumber: nationalIdController.text, + // isForRegister: isComingFromRegister, + // isComingFromResendOTP: true, + // payload: payload, + // isFormFamilyFile: isFormFamilyFile, + // isExcludedUser: isExcludedUser, + // responseID: responseID, + // ); + }, + ); + } + } diff --git a/lib/features/hmg_services/models/req_models/check_activation_e_referral_req_model.dart b/lib/features/hmg_services/models/req_models/check_activation_e_referral_req_model.dart new file mode 100644 index 0000000..a356616 --- /dev/null +++ b/lib/features/hmg_services/models/req_models/check_activation_e_referral_req_model.dart @@ -0,0 +1,57 @@ +class CheckActivationCodeForEReferralRequestModel { + String? logInTokenID; + String? activationCode; + double? versionID; + int? channel; + int? languageID; + String? iPAdress; + String? generalid; + int? patientOutSA; + dynamic sessionID; + bool? isDentalAllowedBackend; + int? deviceTypeID; + + CheckActivationCodeForEReferralRequestModel( + {this.logInTokenID, + this.activationCode, + this.versionID, + this.channel, + this.languageID, + this.iPAdress, + this.generalid, + this.patientOutSA, + this.sessionID, + this.isDentalAllowedBackend, + this.deviceTypeID}); + + CheckActivationCodeForEReferralRequestModel.fromJson( + Map json) { + logInTokenID = json['LogInTokenID']; + activationCode = json['activationCode']; + versionID = json['VersionID']; + channel = json['Channel']; + languageID = json['LanguageID']; + iPAdress = json['IPAdress']; + generalid = json['generalid']; + patientOutSA = json['PatientOutSA']; + sessionID = json['SessionID']; + isDentalAllowedBackend = json['isDentalAllowedBackend']; + deviceTypeID = json['DeviceTypeID']; + } + + Map toJson() { + final Map data = new Map(); + data['LogInTokenID'] = this.logInTokenID; + data['activationCode'] = this.activationCode; + data['VersionID'] = this.versionID; + data['Channel'] = this.channel; + data['LanguageID'] = this.languageID; + data['IPAdress'] = this.iPAdress; + data['generalid'] = this.generalid; + data['PatientOutSA'] = this.patientOutSA; + data['SessionID'] = this.sessionID; + data['isDentalAllowedBackend'] = this.isDentalAllowedBackend; + data['DeviceTypeID'] = this.deviceTypeID; + return data; + } +} diff --git a/lib/features/hmg_services/models/req_models/create_e_referral_model.dart b/lib/features/hmg_services/models/req_models/create_e_referral_model.dart new file mode 100644 index 0000000..1b351fd --- /dev/null +++ b/lib/features/hmg_services/models/req_models/create_e_referral_model.dart @@ -0,0 +1,155 @@ +class CreateEReferralRequestModel { + bool? isInsuredPatient; + String? cityCode; + String? cityName; + String? requesterName; + String? requesterContactNo; + int? requesterRelationship; + String? otherRelationship; + String? fullName; + int? identificationNo; + String? patientMobileNumber; + int? preferredBranchCode; + String? preferredBranchName; + List? medicalReportAttachment; + dynamic insuranceCardAttachment; + double? versionID; + int? channel; + int? languageID; + String? iPAdress; + String? generalid; + int? patientOutSA; + String? sessionID; + bool? isDentalAllowedBackend; + int? deviceTypeID; + int? patientID; + String? tokenID; + int? patientTypeID; + int? patientType; + + CreateEReferralRequestModel( + {this.isInsuredPatient, + this.cityCode, + this.cityName, + this.requesterName, + this.requesterContactNo, + this.requesterRelationship, + this.otherRelationship, + this.fullName, + this.identificationNo, + this.patientMobileNumber, + this.preferredBranchCode, + this.preferredBranchName, + this.medicalReportAttachment, + this.insuranceCardAttachment, + this.versionID, + this.channel, + this.languageID, + this.iPAdress, + this.generalid, + this.patientOutSA, + this.sessionID, + this.isDentalAllowedBackend, + this.deviceTypeID, + this.patientID, + this.tokenID, + this.patientTypeID, + this.patientType}); + + CreateEReferralRequestModel.fromJson(Map json) { + isInsuredPatient = json['IsInsuredPatient']; + cityCode = json['CityCode']; + cityName = json['CityName']; + requesterName = json['RequesterName']; + requesterContactNo = json['RequesterContactNo']; + requesterRelationship = json['RequesterRelationship']; + otherRelationship = json['OtherRelationship']; + fullName = json['FullName']; + identificationNo = json['IdentificationNo']; + patientMobileNumber = json['PatientMobileNumber']; + preferredBranchCode = json['PreferredBranchCode']; + preferredBranchName = json['PreferredBranchName']; + if (json['MedicalReportAttachment'] != null) { + medicalReportAttachment = []; + json['MedicalReportAttachment'].forEach((v) { + medicalReportAttachment!.add(EReferralAttachment.fromJson(v)); + }); + } + insuranceCardAttachment = json['InsuranceCardAttachment'] != null ? EReferralAttachment.fromJson(json['InsuranceCardAttachment']) : null; + versionID = json['VersionID']; + channel = json['Channel']; + languageID = json['LanguageID']; + iPAdress = json['IPAdress']; + generalid = json['generalid']; + patientOutSA = json['PatientOutSA']; + sessionID = json['SessionID']; + isDentalAllowedBackend = json['isDentalAllowedBackend']; + deviceTypeID = json['DeviceTypeID']; + patientID = json['PatientID']; + tokenID = json['TokenID']; + patientTypeID = json['PatientTypeID']; + patientType = json['PatientType']; + } + + Map toJson() { + final Map data = new Map(); + data['IsInsuredPatient'] = this.isInsuredPatient; + data['CityCode'] = this.cityCode; + data['CityName'] = this.cityName; + data['RequesterName'] = this.requesterName; + data['RequesterContactNo'] = this.requesterContactNo; + data['RequesterRelationship'] = this.requesterRelationship; + data['OtherRelationship'] = this.otherRelationship; + data['FullName'] = this.fullName; + data['IdentificationNo'] = this.identificationNo; + data['PatientMobileNumber'] = this.patientMobileNumber; + data['PreferredBranchCode'] = this.preferredBranchCode; + data['PreferredBranchName'] = this.preferredBranchName; + if (this.medicalReportAttachment != null) { + // FIXED: Use map() to convert each item to JSON, then convert to list + data['MedicalReportAttachment'] = this.medicalReportAttachment!.map((v) => v.toJson()).toList(); + } + if (this.insuranceCardAttachment == null) { + data['InsuranceCardAttachment'] = {}; + } else if (this.insuranceCardAttachment is EReferralAttachment) { + // FIXED: Check if it's an EReferralAttachment before calling toJson() + data['InsuranceCardAttachment'] = (this.insuranceCardAttachment as EReferralAttachment).toJson(); + } else { + // If it's something else, assign directly + data['InsuranceCardAttachment'] = this.insuranceCardAttachment; + } + data['VersionID'] = this.versionID; + data['Channel'] = this.channel; + data['LanguageID'] = this.languageID; + data['IPAdress'] = this.iPAdress; + data['generalid'] = this.generalid; + data['PatientOutSA'] = this.patientOutSA; + data['SessionID'] = this.sessionID; + data['isDentalAllowedBackend'] = this.isDentalAllowedBackend; + data['DeviceTypeID'] = this.deviceTypeID; + data['PatientID'] = this.patientID; + data['TokenID'] = this.tokenID; + data['PatientTypeID'] = this.patientTypeID; + data['PatientType'] = this.patientType; + return data; + } +} + +class EReferralAttachment { + String? fileName; + String? base64String; + + EReferralAttachment({this.fileName, this.base64String}); + + EReferralAttachment.fromJson(Map json) { + fileName = json['FileName']; + base64String = json['Base64String']; + } + + Map toJson() { + final Map data = new Map(); + data['FileName'] = this.fileName; + data['Base64String'] = this.base64String; + return data; + } +} \ No newline at end of file diff --git a/lib/features/hmg_services/models/req_models/create_e_referral_req_model.dart b/lib/features/hmg_services/models/req_models/create_e_referral_req_model.dart new file mode 100644 index 0000000..0672fe6 --- /dev/null +++ b/lib/features/hmg_services/models/req_models/create_e_referral_req_model.dart @@ -0,0 +1,150 @@ +class CreateEReferralRequestModel { + bool? isInsuredPatient; + String? cityCode; + String? cityName; + String? requesterName; + String? requesterContactNo; + int? requesterRelationship; + String? otherRelationship; + String? fullName; + int? identificationNo; + String? patientMobileNumber; + int? preferredBranchCode; + String? preferredBranchName; + List? medicalReportAttachment; + dynamic insuranceCardAttachment; + double? versionID; + int? channel; + int? languageID; + String? iPAdress; + String? generalid; + int? patientOutSA; + String? sessionID; + bool? isDentalAllowedBackend; + int? deviceTypeID; + int? patientID; + String? tokenID; + int? patientTypeID; + int? patientType; + + CreateEReferralRequestModel( + {this.isInsuredPatient, + this.cityCode, + this.cityName, + this.requesterName, + this.requesterContactNo, + this.requesterRelationship, + this.otherRelationship, + this.fullName, + this.identificationNo, + this.patientMobileNumber, + this.preferredBranchCode, + this.preferredBranchName, + this.medicalReportAttachment, + this.insuranceCardAttachment, + this.versionID, + this.channel, + this.languageID, + this.iPAdress, + this.generalid, + this.patientOutSA, + this.sessionID, + this.isDentalAllowedBackend, + this.deviceTypeID, + this.patientID, + this.tokenID, + this.patientTypeID, + this.patientType}); + + CreateEReferralRequestModel.fromJson(Map json) { + isInsuredPatient = json['IsInsuredPatient']; + cityCode = json['CityCode']; + cityName = json['CityName']; + requesterName = json['RequesterName']; + requesterContactNo = json['RequesterContactNo']; + requesterRelationship = json['RequesterRelationship']; + otherRelationship = json['OtherRelationship']; + fullName = json['FullName']; + identificationNo = json['IdentificationNo']; + patientMobileNumber = json['PatientMobileNumber']; + preferredBranchCode = json['PreferredBranchCode']; + preferredBranchName = json['PreferredBranchName']; + if (json['MedicalReportAttachment'] != null) { + medicalReportAttachment = []; + json['MedicalReportAttachment'].forEach((v) { + medicalReportAttachment!.add(EReferralAttachment.fromJson(v)); + }); + } + insuranceCardAttachment = json['InsuranceCardAttachment'] != null ? EReferralAttachment.fromJson(json['InsuranceCardAttachment']) : null; + versionID = json['VersionID']; + channel = json['Channel']; + languageID = json['LanguageID']; + iPAdress = json['IPAdress']; + generalid = json['generalid']; + patientOutSA = json['PatientOutSA']; + sessionID = json['SessionID']; + isDentalAllowedBackend = json['isDentalAllowedBackend']; + deviceTypeID = json['DeviceTypeID']; + patientID = json['PatientID']; + tokenID = json['TokenID']; + patientTypeID = json['PatientTypeID']; + patientType = json['PatientType']; + } + + Map toJson() { + final Map data = new Map(); + data['IsInsuredPatient'] = this.isInsuredPatient; + data['CityCode'] = this.cityCode; + data['CityName'] = this.cityName; + data['RequesterName'] = this.requesterName; + data['RequesterContactNo'] = this.requesterContactNo; + data['RequesterRelationship'] = this.requesterRelationship; + data['OtherRelationship'] = this.otherRelationship; + data['FullName'] = this.fullName; + data['IdentificationNo'] = this.identificationNo; + data['PatientMobileNumber'] = this.patientMobileNumber; + data['PreferredBranchCode'] = this.preferredBranchCode; + data['PreferredBranchName'] = this.preferredBranchName; + if (this.medicalReportAttachment != null) { + data['MedicalReportAttachment'] = this.medicalReportAttachment!.map((v) => v.toJson()).toList(); + } + if (this.insuranceCardAttachment == null) { + data['InsuranceCardAttachment'] = {}; + } else + data['InsuranceCardAttachment'] = this.insuranceCardAttachment.toJson(); + + data['VersionID'] = this.versionID; + data['Channel'] = this.channel; + data['LanguageID'] = this.languageID; + data['IPAdress'] = this.iPAdress; + data['generalid'] = this.generalid; + data['PatientOutSA'] = this.patientOutSA; + data['SessionID'] = this.sessionID; + data['isDentalAllowedBackend'] = this.isDentalAllowedBackend; + data['DeviceTypeID'] = this.deviceTypeID; + data['PatientID'] = this.patientID; + data['TokenID'] = this.tokenID; + data['PatientTypeID'] = this.patientTypeID; + data['PatientType'] = this.patientType; + return data; + } +} + +class EReferralAttachment { + String? fileName; + String? base64String; + + EReferralAttachment({this.fileName, this.base64String}); + + EReferralAttachment.fromJson(Map json) { + fileName = json['FileName']; + base64String = json['Base64String']; + } + + Map toJson() { + final Map data = new Map(); + data['FileName'] = this.fileName; + data['Base64String'] = this.base64String; + return data; + } +} diff --git a/lib/features/hmg_services/models/req_models/search_e_referral_req_model.dart b/lib/features/hmg_services/models/req_models/search_e_referral_req_model.dart new file mode 100644 index 0000000..deb3a92 --- /dev/null +++ b/lib/features/hmg_services/models/req_models/search_e_referral_req_model.dart @@ -0,0 +1,60 @@ +class SearchEReferralRequestModel { + String? patientMobileNumber; + double? versionID; + int? channel; + int? languageID; + String? iPAdress; + String? generalid; + int? patientOutSA; + dynamic sessionID; + bool? isDentalAllowedBackend; + int? deviceTypeID; + int? referralNumber; + String? identificationNo; + + SearchEReferralRequestModel( + {this.patientMobileNumber, + this.versionID, + this.channel, + this.languageID, + this.iPAdress, + this.generalid, + this.patientOutSA, + this.sessionID, + this.isDentalAllowedBackend, + this.deviceTypeID, + this.referralNumber, + this.identificationNo}); + + SearchEReferralRequestModel.fromJson(Map json) { + patientMobileNumber = json['PatientMobileNumber']; + versionID = json['VersionID']; + channel = json['Channel']; + languageID = json['LanguageID']; + iPAdress = json['IPAdress']; + generalid = json['generalid']; + patientOutSA = json['PatientOutSA']; + sessionID = json['SessionID']; + isDentalAllowedBackend = json['isDentalAllowedBackend']; + deviceTypeID = json['DeviceTypeID']; + referralNumber = json['ReferralNumber']; + identificationNo = json['IdentificationNo']; + } + + Map toJson() { + final Map data = new Map(); + data['PatientMobileNumber'] = this.patientMobileNumber; + data['VersionID'] = this.versionID; + data['Channel'] = this.channel; + data['LanguageID'] = this.languageID; + data['IPAdress'] = this.iPAdress; + data['generalid'] = this.generalid; + data['PatientOutSA'] = this.patientOutSA; + data['SessionID'] = this.sessionID; + data['isDentalAllowedBackend'] = this.isDentalAllowedBackend; + data['DeviceTypeID'] = this.deviceTypeID; + data['ReferralNumber'] = this.referralNumber; + data['IdentificationNo'] = this.identificationNo; + return data; + } +} diff --git a/lib/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart b/lib/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart new file mode 100644 index 0000000..0380de8 --- /dev/null +++ b/lib/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart @@ -0,0 +1,56 @@ +class SendActivationCodeForEReferralRequestModel { + int? patientMobileNumber; + String? zipCode; + double? versionID; + int? channel; + int? languageID; + String? iPAdress; + String? generalid; + int? patientOutSA; + dynamic sessionID; + bool? isDentalAllowedBackend; + int? deviceTypeID; + + SendActivationCodeForEReferralRequestModel( + {this.patientMobileNumber, + this.zipCode, + this.versionID, + this.channel, + this.languageID, + this.iPAdress, + this.generalid, + this.patientOutSA, + this.sessionID, + this.isDentalAllowedBackend, + this.deviceTypeID}); + + SendActivationCodeForEReferralRequestModel.fromJson(Map json) { + patientMobileNumber = json['PatientMobileNumber']; + zipCode = json['ZipCode']; + versionID = json['VersionID']; + channel = json['Channel']; + languageID = json['LanguageID']; + iPAdress = json['IPAdress']; + generalid = json['generalid']; + patientOutSA = json['PatientOutSA']; + sessionID = json['SessionID']; + isDentalAllowedBackend = json['isDentalAllowedBackend']; + deviceTypeID = json['DeviceTypeID']; + } + + Map toJson() { + final Map data = new Map(); + data['PatientMobileNumber'] = this.patientMobileNumber; + data['ZipCode'] = this.zipCode; + data['VersionID'] = this.versionID; + data['Channel'] = this.channel; + data['LanguageID'] = this.languageID; + data['IPAdress'] = this.iPAdress; + data['generalid'] = this.generalid; + data['PatientOutSA'] = this.patientOutSA; + data['SessionID'] = this.sessionID; + data['isDentalAllowedBackend'] = this.isDentalAllowedBackend; + data['DeviceTypeID'] = this.deviceTypeID; + return data; + } +} diff --git a/lib/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart b/lib/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart new file mode 100644 index 0000000..efc3d58 --- /dev/null +++ b/lib/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart @@ -0,0 +1,21 @@ +class GetAllCitiesResponseModel { + int? iD; + String? description; + String? descriptionN; + + GetAllCitiesResponseModel({this.iD, this.description, this.descriptionN}); + + GetAllCitiesResponseModel.fromJson(Map json) { + iD = json['ID']; + description = json['Description']; + descriptionN = json['DescriptionN']; + } + + Map toJson() { + final Map data = new Map(); + data['ID'] = this.iD; + data['Description'] = this.description; + data['DescriptionN'] = this.descriptionN; + return data; + } +} diff --git a/lib/features/hmg_services/models/resq_models/relationship_type_resp_mode.dart b/lib/features/hmg_services/models/resq_models/relationship_type_resp_mode.dart new file mode 100644 index 0000000..237017d --- /dev/null +++ b/lib/features/hmg_services/models/resq_models/relationship_type_resp_mode.dart @@ -0,0 +1,25 @@ +class GetAllRelationshipTypeResponseModel { + int? iD; + String? text; + String? textAr; + String? textEn; + + GetAllRelationshipTypeResponseModel( + {this.iD, this.text, this.textAr, this.textEn}); + + GetAllRelationshipTypeResponseModel.fromJson(Map json) { + iD = json['ID']; + text = json['Text']; + textAr = json['Text_Ar']; + textEn = json['Text_En']; + } + + Map toJson() { + final Map data = new Map(); + data['ID'] = this.iD; + data['Text'] = this.text; + data['Text_Ar'] = this.textAr; + data['Text_En'] = this.textEn; + return data; + } +} diff --git a/lib/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart b/lib/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart new file mode 100644 index 0000000..df72930 --- /dev/null +++ b/lib/features/hmg_services/models/resq_models/search_e_referral_resp_model.dart @@ -0,0 +1,161 @@ +import 'dart:convert'; + +class SearchEReferralResponseModel { + dynamic acceptedBrachCode; + dynamic acceptedBranchName; + dynamic acceptedBranchNameAr; + dynamic channel; + dynamic identityCardAttachment; + String? identityNumber; + dynamic insuranceCardAttachment; + bool? isInsuredPatient; + List? medicalReportAttachment; + String? otherRelationship; + String? patientContactNo; + int? patientId; + String? patientName; + dynamic preferredBranchCode; + dynamic preferredBranchName; + String? referralDate; + int? referralNumber; + RelationshipType? relationshipType; + String? requesterContactNo; + String? requesterName; + String? status; + String? statusAr; + + SearchEReferralResponseModel({ + this.acceptedBrachCode, + this.acceptedBranchName, + this.acceptedBranchNameAr, + this.channel, + this.identityCardAttachment, + this.identityNumber, + this.insuranceCardAttachment, + this.isInsuredPatient, + this.medicalReportAttachment, + this.otherRelationship, + this.patientContactNo, + this.patientId, + this.patientName, + this.preferredBranchCode, + this.preferredBranchName, + this.referralDate, + this.referralNumber, + this.relationshipType, + this.requesterContactNo, + this.requesterName, + this.status, + this.statusAr, + }); + + factory SearchEReferralResponseModel.fromRawJson(String str) => SearchEReferralResponseModel.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory SearchEReferralResponseModel.fromJson(Map json) => SearchEReferralResponseModel( + acceptedBrachCode: json["AcceptedBrachCode"], + acceptedBranchName: json["AcceptedBranchName"], + acceptedBranchNameAr: json["AcceptedBranchNameAr"], + channel: json["Channel"], + identityCardAttachment: json["IdentityCardAttachment"], + identityNumber: json["IdentityNumber"], + insuranceCardAttachment: json["InsuranceCardAttachment"], + isInsuredPatient: json["IsInsuredPatient"], + medicalReportAttachment: json["MedicalReportAttachment"] == null ? [] : List.from(json["MedicalReportAttachment"]!.map((x) => MedicalReportAttachment.fromJson(x))), + otherRelationship: json["OtherRelationship"], + patientContactNo: json["PatientContactNo"], + patientId: json["PatientId"], + patientName: json["PatientName"], + preferredBranchCode: json["PreferredBranchCode"], + preferredBranchName: json["PreferredBranchName"], + referralDate: json["ReferralDate"], + referralNumber: json["ReferralNumber"], + relationshipType: json["RelationshipType"] == null ? null : RelationshipType.fromJson(json["RelationshipType"]), + requesterContactNo: json["RequesterContactNo"], + requesterName: json["RequesterName"], + status: json["Status"], + statusAr: json["StatusAr"], + ); + + Map toJson() => { + "AcceptedBrachCode": acceptedBrachCode, + "AcceptedBranchName": acceptedBranchName, + "AcceptedBranchNameAr": acceptedBranchNameAr, + "Channel": channel, + "IdentityCardAttachment": identityCardAttachment, + "IdentityNumber": identityNumber, + "InsuranceCardAttachment": insuranceCardAttachment, + "IsInsuredPatient": isInsuredPatient, + "MedicalReportAttachment": medicalReportAttachment == null ? [] : List.from(medicalReportAttachment!.map((x) => x.toJson())), + "OtherRelationship": otherRelationship, + "PatientContactNo": patientContactNo, + "PatientId": patientId, + "PatientName": patientName, + "PreferredBranchCode": preferredBranchCode, + "PreferredBranchName": preferredBranchName, + "ReferralDate": referralDate, + "ReferralNumber": referralNumber, + "RelationshipType": relationshipType?.toJson(), + "RequesterContactNo": requesterContactNo, + "RequesterName": requesterName, + "Status": status, + "StatusAr": statusAr, + }; +} + +class MedicalReportAttachment { + String? base64String; + String? fileName; + + MedicalReportAttachment({ + this.base64String, + this.fileName, + }); + + factory MedicalReportAttachment.fromRawJson(String str) => MedicalReportAttachment.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory MedicalReportAttachment.fromJson(Map json) => MedicalReportAttachment( + base64String: json["Base64String"], + fileName: json["FileName"], + ); + + Map toJson() => { + "Base64String": base64String, + "FileName": fileName, + }; +} + +class RelationshipType { + int? id; + String? text; + String? textAr; + String? textEn; + + RelationshipType({ + this.id, + this.text, + this.textAr, + this.textEn, + }); + + factory RelationshipType.fromRawJson(String str) => RelationshipType.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory RelationshipType.fromJson(Map json) => RelationshipType( + id: json["ID"], + text: json["Text"], + textAr: json["Text_Ar"], + textEn: json["Text_En"], + ); + + Map toJson() => { + "ID": id, + "Text": text, + "Text_Ar": textAr, + "Text_En": textEn, + }; +} diff --git a/lib/features/hmg_services/models/ui_models/e_referral_form_model.dart b/lib/features/hmg_services/models/ui_models/e_referral_form_model.dart new file mode 100644 index 0000000..32964b1 --- /dev/null +++ b/lib/features/hmg_services/models/ui_models/e_referral_form_model.dart @@ -0,0 +1,48 @@ +// models/referral_models.dart +import 'package:hmg_patient_app_new/core/common_models/nationality_country_model.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/relationship_type_resp_mode.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; + +class ReferralFormData { + String requesterName = ''; + String requesterPhone = ''; + String searchPhone =''; + CountryEnum countryEnum = CountryEnum.saudiArabia; + CountryEnum patientCountryEnum = CountryEnum.saudiArabia; + + GetAllRelationshipTypeResponseModel? relationship; + String otherRelationshipName = ''; + + String patientIdentification = ''; + String patientName = ''; + String patientPhone = ''; + GetAllCitiesResponseModel? patientCity; + + List medicalReportImages = []; + HospitalsModel? branch; + bool isPatientInsured = false; + List insuredPatientImages = []; +} + +class FormValidationErrors { + String? requesterName; + String? requesterPhone; + String? relationship; + String? otherRelationshipName; + + String? patientIdentification; + String? patientName; + String? patientCity; + String? patientPhone; + + + String? medicalReport; + String? branch; + String? insuredDocument; + + String? searchValue; + String? searchPhone; +} \ No newline at end of file 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 d5180ae..d6e2654 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 @@ -5,21 +5,26 @@ class HmgServicesComponentModel { String title; String subTitle; String icon; + Color? iconColor; bool isLogin; bool isLocked; Color bgColor; Color textColor; - String route; + String? route; + Function? onTap; HmgServicesComponentModel( this.action, this.title, this.subTitle, this.icon, + this.isLogin, { this.isLocked = false, this.bgColor = Colors.white, this.textColor = Colors.black, - this.route = '', + this.iconColor = Colors.white, + this.route, + this.onTap }); } diff --git a/lib/features/immediate_livecare/immediate_livecare_view_model.dart b/lib/features/immediate_livecare/immediate_livecare_view_model.dart index 599bc39..1baa81b 100644 --- a/lib/features/immediate_livecare/immediate_livecare_view_model.dart +++ b/lib/features/immediate_livecare/immediate_livecare_view_model.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/cupertino.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/cache_consts.dart'; @@ -36,6 +38,10 @@ class ImmediateLiveCareViewModel extends ChangeNotifier { late AppState _appState; + Duration countdownDuration = Duration(minutes: 1, seconds: 0); + late ValueNotifier durationNotifier; + late Timer timer; + initImmediateLiveCare() { _appState = getIt(); immediateLiveCareClinicsList = []; @@ -144,7 +150,11 @@ class ImmediateLiveCareViewModel extends ChangeNotifier { patientLiveCareHistoryList = apiResponse.data!; if (patientLiveCareHistoryList.isNotEmpty) { if (patientLiveCareHistoryList[0].callStatus! < 4) { + countdownDuration = Duration(seconds: 0); patientHasPendingLiveCareRequest = true; + countdownDuration = Duration(minutes: patientLiveCareHistoryList.first.watingtimeInteger!, seconds: 0); + durationNotifier = ValueNotifier(countdownDuration); + startTimer(); } else { patientHasPendingLiveCareRequest = false; } @@ -159,4 +169,20 @@ class ImmediateLiveCareViewModel extends ChangeNotifier { }, ); } + + void startTimer() { + timer = Timer.periodic(const Duration(seconds: 1), (_) => addTime()); + notifyListeners(); + } + + void addTime() { + final seconds = durationNotifier.value.inSeconds - 1; + if (seconds < 0) { + timer?.cancel(); + // Handle end of timer here + // showEndMessage(); + } else { + durationNotifier.value = Duration(seconds: seconds); + } + } } diff --git a/lib/features/insurance/insurance_view_model.dart b/lib/features/insurance/insurance_view_model.dart index 8460bd4..30f4c26 100644 --- a/lib/features/insurance/insurance_view_model.dart +++ b/lib/features/insurance/insurance_view_model.dart @@ -78,10 +78,12 @@ class InsuranceViewModel extends ChangeNotifier { // (failure) async => await errorHandlerService.handleError(failure: failure), (failure) async { isInsuranceLoading = false; + isInsuranceDataToBeLoaded = false; notifyListeners(); }, (apiResponse) { if (apiResponse.messageStatus == 2) { + isInsuranceDataToBeLoaded = false; // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); } else if (apiResponse.messageStatus == 1) { patientInsuranceList = apiResponse.data!; diff --git a/lib/features/lab/lab_view_model.dart b/lib/features/lab/lab_view_model.dart index bad4f89..24aa244 100644 --- a/lib/features/lab/lab_view_model.dart +++ b/lib/features/lab/lab_view_model.dart @@ -289,7 +289,7 @@ class LabViewModel extends ChangeNotifier { ); } - Future getPatientLabResult(PatientLabOrdersResponseModel laborder, String procedureName, String testDescription) async { + Future getPatientLabResult(PatientLabOrdersResponseModel laborder, String procedureName, String testDescription, String unitOfMeasure) async { LoaderBottomSheet.showLoader(); mainLabResults.clear(); filteredGraphValues.clear(); @@ -339,6 +339,7 @@ class LabViewModel extends ChangeNotifier { } catch (e) {} }); LabResult recentResult = recentThree.first; + recentResult.uOM = unitOfMeasure; checkIfGraphShouldBeDisplayed(recentResult); recentResult.verifiedOn = resultDate(DateUtil.convertStringToDate(recentResult.verifiedOnDateTime!)); // filteredGraphValues = [filteredGraphValues.first]; diff --git a/lib/features/my_appointments/models/resp_models/patient_appointment_share_response_model.dart b/lib/features/my_appointments/models/resp_models/patient_appointment_share_response_model.dart index 2021fff..1dc1cbe 100644 --- a/lib/features/my_appointments/models/resp_models/patient_appointment_share_response_model.dart +++ b/lib/features/my_appointments/models/resp_models/patient_appointment_share_response_model.dart @@ -141,7 +141,7 @@ class PatientAppointmentShareResponseModel { doctorID = json['DoctorID']; doctorImageURL = json['DoctorImageURL']; doctorNameObj = json['DoctorNameObj']; - doctorSpeciality = json['DoctorSpeciality'].cast(); + // doctorSpeciality = json['DoctorSpeciality'].cast(); errCode = json['ErrCode']; groupID = json['GroupID']; iSAllowOnlineCheckedIN = json['ISAllowOnlineCheckedIN']; diff --git a/lib/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart b/lib/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart new file mode 100644 index 0000000..c221e90 --- /dev/null +++ b/lib/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart @@ -0,0 +1,318 @@ +class PrescriptionDeliveryResponseModel { + int? iD; + int? patientId; + int? patientOutSa; + bool? isOutPatient; + int? projectId; + int? nearestProjectId; + dynamic longitude; + dynamic latitude; + dynamic appointmentNo; + dynamic dischargeId; + int? statusId; + int? serviceId; + int? channel; + Orderpayment? orderpayment; + dynamic orderselectedservice; + dynamic wforder; + dynamic orderapprovalobj; + String? created; + dynamic createdBy; + dynamic modified; + dynamic modifiedBy; + bool? isDeleted; + String? statusText; + int? paymentStatus; + dynamic clientRequestid; + dynamic paymentStatusText; + String? projectName; + String? nearestProjectName; + dynamic paymentAmount; + WFOrder? wFOrder; + String? serviceText; + bool? isSentForApproval; + int? exaCartOrderId; + bool? isTimer; + int? timeSeconds; + int? totalPendingSeconds; + int? timeMinute; + int? timeHour; + int? timeTotalSeconds; + int? timeTotalMinute; + int? timeTotalHour; + dynamic approvalStatus; + bool? isActive; + int? clickButton; + List? procedures; + dynamic pickupLocation; + dynamic dropOffLocation; + dynamic clinicName; + dynamic doctorName; + dynamic branch; + dynamic time; + dynamic notes; + + PrescriptionDeliveryResponseModel( + {this.iD, + this.patientId, + this.patientOutSa, + this.isOutPatient, + this.projectId, + this.nearestProjectId, + this.longitude, + this.latitude, + this.appointmentNo, + this.dischargeId, + this.statusId, + this.serviceId, + this.channel, + this.orderpayment, + this.orderselectedservice, + this.wforder, + this.orderapprovalobj, + this.created, + this.createdBy, + this.modified, + this.modifiedBy, + this.isDeleted, + this.statusText, + this.paymentStatus, + this.clientRequestid, + this.paymentStatusText, + this.projectName, + this.nearestProjectName, + this.paymentAmount, + this.wFOrder, + this.serviceText, + this.isSentForApproval, + this.exaCartOrderId, + this.isTimer, + this.timeSeconds, + this.totalPendingSeconds, + this.timeMinute, + this.timeHour, + this.timeTotalSeconds, + this.timeTotalMinute, + this.timeTotalHour, + this.approvalStatus, + this.isActive, + this.clickButton, + this.procedures, + this.pickupLocation, + this.dropOffLocation, + this.clinicName, + this.doctorName, + this.branch, + this.time, + this.notes}); + + PrescriptionDeliveryResponseModel.fromJson(Map json) { + iD = json['ID']; + patientId = json['PatientId']; + patientOutSa = json['PatientOutSa']; + isOutPatient = json['IsOutPatient']; + projectId = json['ProjectId']; + nearestProjectId = json['NearestProjectId']; + longitude = json['Longitude']; + latitude = json['Latitude']; + appointmentNo = json['AppointmentNo']; + dischargeId = json['DischargeId']; + statusId = json['StatusId']; + serviceId = json['ServiceId']; + channel = json['Channel']; + orderpayment = json['orderpayment'] != null ? new Orderpayment.fromJson(json['orderpayment']) : null; + orderselectedservice = json['orderselectedservice']; + wforder = json['wforder']; + orderapprovalobj = json['orderapprovalobj']; + created = json['Created']; + createdBy = json['CreatedBy']; + modified = json['Modified']; + modifiedBy = json['ModifiedBy']; + isDeleted = json['IsDeleted']; + statusText = json['StatusText']; + paymentStatus = json['PaymentStatus']; + clientRequestid = json['ClientRequestid']; + paymentStatusText = json['PaymentStatusText']; + projectName = json['ProjectName']; + nearestProjectName = json['NearestProjectName']; + paymentAmount = json['PaymentAmount']; + wFOrder = json['WF_order'] != null ? new WFOrder.fromJson(json['WF_order']) : null; + serviceText = json['ServiceText']; + isSentForApproval = json['isSentForApproval']; + exaCartOrderId = json['ExaCart_OrderId']; + isTimer = json['isTimer']; + timeSeconds = json['TimeSeconds']; + totalPendingSeconds = json['TotalPendingSeconds']; + timeMinute = json['TimeMinute']; + timeHour = json['TimeHour']; + timeTotalSeconds = json['TimeTotalSeconds']; + timeTotalMinute = json['TimeTotalMinute']; + timeTotalHour = json['TimeTotalHour']; + approvalStatus = json['ApprovalStatus']; + isActive = json['isActive']; + clickButton = json['ClickButton']; + pickupLocation = json['PickupLocation']; + dropOffLocation = json['DropOffLocation']; + clinicName = json['clinicName']; + doctorName = json['DoctorName']; + branch = json['Branch']; + time = json['Time']; + notes = json['Notes']; + } + + Map toJson() { + final Map data = new Map(); + data['ID'] = this.iD; + data['PatientId'] = this.patientId; + data['PatientOutSa'] = this.patientOutSa; + data['IsOutPatient'] = this.isOutPatient; + data['ProjectId'] = this.projectId; + data['NearestProjectId'] = this.nearestProjectId; + data['Longitude'] = this.longitude; + data['Latitude'] = this.latitude; + data['AppointmentNo'] = this.appointmentNo; + data['DischargeId'] = this.dischargeId; + data['StatusId'] = this.statusId; + data['ServiceId'] = this.serviceId; + data['Channel'] = this.channel; + if (this.orderpayment != null) { + data['orderpayment'] = this.orderpayment!.toJson(); + } + data['orderselectedservice'] = this.orderselectedservice; + + data['wforder'] = this.wforder; + data['orderapprovalobj'] = this.orderapprovalobj; + data['Created'] = this.created; + data['CreatedBy'] = this.createdBy; + data['Modified'] = this.modified; + data['ModifiedBy'] = this.modifiedBy; + data['IsDeleted'] = this.isDeleted; + data['StatusText'] = this.statusText; + data['PaymentStatus'] = this.paymentStatus; + data['ClientRequestid'] = this.clientRequestid; + data['PaymentStatusText'] = this.paymentStatusText; + data['ProjectName'] = this.projectName; + data['NearestProjectName'] = this.nearestProjectName; + data['PaymentAmount'] = this.paymentAmount; + if (this.wFOrder != null) { + data['WF_order'] = this.wFOrder!.toJson(); + } + data['ServiceText'] = this.serviceText; + data['isSentForApproval'] = this.isSentForApproval; + data['ExaCart_OrderId'] = this.exaCartOrderId; + data['isTimer'] = this.isTimer; + data['TimeSeconds'] = this.timeSeconds; + data['TotalPendingSeconds'] = this.totalPendingSeconds; + data['TimeMinute'] = this.timeMinute; + data['TimeHour'] = this.timeHour; + data['TimeTotalSeconds'] = this.timeTotalSeconds; + data['TimeTotalMinute'] = this.timeTotalMinute; + data['TimeTotalHour'] = this.timeTotalHour; + data['ApprovalStatus'] = this.approvalStatus; + data['isActive'] = this.isActive; + data['ClickButton'] = this.clickButton; + data['PickupLocation'] = this.pickupLocation; + data['DropOffLocation'] = this.dropOffLocation; + data['clinicName'] = this.clinicName; + data['DoctorName'] = this.doctorName; + data['Branch'] = this.branch; + data['Time'] = this.time; + data['Notes'] = this.notes; + return data; + } +} + +class Orderpayment { + int? iD; + int? orderId; + dynamic clientRequestId; + dynamic totalAmount; + int? paymentStatus; + dynamic order; + String? created; + dynamic createdBy; + dynamic modified; + dynamic modifiedBy; + bool? isDeleted; + + Orderpayment({this.iD, this.orderId, this.clientRequestId, this.totalAmount, this.paymentStatus, this.order, this.created, this.createdBy, this.modified, this.modifiedBy, this.isDeleted}); + + Orderpayment.fromJson(Map json) { + iD = json['ID']; + orderId = json['OrderId']; + clientRequestId = json['ClientRequestId']; + totalAmount = json['TotalAmount']; + paymentStatus = json['PaymentStatus']; + order = json['Order']; + created = json['Created']; + createdBy = json['CreatedBy']; + modified = json['Modified']; + modifiedBy = json['ModifiedBy']; + isDeleted = json['IsDeleted']; + } + + Map toJson() { + final Map data = new Map(); + data['ID'] = this.iD; + data['OrderId'] = this.orderId; + data['ClientRequestId'] = this.clientRequestId; + data['TotalAmount'] = this.totalAmount; + data['PaymentStatus'] = this.paymentStatus; + data['Order'] = this.order; + data['Created'] = this.created; + data['CreatedBy'] = this.createdBy; + data['Modified'] = this.modified; + data['ModifiedBy'] = this.modifiedBy; + data['IsDeleted'] = this.isDeleted; + return data; + } +} + +class WFOrder { + dynamic wfButtonsDTO; + int? iD; + int? orderId; + int? previousStep; + int? nextStep; + int? serviceId; + dynamic order; + String? created; + dynamic createdBy; + dynamic modified; + dynamic modifiedBy; + bool? isDeleted; + + WFOrder({this.wfButtonsDTO, this.iD, this.orderId, this.previousStep, this.nextStep, this.serviceId, this.order, this.created, this.createdBy, this.modified, this.modifiedBy, this.isDeleted}); + + WFOrder.fromJson(Map json) { + wfButtonsDTO = json['wf_ButtonsDTO']; + iD = json['ID']; + orderId = json['OrderId']; + previousStep = json['PreviousStep']; + nextStep = json['NextStep']; + serviceId = json['ServiceId']; + order = json['Order']; + created = json['Created']; + createdBy = json['CreatedBy']; + modified = json['Modified']; + modifiedBy = json['ModifiedBy']; + isDeleted = json['IsDeleted']; + } + + Map toJson() { + final Map data = new Map(); + data['wf_ButtonsDTO'] = this.wfButtonsDTO; + data['ID'] = this.iD; + data['OrderId'] = this.orderId; + data['PreviousStep'] = this.previousStep; + data['NextStep'] = this.nextStep; + data['ServiceId'] = this.serviceId; + data['Order'] = this.order; + data['Created'] = this.created; + data['CreatedBy'] = this.createdBy; + data['Modified'] = this.modified; + data['ModifiedBy'] = this.modifiedBy; + data['IsDeleted'] = this.isDeleted; + return data; + } +} diff --git a/lib/features/prescriptions/prescriptions_repo.dart b/lib/features/prescriptions/prescriptions_repo.dart index 2e3f1aa..e7a4f07 100644 --- a/lib/features/prescriptions/prescriptions_repo.dart +++ b/lib/features/prescriptions/prescriptions_repo.dart @@ -5,6 +5,7 @@ import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart'; import 'package:dartz/dartz.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/patient_prescriptions_response_model.dart'; +import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_detail_response_model.dart'; import 'package:hmg_patient_app_new/services/logger_service.dart'; @@ -15,7 +16,13 @@ abstract class PrescriptionsRepo { Future>> getPrescriptionInstructionsPDF({required PatientPrescriptionsResponseModel prescriptionsResponseModel}); - Future>> getPrescriptionPDF({required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List prescriptionDetailsList}); + Future>> getPrescriptionPDF( + {required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List prescriptionDetailsList}); + + Future>> submitPrescriptionDeliveryRequest( + {required String latitude, required String longitude, required String appointmentNo, required String dischargeID, required String projectID}); + + Future>> getPrescriptionOrdersList(); } class PrescriptionsRepoImp implements PrescriptionsRepo { @@ -158,7 +165,8 @@ class PrescriptionsRepoImp implements PrescriptionsRepo { } @override - Future> getPrescriptionPDF({required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List prescriptionDetailsList}) async { + Future> getPrescriptionPDF( + {required PatientPrescriptionsResponseModel prescriptionsResponseModel, required List prescriptionDetailsList}) async { Map mapDevice = { "AppointmentDate": prescriptionsResponseModel.appointmentDate, "ClinicName": prescriptionsResponseModel.clinicDescription, @@ -206,4 +214,84 @@ class PrescriptionsRepoImp implements PrescriptionsRepo { return Left(UnknownFailure(e.toString())); } } + + @override + Future> submitPrescriptionDeliveryRequest( + {required String latitude, required String longitude, required String appointmentNo, required String dischargeID, required String projectID}) async { + Map mapDevice = { + "latitude": latitude, + "longitude": longitude, + "AppointmentNo": appointmentNo, + "DischargeID": dischargeID, + "ProjectID": projectID, + }; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + isRCService: true, + ADD_PRESCRIPTION_ORDER_RC, + body: mapDevice, + 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())); + } + } + + @override + Future> getPrescriptionOrdersList() async { + Map mapDevice = {}; + + try { + GenericApiModel? apiResponse; + Failure? failure; + await apiClient.post( + isRCService: true, + GET_ALL_PRESCRIPTION_ORDERS_RC, + body: mapDevice, + onFailure: (error, statusCode, {messageStatus, failureType}) { + failure = failureType; + }, + onSuccess: (response, statusCode, {messageStatus, errorMessage}) { + try { + + final prescriptionOrders = response['response'].map((item) => PrescriptionDeliveryResponseModel.fromJson(item as Map)).toList().cast(); + + apiResponse = GenericApiModel( + messageStatus: messageStatus, + statusCode: statusCode, + errorMessage: null, + data: prescriptionOrders, + ); + } 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/prescriptions/prescriptions_view_model.dart b/lib/features/prescriptions/prescriptions_view_model.dart index aac25c1..7517134 100644 --- a/lib/features/prescriptions/prescriptions_view_model.dart +++ b/lib/features/prescriptions/prescriptions_view_model.dart @@ -1,8 +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/location_util.dart'; +import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; +import 'package:hmg_patient_app_new/features/location/GeocodeResponse.dart'; +import 'package:hmg_patient_app_new/features/location/PlaceDetails.dart'; +import 'package:hmg_patient_app_new/features/location/PlacePrediction.dart'; +import 'package:hmg_patient_app_new/features/location/location_view_model.dart'; +import 'package:hmg_patient_app_new/core/dependencies.dart'; +import 'package:hmg_patient_app_new/core/utils/calender_utils_new.dart'; import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/patient_prescriptions_response_model.dart'; +import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_delivery_response_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/prescription_detail_response_model.dart'; import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_repo.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_delivery_order_summary_page.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/map/map_utility_screen.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; class PrescriptionsViewModel extends ChangeNotifier { bool isPrescriptionsOrdersLoading = false; @@ -10,6 +28,7 @@ class PrescriptionsViewModel extends ChangeNotifier { PrescriptionsRepo prescriptionsRepo; ErrorHandlerService errorHandlerService; + NavigationService navServices; // Prescription Orders Lists List patientPrescriptionOrders = []; @@ -27,19 +46,31 @@ class PrescriptionsViewModel extends ChangeNotifier { String prescriptionPDFBase64Data = ""; - PrescriptionsViewModel({required this.prescriptionsRepo, required this.errorHandlerService}); + late GeocodeResponse locationGeocodeResponse; + + bool isPrescriptionsDeliveryOrdersLoading = false; + 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; isSortByClinic = true; + isPrescriptionsDeliveryOrdersLoading = true; getPatientPrescriptionOrders(); notifyListeners(); } + + checkIfReminderExistForPrescription(int index) async { + prescriptionDetailsList[index].hasReminder = await CalenderUtilsNew.instance.checkIfEventExist(prescriptionDetailsList[index].itemID?.toString() ?? ""); + } + setPrescriptionsDetailsLoading() { isPrescriptionsDetailsLoading = true; prescriptionDetailsList.clear(); @@ -121,6 +152,9 @@ class PrescriptionsViewModel extends ChangeNotifier { // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {}); } else if (apiResponse.messageStatus == 1) { prescriptionDetailsList = apiResponse.data!; + prescriptionDetailsList.forEach((element) async { + await checkIfReminderExistForPrescription(prescriptionDetailsList.indexOf(element)); + }); isPrescriptionsDetailsLoading = false; notifyListeners(); if (onSuccess != null) { @@ -173,4 +207,92 @@ class PrescriptionsViewModel extends ChangeNotifier { }, ); } + + showError(String errorMessage) { + getIt().showErrorBottomSheet(message: errorMessage); + } + + Future submitPrescriptionDeliveryRequest( + {required String latitude, + required String longitude, + required String appointmentNo, + required String dischargeID, + required String projectID, + Function(dynamic)? onSuccess, + Function(String)? onError}) async { + final result = await prescriptionsRepo.submitPrescriptionDeliveryRequest(latitude: latitude, longitude: longitude, appointmentNo: appointmentNo, dischargeID: dischargeID, projectID: projectID); + + result.fold( + (failure) async { + onError!(failure.message); + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + onError!(apiResponse.errorMessage!); + } else if (apiResponse.messageStatus == 1) { + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } + + void initiatePrescriptionDelivery() async { + getIt.get().getLocation( + isShowConfirmDialog: true, + onSuccess: (position) async { + bool result = await navServices.push( + CustomPageRoute( + page: MapUtilityScreen( + confirmButtonString: LocaleKeys.next.tr(), + titleString: "Select Location".needTranslation, + subTitleString: "Please select the location for prescription delivery".needTranslation, + isGmsAvailable: getIt.get().isGMSAvailable, + ), + direction: AxisDirection.down), + ); + print("Location Selected: $result"); + if (result) { + LocationViewModel locationViewModel = getIt.get(); + locationGeocodeResponse = locationViewModel.geocodeResponse!; + navServices.push( + CustomPageRoute( + page: PrescriptionDeliveryOrderSummaryPage(), + ), + ); + } + }); + } + + Future getPrescriptionOrdersList({Function(dynamic)? onSuccess, Function(String)? onError}) async { + isPrescriptionsDeliveryOrdersLoading = true; + prescriptionsOrderList.clear(); + notifyListeners(); + + final result = await prescriptionsRepo.getPrescriptionOrdersList(); + + result.fold( + (failure) async { + isPrescriptionsDeliveryOrdersLoading = false; + notifyListeners(); + onError!(failure.message); + }, + (apiResponse) { + if (apiResponse.messageStatus == 2) { + isPrescriptionsDeliveryOrdersLoading = false; + notifyListeners(); + onError!(apiResponse.errorMessage!); + } else if (apiResponse.messageStatus == 1) { + isPrescriptionsDeliveryOrdersLoading = false; + prescriptionsOrderList = apiResponse.data!; + notifyListeners(); + if (onSuccess != null) { + onSuccess(apiResponse); + } + } + }, + ); + } } diff --git a/lib/presentation/appointments/appointment_details_page.dart b/lib/presentation/appointments/appointment_details_page.dart index 4c725aa..a2b7475 100644 --- a/lib/presentation/appointments/appointment_details_page.dart +++ b/lib/presentation/appointments/appointment_details_page.dart @@ -1,10 +1,15 @@ import 'dart:async'; +import 'dart:collection'; +import 'dart:io'; +import 'package:device_calendar/device_calendar.dart'; 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/app_state.dart'; +import 'package:hmg_patient_app_new/core/utils/calender_utils_new.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'; @@ -58,11 +63,15 @@ class _AppointmentDetailsPageState extends State { @override void initState() { - scheduleMicrotask(() { - // if (AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)) { - // prescriptionsViewModel.setPrescriptionsDetailsLoading(); - // prescriptionsViewModel.getPrescriptionDetails(getPrescriptionRequestModel()); - // } + scheduleMicrotask(() async { + CalenderUtilsNew calendarUtils = await CalenderUtilsNew.instance; + var doesExist = await calendarUtils.checkIfEventExist("${widget.patientAppointmentHistoryResponseModel.appointmentNo}"); + print("the appointment reminder exist $doesExist"); + myAppointmentsViewModel.setAppointmentReminder(doesExist, widget.patientAppointmentHistoryResponseModel); + setState((){ + + }); + }); super.initState(); } @@ -130,6 +139,10 @@ class _AppointmentDetailsPageState extends State { }, onCancelTap: () async { myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true); + var isEventAddedOrRemoved = await CalenderUtilsNew.instance.checkAndRemove( id:"${widget.patientAppointmentHistoryResponseModel.appointmentNo}", ); + setState(() { + myAppointmentsViewModel.setAppointmentReminder(isEventAddedOrRemoved, widget.patientAppointmentHistoryResponseModel); + }); LoaderBottomSheet.showLoader(loadingText: "Cancelling Appointment, Please Wait...".needTranslation); await myAppointmentsViewModel.cancelAppointment( patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, @@ -268,10 +281,54 @@ class _AppointmentDetailsPageState extends State { // activeThumbColor: AppColors.successColor, activeTrackColor: AppColors.successColor.withValues(alpha: .15), value: widget.patientAppointmentHistoryResponseModel.hasReminder!, - onChanged: (newValue) { - setState(() { - myAppointmentsViewModel.setAppointmentReminder(newValue, widget.patientAppointmentHistoryResponseModel); - }); + onChanged: (newValue) async { + CalenderUtilsNew calender = CalenderUtilsNew.instance; + bool isEventAddedOrRemoved = false; + if(newValue == true){ + DateTime startDate = DateTime.now(); + DateTime endDate = DateUtil.convertStringToDate(widget + .patientAppointmentHistoryResponseModel.appointmentDate); + BottomSheetUtils().showReminderBottomSheet( + context, + endDate, + widget.patientAppointmentHistoryResponseModel.doctorNameObj??"", + "${widget.patientAppointmentHistoryResponseModel.appointmentNo}"??"", + "", + "", + title: "Appointment with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj}".needTranslation, + description:"${widget.patientAppointmentHistoryResponseModel.doctorNameObj} will be having an appointment on ${widget.patientAppointmentHistoryResponseModel.appointmentDate}".needTranslation, + onSuccess: () { + setState(() { + myAppointmentsViewModel.setAppointmentReminder(newValue, widget.patientAppointmentHistoryResponseModel); + }); + }, + isMultiAllowed: true, + 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}", + scheduleDateTime: DateUtil.convertStringToDate(widget + .patientAppointmentHistoryResponseModel.appointmentDate), + eventId: "${widget.patientAppointmentHistoryResponseModel.appointmentNo}", + location: '', + reminderMinutes: selectedIndex + ); + setState(() { + myAppointmentsViewModel.setAppointmentReminder(isEventAddedOrRemoved, widget.patientAppointmentHistoryResponseModel); + }); + }, + ); + }else { + isEventAddedOrRemoved = await calender.checkAndRemove( id:"${widget.patientAppointmentHistoryResponseModel.appointmentNo}", ); + setState(() { + myAppointmentsViewModel.setAppointmentReminder(!isEventAddedOrRemoved, widget.patientAppointmentHistoryResponseModel); + }); + } + + }, ), ], @@ -693,8 +750,8 @@ class _AppointmentDetailsPageState extends State { onPressed: () { openDoctorScheduleCalendar(); }, - backgroundColor: AppColors.primaryRedColor, - borderColor: AppColors.primaryRedColor, + backgroundColor: AppColors.successColor, + borderColor: AppColors.successColor, textColor: AppColors.whiteColor, fontSize: 16.f, fontWeight: FontWeight.w500, diff --git a/lib/presentation/appointments/widgets/appointment_card.dart b/lib/presentation/appointments/widgets/appointment_card.dart index 3cf56a6..7bc9c62 100644 --- a/lib/presentation/appointments/widgets/appointment_card.dart +++ b/lib/presentation/appointments/widgets/appointment_card.dart @@ -123,22 +123,56 @@ class AppointmentCard extends StatelessWidget { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Image.network( - isLoading - ? 'https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png' - : patientAppointmentHistoryResponseModel.doctorImageURL!, - width: 63.h, - height: 63.h, - fit: BoxFit.cover, - ).circle(100).toShimmer2(isShow: isLoading), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Stack( + children: [ + Image.network( + isLoading ? 'https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png' : patientAppointmentHistoryResponseModel.doctorImageURL!, + width: 63.w, + height: 63.h, + fit: BoxFit.cover, + ), + Positioned( + bottom: 0, + left: 0, + right: 0, + child: Container( + width: 63.w, + height: 20, + color: AppColors.textColorLight.withValues(alpha: 0.25), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.rating_icon, + width: 12.w, + height: 12.h, + fit: BoxFit.contain, + ), + SizedBox(width: 4.w), + isLoading ? "Rating".toText12() : patientAppointmentHistoryResponseModel.decimalDoctorRate.toString().toText12(), + ], + ), + ), + ) + ], + ).circle(100).toShimmer2(isShow: isLoading), + // SizedBox(height: 12.h), + // AppCustomChipWidget( + // icon: AppAssets.rating_icon, + // iconColor: AppColors.ratingColorYellow, + // labelText: isLoading ? "Rating" : "Rating: ${patientAppointmentHistoryResponseModel.decimalDoctorRate}".needTranslation) + // .toShimmer2(isShow: isLoading), + ], + ), SizedBox(width: 16.h), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - (isLoading - ? 'https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png' - : patientAppointmentHistoryResponseModel.doctorNameObj!) + (isLoading ? 'John Doe' : "${patientAppointmentHistoryResponseModel.doctorTitle} ${patientAppointmentHistoryResponseModel.doctorNameObj!}") .toText16(isBold: true, maxlines: 1) .toShimmer2(isShow: isLoading), SizedBox(height: 8.h), @@ -147,26 +181,35 @@ class AppointmentCard extends StatelessWidget { spacing: 3.h, runSpacing: 4.h, children: [ - if (!isFromHomePage) AppCustomChipWidget(labelText: isLoading ? 'Cardiology' : patientAppointmentHistoryResponseModel.clinicName!) .toShimmer2(isShow: isLoading), - if (!isFromHomePage) AppCustomChipWidget(labelText: isLoading ? 'Olaya' : patientAppointmentHistoryResponseModel.projectName!) .toShimmer2(isShow: isLoading), AppCustomChipWidget( icon: AppAssets.appointment_calendar_icon, labelText: isLoading ? 'Cardiology' - : DateUtil.formatDateToDate(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false), + : "${DateUtil.formatDateToDate(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false)} ${DateUtil.formatDateToTimeLang(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false)}", + ).toShimmer2(isShow: isLoading), + AppCustomChipWidget( + isIconPNG: true, + icon: getIt.get().getAuthenticatedUser()?.gender == 1 ? AppAssets.male_img : AppAssets.femaleImg, + iconSize: 18.h, + labelText: isLoading ? 'Cardiology' : "Patient: ${getIt.get().getAuthenticatedUser()!.firstName!}", ).toShimmer2(isShow: isLoading), - if (!isFromMedicalReport) - AppCustomChipWidget( - icon: AppAssets.appointment_time_icon, - labelText: isLoading - ? 'Cardiology' - : DateUtil.formatDateToTimeLang( - DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false), - ).toShimmer2(isShow: isLoading), + // if (!isFromMedicalReport) + // AppCustomChipWidget( + // icon: AppAssets.appointment_time_icon, + // labelText: isLoading + // ? 'Cardiology' + // : DateUtil.formatDateToTimeLang( + // DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false), + // ).toShimmer2(isShow: isLoading), + // AppCustomChipWidget( + // icon: AppAssets.rating_icon, + // iconColor: AppColors.ratingColorYellow, + // labelText: isLoading ? "Rating" : "Rating: ${patientAppointmentHistoryResponseModel.decimalDoctorRate}".needTranslation) + // .toShimmer2(isShow: isLoading), ], ), ], @@ -269,7 +312,6 @@ class AppointmentCard extends StatelessWidget { clinicId: patientAppointmentHistoryResponseModel.clinicID, onSuccess: (value) async { if (value) { - print("Doctor is available"); await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) { LoaderBottomSheet.hideLoader(); showCommonBottomSheetWithoutHeight( diff --git a/lib/presentation/appointments/widgets/appointment_doctor_card.dart b/lib/presentation/appointments/widgets/appointment_doctor_card.dart index 8d0f4e7..b2d74ca 100644 --- a/lib/presentation/appointments/widgets/appointment_doctor_card.dart +++ b/lib/presentation/appointments/widgets/appointment_doctor_card.dart @@ -42,12 +42,18 @@ class AppointmentDoctorCard extends StatelessWidget { Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Image.network( - patientAppointmentHistoryResponseModel.doctorImageURL!, - width: 63.w, - height: 63.h, - fit: BoxFit.cover, - ).circle(100.r), + Column( + children: [ + Image.network( + patientAppointmentHistoryResponseModel.doctorImageURL!, + width: 63.w, + height: 63.h, + fit: BoxFit.cover, + ).circle(100.r), + SizedBox(height: 12.h), + AppCustomChipWidget(icon: AppAssets.rating_icon, iconColor: AppColors.ratingColorYellow, labelText: "Rating: ${patientAppointmentHistoryResponseModel.decimalDoctorRate}"), + ], + ), SizedBox(width: 16.w), Expanded( child: Column( @@ -87,10 +93,6 @@ class AppointmentDoctorCard extends StatelessWidget { !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.greyColor : AppColors.successColor, textColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.textColor : AppColors.whiteColor, ), - AppCustomChipWidget( - icon: AppAssets.rating_icon, - iconColor: AppColors.ratingColorYellow, - labelText: "Rating: ${patientAppointmentHistoryResponseModel.decimalDoctorRate}"), ], ), ], 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 9f06a4d..69cdca3 100644 --- a/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart +++ b/lib/presentation/appointments/widgets/ask_doctor_request_type_select.dart @@ -79,15 +79,15 @@ class AskDoctorRequestTypeSelect extends StatelessWidget { onPressed: () { Navigator.pop(context); }, - backgroundColor: AppColors.primaryRedColor, - borderColor: AppColors.primaryRedColor, - textColor: AppColors.whiteColor, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, icon: AppAssets.cancel, - iconColor: AppColors.whiteColor, + iconColor: AppColors.primaryRedColor, borderRadius: 12.r, - iconSize: 14.h, - fontSize: 14.f, - height: 40.h, + iconSize: 16.5.h, + fontSize: 16.f, + height: 56.h, ), ), SizedBox(width: 8.h), @@ -120,14 +120,15 @@ class AskDoctorRequestTypeSelect extends StatelessWidget { LoaderBottomSheet.hideLoader(); }); }, - backgroundColor: AppColors.bgGreenColor, - borderColor: AppColors.bgGreenColor, - textColor: Colors.white, + backgroundColor: AppColors.bgGreenColor.withValues(alpha: 0.20), + borderColor: AppColors.bgGreenColor.withValues(alpha: 0.0), + textColor: AppColors.bgGreenColor, + iconColor: AppColors.bgGreenColor, icon: AppAssets.confirm, - iconSize: 14.h, + iconSize: 16.5.h, borderRadius: 12.r, - fontSize: 14.f, - height: 40.h, + fontSize: 16.f, + height: 56.h, ), ), ], diff --git a/lib/presentation/authentication/login.dart b/lib/presentation/authentication/login.dart index 7e5f4a1..0fa995d 100644 --- a/lib/presentation/authentication/login.dart +++ b/lib/presentation/authentication/login.dart @@ -1,6 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.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'; @@ -154,7 +155,7 @@ class LoginScreenState extends State { required BuildContext context, required TextEditingController? phoneNumberController, required AuthenticationViewModel authViewModel, - }) { + }) async { AppState appState = getIt(); context.showBottomSheet( isScrollControlled: true, diff --git a/lib/presentation/book_appointment/book_appointment_page.dart b/lib/presentation/book_appointment/book_appointment_page.dart index a66ea4d..8a0f7e7 100644 --- a/lib/presentation/book_appointment/book_appointment_page.dart +++ b/lib/presentation/book_appointment/book_appointment_page.dart @@ -2,20 +2,25 @@ 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'; 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_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/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/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/immediate_livecare/immediate_livecare_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_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart'; import 'package:hmg_patient_app_new/presentation/appointments/widgets/region_bottomsheet/region_list_widget.dart' show RegionBottomSheetBody; +import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/search_doctor_by_name.dart'; @@ -86,6 +91,111 @@ class _BookAppointmentPageState extends State { ).paddingSymmetrical(24.h, 0.h), SizedBox(height: 24.h), getSelectedTabData(bookAppointmentsVM.selectedTabIndex), + SizedBox(height: 24.h), + "Recent Visits".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0.h), + SizedBox(height: 16.h), + Consumer(builder: (context, myAppointmentsVM, child) { + return myAppointmentsVM.isPatientMyDoctorsLoading + ? Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.network( + "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png", + width: 64.w, + height: 64.h, + 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), + ], + ) + : myAppointmentsVM.patientMyDoctorsList.isEmpty + ? Container( + width: SizeConfig.screenWidth, + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 12.r, + hasShadow: false, + ), + child: Utils.getNoDataWidget( + context, + noDataText: "You don't have any completed visits yet".needTranslation, + isSmallWidget: true, + width: 62.w, + height: 62.h, + ), + ).paddingSymmetrical(24.w, 0.h) + : SizedBox( + height: 110.h, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: myAppointmentsVM.patientMyDoctorsList.length, + shrinkWrap: true, + padding: EdgeInsets.only(left: 24.w, right: 24.w), + 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), + SizedBox( + width: 80.w, + 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), + ), + ); + }), ], ); }), diff --git a/lib/presentation/book_appointment/doctor_profile_page.dart b/lib/presentation/book_appointment/doctor_profile_page.dart index 1223842..c3f4ad9 100644 --- a/lib/presentation/book_appointment/doctor_profile_page.dart +++ b/lib/presentation/book_appointment/doctor_profile_page.dart @@ -48,6 +48,7 @@ class DoctorProfilePage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( + crossAxisAlignment: CrossAxisAlignment.start, children: [ Image.network( bookAppointmentsViewModel.doctorsProfileResponseModel.doctorImageURL!, @@ -59,9 +60,12 @@ class DoctorProfilePage extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - ("${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorTitleForProfile} ${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorName}") - .toString() - .toText28(isBold: true), + SizedBox( + width: 220.h, + child: ("${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorTitleForProfile} ${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorName}") + .toString() + .toText24(isBold: true), + ), (bookAppointmentsViewModel.doctorsProfileResponseModel.specialty!.isNotEmpty ? bookAppointmentsViewModel.doctorsProfileResponseModel.specialty!.first : "") .toString() .toText18(weight: FontWeight.w500, color: AppColors.primaryRedColor), @@ -80,18 +84,49 @@ class DoctorProfilePage extends StatelessWidget { SizedBox(height: 12.h), Wrap( direction: Axis.horizontal, - spacing: 3.h, + spacing: 4.h, runSpacing: 4.h, children: [ AppCustomChipWidget( - icon: AppAssets.rating_icon, iconColor: AppColors.ratingColorYellow, - labelText: "Rating: ${bookAppointmentsViewModel.doctorsProfileResponseModel.decimalDoctorRate}".needTranslation, + labelText: "Branch: ${bookAppointmentsViewModel.doctorsProfileResponseModel.projectName}".needTranslation, ), AppCustomChipWidget( - icon: AppAssets.rating_icon, iconColor: AppColors.ratingColorYellow, - labelText: "Reviews: ${bookAppointmentsViewModel.doctorsProfileResponseModel.noOfPatientsRate}".needTranslation, + labelText: "Clinic: ${bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription}".needTranslation, + ), + ], + ), + SizedBox(height: 24.h), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Column( + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.doctor_profile_rating_icon, + width: 48.w, + height: 48.h, + fit: BoxFit.contain, + ), + SizedBox(height: 16.h), + "Ratings".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + bookAppointmentsViewModel.doctorsProfileResponseModel.decimalDoctorRate.toString().toText16(isBold: true, color: AppColors.textColor), + ], + ), + SizedBox(width: 36.w), + Column( + children: [ + Utils.buildSvgWithAssets( + icon: AppAssets.doctor_profile_reviews_icon, + width: 48.w, + height: 48.h, + fit: BoxFit.contain, + ), + SizedBox(height: 16.h), + "Reviews".toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + bookAppointmentsViewModel.doctorsProfileResponseModel.noOfPatientsRate.toString().toText16(isBold: true, color: AppColors.textColor), + ], ), ], ), 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 d16e441..2877b27 100644 --- a/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart +++ b/lib/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart @@ -13,13 +13,16 @@ import 'package:hmg_patient_app_new/features/book_appointments/book_appointments import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart'; import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart'; +import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart'; 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/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/loader/bottomsheet_loader.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; @@ -71,37 +74,17 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { children: [ "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText16(isBold: true), SizedBox(height: 8.h), - AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old"), - ], - ), - ], - ), - ), - ), - SizedBox(height: 24.h), - "Clinic Information".needTranslation.toText16(isBold: true), - SizedBox(height: 16.h), - Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.h, - hasShadow: false, - ), - child: Padding( - padding: EdgeInsets.all(16.h), - child: Row( - children: [ - Utils.buildSvgWithAssets(icon: AppAssets.generic_clinic_icon, width: 32.h, height: 32.h, fit: BoxFit.contain), - SizedBox(width: 8.h), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (appState.isArabic() - ? immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceNameN - : immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceName)! - .toText16(isBold: true), - // SizedBox(height: 8.h), - // AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old"), + Wrap( + direction: Axis.horizontal, + spacing: 3.h, + runSpacing: 4.h, + children: [ + AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old".needTranslation), + AppCustomChipWidget( + labelText: + "${LocaleKeys.clinic.tr()}: ${(appState.isArabic() ? immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceNameN : immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceName)!}"), + ], + ), ], ), ], @@ -220,15 +203,81 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"), ], ).paddingSymmetrical(24.h, 0.h), - CustomButton( - text: LocaleKeys.payNow.tr(context: context), - onPressed: () async { - await askVideoCallPermission().then((val) { - if (val) { - Navigator.of(context).push( - CustomPageRoute( - page: ImmediateLiveCarePaymentPage(), - ), + (immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.total == "0" || immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.total == "0.0") + ? CustomButton( + text: LocaleKeys.confirmLiveCare.tr(context: context), + onPressed: () async { + await askVideoCallPermission().then((val) async { + if (val) { + LoaderBottomSheet.showLoader(loadingText: "Confirming LiveCare request, Please wait...".needTranslation); + + await immediateLiveCareViewModel.addNewCallRequestForImmediateLiveCare("${appState.getAuthenticatedUser()!.patientId}${DateTime.now().millisecondsSinceEpoch}"); + await immediateLiveCareViewModel.getPatientLiveCareHistory(); + LoaderBottomSheet.hideLoader(); + if (immediateLiveCareViewModel.patientHasPendingLiveCareRequest) { + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + Navigator.of(context).push( + CustomPageRoute( + page: ImmediateLiveCarePendingRequestPage(), + ), + ); + } else { + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: "Unknown error occurred...".needTranslation), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + } 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, + ); + } + }); + }, + backgroundColor: AppColors.successColor, + borderColor: AppColors.successColor, + textColor: AppColors.whiteColor, + fontSize: 16, + fontWeight: FontWeight.w500, + borderRadius: 12, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 50.h, + icon: AppAssets.livecare_book_icon, + iconColor: AppColors.whiteColor, + iconSize: 18.h, + ).paddingSymmetrical(24.h, 24.h) + : CustomButton( + text: LocaleKeys.payNow.tr(context: context), + onPressed: () async { + await askVideoCallPermission().then((val) { + if (val) { + Navigator.of(context).push( + CustomPageRoute( + page: ImmediateLiveCarePaymentPage(), + ), ); } else { showCommonBottomSheetWithoutHeight( @@ -236,16 +285,17 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { context, child: Utils.getWarningWidget( loadingText: - "LiveCare requires Camera, Microphone & Location 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, + "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, ); } @@ -272,12 +322,9 @@ class ImmediateLiveCarePaymentDetails extends StatelessWidget { } Future askVideoCallPermission() async { - Map statuses = await [ - Permission.camera, - Permission.microphone, - ].request(); + Map statuses = await [Permission.camera, Permission.microphone, Permission.notification].request(); - if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted) { + if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted && statuses[Permission.notification] == PermissionStatus.granted) { // Camera permission granted return true; } else { diff --git a/lib/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart b/lib/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart index e9e5c5c..8c8b79c 100644 --- a/lib/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart +++ b/lib/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart @@ -16,6 +16,7 @@ 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/countdown_timer.dart'; import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -32,24 +33,24 @@ class _ImmediateLiveCarePendingRequestPageState extends State durationNotifier = ValueNotifier(countdownDuration); - Timer? timer; + // static Duration countdownDuration = Duration(minutes: 1, seconds: 0); + // late ValueNotifier durationNotifier = ValueNotifier(immediateLiveCareViewModel.countdownDuration); + // Timer? timer; @override void initState() { super.initState(); scheduleMicrotask(() { - countdownDuration = Duration(minutes: immediateLiveCareViewModel.patientLiveCareHistoryList[0].watingtimeInteger!, seconds: 0); - durationNotifier = ValueNotifier(countdownDuration); - startTimer(); + // countdownDuration = Duration(minutes: immediateLiveCareViewModel.patientLiveCareHistoryList[0].watingtimeInteger!, seconds: 0); + // durationNotifier = ValueNotifier(immediateLiveCareViewModel.countdownDuration); + // startTimer(); }); } @override void dispose() { - timer?.cancel(); - durationNotifier.dispose(); + // timer?.cancel(); + // durationNotifier.dispose(); super.dispose(); } @@ -85,7 +86,7 @@ class _ImmediateLiveCarePendingRequestPageState extends State( - valueListenable: durationNotifier, + valueListenable: immediateLiveCareVM.durationNotifier, builder: (context, duration, child) { return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -173,133 +174,133 @@ class _ImmediateLiveCarePendingRequestPageState extends State addTime()); - setState(() {}); - } - - void addTime() { - final seconds = durationNotifier.value.inSeconds - 1; - if (seconds < 0) { - timer?.cancel(); - // Handle end of timer here - // showEndMessage(); - } else { - durationNotifier.value = Duration(seconds: seconds); - } - } - - Future _onWillPop() async { - timer?.cancel(); - Navigator.of(context).pop(); - return true; - } - - Widget buildTime(Duration duration) { - String twoDigits(int n) => n.toString().padLeft(2, '0'); - final hours = twoDigits(duration.inHours); - final minutes = twoDigits(duration.inMinutes.remainder(60)); - final seconds = twoDigits(duration.inSeconds.remainder(60)); - - return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - buildTimeColumn(hours, "Hours".needTranslation), - buildTimeColumn(minutes, "Mins".needTranslation), - buildTimeColumn(seconds, "Secs".needTranslation, isLast: true), - ], - ); - } - - Widget buildTimeColumn(String time, String label, {bool isLast = false}) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Row( - children: [ - buildDigit(time[0]), - buildDigit(time[1]), - if (!isLast) buildTimeSeparator(), - ], - ), - buildLabel(label), - ], - ); - } - - Widget buildDigit(String digit) { - return Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), - // margin: const EdgeInsets.symmetric(horizontal: 2), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - ), - child: ClipRect( - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 600), - switchInCurve: Curves.easeOutExpo, - switchOutCurve: Curves.easeInExpo, - transitionBuilder: (Widget child, Animation animation) { - return Stack( - children: [ - SlideTransition( - position: Tween( - begin: const Offset(0, -1), - end: const Offset(0, 1), - ).animate(CurvedAnimation( - parent: animation, - curve: Curves.easeOutCubic, - )), - child: FadeTransition( - opacity: animation, - child: child, - ), - ), - SlideTransition( - position: Tween( - begin: const Offset(0, -1), - end: const Offset(0, 0), - ).animate(CurvedAnimation( - parent: animation, - curve: Curves.bounceIn, - )), - child: FadeTransition( - opacity: animation, - child: child, - ), - ), - ], - ); - }, - child: Text( - digit, - key: ValueKey(digit), - style: TextStyle( - fontWeight: FontWeight.bold, - color: Colors.black, - fontSize: 20.f, - ), - ), - ), - ), - ); - } - - Widget buildLabel(String label) { - return label.toText14(isBold: true); - } - - Widget buildTimeSeparator() { - return const Padding( - padding: EdgeInsets.symmetric(horizontal: 2.0), - child: Text( - ":", - style: TextStyle( - color: Colors.black, - fontSize: 20, - ), - ), - ); - } + // void startTimer() { + // // timer = Timer.periodic(const Duration(seconds: 1), (_) => addTime()); + // // setState(() {}); + // } + // + // void addTime() { + // final seconds = durationNotifier.value.inSeconds - 1; + // if (seconds < 0) { + // timer?.cancel(); + // // Handle end of timer here + // // showEndMessage(); + // } else { + // durationNotifier.value = Duration(seconds: seconds); + // } + // } + // + // Future _onWillPop() async { + // timer?.cancel(); + // Navigator.of(context).pop(); + // return true; + // } + // + // Widget buildTime(Duration duration) { + // String twoDigits(int n) => n.toString().padLeft(2, '0'); + // final hours = twoDigits(duration.inHours); + // final minutes = twoDigits(duration.inMinutes.remainder(60)); + // final seconds = twoDigits(duration.inSeconds.remainder(60)); + // + // return Row( + // mainAxisAlignment: MainAxisAlignment.center, + // children: [ + // buildTimeColumn(hours, "Hours".needTranslation), + // buildTimeColumn(minutes, "Mins".needTranslation), + // buildTimeColumn(seconds, "Secs".needTranslation, isLast: true), + // ], + // ); + // } + // + // Widget buildTimeColumn(String time, String label, {bool isLast = false}) { + // return Column( + // mainAxisAlignment: MainAxisAlignment.center, + // children: [ + // Row( + // children: [ + // buildDigit(time[0]), + // buildDigit(time[1]), + // if (!isLast) buildTimeSeparator(), + // ], + // ), + // buildLabel(label), + // ], + // ); + // } + // + // Widget buildDigit(String digit) { + // return Container( + // padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + // // margin: const EdgeInsets.symmetric(horizontal: 2), + // decoration: BoxDecoration( + // color: Colors.white, + // borderRadius: BorderRadius.circular(8), + // ), + // child: ClipRect( + // child: AnimatedSwitcher( + // duration: const Duration(milliseconds: 600), + // switchInCurve: Curves.easeOutExpo, + // switchOutCurve: Curves.easeInExpo, + // transitionBuilder: (Widget child, Animation animation) { + // return Stack( + // children: [ + // SlideTransition( + // position: Tween( + // begin: const Offset(0, -1), + // end: const Offset(0, 1), + // ).animate(CurvedAnimation( + // parent: animation, + // curve: Curves.easeOutCubic, + // )), + // child: FadeTransition( + // opacity: animation, + // child: child, + // ), + // ), + // SlideTransition( + // position: Tween( + // begin: const Offset(0, -1), + // end: const Offset(0, 0), + // ).animate(CurvedAnimation( + // parent: animation, + // curve: Curves.bounceIn, + // )), + // child: FadeTransition( + // opacity: animation, + // child: child, + // ), + // ), + // ], + // ); + // }, + // child: Text( + // digit, + // key: ValueKey(digit), + // style: TextStyle( + // fontWeight: FontWeight.bold, + // color: Colors.black, + // fontSize: 20.f, + // ), + // ), + // ), + // ), + // ); + // } + // + // Widget buildLabel(String label) { + // return label.toText14(isBold: true); + // } + // + // Widget buildTimeSeparator() { + // return const Padding( + // padding: EdgeInsets.symmetric(horizontal: 2.0), + // child: Text( + // ":", + // style: TextStyle( + // color: Colors.black, + // fontSize: 20, + // ), + // ), + // ); + // } } diff --git a/lib/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart b/lib/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart index 8181d25..15598f3 100644 --- a/lib/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart +++ b/lib/presentation/book_appointment/livecare/select_immediate_livecare_clinic_page.dart @@ -66,35 +66,6 @@ class _SelectImmediateLiveCareClinicPageState extends State(builder: (context, immediateLiveCareVM, child) { return Column( children: [ - // SizedBox(height: 16.h), - // TextInputWidget( - // labelText: LocaleKeys.search.tr(context: context), - // hintText: LocaleKeys.clinicName.tr(context: context), - // controller: searchEditingController, - // isEnable: true, - // prefix: null, - // autoFocus: false, - // isBorderAllowed: false, - // keyboardType: TextInputType.text, - // focusNode: textFocusNode, - // suffix: searchEditingController.text.isNotEmpty - // ? GestureDetector( - // onTap: () { - // searchEditingController.clear(); - // bookAppointmentsViewModel.filterClinics(""); - // textFocusNode.unfocus(); - // }, - // child: Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown), - // ) - // : null, - // onChange: (value) { - // bookAppointmentsViewModel.filterClinics(value!); - // }, - // padding: EdgeInsets.symmetric( - // vertical: ResponsiveExtension(10).h, - // horizontal: ResponsiveExtension(15).h, - // ), - // ), ListView.separated( padding: EdgeInsets.only(top: 16.h), shrinkWrap: true, diff --git a/lib/presentation/book_appointment/livecare/widgets/livecare_clinic_card.dart b/lib/presentation/book_appointment/livecare/widgets/livecare_clinic_card.dart index 7385c6b..3913f10 100644 --- a/lib/presentation/book_appointment/livecare/widgets/livecare_clinic_card.dart +++ b/lib/presentation/book_appointment/livecare/widgets/livecare_clinic_card.dart @@ -12,6 +12,7 @@ import 'package:hmg_patient_app_new/features/immediate_livecare/models/resp_mode import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_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/chip/app_custom_chip_widget.dart'; class LiveCareClinicCard extends StatelessWidget { LiveCareClinicCard({super.key, required this.liveCareClinicListResponseModel, required this.isLoading, required this.immediateLiveCareViewModel}); @@ -34,20 +35,12 @@ class LiveCareClinicCard extends StatelessWidget { 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), - Column( - children: [ - Utils.buildSvgWithAssets( - icon: AppAssets.livecare_online_icon, - width: 16.h, - height: 16.h, - fit: BoxFit.contain, - iconColor: liveCareClinicListResponseModel.isOnline == 1 ? AppColors.successColor : AppColors.primaryRedColor) - .toShimmer2(isShow: isLoading), - SizedBox(height: 4.h), - liveCareClinicListResponseModel.isOnline == 1 - ? LocaleKeys.online.tr(context: context).toText10(isBold: true, color: AppColors.successColor).toShimmer2(isShow: isLoading) - : "Offline".toText10(isBold: true, color: AppColors.primaryRedColor).toShimmer2(isShow: isLoading), - ], + AppCustomChipWidget( + icon: AppAssets.livecare_online_icon, + iconColor: AppColors.whiteColor, + richText: (liveCareClinicListResponseModel.isOnline == 1 ? LocaleKeys.online.tr(context: context) : "Offline".needTranslation).toText10(isBold: true, color: AppColors.whiteColor), + backgroundColor: liveCareClinicListResponseModel.isOnline == 1 ? AppColors.successColor : AppColors.primaryRedColor, + textColor: AppColors.whiteColor, ), ]), SizedBox(height: 8.h), diff --git a/lib/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart b/lib/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart index 226ac50..e4d69b1 100644 --- a/lib/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart +++ b/lib/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart @@ -1,10 +1,14 @@ import 'package:flutter/cupertino.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/book_appointments/book_appointments_view_model.dart'; import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; import 'package:hmg_patient_app_new/presentation/medical_file/widgets/medical_file_card.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; @@ -16,46 +20,30 @@ class SelectLiveCareCallType extends StatelessWidget { @override Widget build(BuildContext context) { //TODO: Replace with actual icons - return GridView( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - crossAxisSpacing: 16, - mainAxisSpacing: 16, - mainAxisExtent: 130, - ), - physics: NeverScrollableScrollPhysics(), - padding: EdgeInsets.zero, - shrinkWrap: true, + return Column( children: [ - MedicalFileCard( - label: "Video Call".needTranslation, - textColor: AppColors.blackColor, - backgroundColor: AppColors.whiteColor, - svgIcon: AppAssets.eye_result_icon, - isLargeText: true, - iconSize: 36.h, + checkInOptionCard( + AppAssets.checkin_location_icon, + "Video Call".needTranslation, + "View your nearest HMG locations".needTranslation, ).onPress(() { Navigator.of(context).pop(); immediateLiveCareViewModel.setLiveCareSelectedCallType(1); }), - MedicalFileCard( - label: "Audio Call".needTranslation, - textColor: AppColors.blackColor, - backgroundColor: AppColors.whiteColor, - svgIcon: AppAssets.allergy_info_icon, - isLargeText: true, - iconSize: 36.h, + SizedBox(height: 16.h), + checkInOptionCard( + AppAssets.checkin_location_icon, + "Audio Call".needTranslation, + "Provide your feedback on our services".needTranslation, ).onPress(() { Navigator.of(context).pop(); immediateLiveCareViewModel.setLiveCareSelectedCallType(2); }), - MedicalFileCard( - label: "Phone Call".needTranslation, - textColor: AppColors.blackColor, - backgroundColor: AppColors.whiteColor, - svgIcon: AppAssets.vaccine_info_icon, - isLargeText: true, - iconSize: 36.h, + SizedBox(height: 16.h), + checkInOptionCard( + AppAssets.checkin_location_icon, + "Phone Call".needTranslation, + "Live chat option with HMG".needTranslation, ).onPress(() { Navigator.of(context).pop(); immediateLiveCareViewModel.setLiveCareSelectedCallType(3); @@ -63,4 +51,45 @@ class SelectLiveCareCallType extends StatelessWidget { ], ); } + + Widget checkInOptionCard(String icon, String title, String subTitle) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + hasShadow: false, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Utils.buildSvgWithAssets(icon: icon, width: 40.h, height: 40.h, fit: BoxFit.fill), + SizedBox(height: 16.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title.toText16(isBold: true, color: AppColors.textColor), + subTitle.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + ], + ), + ), + Transform.flip( + flipX: getIt.get().isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 18.h, + height: 13.h, + fit: BoxFit.contain, + ), + ), + ], + ), + ], + ).paddingAll(16.h), + ); + } } diff --git a/lib/presentation/book_appointment/review_appointment_page.dart b/lib/presentation/book_appointment/review_appointment_page.dart index 4005c37..f76a5b0 100644 --- a/lib/presentation/book_appointment/review_appointment_page.dart +++ b/lib/presentation/book_appointment/review_appointment_page.dart @@ -3,6 +3,7 @@ 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/loading_utils.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; @@ -12,11 +13,15 @@ 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/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/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.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/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +import 'package:hmg_patient_app_new/widgets/loading_dialog.dart'; import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; import 'package:provider/provider.dart'; @@ -113,10 +118,14 @@ class _ReviewAppointmentPageState extends State { labelText: "${LocaleKeys.branch.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.projectName}".needTranslation, ), AppCustomChipWidget( - labelText: "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.selectedAppointmentDate}".needTranslation, + labelText: + "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? DateUtil.formatDateToDate(DateTime.now(), false) : bookAppointmentsViewModel.selectedAppointmentDate}" + .needTranslation, ), AppCustomChipWidget( - labelText: "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.selectedAppointmentTime}".needTranslation, + labelText: + "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? "Waiting Appointment".needTranslation : bookAppointmentsViewModel.selectedAppointmentTime}" + .needTranslation, ), ], ), @@ -185,9 +194,13 @@ class _ReviewAppointmentPageState extends State { hasShadow: true, ), child: CustomButton( - text: LocaleKeys.bookAppo.tr(context: context), + text: bookAppointmentsViewModel.isWaitingAppointmentSelected ? "Add to waiting list" : LocaleKeys.bookAppo.tr(context: context), onPressed: () async { - initiateBookAppointment(); + if (bookAppointmentsViewModel.isWaitingAppointmentSelected) { + getWalkInAppointmentPatientShare(); + } else { + initiateBookAppointment(); + } }, backgroundColor: AppColors.primaryRedColor, borderColor: AppColors.primaryRedColor, @@ -204,6 +217,27 @@ class _ReviewAppointmentPageState extends State { ); } + void getWalkInAppointmentPatientShare() async { + LoaderBottomSheet.showLoader(loadingText: "Fetching Appointment Share...".needTranslation); + await bookAppointmentsViewModel.getWalkInPatientShareAppointment(onSuccess: (val) { + LoaderBottomSheet.hideLoader(); + Navigator.of(context).push( + CustomPageRoute( + page: WaitingAppointmentPaymentPage(), + ), + ); + }, onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + } + void initiateBookAppointment() async { LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: "Booking your appointment...".needTranslation); myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true); diff --git a/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart new file mode 100644 index 0000000..f832db6 --- /dev/null +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_info.dart @@ -0,0 +1,118 @@ +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/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/waiting_appointment/waiting_appointment_online_checkin_sheet.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 WaitingAppointmentInfo extends StatelessWidget { + WaitingAppointmentInfo({super.key}); + + late BookAppointmentsViewModel bookAppointmentsViewModel; + + @override + Widget build(BuildContext context) { + bookAppointmentsViewModel = Provider.of(context, listen: false); + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: Column( + children: [ + Expanded( + child: CollapsingListView( + title: "Waiting Appointment".needTranslation, + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 24.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + 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), + 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), + SizedBox(height: 16.h), + "The appointment with the doctor is confirmed, but the time of entry is uncertain.".needTranslation.toText14(isBold: false), + SizedBox(height: 24.h), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.warning, + size: 20, + color: AppColors.warningColorYellow, + ), + 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), + ), + ], + ), + ], + ), + ), + ), + ], + ).paddingSymmetrical(24.w, 0), + ), + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + child: CustomButton( + text: "Continue".needTranslation, + onPressed: () async { + showCommonBottomSheetWithoutHeight(context, + title: LocaleKeys.onlineCheckIn.tr(), + child: WaitingAppointmentOnlineCheckinSheet( + bookAppointmentsViewModel: bookAppointmentsViewModel, + ), + callBackFunc: () {}, + isFullScreen: false); + }, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedColor, + textColor: AppColors.whiteColor, + fontSize: 16, + fontWeight: FontWeight.w500, + borderRadius: 12, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 50.h, + icon: AppAssets.calendar, + iconColor: AppColors.whiteColor, + iconSize: 20.h, + ).paddingSymmetrical(24.h, 24.h), + ), + ], + ), + ); + } +} 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 new file mode 100644 index 0000000..965844a --- /dev/null +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_online_checkin_sheet.dart @@ -0,0 +1,161 @@ +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'; +import 'package:hmg_patient_app_new/core/app_state.dart'; +import 'package:hmg_patient_app_new/core/common_models/privilege/ProjectDetailListModel.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/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/book_appointments/book_appointments_view_model.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'; +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/nfc/nfc_reader_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; + +class WaitingAppointmentOnlineCheckinSheet extends StatelessWidget { + WaitingAppointmentOnlineCheckinSheet({super.key, required this.bookAppointmentsViewModel}); + + BookAppointmentsViewModel bookAppointmentsViewModel; + + bool _supportsNFC = false; + + late LocationUtils locationUtils; + late AppState appState; + ProjectDetailListModel projectDetailListModel = ProjectDetailListModel(); + + @override + Widget build(BuildContext context) { + appState = getIt.get(); + locationUtils = getIt.get(); + locationUtils.isShowConfirmDialog = true; + FlutterNfcKit.nfcAvailability.then((value) { + _supportsNFC = (value == NFCAvailability.available); + }); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + checkInOptionCard( + AppAssets.checkin_location_icon, + "Live Location".needTranslation, + "Verify your location to be at hospital to check in".needTranslation, + ).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; + print(dist); + if (dist <= projectDetailListModel.geofenceRadius!) { + 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: () { + Navigator.of(context).pop(); + }, isFullScreen: false); + } + }); + }), + SizedBox(height: 16.h), + checkInOptionCard( + AppAssets.checkin_nfc_icon, + "NFC (Near Field Communication)".needTranslation, + "Scan your phone via NFC board to check in".needTranslation, + ).onPress(() { + Future.delayed(const Duration(milliseconds: 500), () { + showNfcReader(context, onNcfScan: (String nfcId) { + Future.delayed(const Duration(milliseconds: 100), () { + checkScannedNFCAndQRCode(nfcId, context); + }); + }, onCancel: () {}); + }); + }), + SizedBox(height: 16.h), + checkInOptionCard( + AppAssets.checkin_qr_icon, + "QR Code".needTranslation, + "Scan QR code with your camera to check in".needTranslation, + ).onPress(() async { + String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent)); + if (onlineCheckInQRCode != "") { + checkScannedNFCAndQRCode(onlineCheckInQRCode, context); + } else {} + }), + ], + ); + } + + Widget checkInOptionCard(String icon, String title, String subTitle) { + return Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Utils.buildSvgWithAssets(icon: icon, width: 40.h, height: 40.h, fit: BoxFit.fill), + SizedBox(height: 16.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title.toText16(isBold: true, color: AppColors.textColor), + subTitle.toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor), + ], + ), + ), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 18.h, + height: 13.h, + fit: BoxFit.contain, + ), + ), + ], + ), + ], + ).paddingAll(16.h), + ); + } + + void checkScannedNFCAndQRCode(String scannedCode, BuildContext context) async { + LoaderBottomSheet.showLoader(loadingText: "Processing Check-In...".needTranslation); + bookAppointmentsViewModel.checkScannedNFCAndQRCode( + scannedCode, + bookAppointmentsViewModel.waitingAppointmentProjectID, + onSuccess: (value) { + LoaderBottomSheet.hideLoader(); + bookAppointmentsViewModel.setIsWaitingAppointmentSelected(true); + Navigator.of(context).push( + CustomPageRoute( + page: ReviewAppointmentPage(), + ), + ); + }, + onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight(context, title: "Error".needTranslation, 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 new file mode 100644 index 0000000..8f9943c --- /dev/null +++ b/lib/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart @@ -0,0 +1,644 @@ +import 'dart:async'; +import 'dart:developer'; +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/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_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/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/features/payfort/models/apple_pay_request_insert_model.dart'; +import 'package:hmg_patient_app_new/features/payfort/payfort_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/presentation/insurance/insurance_home_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: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/in_app_browser/InAppBrowser.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'; +import 'package:smooth_corner/smooth_corner.dart'; + +class WaitingAppointmentPaymentPage extends StatefulWidget { + WaitingAppointmentPaymentPage({super.key}); + + // PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel; + + @override + State createState() => _WaitingAppointmentPaymentPageState(); +} + +class _WaitingAppointmentPaymentPageState extends State { + late BookAppointmentsViewModel bookAppointmentsViewModel; + late MyAppointmentsViewModel myAppointmentsViewModel; + late PayfortViewModel payfortViewModel; + late AppState appState; + + MyInAppBrowser? browser; + String selectedPaymentMethod = ""; + + String transID = ""; + + bool isShowTamara = false; + String tamaraPaymentStatus = ""; + String tamaraOrderID = ""; + + @override + void initState() { + scheduleMicrotask(() { + payfortViewModel.initPayfortViewModel(); + payfortViewModel.setIsApplePayConfigurationLoading(false); + // myAppointmentsViewModel.getPatientShareAppointment( + // widget.patientAppointmentHistoryResponseModel.projectID, + // widget.patientAppointmentHistoryResponseModel.clinicID, + // widget.patientAppointmentHistoryResponseModel.appointmentNo.toString(), widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false, onSuccess: (val) { + // myAppointmentsViewModel.getTamaraInstallmentsDetails().then((val) { + // if (myAppointmentsViewModel.patientAppointmentShareResponseModel!.patientShareWithTax! >= myAppointmentsViewModel.getTamaraInstallmentsDetailsResponseModel!.minLimit!.amount! && + // myAppointmentsViewModel.patientAppointmentShareResponseModel!.patientShareWithTax! <= myAppointmentsViewModel.getTamaraInstallmentsDetailsResponseModel!.maxLimit!.amount!) { + // setState(() { + // isShowTamara = true; + // }); + // } + // }); + // }, onError: (err) { + // Navigator.of(context).pop(); + // Navigator.of(context).pop(); + // }); + }); + super.initState(); + } + + @override + Widget build(BuildContext context) { + appState = getIt.get(); + bookAppointmentsViewModel = Provider.of(context); + myAppointmentsViewModel = Provider.of(context); + payfortViewModel = Provider.of(context); + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: Consumer(builder: (context, bookAppointmentsVM, child) { + return Column( + children: [ + Expanded( + child: CollapsingListView( + title: "Appointment Payment".needTranslation, + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 24.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Row( + mainAxisSize: MainAxisSize.max, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Image.asset(AppAssets.mada, width: 72.h, height: 25.h), + SizedBox(height: 16.h), + "Mada".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(width: 8.h), + const Spacer(), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 18.h, + height: 13.h, + fit: BoxFit.contain, + ), + ), + ], + ).paddingSymmetrical(16.h, 16.h), + ).paddingSymmetrical(24.h, 0.h).onPress(() { + selectedPaymentMethod = "MADA"; + openPaymentURL("mada"); + }), + SizedBox(height: 16.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Row( + mainAxisSize: MainAxisSize.max, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Image.asset(AppAssets.visa, width: 50.h, height: 50.h), + SizedBox(width: 8.h), + Image.asset(AppAssets.Mastercard, width: 40.h, height: 40.h), + ], + ), + SizedBox(height: 16.h), + "Visa or Mastercard".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(width: 8.h), + const Spacer(), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 18.h, + height: 13.h, + fit: BoxFit.contain, + ), + ), + ], + ).paddingSymmetrical(16.h, 16.h), + ).paddingSymmetrical(24.h, 0.h).onPress(() { + selectedPaymentMethod = "VISA"; + openPaymentURL("visa"); + }), + SizedBox(height: 16.h), + isShowTamara + ? Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.h, + hasShadow: false, + ), + child: Row( + mainAxisSize: MainAxisSize.max, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Image.asset(AppAssets.tamara_en, width: 72.h, height: 25.h), + SizedBox(height: 16.h), + "Tamara".needTranslation.toText16(isBold: true), + ], + ), + SizedBox(width: 8.h), + const Spacer(), + Transform.flip( + flipX: appState.isArabic(), + child: Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 18.h, + height: 13.h, + fit: BoxFit.contain, + ), + ), + ], + ).paddingSymmetrical(16.h, 16.h), + ).paddingSymmetrical(24.h, 0.h).onPress(() { + selectedPaymentMethod = "TAMARA"; + openPaymentURL("tamara"); + }) + : SizedBox.shrink(), + ], + ), + ), + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: false, + ), + child: Consumer(builder: (context, payfortVM, child) { + //TODO: Need to add loading state & animation for Apple Pay Configuration + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + (bookAppointmentsVM.patientWalkInAppointmentShareResponseModel!.isCash ?? true) + ? Container( + height: 50.h, + decoration: ShapeDecoration( + color: AppColors.secondaryLightRedBorderColor, + shape: SmoothRectangleBorder( + borderRadius: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24)), + smoothness: 1, + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "Insurance expired or inactive".needTranslation.toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h), + CustomButton( + text: LocaleKeys.updateInsurance.tr(context: context), + onPressed: () { + Navigator.of(context).push( + CustomPageRoute( + page: InsuranceHomePage(), + ), + ); + }, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.secondaryLightRedBorderColor, + textColor: AppColors.whiteColor, + fontSize: 10.f, + fontWeight: FontWeight.w500, + borderRadius: 8, + padding: EdgeInsets.fromLTRB(15, 0, 15, 0), + height: 30.h, + ).paddingSymmetrical(24.h, 0.h), + ], + ), + ) + : const SizedBox(), + SizedBox(height: 24.h), + "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h), + SizedBox(height: 17.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "Amount before tax".needTranslation.toText14(isBold: true), + Utils.getPaymentAmountWithSymbol(bookAppointmentsVM.patientWalkInAppointmentShareResponseModel!.patientShare!.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), + Utils.getPaymentAmountWithSymbol( + bookAppointmentsVM.patientWalkInAppointmentShareResponseModel!.patientTaxAmount!.toString().toText14(isBold: true, color: AppColors.greyTextColor), + AppColors.greyTextColor, + 13, + isSaudiCurrency: true), + ], + ).paddingSymmetrical(24.h, 0.h), + SizedBox(height: 17.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "".needTranslation.toText14(isBold: true), + Utils.getPaymentAmountWithSymbol( + bookAppointmentsVM.patientWalkInAppointmentShareResponseModel!.patientShareWithTax!.toString().toText24(isBold: true), AppColors.blackColor, 17, + isSaudiCurrency: true), + ], + ).paddingSymmetrical(24.h, 0.h), + Platform.isIOS + ? Utils.buildSvgWithAssets( + icon: AppAssets.apple_pay_button, + width: 200.h, + height: 80.h, + fit: BoxFit.contain, + ).paddingSymmetrical(24.h, 0.h).onPress(() { + // payfortVM.setIsApplePayConfigurationLoading(true); + if (Utils.havePrivilege(103)) { + startApplePay(); + } else { + openPaymentURL("ApplePay"); + } + }) + : SizedBox(height: 12.h), + SizedBox(height: 12.h), + ], + ); + }), + ), + ], + ); + }), + ); + } + + onBrowserLoadStart(String url) { + print("onBrowserLoadStart"); + print(url); + + if (selectedPaymentMethod == "tamara") { + if (Platform.isAndroid) { + Uri uri = new Uri.dataFromString(url); + tamaraPaymentStatus = uri.queryParameters['status']!; + tamaraOrderID = uri.queryParameters['AuthorizePaymentId']!; + } else { + Uri uri = new Uri.dataFromString(url); + tamaraPaymentStatus = uri.queryParameters['paymentStatus']!; + tamaraOrderID = uri.queryParameters['orderId']!; + } + } + + // if(selectedPaymentMethod != "TAMARA") { + MyInAppBrowser.successURLS.forEach((element) { + if (url.contains(element)) { + browser?.close(); + MyInAppBrowser.isPaymentDone = true; + return; + } + }); + // } + + // if(selectedPaymentMethod != "TAMARA") { + MyInAppBrowser.errorURLS.forEach((element) { + if (url.contains(element)) { + browser?.close(); + MyInAppBrowser.isPaymentDone = false; + return; + } + }); + // } + } + + onBrowserExit(bool isPaymentMade) async { + checkPaymentStatus(); + } + + void checkPaymentStatus() async { + LoaderBottomSheet.showLoader(loadingText: "Checking payment status, Please wait...".needTranslation); + if (selectedPaymentMethod == "TAMARA") { + await payfortViewModel.checkTamaraPaymentStatus( + transactionID: transID, + onSuccess: (apiResponse) async { + if (apiResponse.data["status"].toString().toLowerCase() == "success") { + tamaraOrderID = apiResponse.data["tamara_order_id"].toString(); + await payfortViewModel.updateTamaraRequestStatus(responseMessage: "success", status: "14", clientRequestID: transID, tamaraOrderID: tamaraOrderID); + await payfortViewModel.markAppointmentAsTamaraPaid(projectID: bookAppointmentsViewModel.selectedDoctor.projectID!, appointmentNo: DateTime.now().millisecondsSinceEpoch); + // await myAppointmentsViewModel.addAdvanceNumberRequest( + // advanceNumber: "Tamara-Advance-0000", + // paymentReference: tamaraOrderID, + // appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo.toString(), + // onSuccess: (value) async { + // if (widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment!) { + // //TODO: Implement LiveCare Check-In API Call + // await myAppointmentsViewModel.insertLiveCareVIDARequest( + // clientRequestID: tamaraOrderID, + // patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel, + // onSuccess: (apiResponse) { + // Future.delayed(Duration(milliseconds: 500), () { + // LoaderBottomSheet.hideLoader(); + // Navigator.pushAndRemoveUntil( + // context, + // CustomPageRoute( + // page: LandingNavigation(), + // ), + // (r) => false); + // }); + // }, + // onError: (error) {}); + // } else { + // await myAppointmentsViewModel.generateAppointmentQR( + // clinicID: widget.patientAppointmentHistoryResponseModel.clinicID, + // projectID: widget.patientAppointmentHistoryResponseModel.projectID, + // appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo.toString(), + // isFollowUp: myAppointmentsViewModel.patientAppointmentShareResponseModel!.isFollowup!, + // onSuccess: (apiResponse) { + // Future.delayed(Duration(milliseconds: 500), () { + // LoaderBottomSheet.hideLoader(); + // Navigator.pushAndRemoveUntil( + // context, + // CustomPageRoute( + // page: LandingNavigation(), + // ), + // (r) => false); + // }); + // }); + // } + // }); + } else { + await payfortViewModel.updateTamaraRequestStatus(responseMessage: "Failed", status: "00", clientRequestID: transID, tamaraOrderID: tamaraOrderID); + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + }, + onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }); + } else { + await payfortViewModel.checkPaymentStatus( + transactionID: transID, + onSuccess: (apiResponse) async { + print(apiResponse.data); + if (payfortViewModel.payfortCheckPaymentStatusResponseModel!.responseMessage!.toLowerCase() == "success") { + LoaderBottomSheet.hideLoader(); + LoaderBottomSheet.showLoader(loadingText: "Booking Waiting Appointment, Please wait...".needTranslation); + await bookAppointmentsViewModel.insertSpecificAppointmentForWalkIn(onSuccess: (val) async { + String appointmentNo = val.data['AppointmentNo'].toString(); + await myAppointmentsViewModel.createAdvancePayment( + paymentMethodName: selectedPaymentMethod, + projectID: bookAppointmentsViewModel.waitingAppointmentProjectID, + clinicID: bookAppointmentsViewModel.selectedDoctor.clinicID!, + appointmentNo: appointmentNo, + payedAmount: payfortViewModel.payfortCheckPaymentStatusResponseModel!.amount!, + paymentReference: payfortViewModel.payfortCheckPaymentStatusResponseModel!.fortId!, + patientID: appState.getAuthenticatedUser()!.patientId.toString(), + patientType: appState.getAuthenticatedUser()!.patientType!, + onSuccess: (value) async { + print(value); + await myAppointmentsViewModel.addAdvanceNumberRequest( + advanceNumber: Utils.isVidaPlusProject(bookAppointmentsViewModel.waitingAppointmentProjectID) + ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString() + : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(), + paymentReference: payfortViewModel.payfortCheckPaymentStatusResponseModel!.fortId!, + appointmentNo: appointmentNo, + onSuccess: (value) async { + LoaderBottomSheet.hideLoader(); + sendCheckInRequest(bookAppointmentsViewModel.waitingAppointmentNFCCode, appointmentNo, context); + }); + }); + }); + } else { + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: "Payment Failed! Please try again.".needTranslation), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + }); + } + } + + openPaymentURL(String paymentMethod) { + browser = MyInAppBrowser(onExitCallback: onBrowserExit, onLoadStartCallback: onBrowserLoadStart, context: context); + transID = Utils.getAppointmentTransID( + bookAppointmentsViewModel.selectedDoctor.projectID!, + bookAppointmentsViewModel.selectedDoctor.clinicID!, + bookAppointmentsViewModel.selectedDoctor.doctorID!, + ); + + //TODO: Need to pass dynamic params to the payment request instead of static values + browser?.openPaymentBrowser( + bookAppointmentsViewModel.patientWalkInAppointmentShareResponseModel!.patientShareWithTax!, + "Appointment check in", + transID, + bookAppointmentsViewModel.selectedDoctor.projectID.toString(), + "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com", + selectedPaymentMethod, + appState.getAuthenticatedUser()!.patientType.toString(), + "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}", + appState.getAuthenticatedUser()!.patientId.toString(), + appState.getAuthenticatedUser()!, + browser!, + false, + "2", + "", + context, + "", + "", + "", + "", + "3"); + } + + startApplePay() async { + showCommonBottomSheet(context, + child: Utils.getLoadingWidget(), callBackFunc: (str) {}, title: "", height: ResponsiveExtension.screenHeight * 0.3, isCloseButtonVisible: false, isDismissible: false, isFullScreen: false); + transID = Utils.getAppointmentTransID( + bookAppointmentsViewModel.selectedDoctor.projectID!, + bookAppointmentsViewModel.selectedDoctor.clinicID!, + bookAppointmentsViewModel.selectedDoctor.doctorID!, + ); + + ApplePayInsertRequest applePayInsertRequest = ApplePayInsertRequest(); + + await payfortViewModel.getPayfortConfigurations( + serviceId: ServiceTypeEnum.appointmentPayment.getIdFromServiceEnum(), projectId: bookAppointmentsViewModel.selectedDoctor.projectID!, integrationId: 2); + + applePayInsertRequest.clientRequestID = transID; + applePayInsertRequest.clinicID = bookAppointmentsViewModel.selectedDoctor.clinicID!; + + applePayInsertRequest.currency = appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED"; + applePayInsertRequest.customerEmail = "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com"; + applePayInsertRequest.customerID = appState.getAuthenticatedUser()!.patientId.toString(); + applePayInsertRequest.customerName = "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}"; + + applePayInsertRequest.deviceToken = await Utils.getStringFromPrefs(CacheConst.pushToken); + applePayInsertRequest.voipToken = await Utils.getStringFromPrefs(CacheConst.voipToken); + applePayInsertRequest.doctorID = bookAppointmentsViewModel.selectedDoctor.doctorID; + applePayInsertRequest.projectID = bookAppointmentsViewModel.selectedDoctor.projectID.toString(); + applePayInsertRequest.serviceID = ServiceTypeEnum.appointmentPayment.getIdFromServiceEnum().toString(); + applePayInsertRequest.channelID = 3; + applePayInsertRequest.patientID = appState.getAuthenticatedUser()!.patientId.toString(); + applePayInsertRequest.patientTypeID = appState.getAuthenticatedUser()!.patientType; + applePayInsertRequest.patientOutSA = appState.getAuthenticatedUser()!.outSa; + applePayInsertRequest.appointmentDate = DateUtil.convertDateToString(DateTime.now()); + applePayInsertRequest.appointmentNo = DateTime.now().millisecondsSinceEpoch; + applePayInsertRequest.orderDescription = "Appointment Payment"; + applePayInsertRequest.liveServiceID = "0"; + applePayInsertRequest.latitude = "0.0"; + applePayInsertRequest.longitude = "0.0"; + applePayInsertRequest.amount = bookAppointmentsViewModel.patientWalkInAppointmentShareResponseModel!.patientShareWithTax!.toString(); + applePayInsertRequest.isSchedule = "0"; + applePayInsertRequest.language = appState.isArabic() ? 'ar' : 'en'; + applePayInsertRequest.languageID = appState.isArabic() ? 1 : 2; + applePayInsertRequest.userName = appState.getAuthenticatedUser()!.patientId; + applePayInsertRequest.responseContinueURL = "http://hmg.com/Documents/success.html"; + applePayInsertRequest.backClickUrl = "http://hmg.com/Documents/success.html"; + applePayInsertRequest.paymentOption = "ApplePay"; + + applePayInsertRequest.isMobSDK = true; + applePayInsertRequest.merchantReference = transID; + applePayInsertRequest.merchantIdentifier = payfortViewModel.payfortProjectDetailsRespModel!.merchantIdentifier; + applePayInsertRequest.commandType = "PURCHASE"; + applePayInsertRequest.signature = payfortViewModel.payfortProjectDetailsRespModel!.signature; + applePayInsertRequest.accessCode = payfortViewModel.payfortProjectDetailsRespModel!.accessCode; + applePayInsertRequest.shaRequestPhrase = payfortViewModel.payfortProjectDetailsRespModel!.shaRequest; + applePayInsertRequest.shaResponsePhrase = payfortViewModel.payfortProjectDetailsRespModel!.shaResponse; + applePayInsertRequest.returnURL = ""; + + //TODO: Need to pass dynamic params to the Apple Pay instead of static values + await payfortViewModel.applePayRequestInsert(applePayInsertRequest: applePayInsertRequest).then((value) { + payfortViewModel.paymentWithApplePay( + customerName: "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}", + // customerEmail: projectViewModel.authenticatedUserObject.user.emailAddress, + customerEmail: "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com", + orderDescription: "Appointment Payment", + orderAmount: double.parse(bookAppointmentsViewModel.patientWalkInAppointmentShareResponseModel!.patientShareWithTax!.toString()), + merchantReference: transID, + merchantIdentifier: payfortViewModel.payfortProjectDetailsRespModel!.merchantIdentifier, + applePayAccessCode: payfortViewModel.payfortProjectDetailsRespModel!.accessCode, + applePayShaRequestPhrase: payfortViewModel.payfortProjectDetailsRespModel!.shaRequest, + currency: appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED", + onFailed: (failureResult) async { + log("failureResult: ${failureResult.message.toString()}"); + Navigator.of(context).pop(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: failureResult.message.toString()), + callBackFunc: () {}, + isFullScreen: false, + isCloseButtonVisible: true, + ); + }, + onSucceeded: (successResult) async { + log("successResult: ${successResult.responseMessage.toString()}"); + selectedPaymentMethod = successResult.paymentOption ?? "VISA"; + checkPaymentStatus(); + }, + // projectId: appo.projectID, + // serviceTypeEnum: ServiceTypeEnum.appointmentPayment, + ); + }); + } + + void sendCheckInRequest(String scannedCode, String appointmentNo, BuildContext context) async { + LoaderBottomSheet.showLoader(loadingText: "Processing Check-In...".needTranslation); + PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel = PatientAppointmentHistoryResponseModel( + appointmentNo: appointmentNo, + clinicID: bookAppointmentsViewModel.selectedDoctor.clinicID, + projectID: bookAppointmentsViewModel.selectedDoctor.projectID, + ); + await myAppointmentsViewModel.sendCheckInNfcRequest( + patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel, + scannedCode: scannedCode, + checkInType: 2, + onSuccess: (apiResponse) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight(context, title: "Success".needTranslation, child: Utils.getSuccessWidget(loadingText: apiResponse.data["SuccessMsg"]), callBackFunc: () { + Navigator.of(context).pop(); + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + }, isFullScreen: false); + }, + onError: (error) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight(context, title: "Error".needTranslation, child: Utils.getErrorWidget(loadingText: error), callBackFunc: () { + Navigator.of(context).pop(); + }, isFullScreen: false); + }, + ); + } + + void insertWalkInAppointment() async {} +} diff --git a/lib/presentation/book_appointment/widgets/appointment_calendar.dart b/lib/presentation/book_appointment/widgets/appointment_calendar.dart index 54ff282..7c4226c 100644 --- a/lib/presentation/book_appointment/widgets/appointment_calendar.dart +++ b/lib/presentation/book_appointment/widgets/appointment_calendar.dart @@ -15,6 +15,7 @@ import 'package:hmg_patient_app_new/features/book_appointments/book_appointments import 'package:hmg_patient_app_new/features/book_appointments/models/timeslots.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/presentation/book_appointment/waiting_appointment/waiting_appointment_info.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'; @@ -27,7 +28,7 @@ import 'package:smooth_corner/smooth_corner.dart'; import 'package:syncfusion_flutter_calendar/calendar.dart'; class AppointmentCalendar extends StatefulWidget { - const AppointmentCalendar({super.key}); + AppointmentCalendar({super.key}); @override State createState() => _AppointmentCalendarState(); @@ -54,7 +55,6 @@ class _AppointmentCalendarState extends State { String selectedTime = ""; - bool isWaitingAppointmentAvailable = false; final _selectedDay = DateTime.now(); @override @@ -176,13 +176,25 @@ class _AppointmentCalendarState extends State { text: "Select".needTranslation, onPressed: () async { if (appState.isAuthenticated) { - bookAppointmentsViewModel.setSelectedAppointmentDateTime(selectedDate, selectedTime); - Navigator.of(context).pop(); - Navigator.of(context).push( - CustomPageRoute( - page: ReviewAppointmentPage(), - ), - ); + if(selectedTime == "Waiting Appointment".needTranslation){ + bookAppointmentsViewModel.setWaitingAppointmentProjectID(bookAppointmentsViewModel.selectedDoctor.projectID!); + bookAppointmentsViewModel.setWaitingAppointmentDoctor(bookAppointmentsViewModel.selectedDoctor); + + Navigator.of(context).pop(); + Navigator.of(context).push( + CustomPageRoute( + page: WaitingAppointmentInfo(), + ), + ); + } else { + bookAppointmentsViewModel.setSelectedAppointmentDateTime(selectedDate, selectedTime); + Navigator.of(context).pop(); + Navigator.of(context).push( + CustomPageRoute( + page: ReviewAppointmentPage(), + ), + ); + } } else { showCommonBottomSheetWithoutHeight( context, @@ -281,8 +293,8 @@ class _AppointmentCalendarState extends State { openTimeSlotsPickerForDate(DateTime dateStart, List freeSlots) { dayEvents.clear(); DateTime dateStartObj = new DateTime(dateStart.year, dateStart.month, dateStart.day, 0, 0, 0, 0, 0); - if (isWaitingAppointmentAvailable && DateUtils.isSameDay(dateStart, DateTime.now())) { - dayEvents.add(TimeSlot(isoTime: "Waiting Appointment", start: DateTime.now(), end: DateTime.now(), vidaDate: "")); + if (bookAppointmentsViewModel.isWaitingAppointmentAvailable && DateUtils.isSameDay(dateStart, DateTime.now())) { + dayEvents.add(TimeSlot(isoTime: "Waiting Appointment".needTranslation, start: DateTime.now(), end: DateTime.now(), vidaDate: "")); } freeSlots.forEach((v) { if (v.start == dateStartObj) dayEvents.add(v); @@ -321,9 +333,25 @@ class TimeSlotChip extends StatelessWidget { Widget build(BuildContext context) { return GestureDetector( onTap: onTap, - child: Container( - padding: EdgeInsets.symmetric(horizontal: 14.h, vertical: 8.h), - decoration: ShapeDecoration( + child: label == "Waiting Appointment".needTranslation + ? Container( + padding: EdgeInsets.symmetric(horizontal: 14.h, vertical: 8.h), + decoration: ShapeDecoration( + color: isSelected ? AppColors.warningColorYellow : AppColors.whiteColor, + shape: SmoothRectangleBorder( + borderRadius: BorderRadius.circular(8.h), + smoothness: 1, + side: BorderSide(color: isSelected ? AppColors.warningColorYellow : AppColors.borderOnlyColor.withOpacity(0.2), width: 1), + ), + ), + child: label.toText12( + color: isSelected ? AppColors.whiteColor : Colors.black87, + fontWeight: FontWeight.w500, + ), + ) + : Container( + padding: EdgeInsets.symmetric(horizontal: 14.h, vertical: 8.h), + decoration: ShapeDecoration( color: AppColors.whiteColor, shape: SmoothRectangleBorder( borderRadius: BorderRadius.circular(8.h), diff --git a/lib/presentation/book_appointment/widgets/doctor_card.dart b/lib/presentation/book_appointment/widgets/doctor_card.dart index 4cd147a..7257dbf 100644 --- a/lib/presentation/book_appointment/widgets/doctor_card.dart +++ b/lib/presentation/book_appointment/widgets/doctor_card.dart @@ -1,6 +1,7 @@ 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/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'; @@ -49,7 +50,7 @@ class DoctorCard extends StatelessWidget { : doctorsListResponseModel.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png", width: 63.h, height: 63.h, - fit: BoxFit.fill, + fit: BoxFit.cover, ).circle(100).toShimmer2(isShow: isLoading), SizedBox(width: 8.h), Expanded( @@ -114,6 +115,13 @@ class DoctorCard extends StatelessWidget { iconColor: AppColors.ratingColorYellow, labelText: "Rating: ${isLoading ? 4.78 : doctorsListResponseModel.decimalDoctorRate}".needTranslation, ).toShimmer2(isShow: isLoading), + doctorsListResponseModel.nearestFreeSlot != null + ? AppCustomChipWidget( + labelText: (isLoading ? "Cardiologist" : DateUtil.getDateStringForNearestSlot(doctorsListResponseModel.nearestFreeSlot)).needTranslation, + backgroundColor: AppColors.successColor, + textColor: AppColors.whiteColor, + ).toShimmer2(isShow: isLoading) + : SizedBox.shrink(), ], ), SizedBox(height: 12.h), diff --git a/lib/presentation/e_referral/e-referral_validator.dart b/lib/presentation/e_referral/e-referral_validator.dart new file mode 100644 index 0000000..e0a8006 --- /dev/null +++ b/lib/presentation/e_referral/e-referral_validator.dart @@ -0,0 +1,85 @@ +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'; + +class ReferralValidator { + static FormValidationErrors validateStep1(ReferralFormData formData) { + final errors = FormValidationErrors(); + + if (formData.requesterName.trim().isEmpty) { + errors.requesterName = 'Referral requester name is required'.needTranslation; + } + + + + if (formData.relationship == null) { + errors.relationship = 'Please select a relationship'.needTranslation; + } + + if (formData.relationship != null && + formData.relationship?.iD == 5 && + formData.otherRelationshipName.trim().isEmpty) { + errors.otherRelationshipName = 'Other relationship name is required'.needTranslation; + } + + return errors; + } + + static FormValidationErrors validateStep2(ReferralFormData formData) { + final errors = FormValidationErrors(); + + if (formData.patientIdentification.trim().isEmpty) { + errors.patientIdentification = 'Identification number is required'.needTranslation; + } + + if (formData.patientName.trim().isEmpty) { + errors.patientName = 'Patient name is required'.needTranslation; + } + + if (formData.patientPhone == null) { + errors.patientPhone = 'Please Enter patient phone number'.needTranslation; + } + + if (formData.patientCity == null) { + errors.patientCity = 'Please select patient city'.needTranslation; + } + + return errors; + } + + static FormValidationErrors validateStep3(ReferralFormData formData) { + final errors = FormValidationErrors(); + + if (formData.medicalReportImages.isEmpty) { + errors.medicalReport = 'At least one medical report is required'.needTranslation; + } + + if (formData.branch == null) { + errors.branch = 'Please select a branch'.needTranslation; + } + + if (formData.isPatientInsured && formData.insuredPatientImages.isEmpty) { + errors.insuredDocument = 'Insurance document is required for insured patients'.needTranslation; + } + + return errors; + } + + static bool _isValidSaudiPhone(String phone) { + final regex = RegExp(r'^5\d{8}$'); + return regex.hasMatch(phone); + } + + static bool hasErrors(FormValidationErrors errors) { + return errors.requesterName != null || + errors.requesterPhone != null || + errors.relationship != null || + errors.otherRelationshipName != null || + errors.patientIdentification != null || + errors.patientName != null || + errors.patientPhone != null || + errors.patientCity != null || + errors.medicalReport != null || + errors.branch != null || + errors.insuredDocument != null; + } +} \ No newline at end of file diff --git a/lib/presentation/e_referral/e_referral_form_manager.dart b/lib/presentation/e_referral/e_referral_form_manager.dart new file mode 100644 index 0000000..f7093c5 --- /dev/null +++ b/lib/presentation/e_referral/e_referral_form_manager.dart @@ -0,0 +1,290 @@ +// managers/referral_form_manager.dart +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/common_models/nationality_country_model.dart'; +import 'package:hmg_patient_app_new/core/enums.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_all_cities_resp_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/relationship_type_resp_mode.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/e_referral_form_model.dart'; +import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart'; + + +class ReferralFormManager extends ChangeNotifier { + final ReferralFormData _formData = ReferralFormData(); + final FormValidationErrors _errors = FormValidationErrors(); + + ReferralFormData get formData => _formData; + FormValidationErrors get errors => _errors; + + + int _searchCriteria = 0; // 0 = Identification Number, 1 = Referral Number + String? _searchValue; + String? _searchPhone; + +// Getters + int get searchCriteria => _searchCriteria; + String? get searchValue => _searchValue; + String? get searchPhone => _searchPhone; + + void updateRequesterName(String value) { + _formData.requesterName = value; + _clearError('requesterName'); + } + + void updateRequesterPhone(String value) { + _formData.requesterPhone = value; + _clearError('requesterPhone'); + } + + void updateCountryEnum(CountryEnum value) { + _formData.countryEnum = value; + } + void updatePatientCountryEnum(CountryEnum value) { + _formData.patientCountryEnum = value; + } + + void updateRelationship(GetAllRelationshipTypeResponseModel? value) { + _formData.relationship = value; + notifyListeners(); + _clearError('relationship'); + } + + void updateOtherRelationshipName(String value) { + _formData.otherRelationshipName = value; + _clearError('otherRelationshipName'); + } + + void updatePatientIdentification(String value) { + _formData.patientIdentification = value; + _clearError('patientIdentification'); + } + + void updatePatientName(String value) { + _formData.patientName = value; + _clearError('patientName'); + } + + void updatePatientPhone(String? value) { + _formData.patientPhone = value!; + _clearError('patientPhone'); + } + + void updatePatientCity(GetAllCitiesResponseModel? value) { + _formData.patientCity = value; + _clearError('patientCity'); + notifyListeners(); + } + + void updateBranch(HospitalsModel? value) { + _formData.branch = value; + _clearError('branch'); + } + + void updateIsPatientInsured(bool value) { + _formData.isPatientInsured = value; + if (!value) { + _formData.insuredPatientImages.clear(); + } + _clearError('insuredDocument'); + } + + void addMedicalReport(EReferralAttachment attachment) { + _formData.medicalReportImages.add(attachment); + _clearError('medicalReport'); + } + + void removeMedicalReport(int index) { + if (index >= 0 && index < _formData.medicalReportImages.length) { + _formData.medicalReportImages.removeAt(index); + } + notifyListeners(); + } + + void addInsuranceDocument(EReferralAttachment attachment) { + _formData.insuredPatientImages.add(attachment); + _clearError('insuredDocument'); + } + + void removeInsuranceDocument(int index) { + if (index >= 0 && index < _formData.insuredPatientImages.length) { + _formData.insuredPatientImages.removeAt(index); + } + + notifyListeners(); + } + + + // Error management + void setErrors(FormValidationErrors newErrors) { + _errors.requesterName = newErrors.requesterName; + _errors.requesterPhone = newErrors.requesterPhone; + _errors.relationship = newErrors.relationship; + _errors.otherRelationshipName = newErrors.otherRelationshipName; + _errors.patientIdentification = newErrors.patientIdentification; + _errors.patientName = newErrors.patientName; + _errors.patientPhone = newErrors.patientPhone; + _errors.patientCity = newErrors.patientCity; + _errors.medicalReport = newErrors.medicalReport; + _errors.branch = newErrors.branch; + _errors.insuredDocument = newErrors.insuredDocument; + notifyListeners(); // Only notify when errors change + } + + void clearAllErrors() { + _errors.requesterName = null; + _errors.requesterPhone = null; + _errors.relationship = null; + _errors.otherRelationshipName = null; + _errors.patientIdentification = null; + _errors.patientName = null; + _errors.patientPhone = null; + _errors.patientCity = null; + _errors.medicalReport = null; + _errors.branch = null; + _errors.insuredDocument = null; + notifyListeners(); + } + + void _clearError(String field) { + bool shouldNotify = false; + + switch (field) { + case 'requesterName': + if (_errors.requesterName != null) { + _errors.requesterName = null; + shouldNotify = true; + } + break; + case 'requesterPhone': + if (_errors.requesterPhone != null) { + _errors.requesterPhone = null; + shouldNotify = true; + } + break; + case 'relationship': + if (_errors.relationship != null) { + _errors.relationship = null; + shouldNotify = true; + } + break; + case 'otherRelationshipName': + if (_errors.otherRelationshipName != null) { + _errors.otherRelationshipName = null; + shouldNotify = true; + } + break; + case 'patientIdentification': + if (_errors.patientIdentification != null) { + _errors.patientIdentification = null; + shouldNotify = true; + } + break; + case 'patientName': + if (_errors.patientName != null) { + _errors.patientName = null; + shouldNotify = true; + } + break; + case 'patientPhone': + if (_errors.patientPhone != null) { + _errors.patientPhone = null; + shouldNotify = true; + } + break; + case 'patientCity': + if (_errors.patientCity != null) { + _errors.patientCity = null; + shouldNotify = true; + } + break; + case 'medicalReport': + if (_errors.medicalReport != null) { + _errors.medicalReport = null; + shouldNotify = true; + } + break; + case 'branch': + if (_errors.branch != null) { + _errors.branch = null; + shouldNotify = true; + } + break; + case 'insuredDocument': + if (_errors.insuredDocument != null) { + _errors.insuredDocument = null; + shouldNotify = true; + } + break; + } + + if (shouldNotify) { + notifyListeners(); + } + } + void updateSearchCriteria(int criteria) { + _searchCriteria = criteria; + _errors.searchValue = _validateSearchValue(); + notifyListeners(); + } + + void updateSearchValue(String value) { + _searchValue = value; + _errors.searchValue = _validateSearchValue(); + } + void updateSearchPhone(String value) { + _searchPhone = value; + _errors.searchPhone = _validateSearchPhone(); + } + + String? _validateSearchValue() { + if (_searchValue == null || _searchValue!.isEmpty) { + return _searchCriteria == 0 + ? 'Identification Number is required' + : 'Referral Number is required'; + } + + if (_searchCriteria == 0) { + // Validate identification number format + if (!_isValidIdentificationNumber(_searchValue!)) { + return 'Please enter a valid identification number'; + } + } else { + // Validate referral number format + if (!_isValidReferralNumber(_searchValue!)) { + return 'Please enter a valid referral number'; + } + } + + return null; + } + + bool _isValidIdentificationNumber(String value) { + // Add your identification number validation logic + return value.isNotEmpty; // Basic validation + } + + bool _isValidReferralNumber(String value) { + // Add your referral number validation logic + return value.isNotEmpty; // Basic validation + } + + void validateSearchForm() { + _errors.searchValue = _validateSearchValue(); + _errors.searchPhone = _validateSearchPhone(); + notifyListeners(); + } + + String? _validateSearchPhone() { + if (_searchPhone == null || _searchPhone!.isEmpty) { + return 'Phone number is required'; + } + return null; + } + bool get isSearchFormInValid { + return ( + _errors.searchValue != null && + _errors.searchValue!.isNotEmpty || + _errors.searchPhone != null && + _errors.searchPhone!.isNotEmpty); + } +} \ No newline at end of file diff --git a/lib/presentation/e_referral/e_referral_page_home.dart b/lib/presentation/e_referral/e_referral_page_home.dart deleted file mode 100644 index bacca47..0000000 --- a/lib/presentation/e_referral/e_referral_page_home.dart +++ /dev/null @@ -1,97 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter/cupertino.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/prescriptions/prescriptions_view_model.dart'; -import 'package:hmg_patient_app_new/presentation/e_referral/new_referral.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 EReferralPage extends StatefulWidget { - const EReferralPage({super.key}); - - @override - _EReferralPageState createState() => _EReferralPageState(); -} - -class _EReferralPageState extends State - { - - - @override - void initState() { - super.initState(); - } - - @override - void dispose() { - super.dispose(); - } - bool isNewReferral = true; - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: AppColors.bgScaffoldColor, - body: CollapsingListView( - title:"E Referral".needTranslation, - child: SingleChildScrollView( - child: Consumer(builder: (context, model, child) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox(height: 16.h), - Row( - children: [ - CustomButton( - text: "New Referral".needTranslation, - onPressed: () { - isNewReferral =true; - setState(() { - - }); - }, - backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor, - borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(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: "Search Referral".needTranslation, - onPressed: () { - isNewReferral =false; - }, - backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor, - borderColor: model.isSortByClinic ? AppColors.textColor.withOpacity(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, - ), - ], - ).paddingSymmetrical(24.h, 0.h), - SizedBox(height: 20.h), - isNewReferral ? NewEReferral() : SizedBox(), - ], - ); - }), - ), - ), - ); - - - - - } -} diff --git a/lib/presentation/e_referral/e_referral_search_result.dart b/lib/presentation/e_referral/e_referral_search_result.dart new file mode 100644 index 0000000..ba31f1b --- /dev/null +++ b/lib/presentation/e_referral/e_referral_search_result.dart @@ -0,0 +1,280 @@ +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'; +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/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart'; +import 'package:provider/provider.dart'; +import 'package:smooth_corner/smooth_corner.dart'; + +class SearchResultPage extends StatefulWidget { + const SearchResultPage({super.key}); + + @override + _SearchResultPageState createState() => _SearchResultPageState(); +} + +class _SearchResultPageState extends State { + HmgServicesViewModel? hmgServicesVM; + + String _selectedFilter = 'All'; + + @override + void initState() { + hmgServicesVM = context.read(); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return CollapsingListView( + title: "Search Result".needTranslation, + child: Column( + children: [ + // List of referrals + ListView.builder( + padding: EdgeInsets.zero, + shrinkWrap: true, + itemCount: hmgServicesVM?.searchReferralList.length, + itemBuilder: (context, index) { + return _buildReferralCard(hmgServicesVM!.searchReferralList[index]); + }, + ), + ], + ), + ); + } + + Widget _buildReferralCard(SearchEReferralResponseModel referral) { + return SmoothCard( + borderRadius: BorderRadius.circular(16.h), + margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + color: AppColors.whiteColor, + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + + 'Referral No ${referral.referralNumber}'.needTranslation.toText18(isBold: true, color: AppColors.textColor), + + + Container( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: _getStatusColor(referral.status!), + borderRadius: BorderRadius.circular(20), + ), + child: + referral.status!.toText12(color: AppColors.whiteColor, + // style: TextStyle( + // color: Colors.white, + // fontSize: 12, + // fontWeight: FontWeight.w500, + // ), + ), + ), + ], + ), + + SizedBox(height: 16), + + // Patient information + Row( + children: [ + Container( + width: 50, + height: 50, + decoration: BoxDecoration( + color: AppColors.lightGrayBGColor, + shape: BoxShape.circle, + ), + child: Icon( + Icons.person, + color: AppColors.lightGrayBGColor, + size: 30, + ), + ), + SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + //Text( + referral.patientName!.toText16(isBold: true, color: AppColors.textColor), + // style: TextStyle( + // fontSize: 16, + // fontWeight: FontWeight.bold, + // ), + // ), + SizedBox(height: 4), + // Text( + 'ID: ${referral.identityNumber}'.toText14(color: AppColors.greyTextColor), + // style: TextStyle( + // color: Colors.grey[600], + // ), + // ), + ], + ), + ), + ], + ), + + SizedBox(height: 16), + + // Details row + Row( + children: [ + _buildDetailItem( + Icons.phone, + referral.patientContactNo!, + ), + SizedBox(width: 16), + _buildDetailItem(Icons.calendar_today, Utils.getDayMonthYearDateFormatted(DateUtil.convertStringToDateNoTimeZone(referral.referralDate!))), + ], + ), + + SizedBox(height: 16), + + // Requester information + Container( + padding: EdgeInsets.all(5.h), + decoration: BoxDecoration( + color: AppColors.lightGrayBGColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Icon( + Icons.person_outline, + color: Colors.grey[600], + size: 20, + ), + SizedBox(width: 8), + //Text( + 'Requester: ${referral.requesterName}'.toText14(), + // style: TextStyle( + // color: Colors.grey[700], + // ), + // ), + SizedBox(width: 16), + Icon( + Icons.phone, + color: Colors.grey[600], + size: 16, + ), + SizedBox(width: 4), + // Text( + referral.requesterContactNo!.toText14(), + // style: TextStyle( + // color: Colors.grey[700], + // ), + // ), + ], + ), + ), + + SizedBox(height: 12), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Icon( + Icons.group, + color: Colors.grey[600], + size: 16, + ), + SizedBox(width: 4), + //Text( + 'Relationship: ${referral.relationshipType?.text}'.toText14(color:AppColors.greyTextColor), + // style: TextStyle( + // color: Colors.grey[700], + // fontSize: 14, + // ), + // ), + ], + ), + Row( + children: [ + Icon( + Icons.attach_file, + color: Colors.grey[600], + size: 16, + ), + SizedBox(width: 4), + // Text( + '${referral.medicalReportAttachment?.length} file(s)'.toText14(color:AppColors.greyTextColor), + // style: TextStyle( + // color: Colors.grey[700], + // fontSize: 14, + // ), + // ), + ], + ), + ], + ), + + SizedBox(height: 16), + + // Action buttons + ], + ), + ), + ); + } + + Widget _buildDetailItem(IconData icon, String text) { + return Row( + children: [ + Icon( + icon, + color: Colors.grey[600], + size: 16, + ), + SizedBox(width: 4), + + text.toText14(color: AppColors.greyTextColor), + + ], + ); + } + + Color _getStatusColor(String status) { + switch (status) { + case 'Pending': + return AppColors.alertColor; + case 'Completed': + return AppColors.bgGreenColor; + case 'Rejected': + return AppColors.primaryRedColor; + default: + return AppColors.lightGrayColor; + } + } + + + Widget _buildFilterOption(String filter) { + return ListTile( + leading: Icon( + _selectedFilter == filter ? Icons.radio_button_checked : Icons.radio_button_off, + color: _selectedFilter == filter ? Colors.blue[700] : Colors.grey, + ), + title: Text(filter), + onTap: () { + setState(() { + _selectedFilter = filter; + }); + Navigator.pop(context); + }, + ); + } +} diff --git a/lib/presentation/e_referral/new_e_referral.dart b/lib/presentation/e_referral/new_e_referral.dart new file mode 100644 index 0000000..b28b8df --- /dev/null +++ b/lib/presentation/e_referral/new_e_referral.dart @@ -0,0 +1,267 @@ +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/common_models/generic_api_model.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/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/hmg_services/hmg_services_view_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.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'; +import 'package:hmg_patient_app_new/presentation/e_referral/search_e_referral.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/widget/e-referral_otp.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_other_details.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_patient_info.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/widget/e_referral_requester_form.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:hmg_patient_app_new/widgets/stepper/stepper_widget.dart'; +import 'package:provider/provider.dart'; +import 'e-referral_validator.dart'; +import 'e_referral_form_manager.dart'; + +class NewReferralPage extends StatefulWidget { + const NewReferralPage({ + super.key, + }); + + @override + State createState() => _NewReferralPageState(); +} + +class _NewReferralPageState extends State { + final PageController _pageController = PageController(); + final ReferralFormManager _formManager = ReferralFormManager(); // Use manager + int _currentStep = 0; + + double widthOfOneState = ((ResponsiveExtension.screenWidth) / 3) - (20.h); + + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _loadData(); + }); + } + + void _handleNextStep() { + switch (_currentStep) { + case 0: + if (_validateCurrentStep()) { + OTPService.openOTPScreen( + context: context, + formManager: _formManager, + onSuccess: _proceedToNextStep, + ); + } + break; + case 1: + if (_validateCurrentStep()) { + _proceedToNextStep(); + } + break; + case 2: + if (_validateCurrentStep()) { + _submitReferral(); + } + break; + } + } + + bool _validateCurrentStep() { + FormValidationErrors stepErrors; + + switch (_currentStep) { + case 0: + stepErrors = ReferralValidator.validateStep1(_formManager.formData); + break; + case 1: + stepErrors = ReferralValidator.validateStep2(_formManager.formData); + break; + case 2: + stepErrors = ReferralValidator.validateStep3(_formManager.formData); + break; + default: + stepErrors = FormValidationErrors(); + } + + // Update errors through manager + _formManager.setErrors(stepErrors); + + return !ReferralValidator.hasErrors(stepErrors); + } + + void _proceedToNextStep() { + _pageController.nextPage( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + // setState(() { + _currentStep++; + // }); + // widget.onStepChanged(_currentStep); + } + + void _submitReferral() { + CreateEReferralRequestModel createReferralRequestModel = CreateEReferralRequestModel( + isInsuredPatient: _formManager.formData.isPatientInsured, + cityCode: _formManager.formData.patientCity!.iD!.toString(), + cityName: _formManager.formData.patientCity!.description, + requesterName: _formManager.formData.requesterName, + requesterContactNo: _formManager.formData.countryEnum.countryCode + _formManager.formData.requesterPhone, + requesterRelationship: _formManager.formData.relationship?.iD, + otherRelationship: _formManager.formData.relationship!.iD.toString(), + fullName: _formManager.formData.patientName, + identificationNo: int.tryParse(_formManager.formData!.patientIdentification ?? '0'), + patientMobileNumber: _formManager.formData.patientCountryEnum.countryCode + _formManager.formData.patientPhone, + preferredBranchCode: _formManager.formData.branch!.iD, + medicalReportAttachment: _formManager.formData.medicalReportImages, + insuranceCardAttachment: _formManager.formData.insuredPatientImages, + preferredBranchName: _formManager.formData.branch!.desciption); + + final hmgServicesVM = context.read(); + LoaderBottomSheet.showLoader(); + + hmgServicesVM.createEReferral( + requestModel: createReferralRequestModel, + onSuccess: (GenericApiModel response) { + + showSuccessBottomSheet(int.parse(response.data), hmgServicesVM); + LoaderBottomSheet.hideLoader(); + + }, + onError: (errorMessage) { + // Handle error (e.g., show error message) + print(errorMessage); + }, + ); + } + + void _loadData() { + + + + final authVM = context.read(); + final habibWalletVM = context.read(); + final hmgServicesVM = context.read(); + + hmgServicesVM.getRelationshipType(); + authVM.loadCountriesData(); + hmgServicesVM.getAllCities(); + habibWalletVM.getProjectsList(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: "E Referral".needTranslation, + isClose: false, + search: () async { + await Navigator.of(context).push( + CustomPageRoute( + page: SearchEReferralPage(), + fullScreenDialog: true, + direction: AxisDirection.down, + ), + ); + }, + bottomChild: Container( + color: Colors.white, + padding: EdgeInsets.all(ResponsiveExtension(20).h), + child: CustomButton( + text: _currentStep <=1 ? LocaleKeys.next.tr() : LocaleKeys.submit.tr(), + // icon: AppAssets.search_icon, + iconColor: Colors.white, + onPressed: () => {_handleNextStep()}, + ), + ), + child: ChangeNotifierProvider.value( + value: _formManager, + child: SizedBox( + height: ResponsiveExtension.screenHeight * 0.65, + child: Column( + children: [ + const SizedBox(height: 8), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(3, (index) { + if (_currentStep == index) { + return StepperWidget(widthOfOneState, AppColors.primaryRedColor, true, 4.h); + } else { + return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, 4.h); + } + })), + Expanded( + child: PageView( + controller: _pageController, + physics: const NeverScrollableScrollPhysics(), + onPageChanged: (index) => { + // setState(() => _currentStep = index) + }, + children: [ + RequesterFormStep(), + PatientInformationStep(), + OtherDetailsStep(), + ], + )), + ], + )), + ))); + // ); + } + + + showSuccessBottomSheet(int requestId, HmgServicesViewModel hmgServicesViewModel) { + return showCommonBottomSheetWithoutHeight( + context, + child: Padding( + padding: EdgeInsets.all(16.w), + child: Column( + children: [ + Utils.getSuccessWidget(loadingText: "Your Referral has been created Successfully.".needTranslation), + Row( + children: [ + "Here is your Referral #: ".needTranslation.toText14( + color: AppColors.textColorLight, + weight: FontWeight.w500, + ), + SizedBox(width: 4.w), + ("$requestId").toText16(isBold: true), + ], + ), + SizedBox(height: 24.h), + Row( + children: [ + Expanded( + child: CustomButton( + height: 56.h, + text: LocaleKeys.ok.tr(), + onPressed: () { + context.pop(); + context.pop(); + _currentStep =0; + }, + textColor: AppColors.whiteColor, + ), + ), + ], + ), + ], + ), + ), + isCloseButtonVisible: false, + isDismissible: false, + isFullScreen: false, + ); + } +} diff --git a/lib/presentation/e_referral/new_referral.dart b/lib/presentation/e_referral/new_referral.dart deleted file mode 100644 index 4ed9b8e..0000000 --- a/lib/presentation/e_referral/new_referral.dart +++ /dev/null @@ -1,172 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:hmg_patient_app_new/extensions/string_extensions.dart'; -import 'package:hmg_patient_app_new/theme/colors.dart'; - -class NewEReferral extends StatefulWidget { - NewEReferral(); - - @override - _NewEReferralState createState() => _NewEReferralState(); -} - -class _NewEReferralState extends State with TickerProviderStateMixin { - late PageController _controller; - int _currentIndex = 0; - int pageSelected = 2; - - // CreateEReferralRequestModel createEReferralRequestModel = new CreateEReferralRequestModel(); - - @override - void initState() { - super.initState(); - _controller = new PageController(); - } - - @override - void dispose() { - super.dispose(); - } - - changePageViewIndex(pageIndex) { - _controller.jumpToPage(pageIndex); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - body: Container( - height: double.infinity, - child: Column( - children: [ - Container( - width: double.infinity, - padding: EdgeInsets.only(left: 12,right: 12,top: 12), - child: Row( - children: [ - Expanded( - child: showProgress( - title: "Requester Info".needTranslation, - status: _currentIndex == 0 - ? "InProgress".needTranslation - : _currentIndex > 0 - ? "Completed".needTranslation - : "Locked".needTranslation, - color: _currentIndex == 0 ? AppColors.infoColor : AppColors.successColor, - ), - ), - Expanded( - child: showProgress( - title:"Patient Info".needTranslation, - status: _currentIndex == 1 - ? "InProgress".needTranslation - : _currentIndex > 1 - ? "Completed".needTranslation - : "Locked".needTranslation, - color: _currentIndex == 1 - ? AppColors.infoColor - : _currentIndex > 1 - ? AppColors.successColor - : AppColors.greyColor, - ), - ), - showProgress( - title: "Other Info".needTranslation, - status: _currentIndex == 2 ? "InProgress".needTranslation :"Locked".needTranslation, - color: _currentIndex == 2 - ? AppColors.infoColor - : _currentIndex > 3 - ? AppColors.successColor - : AppColors.greyColor, - isNeedBorder: false, - ), - ], - ), - ), - Expanded( - child: PageView( - physics: NeverScrollableScrollPhysics(), - controller: _controller, - onPageChanged: (index) { - setState(() { - _currentIndex = index; - }); - }, - scrollDirection: Axis.horizontal, - children: [ - // NewEReferralStepOnePage( - // changePageViewIndex: changePageViewIndex, - // createEReferralRequestModel: createEReferralRequestModel, - // ), - // NewEReferralStepTowPage( - // changePageViewIndex: changePageViewIndex, - // createEReferralRequestModel: createEReferralRequestModel, - // ), - // NewEReferralStepThreePage( - // changePageViewIndex: changePageViewIndex, - // createEReferralRequestModel: createEReferralRequestModel, - // ), - ], - ), - ), - ], - ), - ), - ); - } - - Widget showProgress({required String title, required String status, required Color color, bool isNeedBorder = true}) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Container( - width: 26, - height: 26, - // decoration: containerRadius(color, 200), - child: Icon( - Icons.done, - color: Colors.white, - size: 16, - ), - ), - if (isNeedBorder) - Expanded( - child: Padding( - padding: const EdgeInsets.all(8.0), - child:Divider(), - )), - ], - ), - // mHeight(8), - Text( - title, - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w600, - letterSpacing: -0.44, - ), - ), - // mHeight(2), - Container( - padding: EdgeInsets.all(5), - // decoration: containerRadius(color.withOpacity(0.2), 4), - child: Text( - status, - style: TextStyle( - fontSize: 8, - fontWeight: FontWeight.w600, - letterSpacing: -0.32, - color: color, - ), - ), - ), - ], - ) - ], - ); - } -} diff --git a/lib/presentation/e_referral/search_e_referral.dart b/lib/presentation/e_referral/search_e_referral.dart new file mode 100644 index 0000000..1a243da --- /dev/null +++ b/lib/presentation/e_referral/search_e_referral.dart @@ -0,0 +1,119 @@ +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/features/hmg_services/hmg_services_view_model.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/search_e_referral_req_model.dart'; +import 'package:hmg_patient_app_new/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/widget/search_e_referral_form.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/loader/bottomsheet_loader.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:provider/provider.dart'; +import 'e_referral_form_manager.dart'; +import 'e_referral_search_result.dart'; + +class SearchEReferralPage extends StatefulWidget { + + const SearchEReferralPage({ + super.key, + }); + + @override + State createState() => _SearchEReferralPageState(); +} + +class _SearchEReferralPageState extends State { + final ReferralFormManager _formManager = ReferralFormManager(); + late HmgServicesViewModel hmgServicesVM; + @override + void initState() { + super.initState(); + _loadData(); + } + + void _handleSearch() { + _formManager.validateSearchForm(); + if (!_formManager.isSearchFormInValid) { + _searchReferral(); + } + } + + void _searchReferral() { + SearchEReferralRequestModel searchEReferralReq; + + if (_formManager.searchCriteria == 0) { + searchEReferralReq = SearchEReferralRequestModel( + identificationNo: _formManager.searchValue, + patientMobileNumber: _formManager.formData.countryEnum.countryCode + _formManager.searchPhone!, + referralNumber: 0, + ); + } else { + + searchEReferralReq = SearchEReferralRequestModel(referralNumber: int.parse(_formManager.searchValue!), patientMobileNumber: _formManager.formData.patientPhone, identificationNo: ''); + } + + hmgServicesVM = context.read(); + LoaderBottomSheet.showLoader(); + hmgServicesVM.searchEReferral( + requestModel: searchEReferralReq, + onSuccess: (response) async { + LoaderBottomSheet.hideLoader(); + await Navigator.of(context).push( + CustomPageRoute( + page: SearchResultPage(), + fullScreenDialog: true, + direction: AxisDirection.down, + ), + ); + }, + + ); + } + + void _loadData() { + WidgetsBinding.instance.addPostFrameCallback((_) {}); + } + + @override + Widget build(BuildContext context) { + return CollapsingListView( + title: "Search E-Referral".needTranslation, + isClose: true, + bottomChild: Container( + color: Colors.white, + padding: EdgeInsets.all(ResponsiveExtension(20).h), + child: CustomButton( + text: LocaleKeys.search.tr(), + icon: AppAssets.search_icon, + iconColor: Colors.white, + onPressed: () => { + _handleSearch() + }, + ), + ), + child: ChangeNotifierProvider.value( + value: _formManager, + child: Column( + children: [ + _buildHeader(), + SearchEReferralFormForm(), + + ], + )), + ); + } + + Widget _buildHeader() { + return Padding( + 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()], + ), + ); + } + +} diff --git a/lib/presentation/e_referral/widget/e-referral_otp.dart b/lib/presentation/e_referral/widget/e-referral_otp.dart new file mode 100644 index 0000000..390fc71 --- /dev/null +++ b/lib/presentation/e_referral/widget/e-referral_otp.dart @@ -0,0 +1,102 @@ +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/enums.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/generated/locale_keys.g.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/bottomsheet/generic_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; +import 'package:provider/provider.dart'; +import 'package:hmg_patient_app_new/core/common_models/generic_api_model.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/req_models/send_activation_code_ereferral_req_model.dart'; + +class OTPService { + static void openOTPScreen({ + required BuildContext context, + required ReferralFormManager formManager, + required Function onSuccess, + }) { + _showOTPVerificationSheet(context: context, formManager: formManager, onSuccess: onSuccess); + } + + static void _showOTPVerificationSheet({ + required BuildContext context, + required ReferralFormManager formManager, + required Function onSuccess, + }) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + isDismissible: false, + useSafeArea: true, + backgroundColor: Colors.transparent, + builder: (bottomSheetContext) => Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom), + child: SingleChildScrollView( + child: GenericBottomSheet( + isEnableCountryDropdown: true, + textController: TextEditingController(), + onChange: (value) { + formManager.updateRequesterPhone(value ?? ''); + }, + onCountryChange: (value) { + formManager.updateCountryEnum(value); + }, + autoFocus: true, + buttons: [ + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: CustomButton( + text: LocaleKeys.sendOTPSMS.tr(), + onPressed: () async { + if (ValidationUtils.isValidatePhone( + phoneNumber: formManager.formData.requesterPhone, + onOkPress: () { + Navigator.pop(context); + }, + )) { + Navigator.pop(context); + final hmgServicesViewModel = context.read(); + + LoaderBottomSheet.showLoader(); + hmgServicesViewModel.eReferralSendActivationCode( + requestModel: SendActivationCodeForEReferralRequestModel( + patientMobileNumber: int.parse(formManager.formData.requesterPhone), + zipCode: formManager.formData.countryEnum.countryCode, + patientOutSA: formManager.formData.countryEnum.countryCode == '966' ? 0 : 1, + ), + onSuccess: (GenericApiModel response) { + LoaderBottomSheet.hideLoader(); + hmgServicesViewModel.navigateToOTPScreen( + otpTypeEnum: OTPTypeEnum.sms, + phoneNumber: formManager.formData.requesterPhone, + loginToken: response.data, + onSuccess: () { + Navigator.pop(context); + onSuccess(); + }); + }, + onError: (String errorMessage) { + LoaderBottomSheet.hideLoader(); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage))); + }, + ); + } + }, + backgroundColor: AppColors.primaryRedColor, + borderColor: AppColors.primaryRedBorderColor, + textColor: AppColors.whiteColor, + icon: AppAssets.message, + ), + ), + ], + ), + )), + ); + } +} diff --git a/lib/presentation/e_referral/widget/e_referral_other_details.dart b/lib/presentation/e_referral/widget/e_referral_other_details.dart new file mode 100644 index 0000000..fd1649f --- /dev/null +++ b/lib/presentation/e_referral/widget/e_referral_other_details.dart @@ -0,0 +1,319 @@ +import 'dart:io'; +import 'dart:convert'; +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/presentation/e_referral/e_referral_form_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart'; +import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/image_picker.dart'; + + +class OtherDetailsStep extends StatefulWidget { + const OtherDetailsStep({super.key}); + + @override + State createState() => _OtherDetailsStepState(); +} + +class _OtherDetailsStepState extends State { + final TextEditingController _medicalReportController = TextEditingController(); + final TextEditingController _insuranceController = TextEditingController(); + + late ReferralFormManager _formManager; + + @override + void initState() { + super.initState(); + _formManager = context.read(); + _updateMedicalReportText(); + _updateInsuranceText(); + } + + @override + void didUpdateWidget(OtherDetailsStep oldWidget) { + super.didUpdateWidget(oldWidget); + _updateMedicalReportText(); + _updateInsuranceText(); + } + + void _updateMedicalReportText() { + final hasMedicalReports = _formManager.formData.medicalReportImages.isNotEmpty; + _medicalReportController.text = hasMedicalReports + ? '${_formManager.formData.medicalReportImages.length} file(s) selected'.needTranslation + : ''; + } + + void _updateInsuranceText() { + final hasInsuranceDocs = _formManager.formData.insuredPatientImages.isNotEmpty; + _insuranceController.text = hasInsuranceDocs + ? '${_formManager.formData.insuredPatientImages.length} file(s) selected'.needTranslation + : ''; + + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, formManager, child) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: ListView( + physics: const BouncingScrollPhysics(), + children: [ + const SizedBox(height: 12), + _buildSectionTitle('Other Details'.needTranslation), + const SizedBox(height: 12), + _buildMedicalReportField(formManager), + _buildBranchField(context, formManager), + _buildInsuranceCheckbox(formManager), + if (formManager.formData.isPatientInsured) _buildInsuranceField(formManager), + ], + ), + ); + }, + ); + } + + Widget _buildSectionTitle(String title) { + return Text( + title, + style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16) + ).paddingSymmetrical(4, 0); + } + + Widget _buildMedicalReportField(ReferralFormManager formManager) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InkWell( + child: TextInputWidget( + controller: _medicalReportController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Medical Report'.needTranslation, + labelText: 'Select Attachment'.needTranslation, + suffix: const Icon(Icons.attachment), + isReadOnly: true, + errorMessage: formManager.errors.medicalReport, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.medicalReport), + ), + onTap: () { + ImageOptions.showImageOptionsNew( + context, + false, + (String image, File file) { + _addMedicalReport(image, file, formManager); + }, + ); + }, + ), + if (formManager.formData.medicalReportImages.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + child: Wrap( + spacing: 8.0, + children: formManager.formData.medicalReportImages.asMap().entries.map((entry) { + final index = entry.key; + return Chip( + label: Text('Medical Report ${index + 1}'.needTranslation), + deleteIcon: const Icon(Icons.close, size: 16), + onDeleted: () { + _removeMedicalReport(index, formManager); + }, + ); + }).toList(), + ), + ), + ], + ).paddingSymmetrical(0, 4); + } + + Widget _buildBranchField(BuildContext context, ReferralFormManager formManager) { + return DropdownWidget( + labelText: 'Branch', + hintText: formManager.formData.branch?.desciption ?? "Select Branch", + isEnable: false, + hasSelectionCustomIcon: true, + labelColor: Colors.black, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + selectionCustomIcon: AppAssets.arrow_down, + leadingIcon: AppAssets.hospital, + dropdownItems: [], + errorMessage: formManager.errors.branch, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.branch), + ).paddingSymmetrical(0, 4).onPress(() { + _showBranchBottomSheet(context, formManager); + }); + } + + Widget _buildInsuranceCheckbox(ReferralFormManager formManager) { + return Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Row( + children: [ + Checkbox( + value: formManager.formData.isPatientInsured, + activeColor: Colors.red, + onChanged: (bool? newValue) { + final value = newValue ?? false; + formManager.updateIsPatientInsured(value); + if (!value) { + _updateInsuranceText(); + } + }, + ), + Padding( + padding: EdgeInsets.all(5.0), + child: + "Patient is Insured".needTranslation.toText14( + color: Colors.black, + weight: FontWeight.w600, + ), + // style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), + //), + ), + ], + ), + ], + ).paddingSymmetrical(0, 4); + } + + Widget _buildInsuranceField(ReferralFormManager formManager) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InkWell( + child: TextInputWidget( + controller: _insuranceController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Insurance Document'.needTranslation, + labelText: 'Select Attachment'.needTranslation, + suffix: const Icon(Icons.attachment), + isReadOnly: true, + errorMessage: formManager.errors.insuredDocument, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.insuredDocument), + ), + onTap: () { + ImageOptions.showImageOptionsNew( + context, + false, + (String image, File file) { + _addInsuranceDocument(image, file, formManager); + }, + ); + }, + ), + if (formManager.formData.insuredPatientImages.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + child: Wrap( + spacing: 8.0, + children: formManager.formData.insuredPatientImages.asMap().entries.map((entry) { + final index = entry.key; + return Chip( + label: Text('Insurance ${index + 1}'), + deleteIcon: const Icon(Icons.close, size: 16), + onDeleted: () { + _removeInsuranceDocument(index, formManager); + }, + ); + }).toList(), + ), + ), + ], + ); + } + + void _showBranchBottomSheet(BuildContext context, ReferralFormManager formManager) { + final habibWalletVM = context.read(); + + showCommonBottomSheetWithoutHeight( + context, + title: "Select Branch".needTranslation, + child: Consumer( + builder: (context, habibWalletVM, child) { + final hospitals = habibWalletVM.advancePaymentHospitals; + if (hospitals == null || hospitals.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.all(16.0), + child: Text('No branches available'), + ), + ); + } + + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: Colors.white, + customBorder: BorderRadius.all(Radius.circular(24.h)) , + + ), child: ListView.builder( + shrinkWrap: true, + padding: EdgeInsets.all(16.h), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) { + final branch = hospitals[index]; + return ListTile( + title: (branch.desciption ?? 'Unknown').toText14(), + onTap: () { + formManager.updateBranch(branch); + Navigator.pop(context); + }, + ); + }, + // separatorBuilder: (context, index) => const Divider(), + itemCount: hospitals.length, + )); + }, + ), + useSafeArea: true, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + void _addMedicalReport(String image, File file, ReferralFormManager formManager) { + final newAttachment = EReferralAttachment( + fileName: 'medical_report_${formManager.formData.medicalReportImages.length + 1}.png', + base64String: image + ); + + formManager.addMedicalReport(newAttachment); + _updateMedicalReportText(); + } + + void _removeMedicalReport(int index, ReferralFormManager formManager) { + formManager.removeMedicalReport(index); + _updateMedicalReportText(); + } + + void _addInsuranceDocument(String image, File file, ReferralFormManager formManager) { + final newAttachment = EReferralAttachment( + fileName: 'insurance_${formManager.formData.insuredPatientImages.length + 1}.png', + base64String: image + ); + + formManager.addInsuranceDocument(newAttachment); + _updateInsuranceText(); + } + + void _removeInsuranceDocument(int index, ReferralFormManager formManager) { + formManager.removeInsuranceDocument(index); + _updateInsuranceText(); + } + + @override + void dispose() { + _medicalReportController.dispose(); + _insuranceController.dispose(); + super.dispose(); + } +} \ No newline at end of file diff --git a/lib/presentation/e_referral/widget/e_referral_patient_info.dart b/lib/presentation/e_referral/widget/e_referral_patient_info.dart new file mode 100644 index 0000000..469755c --- /dev/null +++ b/lib/presentation/e_referral/widget/e_referral_patient_info.dart @@ -0,0 +1,235 @@ +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/presentation/e_referral/e_referral_form_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; +import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; + +class PatientInformationStep extends StatefulWidget { + const PatientInformationStep({super.key}); + + @override + State createState() => PatientInformationStepState(); +} + +class PatientInformationStepState extends State { + late TextEditingController _identificationController; + late TextEditingController _nameController; + late TextEditingController _phoneController; + + late FocusNode _identificationFocusNode; + late FocusNode _nameFocusNode; + late FocusNode _phoneFocusNode; + + late ReferralFormManager _formManager; + + @override + void initState() { + super.initState(); + _formManager = context.read(); + + _identificationController = TextEditingController(); + _nameController = TextEditingController(); + _phoneController = TextEditingController(); + + _identificationFocusNode = FocusNode(); + _nameFocusNode = FocusNode(); + _phoneFocusNode = FocusNode(); + + // Initialize controllers with current values + _identificationController.text = _formManager.formData.patientIdentification ?? ''; + _nameController.text = _formManager.formData.patientName ?? ''; + _phoneController.text = _formManager.formData.patientPhone ?? ''; + + // Auto-focus the identification field when the step loads + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _identificationFocusNode.requestFocus(); + } + }); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, formManager, child) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: ListView( + physics: const BouncingScrollPhysics(), + children: [ + const SizedBox(height: 12), + _buildSectionTitle('Patient information'.needTranslation), + const SizedBox(height: 12), + _buildIdentificationField(formManager), + _buildPatientNameField(formManager), + // _buildPatientCountryField(context, formManager), + _buildPatientPhoneField(formManager), + const SizedBox(height: 20), + _buildSectionTitle('Where the patient located'.needTranslation), + _buildPatientCityField(context, formManager), + ], + ), + ); + }, + ); + } + + Widget _buildSectionTitle(String title) { + return Text( + title, + style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16) + ).paddingSymmetrical(4, 0); + } + + Widget _buildIdentificationField(ReferralFormManager formManager) { + return Focus( + focusNode: _identificationFocusNode, + child: TextInputWidget( + controller: _identificationController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Enter Identification Number*'.needTranslation, + labelText: 'Identification Number'.needTranslation, + errorMessage: formManager.errors.patientIdentification, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientIdentification), + onChange: (value) { + formManager.updatePatientIdentification(value ?? ''); + }, + onSubmitted: (value) { + _nameFocusNode.requestFocus(); + }, + ).paddingSymmetrical(0, 4), + ); + } + + Widget _buildPatientNameField(ReferralFormManager formManager) { + return Focus( + focusNode: _nameFocusNode, + child: TextInputWidget( + controller: _nameController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Patient Name*'.needTranslation, + labelText: 'Name'.needTranslation, + keyboardType: TextInputType.text, + errorMessage: formManager.errors.patientName, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientName), + onChange: (value) { + formManager.updatePatientName(value ?? ''); + }, + onSubmitted: (value) { + // Optionally move to next field or keep focus + }, + ).paddingSymmetrical(0, 4), + ); + } + + Widget _buildPatientPhoneField(ReferralFormManager formManager) { + return Focus( + focusNode: _phoneFocusNode, + child: TextInputWidget( + labelText: 'Phone Number'.needTranslation, + hintText: "5xxxxxxxx", + controller: _phoneController, + padding: const EdgeInsets.all(8), + keyboardType: TextInputType.number, + onChange: (value) { + formManager.updatePatientPhone(value ?? ''); + }, + onCountryChange: (value) { + formManager.updatePatientCountryEnum(value); + }, + prefix: '966', + isBorderAllowed: false, + isAllowLeadingIcon: true, + fontSize: 13, + isCountryDropDown: true, + leadingIcon: AppAssets.smart_phone, + errorMessage: formManager.errors.patientPhone, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientPhone) + ).paddingSymmetrical(0, 8), + ); + } + + Widget _buildPatientCityField(BuildContext context, ReferralFormManager formManager) { + return DropdownWidget( + labelText: 'City', + hintText: formManager.formData.patientCity?.description ?? "Select City".needTranslation, + isEnable: false, + hasSelectionCustomIcon: true, + labelColor: Colors.black, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + selectionCustomIcon: AppAssets.arrow_down, + leadingIcon: AppAssets.globe, + dropdownItems: [], + errorMessage: formManager.errors.patientCity, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientCity), + ).paddingSymmetrical(0, 4).onPress(() { + _showCityBottomSheet(context, formManager); + }); + } + + + void _showCityBottomSheet(BuildContext context, ReferralFormManager formManager) { + + showCommonBottomSheetWithoutHeight( + context, + title: "Select City".needTranslation, + child: Consumer( + builder: (context, hmgServicesVM, child) { + final cities = hmgServicesVM.getAllCitiesList; + if (cities == null || cities.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.all(16.0), + child: Text('No cities available'), + ), + ); + } + + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: Colors.white, + customBorder: BorderRadius.all(Radius.circular(24.h)) , + + ), child: ListView.builder( + shrinkWrap: true, + padding: EdgeInsets.all(16.h), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) { + final city = cities[index]; + return ListTile( + title: (city.description ?? 'Unknown').toText14(), + onTap: () { + formManager.updatePatientCity(city); + Navigator.pop(context); + }, + ); + }, + // separatorBuilder: (context, index) => const Divider(), + itemCount: cities.length, + )); + }, + ), + useSafeArea: true, + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + @override + void dispose() { + _identificationController.dispose(); + _nameController.dispose(); + _phoneController.dispose(); + _identificationFocusNode.dispose(); + _nameFocusNode.dispose(); + _phoneFocusNode.dispose(); + super.dispose(); + } +} \ No newline at end of file diff --git a/lib/presentation/e_referral/widget/e_referral_requester_form.dart b/lib/presentation/e_referral/widget/e_referral_requester_form.dart new file mode 100644 index 0000000..cc981a9 --- /dev/null +++ b/lib/presentation/e_referral/widget/e_referral_requester_form.dart @@ -0,0 +1,206 @@ +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/presentation/e_referral/e_referral_form_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:hmg_patient_app_new/core/app_assets.dart'; +import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart'; +import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; + +class RequesterFormStep extends StatefulWidget { + const RequesterFormStep({super.key}); + + @override + State createState() => RequesterFormStepState(); +} + +class RequesterFormStepState extends State { + late TextEditingController _nameController; + late TextEditingController _phoneController; + late TextEditingController _otherNameController; + + late FocusNode _nameFocusNode; + late FocusNode _phoneFocusNode; + late FocusNode _otherNameFocusNode; + + late ReferralFormManager _formManager; + + @override + void initState() { + super.initState(); + _formManager = context.read(); + + _nameController = TextEditingController(); + _phoneController = TextEditingController(); + _otherNameController = TextEditingController(); + + _nameFocusNode = FocusNode(); + _phoneFocusNode = FocusNode(); + _otherNameFocusNode = FocusNode(); + + // Initialize controllers with current values + _nameController.text = _formManager.formData.requesterName ?? ''; + _phoneController.text = _formManager.formData.requesterPhone ?? ''; + _otherNameController.text = _formManager.formData.otherRelationshipName ?? ''; + + // Auto-focus the name field when the step loads + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _nameFocusNode.requestFocus(); + } + }); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, formManager, child) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 0.0), + child: ListView( + padding: EdgeInsets.zero, + shrinkWrap: true, + physics: const BouncingScrollPhysics(), + children: [ + // const SizedBox(height: 12), + _buildSectionTitle('Referral requester information'.needTranslation), + const SizedBox(height: 12), + _buildNameField(formManager), + // _buildPhoneField(formManager), + _buildRelationshipField(context, formManager), + if (_showOtherNameField(formManager)) _buildOtherNameField(formManager), + ], + ), + ); + }, + ); + } + + Widget _buildSectionTitle(String title) { + return Text( + title, + style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16) + ).paddingSymmetrical(4, 0); + } + + Widget _buildNameField(ReferralFormManager formManager) { + return Focus( + focusNode: _nameFocusNode, + child: TextInputWidget( + controller: _nameController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Enter Referral Requester Name*'.needTranslation, + labelText: 'Requester Name'.needTranslation, + keyboardType: TextInputType.text, + errorMessage: formManager.errors.requesterName, + isAllowLeadingIcon: true, + leadingIcon: AppAssets.user_circle, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.requesterName), + onChange: (value) { + formManager.updateRequesterName(value ?? ''); + }, + + ).paddingSymmetrical(0, 8), + ); + } + Widget _buildRelationshipField(BuildContext context, ReferralFormManager formManager) { + return DropdownWidget( + labelText: "Relationship".needTranslation, + hintText: formManager.formData.relationship?.textEn ?? "Select Relation".needTranslation, + isEnable: false, + selectedValue: formManager.formData.relationship?.textEn ?? "Select Relation".needTranslation, + errorMessage: formManager.errors.relationship, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.relationship), + hasSelectionCustomIcon: false, + labelColor: Colors.black, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + leadingIcon: AppAssets.user_circle, + dropdownItems: [], + ).paddingSymmetrical(0, 8).onPress(() { + _showRelationshipBottomSheet(context, formManager); + }); + } + + Widget _buildOtherNameField(ReferralFormManager formManager) { + return Focus( + focusNode: _otherNameFocusNode, + child: TextInputWidget( + controller: _otherNameController, + keyboardType: TextInputType.text, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: 'Other Name*'.needTranslation, + labelText: 'Other Name'.needTranslation, + errorMessage: formManager.errors.otherRelationshipName, + onChange: (value) { + formManager.updateOtherRelationshipName(value ?? ''); + }, + ).paddingSymmetrical(0, 4), + ); + } + + bool _showOtherNameField(ReferralFormManager formManager) { + return formManager.formData.relationship != null && + formManager.formData.relationship?.iD == 5; + } + + void _showRelationshipBottomSheet(BuildContext context, ReferralFormManager formManager) { + final hmgServicesVM = context.read(); + + showCommonBottomSheetWithoutHeight( + context, + title: "Select Relation".needTranslation, + child: Consumer( + builder: (context, hmgServicesVM, child) { + if (hmgServicesVM.relationTypes.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.all(16.0), + child: Text('No relationships available'), + ), + ); + } + + return DecoratedBox( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: Colors.white, + customBorder: BorderRadius.all(Radius.circular(24.h)) , + + ), child: ListView.builder( + shrinkWrap: true, + padding: EdgeInsets.all(16.h), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) { + final relationship = hmgServicesVM.relationTypes[index]; + return ListTile( + title:relationship.textEn?.toText14(), + onTap: () { + formManager.updateRelationship(relationship); + Navigator.pop(context); + }, + ); + }, + //separatorBuilder: (context, index) => const Divider(), + itemCount: hmgServicesVM.relationTypes.length, + )); + }, + ), + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + @override + void dispose() { + _nameController.dispose(); + _phoneController.dispose(); + _otherNameController.dispose(); + _nameFocusNode.dispose(); + _phoneFocusNode.dispose(); + _otherNameFocusNode.dispose(); + super.dispose(); + } +} \ No newline at end of file diff --git a/lib/presentation/e_referral/widget/search_e_referral_form.dart b/lib/presentation/e_referral/widget/search_e_referral_form.dart new file mode 100644 index 0000000..fa3ae19 --- /dev/null +++ b/lib/presentation/e_referral/widget/search_e_referral_form.dart @@ -0,0 +1,199 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/utils/validation_utils.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.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'; +import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart'; +import 'package:hmg_patient_app_new/widgets/input_widget.dart'; +import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart'; + +class SearchEReferralFormForm extends StatefulWidget { + final VoidCallback? onFormValidated; + const SearchEReferralFormForm({super.key, this.onFormValidated}); + + @override + State createState() => SearchEReferralFormFormState(); +} + +class SearchEReferralFormFormState extends State { + late TextEditingController _searchController; + late TextEditingController _phoneController; + late FocusNode _searchFocusNode; + late FocusNode _phoneFocusNode; + + @override + void initState() { + super.initState(); + + _searchController = TextEditingController(); + _phoneController = TextEditingController(); + _searchFocusNode = FocusNode(); + _phoneFocusNode = FocusNode(); + + // Initialize controllers with current values from form manager + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + final formManager = context.read(); + _searchController.text = formManager.searchValue ?? ''; + _phoneController.text = formManager.searchPhone ?? ''; + // _searchFocusNode.requestFocus(); + } + }); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, formManager, child) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: ListView( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + children: [ + // const SizedBox(height: 12), + _buildSelectionField(context, formManager), + _buildNameField(formManager), + _buildPhoneField(formManager), + ], + ), + ); + }, + ); + } + + Widget _buildNameField(ReferralFormManager formManager) { + return Focus( + focusNode: _searchFocusNode, + autofocus: true, + child: TextInputWidget( + controller: _searchController, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + hintText: formManager.searchCriteria == 0 ? "Enter Identification Number" : "Enter Referral Number", + labelText: formManager.searchCriteria == 0 ? "Identification Number" : "Referral Number", + keyboardType: TextInputType.number, + errorMessage: formManager.errors.searchValue, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.searchValue), + onChange: (value) { + formManager.updateSearchValue(value ?? ''); + //_validateForm(formManager); + }, + ).paddingSymmetrical(0, 8), + ); + } + + Widget _buildPhoneField(ReferralFormManager formManager) { + return Focus( + focusNode: _phoneFocusNode, + autofocus: false, + child: TextInputWidget( + autoFocus: false, + labelText: 'Phone Number', + hintText: "5xxxxxxxx", + controller: _phoneController, + padding: const EdgeInsets.all(8), + keyboardType: TextInputType.number, + onChange: (value) { + formManager.updateSearchPhone(value ?? ''); + // _validateForm(formManager); + }, + // onSubmitted: (value) { + // formManager.updateRequesterPhone(value ?? ''); + // _validateForm(formManager); + // }, + onCountryChange: (value) { + formManager.updateCountryEnum(value); + // _validateForm(formManager); + }, + prefix: '966', + isBorderAllowed: false, + isAllowLeadingIcon: true, + fontSize: 13, + isCountryDropDown: true, + leadingIcon: AppAssets.smart_phone, + errorMessage: formManager.errors.searchPhone, + hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.searchPhone), + ).paddingSymmetrical(0, 8), + ); + } + + Widget _buildSelectionField(BuildContext context, ReferralFormManager formManager) { + return DropdownWidget( + labelText: "Select the Search Criteria", + hintText: formManager.searchCriteria == 0 ? "Identification Number" : "Referral Number", + isEnable: false, + hasSelectionCustomIcon: false, + labelColor: Colors.black, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + leadingIcon: AppAssets.search_icon, + dropdownItems: [], + ).paddingSymmetrical(0, 8).onPress(() { + _showCriteriaBottomSheet(context, formManager); + }); + } + + void _showCriteriaBottomSheet(BuildContext context, ReferralFormManager formManager) { + final criteriaList = [ + {0: 'Identification Number'}, + {1: 'Referral Number'}, + ]; + + showCommonBottomSheetWithoutHeight( + context, + title: "Select Criteria", + child: ListView.separated( + shrinkWrap: true, + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) { + final criteria = criteriaList[index]; + final criteriaKey = criteria.keys.first; + final criteriaValue = criteria.values.first; + + return ListTile( + leading: Radio( + value: criteriaKey, + groupValue: formManager.searchCriteria, + onChanged: (value) { + if (value != null) { + formManager.updateSearchCriteria(value); + _searchController.clear(); + _validateForm(formManager); + Navigator.pop(context); + } + }, + ), + title: Text(criteriaValue), + onTap: () { + formManager.updateSearchCriteria(criteriaKey); + _searchController.clear(); + _validateForm(formManager); + Navigator.pop(context); + }, + ); + }, + separatorBuilder: (context, index) => const Divider(), + itemCount: criteriaList.length, + ), + isFullScreen: false, + isCloseButtonVisible: true, + ); + } + + void _validateForm(ReferralFormManager formManager) { + // Trigger validation + formManager.validateSearchForm(); + + // Notify parent if form validation state changes + widget.onFormValidated?.call(); + } + + @override + void dispose() { + _searchController.dispose(); + _phoneController.dispose(); + _searchFocusNode.dispose(); + _phoneFocusNode.dispose(); + super.dispose(); + } +} 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 9410af1..051c850 100644 --- a/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart +++ b/lib/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart @@ -23,7 +23,7 @@ class PickupLocation extends StatelessWidget { children: [ "Select Pickup Direction" .needTranslation - .toText24(color: AppColors.textColor,isBold: true), + .toText24(color: AppColors.textColor, isBold: true), SizedBox( height: 16.h, ), @@ -34,128 +34,147 @@ class PickupLocation extends StatelessWidget { height: 12.h, ), Selector( - selector: (context, viewModel) => viewModel.callingPlace, - builder: (context, value, _) { - return Column( - spacing: 12.h, - children: [ - RadioGroup( - groupValue: value, - onChanged: (value) { - context - .read() - .updateCallingPlace(value); - }, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - spacing: 24.h, - children: [ - Row( - children: [ - Radio( - value: AmbulanceCallingPlace.TO_HOSPITAL, - groupValue: value, - activeColor: AppColors.primaryRedColor, - - fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), - ), - "To Hospital" - .needTranslation - .toText14(color: AppColors.textColor, weight: FontWeight.w500) - ], - ).onPress((){ - context - .read() - .updateCallingPlace(AmbulanceCallingPlace.TO_HOSPITAL); - }), - Row( - children: [ - Radio( - value: AmbulanceCallingPlace.FROM_HOSPITAL, - activeColor: AppColors.primaryRedColor, - - fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), - ), - "From Hospital" - .needTranslation - .toText14(color: AppColors.textColor, weight: FontWeight.w500) - ], - ).onPress((){ - context - .read() - .updateCallingPlace(AmbulanceCallingPlace.FROM_HOSPITAL); - }), - ], + selector: (context, viewModel) => viewModel.callingPlace, + builder: (context, value, _) { + return Column( + children: [ + SizedBox(height: 12.h), + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + child: Row( + children: [ + Radio( + value: AmbulanceCallingPlace.TO_HOSPITAL, + groupValue: value, + onChanged: (AmbulanceCallingPlace? newValue) { + if (newValue != null) { + context + .read() + .updateCallingPlace(newValue); + } + }, + activeColor: AppColors.primaryRedColor, + fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), + ), + "To Hospital" + .needTranslation + .toText14(color: AppColors.textColor, weight: FontWeight.w500) + ], + ).onPress(() { + context + .read() + .updateCallingPlace(AmbulanceCallingPlace.TO_HOSPITAL); + }), ), - ), - Visibility( - visible: value == AmbulanceCallingPlace.TO_HOSPITAL, - child: Selector( - selector: (context, viewModel) => - viewModel.ambulanceDirection, - builder: (context, directionValue, _) { - return Column( - spacing: 12.h, - crossAxisAlignment: CrossAxisAlignment.start, + Expanded( + child: Row( + children: [ + Radio( + value: AmbulanceCallingPlace.FROM_HOSPITAL, + groupValue: value, + onChanged: (AmbulanceCallingPlace? newValue) { + if (newValue != null) { + context + .read() + .updateCallingPlace(newValue); + } + }, + activeColor: AppColors.primaryRedColor, + fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), + ), + "From Hospital" + .needTranslation + .toText14(color: AppColors.textColor, weight: FontWeight.w500) + ], + ).onPress(() { + context + .read() + .updateCallingPlace(AmbulanceCallingPlace.FROM_HOSPITAL); + }), + ), + ], + ), + Visibility( + visible: value == AmbulanceCallingPlace.TO_HOSPITAL, + child: Selector( + selector: (context, viewModel) => viewModel.ambulanceDirection, + builder: (context, directionValue, _) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + "Select Way" + .needTranslation + .toText16(color: AppColors.textColor, weight: FontWeight.w600), + SizedBox(height: 12.h), + Row( + mainAxisAlignment: MainAxisAlignment.start, children: [ - "Select Way" - .needTranslation - .toText16(color: AppColors.textColor, weight: FontWeight.w600), - RadioGroup( - groupValue: directionValue, - onChanged: (value) { + Expanded( + child: Row( + children: [ + Radio( + value: AmbulanceDirection.ONE_WAY, + groupValue: directionValue, + onChanged: (AmbulanceDirection? newValue) { + if (newValue != null) { + context + .read() + .updateDirection(newValue); + } + }, + activeColor: AppColors.primaryRedColor, + fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), + ), + "One Way" + .needTranslation + .toText12(color: AppColors.textColor, fontWeight: FontWeight.w500) + ], + ).onPress(() { context .read() - .updateDirection(value); - }, + .updateDirection(AmbulanceDirection.ONE_WAY); + }), + ), + Expanded( child: Row( - mainAxisAlignment: MainAxisAlignment.start, - spacing: 24.h, children: [ - Row( - children: [ - Radio( - value: AmbulanceDirection.ONE_WAY, - activeColor: AppColors.primaryRedColor, - - fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), - ), - "One Way" - .needTranslation - .toText12(color: AppColors.textColor, fontWeight: FontWeight.w500) - ], - ).onPress((){ - context - .read() - .updateDirection(AmbulanceDirection.ONE_WAY); - }), - Row( - children: [ - Radio( - value: AmbulanceDirection.TWO_WAY, - // activeColor: AppColors.primaryRedColor, - - fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), - ), - "Two Way" - .needTranslation - .toText14(color: AppColors.textColor, weight: FontWeight.w500) - ], - ).onPress((){ - context - .read() - .updateDirection(AmbulanceDirection.TWO_WAY); - }), + Radio( + value: AmbulanceDirection.TWO_WAY, + groupValue: directionValue, + onChanged: (AmbulanceDirection? newValue) { + if (newValue != null) { + context + .read() + .updateDirection(newValue); + } + }, + activeColor: AppColors.primaryRedColor, + fillColor: MaterialStateProperty.all(AppColors.primaryRedColor), + ), + "Two Way" + .needTranslation + .toText14(color: AppColors.textColor, weight: FontWeight.w500) ], - ), + ).onPress(() { + context + .read() + .updateDirection(AmbulanceDirection.TWO_WAY); + }), ), ], - ); - }), - ) - ], - ); - }), + ), + ], + ); + }, + ), + ) + ], + ); + }, + ), SizedBox( height: 16.h, ), @@ -170,4 +189,4 @@ class PickupLocation extends StatelessWidget { ], ); } -} +} \ No newline at end of file diff --git a/lib/presentation/hmg_services/services_page.dart b/lib/presentation/hmg_services/services_page.dart index af576aa..fd6e976 100644 --- a/lib/presentation/hmg_services/services_page.dart +++ b/lib/presentation/hmg_services/services_page.dart @@ -1,6 +1,7 @@ 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/features/hmg_services/models/ui_models/hmg_services_component_model.dart'; import 'package:hmg_patient_app_new/presentation/hmg_services/services_view.dart'; @@ -22,7 +23,7 @@ class ServicesPage extends StatelessWidget { route: AppRoutes.eReferralPage, ), HmgServicesComponentModel( - 12, + 5, "Comprehensive Checkup".needTranslation, "".needTranslation, AppAssets.comprehensiveCheckup, @@ -32,7 +33,7 @@ class ServicesPage extends StatelessWidget { route: AppRoutes.comprehensiveCheckupPage, ), HmgServicesComponentModel( - 12, + 3, "Home Health Care".needTranslation, "".needTranslation, AppAssets.emergency_services_icon, @@ -41,6 +42,21 @@ class ServicesPage extends StatelessWidget { textColor: AppColors.blackColor, route: AppRoutes.homeHealthCarePage, ), + HmgServicesComponentModel( + 11, + "Virtual Tour".needTranslation, + "".needTranslation, + AppAssets.my_address, + true, + bgColor: Colors.orange, + textColor: AppColors.blackColor, + route: null, + onTap:(){ + Utils.openWebView( + url: 'https://hmgwebservices.com/vt_mobile/html/index.html', + ); + }, + ) ]; @override @@ -49,7 +65,7 @@ class ServicesPage extends StatelessWidget { title: "Explore Services".needTranslation, isLeading: Navigator.canPop(context), child: Padding( - padding: EdgeInsets.all(24.h), + padding: EdgeInsets.symmetric(horizontal: 24.h), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -60,9 +76,9 @@ class ServicesPage extends StatelessWidget { child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, // 4 icons per row - crossAxisSpacing: 16.w, - mainAxisSpacing: 24.h, - childAspectRatio: 0.75, + crossAxisSpacing: 24.w, + mainAxisSpacing: 0.h, + childAspectRatio: 0.85, ), physics: NeverScrollableScrollPhysics(), shrinkWrap: true, diff --git a/lib/presentation/hmg_services/services_view.dart b/lib/presentation/hmg_services/services_view.dart index 225bd96..2cd923f 100644 --- a/lib/presentation/hmg_services/services_view.dart +++ b/lib/presentation/hmg_services/services_view.dart @@ -11,13 +11,19 @@ class ServiceGridViewItem extends StatelessWidget { final int index; final bool isHomePage; final bool isLocked; - - const ServiceGridViewItem(this.hmgServiceComponentModel, this.index, this.isHomePage, {super.key, this.isLocked = false}); + final Function? onTap; + const ServiceGridViewItem(this.hmgServiceComponentModel, this.index, this.isHomePage, {super.key, this.isLocked = false, this.onTap}); @override Widget build(BuildContext context) { return InkWell( - onTap: () => getIt.get().pushPageRoute(hmgServiceComponentModel.route), + onTap: () { + hmgServiceComponentModel.route != null + ? getIt.get().pushPageRoute(hmgServiceComponentModel.route!) + : hmgServiceComponentModel.onTap != null + ? hmgServiceComponentModel.onTap!() + : null; + }, child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, @@ -33,6 +39,7 @@ class ServiceGridViewItem extends StatelessWidget { ), child: Utils.buildSvgWithAssets( icon: hmgServiceComponentModel.icon, + iconColor: hmgServiceComponentModel.iconColor, height: 21.h, width: 21.w, fit: BoxFit.none, diff --git a/lib/presentation/home/data/landing_page_data.dart b/lib/presentation/home/data/landing_page_data.dart index 0178720..e6716cc 100644 --- a/lib/presentation/home/data/landing_page_data.dart +++ b/lib/presentation/home/data/landing_page_data.dart @@ -81,7 +81,7 @@ class LandingPageData { ServiceCardData( serviceName: "lab_results", icon: AppAssets.home_lab_result_icon, - title: "My Lab", + title: "Lab", subtitle: "Results", backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, @@ -91,7 +91,7 @@ class LandingPageData { ServiceCardData( serviceName: "radiology_results", icon: AppAssets.home_lab_result_icon, - title: "My Radiology", + title: "Radiology", subtitle: "Results", backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, @@ -101,8 +101,8 @@ class LandingPageData { ServiceCardData( serviceName: "prescriptions", icon: AppAssets.my_prescription_icon, - title: "My", - subtitle: "Prescriptions", + title: "Prescriptions", + subtitle: "Details", backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -112,7 +112,7 @@ class LandingPageData { serviceName: "insurance_update", icon: AppAssets.insurance_update_icon, title: "Insurance", - subtitle: "Update", + subtitle: "Details", backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, textColor: AppColors.blackColor, @@ -131,7 +131,7 @@ class LandingPageData { ServiceCardData( serviceName: "sick_leaves", icon: AppAssets.insurance_update_icon, - title: "My Sick", + title: "Sick", subtitle: "Leaves", backgroundColor: AppColors.whiteColor, iconColor: AppColors.blackColor, diff --git a/lib/presentation/home/landing_page.dart b/lib/presentation/home/landing_page.dart index 454f1e7..52464b1 100644 --- a/lib/presentation/home/landing_page.dart +++ b/lib/presentation/home/landing_page.dart @@ -9,6 +9,7 @@ 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/cache_consts.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/int_extensions.dart'; @@ -41,11 +42,14 @@ import 'package:hmg_patient_app_new/presentation/home/widgets/welcome_widget.dar import 'package:hmg_patient_app_new/presentation/medical_file/medical_file_page.dart'; import 'package:hmg_patient_app_new/presentation/profile_settings/profile_settings.dart'; import 'package:hmg_patient_app_new/routes/app_routes.dart'; +import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.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/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/countdown_timer.dart'; 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'; @@ -93,259 +97,374 @@ class _LandingPageState extends State { if (appState.isAuthenticated) { habibWalletVM.initHabibWalletProvider(); habibWalletVM.getPatientBalanceAmount(); + immediateLiveCareViewModel.initImmediateLiveCare(); + immediateLiveCareViewModel.getPatientLiveCareHistory(); myAppointmentsViewModel.initAppointmentsViewModel(); myAppointmentsViewModel.getPatientAppointments(true, false); myAppointmentsViewModel.getPatientMyDoctors(); prescriptionsViewModel.initPrescriptionsViewModel(); insuranceViewModel.initInsuranceProvider(); - immediateLiveCareViewModel.initImmediateLiveCare(); - immediateLiveCareViewModel.getPatientLiveCareHistory(); emergencyServicesViewModel.checkPatientERAdvanceBalance(); } }); super.initState(); } - Widget buildOptionsForAuthenticatedUser() { - return Column( - children: [ - SizedBox(height: 12.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "Appointments & Visits".toText16(isBold: true), - Row( - children: [ - LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor), - SizedBox(width: 2.h), - Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), - ], - ), - ], - ).paddingSymmetrical(24.h, 0.h).onPress(() { - Navigator.of(context).push(CustomPageRoute(page: MyAppointmentsPage())); - }), - SizedBox(height: 16.h), - Consumer( - builder: (context, myAppointmentsVM, child) { - return myAppointmentsVM.isMyAppointmentsLoading - ? Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, - ), - child: AppointmentCard( - patientAppointmentHistoryResponseModel: PatientAppointmentHistoryResponseModel(), - myAppointmentsViewModel: myAppointmentsViewModel, - bookAppointmentsViewModel: bookAppointmentsViewModel, - isLoading: true, - isFromHomePage: true, - ), - ).paddingSymmetrical(24.h, 0.h) - : myAppointmentsVM.patientAppointmentsHistoryList.isNotEmpty - ? myAppointmentsVM.patientAppointmentsHistoryList.length == 1 - ? Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, - ), - child: AppointmentCard( - patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList.first, - myAppointmentsViewModel: myAppointmentsViewModel, - bookAppointmentsViewModel: bookAppointmentsViewModel, - isLoading: false, - 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: 200.h, - pagination: const SwiperPagination( - alignment: Alignment.bottomCenter, - margin: EdgeInsets.only(top: 210 + 8 + 24), - builder: DotSwiperPaginationBuilder(color: Color(0xffD9D9D9), activeColor: AppColors.blackBgColor), - ), - itemBuilder: (BuildContext context, int index) { - return Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 24.r, - hasShadow: true, - ), - child: AppointmentCard( - patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index], - myAppointmentsViewModel: myAppointmentsViewModel, - bookAppointmentsViewModel: bookAppointmentsViewModel, - isLoading: false, - isFromHomePage: true, - ), - ); - }, - ) - : Container( - width: double.infinity, - decoration: - RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), - child: Padding( - padding: EdgeInsets.all(12.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), - SizedBox(height: 12.h), - CustomButton( - text: LocaleKeys.bookAppo.tr(context: context), - onPressed: () { - Navigator.of(context).push(CustomPageRoute(page: BookAppointmentPage())); - }, - backgroundColor: Color(0xffFEE9EA), - borderColor: Color(0xffFEE9EA), - textColor: Color(0xffED1C2B), - fontSize: 14.f, - fontWeight: FontWeight.w500, - padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), - icon: AppAssets.add_icon, - iconColor: AppColors.primaryRedColor, - height: 46.h, - ), - ], - ), - ), - ).paddingSymmetrical(24.h, 0.h); - }, - ), + @override + Widget build(BuildContext context) { + bookAppointmentsViewModel = Provider.of(context, listen: false); + myAppointmentsViewModel = Provider.of(context, listen: false); + prescriptionsViewModel = Provider.of(context, listen: false); + insuranceViewModel = Provider.of(context, listen: false); + immediateLiveCareViewModel = Provider.of(context, listen: false); + emergencyServicesViewModel = Provider.of(context, listen: false); + appState = getIt.get(); + return PopScope( + canPop: false, + child: Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: SingleChildScrollView( + padding: EdgeInsets.only(top: kToolbarHeight + 0.h, bottom: 24), + child: Column( + spacing: 16.h, + children: [ + Row( + spacing: 8.h, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + appState.isAuthenticated + ? WelcomeWidget( + onTap: () { + Navigator.of(context).push(springPageRoute(ProfileSettings())); + }, + name: ('${appState.getAuthenticatedUser()!.firstName!} ${appState.getAuthenticatedUser()!.lastName!}'), + imageUrl: appState.getAuthenticatedUser()?.gender == 1 ? AppAssets.male_img : AppAssets.femaleImg, + ).expanded + : CustomButton( + text: LocaleKeys.loginOrRegister.tr(context: context), + onPressed: () async { + await authVM.onLoginPressed(); - // Consumer for LiveCare pending request - Consumer( - builder: (context, immediateLiveCareVM, child) { - return immediateLiveCareVM.patientHasPendingLiveCareRequest - ? 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), + // Navigator.pushReplacementNamed( + // // context, + // context, + // AppRoutes.zoomCallPage, + // // arguments: CallArguments(appointmentID, "111", "Patient", "40", "1", true, 1), + // arguments: CallArguments("test123", "123", "Patient", "40", "0", true, 1), + // // arguments: CallArguments("SmallDailyStandup9875", "123", "Patient", "40", "0", false, int.parse(widget.incomingCallData!.appointmentNo!)), + // ); + }, + backgroundColor: AppColors.secondaryLightRedColor, + borderColor: AppColors.secondaryLightRedColor, + textColor: AppColors.primaryRedColor, + fontSize: 14.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), + height: 40.h, ), - width: double.infinity, - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - AppCustomChipWidget( - labelText: immediateLiveCareViewModel.patientLiveCareHistoryList[0].stringCallStatus, - backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.20), - textColor: AppColors.alertColor, - ), - 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: 40.h, height: 40.h, fit: BoxFit.contain), - ], - ), - SizedBox(height: 8.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "You have a pending LiveCare request".needTranslation.toText12(isBold: true), - Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon_small, - iconColor: AppColors.blackColor, - width: 20.h, - height: 15.h, - fit: BoxFit.contain, - ), - ], - ), - ], + 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(), ), - ), - ).paddingSymmetrical(24.h, 0.h).onPress(() { - Navigator.of(context).push(CustomPageRoute(page: ImmediateLiveCarePendingRequestPage())); + ); + }), + Utils.buildSvgWithAssets(icon: AppAssets.search_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, + ); }), - SizedBox(height: 12.h), ], - ) - : SizedBox(height: 12.h); - }, - ), - - // Consumer for ER Online Check-In pending request - Consumer( - builder: (context, emergencyServicesVM, child) { - return emergencyServicesVM.patientHasAdvanceERBalance - ? Column( - children: [ - SizedBox(height: 4.h), - Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration( - color: AppColors.whiteColor, - borderRadius: 20.r, - hasShadow: true, - side: BorderSide(color: AppColors.primaryRedColor, width: 3.h), + ), + ], + ).paddingSymmetrical(24.h, 0.h), + appState.isAuthenticated + ? Column( + children: [ + SizedBox(height: 12.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "Appointments & Visits".toText16(isBold: true), + Row( + children: [ + LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor), + SizedBox(width: 2.h), + Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h), + ], + ), + ], + ).paddingSymmetrical(24.h, 0.h).onPress(() { + Navigator.of(context).push(CustomPageRoute(page: MyAppointmentsPage())); + }), + SizedBox(height: 16.h), + Consumer2( + builder: (context, myAppointmentsVM, immediateLiveCareVM, child) { + return myAppointmentsVM.isMyAppointmentsLoading + ? Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: AppointmentCard( + patientAppointmentHistoryResponseModel: PatientAppointmentHistoryResponseModel(), + myAppointmentsViewModel: myAppointmentsViewModel, + bookAppointmentsViewModel: bookAppointmentsViewModel, + isLoading: true, + isFromHomePage: true, + ), + ).paddingSymmetrical(24.h, 0.h) + : myAppointmentsVM.patientAppointmentsHistoryList.isNotEmpty + ? myAppointmentsVM.patientAppointmentsHistoryList.length == 1 + ? Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.r, + hasShadow: true, + ), + child: AppointmentCard( + patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList.first, + myAppointmentsViewModel: myAppointmentsViewModel, + bookAppointmentsViewModel: bookAppointmentsViewModel, + isLoading: false, + 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 (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.".toText14(isBold: true), + SizedBox(height: 8.h), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + "Expected waiting time: ".toText12(isBold: true), + SizedBox(height: 8.h), + ValueListenableBuilder( + valueListenable: immediateLiveCareVM.durationNotifier, + builder: (context, duration, child) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + buildTime(duration), + ], + ); + }, + ), + SizedBox(height: 12.h), + ], + ), + // 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), + ], + ) + : 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, + ), + ); + }, + ) + : Container( + width: double.infinity, + decoration: RoundedRectangleBorder() + .toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), + child: Padding( + padding: EdgeInsets.all(12.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), + SizedBox(height: 12.h), + CustomButton( + text: LocaleKeys.bookAppo.tr(context: context), + onPressed: () { + Navigator.of(context).push(CustomPageRoute(page: BookAppointmentPage())); + }, + backgroundColor: Color(0xffFEE9EA), + borderColor: Color(0xffFEE9EA), + textColor: Color(0xffED1C2B), + fontSize: 14.f, + fontWeight: FontWeight.w500, + padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0), + icon: AppAssets.add_icon, + iconColor: AppColors.primaryRedColor, + height: 46.h, + ), + ], + ), + ), + ).paddingSymmetrical(24.h, 0.h); + }, ), - width: double.infinity, - child: Padding( - padding: EdgeInsets.all(16.h), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - AppCustomChipWidget( - labelText: "ER Online Check-In Request", - backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.10), - textColor: AppColors.primaryRedColor, - ), - Utils.buildSvgWithAssets( - icon: AppAssets.appointment_checkin_icon, width: 24.h, height: 24.h, iconColor: AppColors.primaryRedColor), - ], - ), - SizedBox(height: 8.h), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - "You have ER Online Check-In Request".needTranslation.toText12(isBold: true), - Utils.buildSvgWithAssets( - icon: AppAssets.forward_arrow_icon_small, - iconColor: AppColors.blackColor, - width: 20.h, - height: 15.h, - fit: BoxFit.contain, - ), - ], - ), - ], - ), + + // Consumer for ER Online Check-In pending request + Consumer( + builder: (context, emergencyServicesVM, child) { + return emergencyServicesVM.patientHasAdvanceERBalance + ? Column( + children: [ + SizedBox(height: 4.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + hasShadow: true, + side: BorderSide(color: AppColors.primaryRedColor, width: 3.h), + ), + width: double.infinity, + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + AppCustomChipWidget( + labelText: "ER Online Check-In Request", + backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.10), + textColor: AppColors.primaryRedColor, + ), + Utils.buildSvgWithAssets(icon: AppAssets.appointment_checkin_icon, width: 24.h, height: 24.h, iconColor: AppColors.primaryRedColor), + ], + ), + SizedBox(height: 8.h), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "You have ER Online Check-In Request".needTranslation.toText12(isBold: true), + Utils.buildSvgWithAssets( + icon: AppAssets.forward_arrow_icon_small, + iconColor: AppColors.blackColor, + width: 20.h, + height: 15.h, + fit: BoxFit.contain, + ), + ], + ), + ], + ), + ), + ).paddingSymmetrical(24.h, 0.h).onPress(() { + Navigator.of(context).push(CustomPageRoute(page: ErOnlineCheckinHome())); + // context.read().navigateToEROnlineCheckIn(); + }), + SizedBox(height: 12.h), + ], + ) + : SizedBox(height: 12.h); + }, ), - ).paddingSymmetrical(24.h, 0.h).onPress(() { - Navigator.of(context).push(CustomPageRoute(page: ErOnlineCheckinHome())); - // context.read().navigateToEROnlineCheckIn(); - }), - SizedBox(height: 12.h), - ], - ) - : SizedBox(height: 12.h); - }, - ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -525,7 +644,7 @@ class _LandingPageState extends State { Navigator.of(context).push(CustomPageRoute(page: ServicesPage())); }), ], - ).paddingSymmetrical(24.h, 0.h), + ).paddingSymmetrical(24.w, 0.h), SizedBox( height: 340.h, child: ListView.separated( @@ -572,10 +691,13 @@ class _LandingPageState extends State { isDone: isDone, onPressed: () { // sharedPref.setBool(HAS_ENABLED_QUICK_LOGIN, true); - authVM.loginWithFingerPrintFace(() { + authVM.loginWithFingerPrintFace(() async { isDone = true; cacheService.saveBool(key: CacheConst.quickLoginEnabled, value: true); setState(() {}); + await Future.delayed(Duration(milliseconds: 2000)).then((value) { + if (mounted) Navigator.pop(context); + }); }); }, ); diff --git a/lib/presentation/home/navigation_screen.dart b/lib/presentation/home/navigation_screen.dart index 18803cc..f8447d2 100644 --- a/lib/presentation/home/navigation_screen.dart +++ b/lib/presentation/home/navigation_screen.dart @@ -33,7 +33,7 @@ class _LandingNavigationState extends State { appState.isAuthenticated ? MedicalFilePage() : /* need add feedback page */ FeedbackPage(), BookAppointmentPage(), const ToDoPage(), - appState.isAuthenticated ? /* need add news page */ ServicesPage() : const LandingPage(), + ServicesPage(), ], ), bottomNavigationBar: BottomNavigation( diff --git a/lib/presentation/insurance/insurance_approval_details_page.dart b/lib/presentation/insurance/insurance_approval_details_page.dart index 437c870..150b15c 100644 --- a/lib/presentation/insurance/insurance_approval_details_page.dart +++ b/lib/presentation/insurance/insurance_approval_details_page.dart @@ -118,7 +118,7 @@ class InsuranceApprovalDetailsPage extends StatelessWidget { ), child: Padding( padding: EdgeInsets.all(16.h), - child: Column( + child: insuranceApprovalResponseModel.apporvalDetails != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ "Approval Details".toText16(isBold: true), @@ -128,7 +128,7 @@ class InsuranceApprovalDetailsPage extends StatelessWidget { children: [ LocaleKeys.procedureName.tr(context: context).toText14(isBold: true), Expanded( - child: insuranceApprovalResponseModel.apporvalDetails!.procedureName! + child: (insuranceApprovalResponseModel.apporvalDetails!.procedureName ?? "") .toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor, textAlignment: TextAlign.end, maxLine: 2), ), ], @@ -150,7 +150,7 @@ class InsuranceApprovalDetailsPage extends StatelessWidget { ], ), ], - ), + ) : SizedBox.shrink(), ), ) ], diff --git a/lib/presentation/insurance/widgets/insurance_history.dart b/lib/presentation/insurance/widgets/insurance_history.dart index a5114dd..3e6ee86 100644 --- a/lib/presentation/insurance/widgets/insurance_history.dart +++ b/lib/presentation/insurance/widgets/insurance_history.dart @@ -68,7 +68,7 @@ class InsuranceHistory extends StatelessWidget { Row( children: [ CustomButton( - text: insuranceVM.patientInsuranceCardHistoryList[index].statusDescription!, + text: insuranceVM.patientInsuranceCardHistoryList[index].statusDescription ?? "", onPressed: () {}, backgroundColor: AppColors.primaryRedColor.withOpacity(0.1), borderColor: AppColors.primaryRedColor.withOpacity(0.0), diff --git a/lib/presentation/lab/lab_orders_page.dart b/lib/presentation/lab/lab_orders_page.dart index 0efa5da..874ef6c 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/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_order_by_test.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/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 '../../widgets/appbar/collapsing_list_view.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 Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( 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: SingleChildScrollView( padding: EdgeInsets.all(24.h), physics: NeverScrollableScrollPhysics(), child: Consumer( builder: (context, model, child) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ 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(() {}); }, ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.isLabOrdersLoading ? 5 : model.patientLabOrders.isNotEmpty ? model.patientLabOrders.length : 1, itemBuilder: (context, index) { final isExpanded = expandedIndex == index; return model.isLabOrdersLoading ? LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ) : model.patientLabOrders.isNotEmpty ? AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: LabResultItemView( onTap: () { model.currentlySelectedPatientOrder = model.patientLabOrders[index]; labProvider.getPatientLabResultByHospital(model.patientLabOrders[index]); labProvider.getPatientSpecialResult(model.patientLabOrders[index]); Navigator.push( context, CustomPageRoute( page: LabResultByClinic(labOrder: model.patientLabOrders[index]), )); }, labOrder: model.patientLabOrders[index], index: index, isExpanded: isExpanded), ), ), ) : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation); }, ) : ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.isLabOrdersLoading ? 5 : model.uniqueTests.toList().isNotEmpty ? model.uniqueTests.toList().length : 1, itemBuilder: (context, index) { final isExpanded = expandedIndex == index; return model.isLabOrdersLoading ? LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ) : model.uniqueTests.toList().isNotEmpty ? AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: LabOrderByTest( appState: _appState, onTap: () { if (model.uniqueTests.toList()[index].model != null) { rangeViewModel.flush(); model.getPatientLabResult( model.uniqueTests.toList()[index].model!, model.uniqueTests.toList()[index].description!, (_appState.isArabic() ? model.uniqueTests.toList()[index].testDescriptionAr! : model.uniqueTests.toList()[index].testDescriptionEn!)); } }, tests: model.uniqueTests.toList()[index], index: index, isExpanded: isExpanded)), ), ) : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation); }, ) ], ); }, ), ), )); } 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/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_order_by_test.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/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 '../../widgets/appbar/collapsing_list_view.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 Scaffold( backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( 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: SingleChildScrollView( padding: EdgeInsets.all(24.h), physics: NeverScrollableScrollPhysics(), child: Consumer( builder: (context, model, child) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ 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(() {}); }, ), SizedBox(height: 8.h), selectedFilterText!.isNotEmpty ? CustomChipWidget( chipText: selectedFilterText!, chipType: ChipTypeEnum.alert, isSelected: true, ) : SizedBox(), activeIndex == 0 ? ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.isLabOrdersLoading ? 5 : model.patientLabOrders.isNotEmpty ? model.patientLabOrders.length : 1, itemBuilder: (context, index) { final isExpanded = expandedIndex == index; return model.isLabOrdersLoading ? LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ) : model.patientLabOrders.isNotEmpty ? AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: LabResultItemView( onTap: () { model.currentlySelectedPatientOrder = model.patientLabOrders[index]; labProvider.getPatientLabResultByHospital(model.patientLabOrders[index]); labProvider.getPatientSpecialResult(model.patientLabOrders[index]); Navigator.push( context, CustomPageRoute( page: LabResultByClinic(labOrder: model.patientLabOrders[index]), )); }, labOrder: model.patientLabOrders[index], index: index, isExpanded: isExpanded), ), ), ) : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation); }, ) : ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: model.isLabOrdersLoading ? 5 : model.uniqueTests.toList().isNotEmpty ? model.uniqueTests.toList().length : 1, itemBuilder: (context, index) { final isExpanded = expandedIndex == index; return model.isLabOrdersLoading ? LabResultItemView( onTap: () {}, labOrder: null, index: index, isLoading: true, ) : model.uniqueTests.toList().isNotEmpty ? AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 500), child: SlideAnimation( verticalOffset: 100.0, child: FadeInAnimation( child: LabOrderByTest( appState: _appState, onTap: () { if (model.uniqueTests.toList()[index].model != null) { rangeViewModel.flush(); model.getPatientLabResult(model.uniqueTests.toList()[index].model!, model.uniqueTests.toList()[index].description!, (_appState.isArabic() ? model.uniqueTests.toList()[index].testDescriptionAr! : model.uniqueTests.toList()[index].testDescriptionEn!), ""); } }, tests: model.uniqueTests.toList()[index], index: index, isExpanded: isExpanded)), ), ) : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation); }, ) ], ); }, ), ), )); } 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/LabResultList.dart b/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart index 8893ffd..3f05443 100644 --- a/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart +++ b/lib/presentation/lab/lab_result_via_clinic/LabResultList.dart @@ -26,7 +26,7 @@ class LabResultList extends StatelessWidget { shrinkWrap: true,itemCount: list.length,itemBuilder: (____, index) { var labItem = list[index]; return LabOrderResultItem(onTap: () { - model.getPatientLabResult(model.currentlySelectedPatientOrder!, labItem.description ?? "", labItem.packageShortDescription!); + model.getPatientLabResult(model.currentlySelectedPatientOrder!, labItem.description ?? "", labItem.packageShortDescription!, labItem.uOM ?? ""); }, tests: labItem, index: index, diff --git a/lib/presentation/lab/lab_results/lab_result_details.dart b/lib/presentation/lab/lab_results/lab_result_details.dart index 2330d0d..67eae63 100644 --- a/lib/presentation/lab/lab_results/lab_result_details.dart +++ b/lib/presentation/lab/lab_results/lab_result_details.dart @@ -59,115 +59,72 @@ class LabResultDetails extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - recentLabResult.testCode ?? "", - style: TextStyle( - fontSize: 32, - fontFamily: 'Poppins', - fontWeight: FontWeight.w600, - color: AppColors.textColor, - letterSpacing: -2), - ), - Text( - "Result of ${recentLabResult.verifiedOn ?? ""}".needTranslation, - style: TextStyle( - fontSize: 12, - fontFamily: 'Poppins', - fontWeight: FontWeight.w500, - color: AppColors.greyTextColor, - ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + (recentLabResult.testCode ?? "").toText28(isBold: true, color: AppColors.textColor, letterSpacing: -2), + Visibility( + visible: recentLabResult.checkIfGraphShouldBeDisplayed() == true, + child: Column( + spacing: 6.h, + children: [ + context + .read() + .getSeverityText( + recentLabResult.calculatedResultFlag ?? "", + ) + .tr() + .toText10(weight: FontWeight.w500, color: AppColors.greyTextColor), + Utils.buildSvgWithAssets( + icon: AppAssets.lab_result_indicator, + width: 21, + height: 23, + iconColor: context.read().getColor( + recentLabResult.calculatedResultFlag ?? "", + )), + ], + ), + ), + ], ), + SizedBox(height: 4.h), + ("Result of ${recentLabResult.verifiedOn ?? ""}".needTranslation).toText11(weight: FontWeight.w500, color: AppColors.greyTextColor), ], ), - //todo change the text color according to the provided test values Row( crossAxisAlignment: CrossAxisAlignment.center, - children: [ Expanded( child: Row( - mainAxisSize: MainAxisSize.max, children: [ Flexible( - child: Text( - "${recentLabResult.resultValue} ${recentLabResult.uOM}" ?? - "", - style: TextStyle( - fontSize: 24.f, - fontWeight: FontWeight.w600, - fontFamily: 'Poppins', + child: ("${recentLabResult.resultValue} ${recentLabResult.uOM}" ?? "").toText28( + isBold: true, color: context.read().getColor( recentLabResult.calculatedResultFlag ?? "", - ), - letterSpacing: -2, - ), - overflow: TextOverflow.ellipsis, // prevent overflow - maxLines: 1, - softWrap: false, - ), + ), + letterSpacing: -2), ), SizedBox(width: 4.h,), - Expanded( - flex: 2, - child: Visibility( - visible: recentLabResult.referanceRange != null, - child: Text( - "(Reference range ${recentLabResult.referanceRange})".needTranslation, - style: TextStyle( - fontSize: 12.f, - fontWeight: FontWeight.w500, - fontFamily: 'Poppins', - color: AppColors.greyTextColor, - ), - // overflow: TextOverflow.ellipsis, - // maxLines: 2, - softWrap: true, - ), - ), - ), - ], - ), - ), - Visibility( - visible: - recentLabResult.checkIfGraphShouldBeDisplayed() == true, - child: Column( - spacing: 6.h, - children: [ - context - .read() - .getSeverityText( - recentLabResult.calculatedResultFlag ?? "", - ) - .tr() - .toText10( - weight: FontWeight.w500, - color: AppColors.greyTextColor), - Utils.buildSvgWithAssets( - icon: AppAssets.lab_result_indicator, - width: 21, - height: 23, - iconColor: context.read().getColor( - recentLabResult.calculatedResultFlag ?? "", - )), ], ), ), - // SizedBox( - // width: 21, - // child: Utils.buildSvgWithAssets( - // icon: AppAssets.lab_result_indicator, - // width: 21, - // height: 23, - // iconColor: context.read().getColor( - // recentLabResult.calculatedResultFlag ?? "", - // ), - // ), - // ), ], - ) - + ), + Visibility( + visible: recentLabResult.referanceRange != null, + child: Text( + "Reference range: \n${recentLabResult.referanceRange!.trim()}".needTranslation, + style: TextStyle( + fontSize: 12.f, + fontWeight: FontWeight.w500, + fontFamily: 'Poppins', + color: AppColors.greyTextColor, + ), + softWrap: true, + ), + ), ], )); diff --git a/lib/presentation/medical_file/medical_file_page.dart b/lib/presentation/medical_file/medical_file_page.dart index 05ae91a..c1922d0 100644 --- a/lib/presentation/medical_file/medical_file_page.dart +++ b/lib/presentation/medical_file/medical_file_page.dart @@ -26,6 +26,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/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/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'; @@ -84,7 +85,6 @@ class _MedicalFilePageState extends State { appState = getIt.get(); scheduleMicrotask(() { if (appState.isAuthenticated) { - labViewModel.initLabProvider(); insuranceViewModel.initInsuranceProvider(); medicalFileViewModel.setIsPatientSickLeaveListLoading(true); medicalFileViewModel.getPatientSickLeaveList(); @@ -225,9 +225,9 @@ class _MedicalFilePageState extends State { ), AppCustomChipWidget( icon: AppAssets.blood_icon, - labelText: "Blood: ${appState.getUserBloodGroup.isEmpty ? "N/A" : appState.getUserBloodGroup.isEmpty}", + labelText: "Blood: ${appState.getUserBloodGroup.isEmpty ? "N/A" : appState.getUserBloodGroup.isEmpty}".needTranslation, iconColor: AppColors.primaryRedColor, - labelPadding: EdgeInsetsDirectional.only(end: 8.w), + labelPadding: EdgeInsetsDirectional.only(end: 4.w, start: 0.w), ), Consumer(builder: (context, insuranceVM, child) { return AppCustomChipWidget( @@ -390,6 +390,7 @@ class _MedicalFilePageState extends State { : ListView.separated( scrollDirection: Axis.horizontal, shrinkWrap: true, + padding: EdgeInsets.only(left: 24.w, right: 24.w), itemCount: myAppointmentsVM.patientAppointmentsHistoryList.length, itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( @@ -407,15 +408,42 @@ class _MedicalFilePageState extends State { onRescheduleTap: () { openDoctorScheduleCalendar(myAppointmentsVM.patientAppointmentsHistoryList[index]); }, - onAskDoctorTap: () {}, + 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) { + 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 { + print("Doctor is not available"); + } + }); + }, )), ), ), ); }, - separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 12.h), + separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 16.w), ), - ).paddingSymmetrical(24.w, 0); + ); }), SizedBox(height: 24.h), "Lab & Radiology".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0.h), @@ -430,6 +458,7 @@ class _MedicalFilePageState extends State { labOrderTests: labViewModel.isLabOrdersLoading ? [] : labViewModel.labOrderTests, isLoading: labViewModel.isLabOrdersLoading, ).onPress(() { + labViewModel.initLabProvider(); Navigator.of(context).push( CustomPageRoute( page: LabOrdersPage(), @@ -544,9 +573,9 @@ class _MedicalFilePageState extends State { }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h), ), - SizedBox(height: 24.h), + SizedBox(height: 8.h), const Divider(color: AppColors.dividerColor), - SizedBox(height: 24.h), + SizedBox(height: 8.h), Row( children: [ Expanded( @@ -667,11 +696,12 @@ class _MedicalFilePageState extends State { ), ).paddingSymmetrical(24.w, 0.h) : SizedBox( - height: 100.h, + height: 110.h, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: myAppointmentsVM.patientMyDoctorsList.length, shrinkWrap: true, + padding: EdgeInsets.only(left: 24.w, right: 24.w), itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( position: index, @@ -691,7 +721,8 @@ class _MedicalFilePageState extends State { fit: BoxFit.cover, ).circle(100).toShimmer2(isShow: false, radius: 50.r), SizedBox(height: 8.h), - Expanded( + SizedBox( + width: 80.w, child: (myAppointmentsVM.patientMyDoctorsList[index].doctorName) .toString() .toText12(fontWeight: FontWeight.w500, isCenter: true, maxLine: 2) @@ -730,7 +761,7 @@ class _MedicalFilePageState extends State { }, separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h), ), - ).paddingSymmetrical(24.w, 0); + ); }), SizedBox(height: 24.h), "Others".needTranslation.toText18(isBold: true).paddingSymmetrical(24.w, 0.h), diff --git a/lib/presentation/medical_file/widgets/lab_rad_card.dart b/lib/presentation/medical_file/widgets/lab_rad_card.dart index 1a56baf..696b332 100644 --- a/lib/presentation/medical_file/widgets/lab_rad_card.dart +++ b/lib/presentation/medical_file/widgets/lab_rad_card.dart @@ -43,29 +43,29 @@ class LabRadCard extends StatelessWidget { Flexible(child: labelText.toText14(isBold: true).toShimmer2(isShow: false, radius: 6.r, height: 32.h)), ], ), - SizedBox(height: 16.h), - labOrderTests.isNotEmpty - ? ListView.separated( - scrollDirection: Axis.vertical, - padding: EdgeInsets.zero, - physics: NeverScrollableScrollPhysics(), - shrinkWrap: true, - itemBuilder: (cxt, index) { - return labOrderTests[index] - .toText12(isBold: true, maxLine: 1) - .toShimmer2(isShow: false, radius: 6.r, height: 24.h, width: 120.w) - .toShimmer2(isShow: isLoading); - }, - separatorBuilder: (cxt, index) => SizedBox(height: 8.h), - itemCount: 3, - ) - : "You don't have any records yet".needTranslation.toText13( - color: AppColors.greyTextColor, isCenter: true), + // SizedBox(height: 16.h), + // labOrderTests.isNotEmpty + // ? ListView.separated( + // scrollDirection: Axis.vertical, + // padding: EdgeInsets.zero, + // physics: NeverScrollableScrollPhysics(), + // shrinkWrap: true, + // itemBuilder: (cxt, index) { + // return labOrderTests[index] + // .toText12(isBold: true, maxLine: 1) + // .toShimmer2(isShow: false, radius: 6.r, height: 24.h, width: 120.w) + // .toShimmer2(isShow: isLoading); + // }, + // separatorBuilder: (cxt, index) => SizedBox(height: 8.h), + // itemCount: 3, + // ) + // : "You don't have any records yet".needTranslation.toText13( + // color: AppColors.greyTextColor, isCenter: true), SizedBox(height: 16.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - SizedBox.shrink(), + "View All".toText12(isBold: true), Transform.flip( flipX: appState.isArabic(), child: Utils.buildSvgWithAssets( 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 3924761..1b09dd5 100644 --- a/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart +++ b/lib/presentation/medical_file/widgets/medical_file_appointment_card.dart @@ -53,7 +53,7 @@ class MedicalFileAppointmentCard extends StatelessWidget { ).toShimmer2(isShow: myAppointmentsViewModel.isMyAppointmentsLoading), SizedBox(height: 16.h), Container( - decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true), + decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false), width: 200.w, child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -167,7 +167,9 @@ class MedicalFileAppointmentCard extends StatelessWidget { return DateTime.now().difference(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate)).inDays <= 15 ? CustomButton( text: LocaleKeys.askDoctor.tr(context: context), - onPressed: () {}, + onPressed: () { + onAskDoctorTap(); + }, backgroundColor: AppColors.secondaryLightRedColor, borderColor: AppColors.secondaryLightRedColor, textColor: AppColors.primaryRedColor, diff --git a/lib/presentation/medical_file/widgets/medical_file_card.dart b/lib/presentation/medical_file/widgets/medical_file_card.dart index 8c38363..6343e2a 100644 --- a/lib/presentation/medical_file/widgets/medical_file_card.dart +++ b/lib/presentation/medical_file/widgets/medical_file_card.dart @@ -29,7 +29,7 @@ class MedicalFileCard extends StatelessWidget { decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: backgroundColor, borderRadius: 12.r, - hasShadow: true + hasShadow: false ), padding: EdgeInsets.all(12.w), child: Column( diff --git a/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart b/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart new file mode 100644 index 0000000..0bedbe2 --- /dev/null +++ b/lib/presentation/prescriptions/prescription_delivery_order_summary_page.dart @@ -0,0 +1,174 @@ +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/string_extensions.dart'; +import 'package:hmg_patient_app_new/extensions/widget_extensions.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/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:provider/provider.dart'; + +class PrescriptionDeliveryOrderSummaryPage extends StatelessWidget { + PrescriptionDeliveryOrderSummaryPage({super.key}); + + late PrescriptionsViewModel prescriptionsViewModel; + + @override + Widget build(BuildContext context) { + prescriptionsViewModel = Provider.of(context, listen: false); + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: Column( + children: [ + Expanded( + child: CollapsingListView( + title: LocaleKeys.orderSummary.tr(context: context), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 16.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.orderDetail.tr(context: context).toText16(isBold: true), + SizedBox(height: 16.h), + ...List.generate( + prescriptionsViewModel.prescriptionDetailsList.length, + (index) => Container( + margin: EdgeInsets.all(0.0), + child: Row( + children: [ + ClipRRect( + borderRadius: BorderRadius.all( + Radius.circular(5.r), + ), + child: Image.network( + prescriptionsViewModel.prescriptionDetailsList[index].imageSRCUrl!, + fit: BoxFit.cover, + width: 60.w, + height: 70.h, + ), + ), + Expanded( + child: Padding( + padding: EdgeInsets.all(8.h), + child: Center( + child: prescriptionsViewModel.prescriptionDetailsList[index].itemDescription!.trim().toText12(), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + SizedBox(height: 16.h), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 20.r, + hasShadow: true, + ), + child: Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LocaleKeys.deliveryLocation.tr(context: context).toText16(isBold: true), + SizedBox(height: 16.h), + ClipRRect( + clipBehavior: Clip.hardEdge, + borderRadius: BorderRadius.circular(20.r), + child: Image.network( + "https://maps.googleapis.com/maps/api/staticmap?center=${prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lat},${prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lng}&zoom=15&size=350x165&maptype=roadmap&markers=color:red%7C${prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lat},${prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lng}&key=AIzaSyB6TERnxIr0yJ3qG4ULBZbu0sAD4tGqtng", + fit: BoxFit.contain, + ), + ), + ], + ), + ), + ), + ], + ).paddingSymmetrical(24.w, 0), + ), + ), + Container( + decoration: RoundedRectangleBorder().toSmoothCornerDecoration( + color: AppColors.whiteColor, + borderRadius: 24.h, + hasShadow: true, + ), + child: CustomButton( + text: LocaleKeys.submit.tr(context: context), + onPressed: () async { + LoaderBottomSheet.showLoader(loadingText: "Submitting your request..."); + await prescriptionsViewModel.submitPrescriptionDeliveryRequest( + latitude: prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lat.toString(), + longitude: prescriptionsViewModel.locationGeocodeResponse.results.first.geometry.location.lng.toString(), + appointmentNo: prescriptionsViewModel.prescriptionDetailsList.first.appointmentNo.toString(), + dischargeID: "0", + projectID: prescriptionsViewModel.prescriptionDetailsList.first.projectID.toString(), + onSuccess: (val) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getSuccessWidget(loadingText: "Request sent successfully.".needTranslation), + callBackFunc: () { + Navigator.of(context).pop(); + }, + title: "", + isCloseButtonVisible: true, + isDismissible: false, + isFullScreen: false, + ); + }, + onError: (err) { + LoaderBottomSheet.hideLoader(); + showCommonBottomSheetWithoutHeight( + context, + child: Utils.getErrorWidget(loadingText: err), + callBackFunc: () { + Navigator.of(context).pop(); + }, + title: "", + isCloseButtonVisible: true, + isDismissible: false, + isFullScreen: false, + ); + }); + }, + backgroundColor: AppColors.successColor, + borderColor: AppColors.successColor.withOpacity(0.01), + textColor: AppColors.whiteColor, + fontSize: 16.f, + fontWeight: FontWeight.w500, + borderRadius: 12.r, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 50.h, + icon: AppAssets.prescription_refill_icon, + iconColor: AppColors.whiteColor, + iconSize: 20.h, + ).paddingSymmetrical(24.h, 24.h), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart b/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart new file mode 100644 index 0000000..9f2b2a2 --- /dev/null +++ b/lib/presentation/prescriptions/prescription_delivery_orders_list_page.dart @@ -0,0 +1,111 @@ +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/prescriptions/prescriptions_view_model.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/presentation/lab/lab_result_item_view.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:provider/provider.dart'; + +class PrescriptionDeliveryOrdersListPage extends StatelessWidget { + const PrescriptionDeliveryOrdersListPage({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgScaffoldColor, + body: CollapsingListView( + title: LocaleKeys.orders.tr(context: context), + child: SingleChildScrollView( + child: Consumer(builder: (context, model, child) { + return Column( + children: [ + ListView.builder( + itemCount: model.isPrescriptionsDeliveryOrdersLoading + ? 4 + : model.prescriptionsOrderList.isNotEmpty + ? model.prescriptionsOrderList.length + : 1, + physics: NeverScrollableScrollPhysics(), + shrinkWrap: true, + padding: const EdgeInsets.only(left: 0, right: 8), + itemBuilder: (context, index) { + return model.isPrescriptionsDeliveryOrdersLoading + ? LabResultItemView( + onTap: () {}, + labOrder: null, + index: index, + isLoading: true, + ) + : model.prescriptionsOrderList.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: InkWell( + onTap: () { + }, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.all(16.h), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8.h, + children: [ + RequestStatus(status: model.prescriptionsOrderList[index].statusId ?? 0), + "Req ID: ${model.prescriptionsOrderList[index].iD}".toText16(color: AppColors.textColor, weight: FontWeight.w600), + Row( + spacing: 4.w, + children: [ + chip(Utils.getDayMonthYearDateFormatted(DateTime.tryParse(model.prescriptionsOrderList[index].created!)), AppAssets.calendar, + AppColors.blackBgColor), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ) + : Utils.getNoDataWidget(context, noDataText: "You don't have any prescription orders yet.".needTranslation); + }, + ).paddingSymmetrical(24.h, 0.h), + ], + ); + }), + ), + ), + ); + } + + chip(String title, String iconString, Color iconColor) { + return AppCustomChipWidget( + labelText: title, + icon: iconString, + iconColor: iconColor, + iconSize: 12.h, + ); + } +} diff --git a/lib/presentation/prescriptions/prescription_detail_page.dart b/lib/presentation/prescriptions/prescription_detail_page.dart index d5e8138..a38ff92 100644 --- a/lib/presentation/prescriptions/prescription_detail_page.dart +++ b/lib/presentation/prescriptions/prescription_detail_page.dart @@ -4,7 +4,6 @@ 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/calendar_utils.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'; @@ -41,7 +40,6 @@ class _PrescriptionDetailPageState extends State { @override void initState() { - checkAndRemove(false); // locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context); // WidgetsBinding.instance.addPostFrameCallback((_) => locationUtils.getCurrentLocation()); if (!widget.isFromAppointments) { diff --git a/lib/presentation/prescriptions/prescription_item_view.dart b/lib/presentation/prescriptions/prescription_item_view.dart index acf03f5..100d963 100644 --- a/lib/presentation/prescriptions/prescription_item_view.dart +++ b/lib/presentation/prescriptions/prescription_item_view.dart @@ -2,7 +2,7 @@ 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/calendar_utils.dart'; +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'; @@ -10,6 +10,8 @@ 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/common_bottom_sheet.dart'; +import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart'; class PrescriptionItemView extends StatelessWidget { int index; @@ -154,15 +156,20 @@ class PrescriptionItemView extends StatelessWidget { activeTrackColor: AppColors.successColor.withValues(alpha: .15), value: isLoading ? false : prescriptionVM.prescriptionDetailsList[index].hasReminder!, onChanged: (newValue) async { + CalenderUtilsNew calender = CalenderUtilsNew.instance; + if (prescriptionVM.prescriptionDetailsList[index].hasReminder ?? false) { - await checkAndRemove(prescriptionVM.prescriptionDetailsList[index].hasReminder, delete: true); - prescriptionVM.notify(); + LoaderBottomSheet.showLoader(loadingText: "Removing Reminders"); + bool resultValue = await calender.checkAndRemoveMultipleItems(id:prescriptionVM.prescriptionDetailsList[index].itemID.toString()); + + prescriptionVM.setPrescriptionItemReminder(newValue, prescriptionVM.prescriptionDetailsList[index]); + LoaderBottomSheet.hideLoader(); return; } DateTime startDate = DateTime.now(); DateTime endDate = DateTime(startDate.year, startDate.month, startDate.day + prescriptionVM.prescriptionDetailsList[index].days!.toInt()); - showReminderBottomSheet( + BottomSheetUtils().showReminderBottomSheet( context, endDate, "", @@ -173,18 +180,29 @@ class PrescriptionItemView extends StatelessWidget { description: "${prescriptionVM.prescriptionDetailsList[index].itemDescription} ${prescriptionVM.prescriptionDetailsList[index].frequency} ${prescriptionVM.prescriptionDetailsList[index].route} ", onSuccess: () { - prescriptionVM.setPrescriptionItemReminder(newValue, prescriptionVM.prescriptionDetailsList[index]); + }, isMultiAllowed: true, - onMultiDateSuccess: (int selectedIndex) { - setCalender(context, - eventId: prescriptionVM.prescriptionDetailsList[index].itemID.toString(), - selectedMinutes: selectedIndex, + onMultiDateSuccess: (int selectedIndex) async{ + bool isEventAdded = await calender.createMultipleEvents( + reminderMinutes: selectedIndex, frequencyNumber: prescriptionVM.prescriptionDetailsList[index].frequencyNumber?.toInt(), - days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(), + days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(), orderDate: prescriptionVM.prescriptionDetailsList[index].orderDate!, itemDescriptionN: prescriptionVM.prescriptionDetailsList[index].itemDescription!, - route: prescriptionVM.prescriptionDetailsList[index].route!); + route: prescriptionVM.prescriptionDetailsList[index].route!, + onFailure: (errorMessage)=> prescriptionVM.showError(errorMessage), + prescriptionNumber: prescriptionVM.prescriptionDetailsList[index].itemID.toString(), + ); + prescriptionVM.setPrescriptionItemReminder(isEventAdded, prescriptionVM.prescriptionDetailsList[index]); + // setCalender(context, + // eventId: prescriptionVM.prescriptionDetailsList[index].itemID.toString(), + // selectedMinutes: selectedIndex, + // frequencyNumber: prescriptionVM.prescriptionDetailsList[index].frequencyNumber?.toInt(), + // days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(), + // orderDate: prescriptionVM.prescriptionDetailsList[index].orderDate!, + // itemDescriptionN: prescriptionVM.prescriptionDetailsList[index].itemDescription!, + // route: prescriptionVM.prescriptionDetailsList[index].route!); }, ); }, diff --git a/lib/presentation/prescriptions/prescription_reminder_view.dart b/lib/presentation/prescriptions/prescription_reminder_view.dart index 8b7df0b..2f1154f 100644 --- a/lib/presentation/prescriptions/prescription_reminder_view.dart +++ b/lib/presentation/prescriptions/prescription_reminder_view.dart @@ -100,7 +100,7 @@ class _PrescriptionReminderViewState extends State { text: LocaleKeys.setReminder.tr(), onPressed: () { Navigator.of(context).pop(); - widget.setReminder(_selectedOption); + widget.setReminder(_options[_selectedOption]); }, backgroundColor: AppColors.bgGreenColor, borderColor: AppColors.bgGreenColor, diff --git a/lib/presentation/prescriptions/prescriptions_list_page.dart b/lib/presentation/prescriptions/prescriptions_list_page.dart index 58c5206..3d631ce 100644 --- a/lib/presentation/prescriptions/prescriptions_list_page.dart +++ b/lib/presentation/prescriptions/prescriptions_list_page.dart @@ -6,6 +6,7 @@ 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/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/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; @@ -14,10 +15,13 @@ import 'package:hmg_patient_app_new/extensions/widget_extensions.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/lab/lab_result_item_view.dart'; +import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_delivery_orders_list_page.dart'; 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/loader/bottomsheet_loader.dart'; +import 'package:hmg_patient_app_new/widgets/map/map_utility_screen.dart'; 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:hmg_patient_app_new/widgets/transitions/fade_page.dart'; @@ -51,6 +55,14 @@ class _PrescriptionsListPageState extends State { backgroundColor: AppColors.bgScaffoldColor, body: CollapsingListView( title: LocaleKeys.prescriptions.tr(context: context), + requests: () { + prescriptionsViewModel.getPrescriptionOrdersList(); + Navigator.of(context).push( + CustomPageRoute( + page: PrescriptionDeliveryOrdersListPage(), + ), + ); + }, child: SingleChildScrollView( child: Consumer(builder: (context, model, child) { return Column( @@ -237,16 +249,26 @@ class _PrescriptionsListPageState extends State { text: prescription.isHomeMedicineDeliverySupported! ? LocaleKeys.resendOrder.tr(context: context) : LocaleKeys.prescriptionDeliveryError.tr(context: context), - onPressed: () {}, - backgroundColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor.withOpacity(0.15) : AppColors.greyF7Color, - borderColor: AppColors.successColor.withOpacity(0.01), - textColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.35), - fontSize: prescription.isHomeMedicineDeliverySupported! ? 14 : 12, - fontWeight: FontWeight.w500, - borderRadius: 12, - padding: EdgeInsets.fromLTRB(10, 0, 10, 0), - height: 40.h, - icon: AppAssets.prescription_refill_icon, + onPressed: () async { + if (prescription.isHomeMedicineDeliverySupported!) { + LoaderBottomSheet.showLoader(loadingText: "Fetching prescription details...".needTranslation); + await prescriptionsViewModel.getPrescriptionDetails(prescriptionsViewModel.patientPrescriptionOrders[index], + onSuccess: (val) { + LoaderBottomSheet.hideLoader(); + prescriptionsViewModel.initiatePrescriptionDelivery(); + }); + } + }, + backgroundColor: + prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor.withOpacity(0.15) : AppColors.greyF7Color, + borderColor: AppColors.successColor.withOpacity(0.01), + textColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.35), + fontSize: prescription.isHomeMedicineDeliverySupported! ? 14 : 12, + fontWeight: FontWeight.w500, + borderRadius: 12, + padding: EdgeInsets.fromLTRB(10, 0, 10, 0), + height: 40.h, + icon: AppAssets.prescription_refill_icon, iconColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.35), iconSize: 14.h, ), diff --git a/lib/presentation/tele_consultation/zoom/call_screen.dart b/lib/presentation/tele_consultation/zoom/call_screen.dart new file mode 100644 index 0000000..21ad42f --- /dev/null +++ b/lib/presentation/tele_consultation/zoom/call_screen.dart @@ -0,0 +1,1840 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:flutter_ios_voip_kit_karmm/flutter_ios_voip_kit.dart'; +import 'package:flutter_zoom_videosdk/flutter_zoom_view.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_camera_device.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_cmd_channel.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_event_listener.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_live_transcription_message_info.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_share_action.dart'; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk_user.dart'; +import 'package:get_it/get_it.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/core/cache_consts.dart'; +import 'package:hmg_patient_app_new/core/utils/jwt.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/presentation/home/navigation_screen.dart'; +import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/video_view.dart'; +import 'package:hmg_patient_app_new/services/cache_service.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; +import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart'; +import 'package:image_picker/image_picker.dart'; + +class CallScreen extends StatefulHookWidget { + const CallScreen({Key? key}) : super(key: key); + + @override + State createState() => _CallScreenState(); +} + +class _CallScreenState extends State { + static TextEditingController changeNameController = TextEditingController(); + double opacityLevel = 1.0; + + final voIPKit = FlutterIOSVoIPKit.instance; + + bool isScreenBeingShared = false; + + void _changeOpacity() { + setState(() => opacityLevel = opacityLevel == 0 ? 1.0 : 0.0); + } + + @override + Widget build(BuildContext context) { + var zoom = ZoomVideoSdk(); + var eventListener = ZoomVideoSdkEventListener(); + var isInSession = useState(false); + var sessionName = useState(''); + var sessionPassword = useState(''); + var users = useState([]); + var fullScreenUser = useState(null); + var sharingUser = useState(null); + var videoInfo = useState(''); + var isSharing = useState(false); + var isMuted = useState(true); + var isVideoOn = useState(false); + var isSpeakerOn = useState(false); + var isRenameModalVisible = useState(false); + var isRecordingStarted = useState(false); + var isMicOriginalOn = useState(false); + var isMounted = useIsMounted(); + var audioStatusFlag = useState(false); + var videoStatusFlag = useState(false); + var userNameFlag = useState(false); + var userShareStatusFlag = useState(false); + var isReceiveSpokenLanguageContentEnabled = useState(false); + var isVideoMirrored = useState(false); + var isOriginalAspectRatio = useState(false); + var isPiPView = useState(false); + var isSharedCamera = useState(false); + CameraShareView cameraShareView = const CameraShareView(creationParams: {}); + + //hide status bar + SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack); + var circleButtonSize = 65.0; + Color backgroundColor = const Color(0xFF232323); + Color buttonBackgroundColor = const Color.fromRGBO(0, 0, 0, 0.6); + Color chatTextColor = const Color(0xFFAAAAAA); + Widget changeNamePopup; + final args = ModalRoute.of(context)!.settings.arguments as CallArguments; + + useEffect(() { + Future.microtask(() async { + var token = generateJwt(args.sessionName, args.role); + + Utils.removeFromPrefs(CacheConst.isAppOpenedFromCall); + + try { + Map SDKaudioOptions = {"connect": true, "mute": false, "autoAdjustSpeakerVolume": false}; + Map SDKvideoOptions = { + "localVideoOn": true, + }; + JoinSessionConfig joinSession = JoinSessionConfig( + sessionName: args.sessionName, + sessionPassword: args.sessionPwd, + token: token, + userName: args.displayName, + audioOptions: SDKaudioOptions, + videoOptions: SDKvideoOptions, + sessionIdleTimeoutMins: int.parse(args.sessionIdleTimeoutMins), + ); + await zoom.joinSession(joinSession); + } catch (e) { + const AlertDialog( + title: Text("Error"), + content: Text("Failed to join the session"), + ); + Future.delayed(const Duration(milliseconds: 1000)).asStream().listen((event) { + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + }); + } + }); + return null; + }, []); + + useEffect(() { + final sessionJoinListener = eventListener.addListener(EventType.onSessionJoin, (data) async { + data = data as Map; + isInSession.value = true; + zoom.session.getSessionName().then((value) => sessionName.value = value!); + sessionPassword.value = await zoom.session.getSessionPassword(); + debugPrint("sessionPhonePasscode: ${await zoom.session.getSessionPhonePasscode()}"); + ZoomVideoSdkUser mySelf = ZoomVideoSdkUser.fromJson(jsonDecode(data['sessionUser'])); + List? remoteUsers = await zoom.session.getRemoteUsers(); + var muted = await mySelf.audioStatus?.isMuted(); + var videoOn = await mySelf.videoStatus?.isOn(); + var speakerOn = await zoom.audioHelper.getSpeakerStatus(); + fullScreenUser.value = mySelf; + remoteUsers?.insert(0, mySelf); + isMuted.value = muted!; + isSpeakerOn.value = speakerOn; + isVideoOn.value = videoOn!; + users.value = remoteUsers!; + isReceiveSpokenLanguageContentEnabled.value = await zoom.liveTranscriptionHelper.isReceiveSpokenLanguageContentEnabled(); + }); + + final sessionLeaveListener = eventListener.addListener(EventType.onSessionLeave, (data) async { + data = data as Map; + debugPrint("onSessionLeave: ${data['reason']}"); + isInSession.value = false; + users.value = []; + fullScreenUser.value = null; + // Navigator.popAndPushNamed( + // context, + // "Join", + // arguments: JoinArguments(args.isJoin, sessionName.value, sessionPassword.value, args.displayName, args.sessionIdleTimeoutMins, args.role), + // ); + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + }); + + final sessionNeedPasswordListener = eventListener.addListener(EventType.onSessionNeedPassword, (data) async { + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Session Need Password'), + content: const Text('Password is required'), + actions: [ + TextButton( + onPressed: () async => { + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false), + await zoom.leaveSession(false), + }, + child: const Text('OK'), + ), + ], + ), + ); + }); + + final sessionPasswordWrongListener = eventListener.addListener(EventType.onSessionPasswordWrong, (data) async { + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Session Password Incorrect'), + content: const Text('Password is wrong'), + actions: [ + TextButton( + onPressed: () async => { + Navigator.popAndPushNamed(context, 'Join', arguments: JoinArguments(args.isJoin, args.sessionName, "", args.displayName, args.sessionIdleTimeoutMins, args.role)), + await zoom.leaveSession(false), + }, + child: const Text('OK'), + ), + ], + ), + ); + }); + + final userVideoStatusChangedListener = eventListener.addListener(EventType.onUserVideoStatusChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + var userListJson = jsonDecode(data['changedUsers']) as List; + List userList = userListJson.map((userJson) => ZoomVideoSdkUser.fromJson(userJson)).toList(); + for (var user in userList) { + { + if (user.userId == mySelf?.userId) { + mySelf?.videoStatus?.isOn().then((on) => isVideoOn.value = on); + } + } + } + videoStatusFlag.value = !videoStatusFlag.value; + }); + + final userAudioStatusChangedListener = eventListener.addListener(EventType.onUserAudioStatusChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + var userListJson = jsonDecode(data['changedUsers']) as List; + List userList = userListJson.map((userJson) => ZoomVideoSdkUser.fromJson(userJson)).toList(); + for (var user in userList) { + { + if (user.userId == mySelf?.userId) { + mySelf?.audioStatus?.isMuted().then((muted) => isMuted.value = muted); + } + } + } + audioStatusFlag.value = !audioStatusFlag.value; + }); + + final userShareStatusChangeListener = eventListener.addListener(EventType.onUserShareStatusChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + ZoomVideoSdkUser shareUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['user'].toString())); + ZoomVideoSdkShareAction? shareAction = ZoomVideoSdkShareAction.fromJson(jsonDecode(data['shareAction'])); + + if (shareAction.shareStatus == ShareStatus.Start || shareAction.shareStatus == ShareStatus.Resume) { + sharingUser.value = shareUser; + fullScreenUser.value = shareUser; + isSharing.value = (shareUser.userId == mySelf?.userId); + + setState(() { + isScreenBeingShared = true; + }); + Future.delayed(const Duration(seconds: 2), () { + setState(() { + isScreenBeingShared = false; + }); + }); + } else { + sharingUser.value = null; + isSharing.value = false; + isSharedCamera.value = false; + fullScreenUser.value = mySelf; + isScreenBeingShared = false; + setState(() { + isScreenBeingShared = true; + }); + Future.delayed(const Duration(seconds: 2), () { + setState(() { + isScreenBeingShared = false; + }); + }); + } + userShareStatusFlag.value = !userShareStatusFlag.value; + }); + + final shareContentChangedListener = eventListener.addListener(EventType.onShareContentChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + ZoomVideoSdkUser shareUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['user'].toString())); + ZoomVideoSdkShareAction? shareAction = ZoomVideoSdkShareAction.fromJson(jsonDecode(data['shareAction'])); + if (shareAction.shareType == ShareType.Camera) { + debugPrint("Camera share started"); + isSharedCamera.value = (shareUser.userId == mySelf?.userId); + } + }); + + final userJoinListener = eventListener.addListener(EventType.onUserJoin, (data) async { + if (!isMounted()) return; + data = data as Map; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + var userListJson = jsonDecode(data['remoteUsers']) as List; + List remoteUserList = userListJson.map((userJson) => ZoomVideoSdkUser.fromJson(userJson)).toList(); + remoteUserList.insert(0, mySelf!); + users.value = remoteUserList; + }); + + final userLeaveListener = eventListener.addListener(EventType.onUserLeave, (data) async { + if (!isMounted()) return; + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + data = data as Map; + List? remoteUserList = await zoom.session.getRemoteUsers(); + var leftUserListJson = jsonDecode(data['leftUsers']) as List; + List leftUserLis = leftUserListJson.map((userJson) => ZoomVideoSdkUser.fromJson(userJson)).toList(); + if (fullScreenUser.value != null) { + for (var user in leftUserLis) { + { + if (fullScreenUser.value?.userId == user.userId) { + fullScreenUser.value = mySelf; + } + } + } + } else { + fullScreenUser.value = mySelf; + } + remoteUserList?.add(mySelf!); + users.value = remoteUserList!; + }); + + final userNameChangedListener = eventListener.addListener(EventType.onUserNameChanged, (data) async { + if (!isMounted()) return; + data = data as Map; + ZoomVideoSdkUser? changedUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['changedUser'])); + int index; + for (var user in users.value) { + if (user.userId == changedUser.userId) { + index = users.value.indexOf(user); + users.value[index] = changedUser; + } + } + userNameFlag.value = !userNameFlag.value; + }); + + final commandReceived = eventListener.addListener(EventType.onCommandReceived, (data) async { + data = data as Map; + debugPrint("sender: ${ZoomVideoSdkUser.fromJson(jsonDecode(data['sender']))}, command: ${data['command']}"); + }); + + final liveStreamStatusChangeListener = eventListener.addListener(EventType.onLiveStreamStatusChanged, (data) async { + data = data as Map; + debugPrint("onLiveStreamStatusChanged: status: ${data['status']}"); + }); + + final liveTranscriptionStatusChangeListener = eventListener.addListener(EventType.onLiveTranscriptionStatus, (data) async { + data = data as Map; + debugPrint("onLiveTranscriptionStatus: status: ${data['status']}"); + }); + + final cloudRecordingStatusListener = eventListener.addListener(EventType.onCloudRecordingStatus, (data) async { + data = data as Map; + debugPrint("onCloudRecordingStatus: status: ${data['status']}"); + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + if (data['status'] == RecordingStatus.Start) { + if (mySelf != null && !mySelf.isHost!) { + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + content: const Text('The session is being recorded.'), + actions: [ + TextButton( + onPressed: () async { + await zoom.acceptRecordingConsent(); + if (context.mounted) { + Navigator.pop(context); + } + ; + }, + child: const Text('accept'), + ), + TextButton( + onPressed: () async { + String currentConsentType = await zoom.getRecordingConsentType(); + if (currentConsentType == ConsentType.ConsentType_Individual) { + await zoom.declineRecordingConsent(); + Navigator.pop(context); + } else { + await zoom.declineRecordingConsent(); + zoom.leaveSession(false); + if (!context.mounted) return; + Navigator.popAndPushNamed( + context, + "Join", + arguments: JoinArguments(args.isJoin, sessionName.value, sessionPassword.value, args.displayName, args.sessionIdleTimeoutMins, args.role), + ); + } + }, + child: const Text('decline'), + ), + ], + ), + ); + } + isRecordingStarted.value = true; + } else { + isRecordingStarted.value = false; + } + }); + + final liveTranscriptionMsgInfoReceivedListener = eventListener.addListener(EventType.onLiveTranscriptionMsgInfoReceived, (data) async { + data = data as Map; + ZoomVideoSdkLiveTranscriptionMessageInfo? messageInfo = ZoomVideoSdkLiveTranscriptionMessageInfo.fromJson(jsonDecode(data['messageInfo'])); + debugPrint("onLiveTranscriptionMsgInfoReceived: content: ${messageInfo.messageContent}"); + }); + + final inviteByPhoneStatusListener = eventListener.addListener(EventType.onInviteByPhoneStatus, (data) async { + data = data as Map; + debugPrint("onInviteByPhoneStatus: status: ${data['status']}, reason: ${data['reason']}"); + }); + + final multiCameraStreamStatusChangedListener = eventListener.addListener(EventType.onMultiCameraStreamStatusChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? changedUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['changedUser'])); + var status = data['status']; + for (var user in users.value) { + { + if (changedUser.userId == user.userId) { + if (status == MultiCameraStreamStatus.Joined) { + user.hasMultiCamera = true; + } else if (status == MultiCameraStreamStatus.Left) { + user.hasMultiCamera = false; + } + } + } + } + }); + + final requireSystemPermission = eventListener.addListener(EventType.onRequireSystemPermission, (data) async { + data = data as Map; + ZoomVideoSdkUser? changedUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['changedUser'])); + var permissionType = data['permissionType']; + switch (permissionType) { + case SystemPermissionType.Camera: + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text("Can't Access Camera"), + content: const Text("please turn on the toggle in system settings to grant permission"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + break; + case SystemPermissionType.Microphone: + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text("Can't Access Microphone"), + content: const Text("please turn on the toggle in system settings to grant permission"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + break; + } + }); + + final networkStatusChangeListener = eventListener.addListener(EventType.onUserVideoNetworkStatusChanged, (data) async { + data = data as Map; + ZoomVideoSdkUser? networkUser = ZoomVideoSdkUser.fromJson(jsonDecode(data['user'])); + + if (data['status'] == NetworkStatus.Bad) { + debugPrint("onUserVideoNetworkStatusChanged: status: ${data['status']}, user: ${networkUser.userName}"); + } + }); + + final eventErrorListener = eventListener.addListener(EventType.onError, (data) async { + data = data as Map; + String errorType = data['errorType']; + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text("Error"), + content: Text(errorType), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + if (errorType == Errors.SessionJoinFailed || errorType == Errors.SessionDisconnecting) { + Timer( + const Duration(milliseconds: 1000), + () => { + Navigator.popAndPushNamed( + context, + "Join", + arguments: JoinArguments(args.isJoin, sessionName.value, sessionPassword.value, args.displayName, args.sessionIdleTimeoutMins, args.role), + ), + }); + } + }); + + final userRecordingConsentListener = eventListener.addListener(EventType.onUserRecordingConsent, (data) async { + data = data as Map; + ZoomVideoSdkUser? user = ZoomVideoSdkUser.fromJson(jsonDecode(data['user'])); + debugPrint('userRecordingConsentListener: user= ${user.userName}'); + }); + + final callCRCDeviceStatusListener = eventListener.addListener(EventType.onCallCRCDeviceStatusChanged, (data) async { + data = data as Map; + debugPrint('onCallCRCDeviceStatusChanged: status = ${data['status']}'); + }); + + final originalLanguageMsgReceivedListener = eventListener.addListener(EventType.onOriginalLanguageMsgReceived, (data) async { + data = data as Map; + ZoomVideoSdkLiveTranscriptionMessageInfo? messageInfo = ZoomVideoSdkLiveTranscriptionMessageInfo.fromJson(jsonDecode(data['messageInfo'])); + debugPrint("onOriginalLanguageMsgReceived: content: ${messageInfo.messageContent}"); + }); + + final chatPrivilegeChangedListener = eventListener.addListener(EventType.onChatPrivilegeChanged, (data) async { + data = data as Map; + String type = data['privilege']; + debugPrint('chatPrivilegeChangedListener: type= $type'); + }); + + final testMicStatusListener = eventListener.addListener(EventType.onTestMicStatusChanged, (data) async { + data = data as Map; + String status = data['status']; + debugPrint('testMicStatusListener: status= $status'); + }); + + final micSpeakerVolumeChangedListener = eventListener.addListener(EventType.onMicSpeakerVolumeChanged, (data) async { + data = data as Map; + int type = data['micVolume']; + debugPrint('onMicSpeakerVolumeChanged: micVolume= $type, speakerVolume'); + }); + + final cameraControlRequestResultListener = eventListener.addListener(EventType.onCameraControlRequestResult, (data) async { + data = data as Map; + bool approved = data['approved']; + debugPrint('onCameraControlRequestResult: approved= $approved'); + }); + + final callOutUserJoinListener = eventListener.addListener(EventType.onCalloutJoinSuccess, (data) async { + data = data as Map; + String phoneNumber = data['phoneNumber']; + ZoomVideoSdkUser? user = ZoomVideoSdkUser.fromJson(jsonDecode(data['user'])); + debugPrint('onCalloutJoinSuccess: phoneNumber= $phoneNumber, user= ${user.userName}'); + }); + + return () => { + sessionJoinListener.cancel(), + sessionLeaveListener.cancel(), + sessionPasswordWrongListener.cancel(), + sessionNeedPasswordListener.cancel(), + userVideoStatusChangedListener.cancel(), + userAudioStatusChangedListener.cancel(), + userJoinListener.cancel(), + userLeaveListener.cancel(), + userNameChangedListener.cancel(), + userShareStatusChangeListener.cancel(), + liveStreamStatusChangeListener.cancel(), + cloudRecordingStatusListener.cancel(), + inviteByPhoneStatusListener.cancel(), + eventErrorListener.cancel(), + commandReceived.cancel(), + liveTranscriptionStatusChangeListener.cancel(), + liveTranscriptionMsgInfoReceivedListener.cancel(), + multiCameraStreamStatusChangedListener.cancel(), + requireSystemPermission.cancel(), + userRecordingConsentListener.cancel(), + networkStatusChangeListener.cancel(), + callCRCDeviceStatusListener.cancel(), + originalLanguageMsgReceivedListener.cancel(), + chatPrivilegeChangedListener.cancel(), + testMicStatusListener.cancel(), + micSpeakerVolumeChangedListener.cancel(), + cameraControlRequestResultListener.cancel(), + callOutUserJoinListener.cancel(), + shareContentChangedListener.cancel(), + }; + }, [zoom, users.value, isMounted]); + + void selectVirtualBackgroundItem() async { + final ImagePicker picker = ImagePicker(); + // Pick an image. + final XFile? image = await picker.pickImage(source: ImageSource.gallery); + await zoom.virtualBackgroundHelper.addVirtualBackgroundItem(image!.path); + } + + void onPressAudio() async { + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + if (mySelf != null) { + final audioStatus = mySelf.audioStatus; + if (audioStatus != null) { + var muted = await audioStatus.isMuted(); + if (muted) { + await zoom.audioHelper.unMuteAudio(mySelf.userId); + } else { + await zoom.audioHelper.muteAudio(mySelf.userId); + } + } + } + } + + void onPressVideo() async { + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + if (mySelf != null) { + final videoStatus = mySelf.videoStatus; + if (videoStatus != null) { + var videoOn = await videoStatus.isOn(); + if (videoOn) { + await zoom.videoHelper.stopVideo(); + } else { + await zoom.videoHelper.startVideo(); + } + } + } + } + + void onPressShare() async { + var isOtherSharing = await zoom.shareHelper.isOtherSharing(); + var isShareLocked = await zoom.shareHelper.isShareLocked(); + String? shareCameraViewResult = Errors.InternalError; + + if (isOtherSharing) { + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text("Error"), + content: const Text('Other is sharing'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + } else if (isShareLocked) { + showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text("Error"), + content: const Text('Share is locked by host'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + } else if (isSharing.value) { + zoom.shareHelper.stopShare(); + } else { + List options = [ + ListTile( + title: Text( + 'Share Device Screen', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + zoom.shareHelper.shareScreen(), + Navigator.of(context).pop(), + }, + ), + ListTile( + title: Text( + 'Share Camera', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + shareCameraViewResult = await zoom.shareHelper.startShareCamera(cameraShareView), + debugPrint('start camera: $shareCameraViewResult'), + Navigator.of(context).pop(), + }, + ), + ]; + showDialog( + context: context, + builder: (context) { + return Dialog( + elevation: 0.0, + insetPadding: const EdgeInsets.symmetric(horizontal: 40), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: SizedBox( + height: options.length * 60, + child: Scrollbar( + child: ListView( + shrinkWrap: true, + scrollDirection: Axis.vertical, + children: ListTile.divideTiles( + context: context, + tiles: options, + ).toList(), + ), + ), + ), + ); + }); + } + } + + void onSelectedUserVolume(ZoomVideoSdkUser user) async { + var isShareAudio = user.isSharing; + bool canSetVolume = await user.canSetUserVolume(user.userId, isShareAudio); + num userVolume; + + List options = [ + ListTile( + title: Text( + 'Adjust Volume', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black, + ), + ), + ), + ListTile( + title: Text( + 'Current volume', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + debugPrint('user volume'), + userVolume = await user.getUserVolume(user.userId, isShareAudio), + debugPrint('user ${user.userName}\'s volume is ${userVolume!}'), + }, + ), + ]; + if (canSetVolume) { + options.add( + ListTile( + title: Text( + 'Volume up', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + userVolume = await user.getUserVolume(user.userId, isShareAudio), + if (userVolume < 10) + { + await user.setUserVolume(user.userId, userVolume + 1, isShareAudio), + } + else + { + debugPrint("Cannot volume up."), + } + }, + ), + ); + options.add( + ListTile( + title: Text( + 'Volume down', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + userVolume = await user.getUserVolume(user.userId, isShareAudio), + if (userVolume > 0) + { + await user.setUserVolume(user.userId, userVolume - 1, isShareAudio), + } + else + { + debugPrint("Cannot volume down."), + } + }, + ), + ); + } + showDialog( + context: context, + builder: (context) { + return Dialog( + elevation: 0.0, + insetPadding: const EdgeInsets.symmetric(horizontal: 40), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: SizedBox( + height: options.length * 58, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ListView( + shrinkWrap: true, + children: ListTile.divideTiles( + context: context, + tiles: options, + ).toList(), + ), + ], + ), + )); + }); + } + + void onPressCameraList() async { + List options = []; + List cameraList = await zoom.videoHelper.getCameraList(); + for (var camera in cameraList) { + options.add( + ListTile( + title: Text( + camera.deviceName, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + await zoom.videoHelper.switchCamera(camera.deviceId), + Navigator.of(context).pop(), + }, + ), + ); + } + options.add( + ListTile( + title: Text( + "Cancel", + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.black, + ), + ), + onTap: () async => { + Navigator.of(context).pop(), + }, + ), + ); + showDialog( + context: context, + builder: (context) { + return Dialog( + elevation: 0.0, + insetPadding: const EdgeInsets.symmetric(horizontal: 40), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: SizedBox( + height: options.length * 60, + child: Scrollbar( + child: ListView( + shrinkWrap: true, + scrollDirection: Axis.vertical, + children: ListTile.divideTiles( + context: context, + tiles: options, + ).toList(), + ), + ), + ), + ); + }); + } + + // Future onPressMore() async { + // ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + // bool isShareLocked = await zoom.shareHelper.isShareLocked(); + // bool canSwitchSpeaker = await zoom.audioHelper.canSwitchSpeaker(); + // bool canStartRecording = (await zoom.recordingHelper.canStartRecording()) == Errors.Success; + // debugPrint("canStartRecording ${await zoom.recordingHelper.canStartRecording()}"); + // var startLiveTranscription = (await zoom.liveTranscriptionHelper.getLiveTranscriptionStatus()) == LiveTranscriptionStatus.Start; + // bool canStartLiveTranscription = await zoom.liveTranscriptionHelper.canStartLiveTranscription(); + // bool isHost = (mySelf != null) ? (await mySelf.getIsHost()) : false; + // isOriginalAspectRatio.value = await zoom.videoHelper.isOriginalAspectRatioEnabled(); + // bool canCallOutToCRC = await zoom.CRCHelper.isCRCEnabled(); + // bool supportVB = await zoom.virtualBackgroundHelper.isSupportVirtualBackground(); + // List? shareActionList = await mySelf?.getShareActionList(); + // + // List options = [ + // ListTile( + // title: Text( + // 'More', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 18, + // fontWeight: FontWeight.w600, + // color: Colors.black, + // ), + // ), + // ), + // ), + // ListTile( + // title: Text( + // 'Get Chat Privilege', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint("Chat Privilege = ${await zoom.chatHelper.getChatPrivilege()}"), + // Navigator.of(context).pop(), + // }, + // ), + // ListTile( + // title: Text( + // 'Get Session Dial-in Number infos', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint("session number = ${await zoom.session.getSessionNumber()}"), + // Navigator.of(context).pop(), + // }, + // ), + // ListTile( + // title: Text( + // 'Get Camera List', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint("camera list= ${await zoom.videoHelper.getCameraList()}"), + // onPressCameraList(), + // Navigator.of(context).pop(), + // }, + // ), + // ListTile( + // title: Text( + // '${isMicOriginalOn.value ? 'Disable' : 'Enable'} Original Sound', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint("${isMicOriginalOn.value}"), + // await zoom.audioSettingHelper.enableMicOriginalInput(!isMicOriginalOn.value), + // isMicOriginalOn.value = await zoom.audioSettingHelper.isMicOriginalInputEnable(), + // debugPrint("Original sound ${isMicOriginalOn.value ? 'Enabled' : 'Disabled'}"), + // Navigator.of(context).pop(), + // }, + // ) + // ]; + // + // if (supportVB) { + // options.add( + // ListTile( + // title: Text( + // 'Add Virtual Background', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // selectVirtualBackgroundItem(), + // Navigator.of(context).pop(), + // }, + // ), + // ); + // } + // + // if (canCallOutToCRC) { + // options.add(ListTile( + // title: Text( + // 'Call-out to CRC devices', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint('CRC result = ${await zoom.CRCHelper.callCRCDevice("bjn.vc", ZoomVideoSdkCRCProtocolType.SIP)}'), + // Navigator.of(context).pop(), + // }, + // )); + // options.add(ListTile( + // title: Text( + // 'Cancel call-out to CRC devices', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint('cancel result= ${await zoom.CRCHelper.cancelCallCRCDevice()}'), + // Navigator.of(context).pop(), + // }, + // )); + // } + // + // if (canSwitchSpeaker) { + // options.add(ListTile( + // title: Text( + // 'Turn ${isSpeakerOn.value ? 'off' : 'on'} Speaker', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // await zoom.audioHelper.setSpeaker(!isSpeakerOn.value), + // isSpeakerOn.value = await zoom.audioHelper.getSpeakerStatus(), + // debugPrint('Turned ${isSpeakerOn.value ? 'on' : 'off'} Speaker'), + // Navigator.of(context).pop(), + // }, + // )); + // } + // + // if (isHost) { + // options.add(ListTile( + // title: Text( + // '${isShareLocked ? 'Unlock' : 'Lock'} Share', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // debugPrint("isShareLocked = ${await zoom.shareHelper.lockShare(!isShareLocked)}"), + // Navigator.of(context).pop(), + // })); + // options.add(ListTile( + // title: Text( + // 'Change Name', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () => { + // isRenameModalVisible.value = true, + // Navigator.of(context).pop(), + // }, + // )); + // } + // + // if (canStartLiveTranscription) { + // options.add(ListTile( + // title: Text( + // "${startLiveTranscription ? 'Stop' : 'Start'} Live Transcription", + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // if (startLiveTranscription) + // { + // debugPrint('stopLiveTranscription= ${await zoom.liveTranscriptionHelper.stopLiveTranscription()}'), + // } + // else + // { + // debugPrint('startLiveTranscription= ${await zoom.liveTranscriptionHelper.startLiveTranscription()}'), + // }, + // Navigator.of(context).pop(), + // }, + // )); + // options.add(ListTile( + // title: Text( + // '${isReceiveSpokenLanguageContentEnabled.value ? 'Disable' : 'Enable'} receiving original caption', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // await zoom.liveTranscriptionHelper.enableReceiveSpokenLanguageContent(!isReceiveSpokenLanguageContentEnabled.value), + // isReceiveSpokenLanguageContentEnabled.value = await zoom.liveTranscriptionHelper.isReceiveSpokenLanguageContentEnabled(), + // debugPrint("isReceiveSpokenLanguageContentEnabled = ${isReceiveSpokenLanguageContentEnabled.value}"), + // Navigator.of(context).pop(), + // })); + // } + // + // if (canStartRecording) { + // options.add(ListTile( + // title: Text( + // '${isRecordingStarted.value ? 'Stop' : 'Start'} Recording', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // if (!isRecordingStarted.value) + // { + // debugPrint('isRecordingStarted = ${await zoom.recordingHelper.startCloudRecording()}'), + // } + // else + // { + // debugPrint('isRecordingStarted = ${await zoom.recordingHelper.stopCloudRecording()}'), + // }, + // Navigator.of(context).pop(), + // })); + // } + // + // if (Platform.isAndroid) { + // bool isFlashlightSupported = await zoom.videoHelper.isSupportFlashlight(); + // bool isFlashlightOn = await zoom.videoHelper.isFlashlightOn(); + // if (isFlashlightSupported) { + // options.add(ListTile( + // title: Text( + // '${isFlashlightOn ? 'Turn Off' : 'Turn On'} Flashlight', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // if (!isFlashlightOn) + // { + // await zoom.videoHelper.turnOnOrOffFlashlight(true), + // } + // else + // { + // await zoom.videoHelper.turnOnOrOffFlashlight(false), + // }, + // Navigator.of(context).pop(), + // })); + // } + // } + // + // if (Platform.isIOS) { + // options.add(ListTile( + // title: Text( + // '${isPiPView.value ? 'Disable' : 'Enable'} picture in picture view', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // isPiPView.value = !isPiPView.value, + // Navigator.of(context).pop(), + // })); + // } + // + // if (isVideoOn.value) { + // options.add(ListTile( + // title: Text( + // 'Mirror the video', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // await zoom.videoHelper.mirrorMyVideo(!isVideoMirrored.value), + // isVideoMirrored.value = await zoom.videoHelper.isMyVideoMirrored(), + // Navigator.of(context).pop(), + // })); + // options.add(ListTile( + // title: Text( + // '${isOriginalAspectRatio.value ? 'Enable' : 'Disable'} original aspect ratio', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.normal, + // color: Colors.black, + // ), + // ), + // ), + // onTap: () async => { + // await zoom.videoHelper.enableOriginalAspectRatio(!isOriginalAspectRatio.value), + // isOriginalAspectRatio.value = await zoom.videoHelper.isOriginalAspectRatioEnabled(), + // debugPrint("isOriginalAspectRatio= ${isOriginalAspectRatio.value}"), + // Navigator.of(context).pop(), + // })); + // } + // + // showDialog( + // context: context, + // builder: (context) { + // return Dialog( + // elevation: 0.0, + // insetPadding: const EdgeInsets.symmetric(horizontal: 40), + // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + // child: SizedBox( + // height: 500, + // child: Scrollbar( + // child: ListView( + // shrinkWrap: true, + // scrollDirection: Axis.vertical, + // children: ListTile.divideTiles( + // context: context, + // tiles: options, + // ).toList(), + // ), + // ), + // ), + // ); + // }); + // } + + void onLeaveSession(bool isEndSession) async { + await zoom.leaveSession(isEndSession); + Navigator.pushAndRemoveUntil( + context, + CustomPageRoute( + page: LandingNavigation(), + ), + (r) => false); + } + + void showLeaveOptions() async { + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + bool isHost = await mySelf!.getIsHost(); + + Widget endSession; + Widget leaveSession; + Widget cancel = TextButton( + child: const Text('Cancel'), + onPressed: () { + Navigator.pop(context); //close Dialog + }, + ); + + switch (defaultTargetPlatform) { + case TargetPlatform.android: + endSession = TextButton( + child: const Text('End Session'), + onPressed: () => onLeaveSession(true), + ); + leaveSession = TextButton( + child: const Text('Leave Session'), + onPressed: () => onLeaveSession(false), + ); + break; + default: + endSession = CupertinoActionSheetAction( + isDestructiveAction: true, + child: const Text('End Session'), + onPressed: () => onLeaveSession(true), + ); + leaveSession = CupertinoActionSheetAction( + child: const Text('Leave Session'), + onPressed: () => onLeaveSession(false), + ); + break; + } + + List options = [ + leaveSession, + cancel, + ]; + + if (Platform.isAndroid) { + if (isHost) { + options.removeAt(1); + options.insert(0, endSession); + } + showDialog( + context: context, + builder: (context) { + return AlertDialog( + content: const Text("Do you want to leave this session?"), + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))), + actions: options, + ); + }); + } else { + options.removeAt(1); + if (isHost) { + options.insert(1, endSession); + } + showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + message: const Text('Are you sure that you want to leave the session?'), + actions: options, + cancelButton: cancel, + ), + ); + } + } + + final chatMessageController = TextEditingController(); + + void sendChatMessage(String message) async { + await zoom.chatHelper.sendChatToAll(message); + ZoomVideoSdkUser? self = await zoom.session.getMySelf(); + ZoomVideoSdkCmdChannel cmdChannel = zoom.cmdChannel; + for (var user in users.value) { + if (user.userId != self?.userId) { + await zoom.cmdChannel.sendCommand(user.userId, message); + } + } + chatMessageController.clear(); + // send the chat as a command + } + + void onSelectedUser(ZoomVideoSdkUser user) async { + setState(() { + fullScreenUser.value = user; + }); + } + + changeNamePopup = Center( + child: Stack( + children: [ + Visibility( + visible: isRenameModalVisible.value, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + alignment: Alignment.bottomLeft, + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(10)), + color: Colors.white, + ), + width: MediaQuery.of(context).size.width - 130, + height: MediaQuery.of(context).size.height * 0.2, + child: Center( + child: (Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 20, left: 20), + child: Text( + 'Change Name', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w500, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 10, left: 20), + child: SizedBox( + width: MediaQuery.of(context).size.width - 230, + child: TextField( + onEditingComplete: () {}, + autofocus: true, + cursorColor: Colors.black, + controller: changeNameController, + decoration: InputDecoration( + isDense: true, + hintText: 'New name', + hintStyle: TextStyle( + fontSize: 14.0, + color: chatTextColor, + ), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 15), + child: Row( + children: [ + Padding( + padding: const EdgeInsets.only(left: 40), + child: InkWell( + child: Text( + 'Apply', + style: const TextStyle( + fontSize: 16, + ), + ), + onTap: () async { + if (fullScreenUser.value != null) { + ZoomVideoSdkUser? mySelf = await zoom.session.getMySelf(); + await zoom.userHelper.changeName((mySelf?.userId)!, changeNameController.text); + changeNameController.clear(); + } + isRenameModalVisible.value = false; + }, + ), + ), + Padding( + padding: const EdgeInsets.only(left: 40), + child: InkWell( + child: Text( + 'Cancel', + style: const TextStyle( + fontSize: 16, + ), + ), + onTap: () async { + isRenameModalVisible.value = false; + }, + ), + ) + ], + ), + ) + ], + )), + ), + ), + ], + )), + ], + ), + ); + + Widget fullScreenView; + Widget smallView; + Widget cameraView; + + if (isInSession.value && fullScreenUser.value != null && users.value.isNotEmpty) { + fullScreenView = AnimatedOpacity( + opacity: opacityLevel, + duration: const Duration(seconds: 3), + child: VideoView( + user: users.value.length > 1 ? users.value[1] : users.value[0], + hasMultiCamera: false, + isPiPView: isPiPView.value, + sharing: sharingUser.value == null ? false : (sharingUser.value?.userId == fullScreenUser.value?.userId), + preview: false, + focused: false, + multiCameraIndex: "0", + videoAspect: VideoAspect.Original, + fullScreen: true, + resolution: VideoResolution.Resolution360, + ), + ); + + smallView = Container( + height: 110, + margin: const EdgeInsets.only(left: 20, right: 20), + alignment: Alignment.center, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: users.value.length, + itemBuilder: (BuildContext context, int index) { + return InkWell( + onTap: () async { + onSelectedUser(users.value[index]); + }, + onDoubleTap: () async { + onSelectedUserVolume(users.value[index]); + }, + child: Center( + child: VideoView( + user: users.value[index], + hasMultiCamera: false, + isPiPView: false, + sharing: false, + preview: false, + focused: false, + multiCameraIndex: "0", + videoAspect: VideoAspect.Original, + fullScreen: false, + resolution: VideoResolution.Resolution180, + ), + ), + ); + }, + separatorBuilder: (BuildContext context, int index) => const Divider(), + ), + ); + } else { + fullScreenView = Container( + color: Colors.black, + child: const Center( + child: Text( + "Connecting...", + style: TextStyle( + fontSize: 20, + color: Colors.white, + ), + ), + )); + smallView = Container( + height: 110, + color: Colors.transparent, + ); + } + + cameraView = Offstage( + offstage: !isSharedCamera.value, + child: AnimatedOpacity( + opacity: isSharedCamera.value ? 1.0 : 0.0, + duration: const Duration(milliseconds: 300), + child: cameraShareView, + ), + ); + + _changeOpacity; + return Scaffold( + resizeToAvoidBottomInset: false, + backgroundColor: backgroundColor, + body: Stack( + children: [ + // isScreenBeingShared ? fullScreenView : SizedBox.shrink(), + isScreenBeingShared ? SizedBox.shrink() : fullScreenView, + cameraView, + Container( + padding: const EdgeInsets.only(top: 35), + child: Stack( + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + height: 80, + width: 180, + margin: const EdgeInsets.only(top: 16, left: 8), + padding: const EdgeInsets.all(8), + alignment: Alignment.topLeft, + decoration: BoxDecoration( + borderRadius: const BorderRadius.all(Radius.circular(8.0)), + // color: buttonBackgroundColor, + ), + // child: InkWell( + // onTap: () async { + // showDialog( + // context: context, + // builder: (context) { + // return Dialog( + // elevation: 0.0, + // insetPadding: const EdgeInsets.symmetric(horizontal: 40), + // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + // child: FractionallySizedBox( + // heightFactor: 0.2, + // widthFactor: 0.3, + // child: Column( + // crossAxisAlignment: CrossAxisAlignment.stretch, + // children: [ + // ListView( + // shrinkWrap: true, + // children: ListTile.divideTiles( + // context: context, + // tiles: [ + // ListTile( + // title: Text( + // 'Session Information', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 18, + // fontWeight: FontWeight.w600, + // ), + // ), + // ), + // ), + // ListTile( + // title: Text( + // 'Session Name', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // ), + // ), + // ), + // subtitle: Text( + // sessionName.value, + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 12, + // ), + // ), + // ), + // ), + // ListTile( + // title: Text( + // 'Session Password', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // ), + // ), + // ), + // subtitle: Text( + // sessionPassword.value, + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 12, + // ), + // ), + // ), + // ), + // ListTile( + // title: Text( + // 'Participants', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // ), + // ), + // ), + // subtitle: Text( + // '${users.value.length}', + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 12, + // ), + // ), + // ), + // ), + // ], + // ).toList(), + // ), + // ], + // ), + // )); + // }); + // }, + // child: Stack( + // children: [ + // Column( + // children: [ + // const Padding(padding: EdgeInsets.symmetric(vertical: 4)), + // Align( + // alignment: Alignment.centerLeft, + // child: Text( + // sessionName.value, + // overflow: TextOverflow.ellipsis, + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.w600, + // color: Colors.white, + // ), + // ), + // ), + // ), + // const Padding(padding: EdgeInsets.symmetric(vertical: 5)), + // Align( + // alignment: Alignment.centerLeft, + // child: Text( + // "Participants: ${users.value.length}", + // style: GoogleFonts.lato( + // textStyle: const TextStyle( + // fontSize: 14, + // fontWeight: FontWeight.w600, + // color: Colors.white, + // ), + // ), + // ), + // ) + // ], + // ), + // Container( + // alignment: Alignment.centerRight, + // child: Image.asset( + // "assets/icons/unlocked@2x.png", + // height: 22, + // )), + // ], + // ), + // ), + ), + TextButton( + onPressed: (showLeaveOptions), + child: Container( + alignment: Alignment.topRight, + margin: const EdgeInsets.only(top: 16, right: 8), + padding: const EdgeInsets.only(top: 5, bottom: 5, left: 16, right: 16), + height: 28, + decoration: BoxDecoration( + borderRadius: const BorderRadius.all(Radius.circular(20.0)), + color: buttonBackgroundColor, + ), + child: const Text( + "LEAVE", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFFE02828), + ), + ), + )), + ], + ), + Align( + alignment: Alignment.centerRight, + child: FractionallySizedBox( + widthFactor: 0.2, + heightFactor: 0.6, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + onPressed: onPressAudio, + icon: isMuted.value ? Image.asset("assets/images/png/zoom/unmute@2x.png") : Image.asset("assets/images/png/zoom/mute@2x.png"), + iconSize: circleButtonSize, + tooltip: isMuted.value == true ? "Unmute" : "Mute", + ), + IconButton( + onPressed: onPressShare, + icon: isSharing.value ? Image.asset("assets/images/png/zoom/share-off@2x.png") : Image.asset("assets/images/png/zoom/share-on@2x.png"), + iconSize: circleButtonSize, + ), + IconButton( + onPressed: onPressVideo, + iconSize: circleButtonSize, + icon: isVideoOn.value ? Image.asset("assets/images/png/zoom/video-off@2x.png") : Image.asset("assets/images/png/zoom/video-on@2x.png"), + ), + Column( + children: [ + IconButton( + onPressed: () async { + onPressCameraList(); + }, + icon: Icon(Icons.cameraswitch, color: Colors.white), + color: Colors.white, + iconSize: 40.h, + ), + "Switch Camera".toText12(color: AppColors.whiteColor, isCenter: true, isBold: true) + ], + ), + ], + ), + )), + Container( + margin: const EdgeInsets.only(left: 16, right: 16, bottom: 40, top: 10), + alignment: Alignment.bottomCenter, + child: SizedBox( + height: MediaQuery.of(context).viewInsets.bottom == 0 ? 65 : MediaQuery.of(context).viewInsets.bottom + 18, + child: TextField( + maxLines: 1, + textAlign: TextAlign.left, + style: TextStyle(color: chatTextColor), + cursorColor: chatTextColor, + textAlignVertical: TextAlignVertical.center, + controller: chatMessageController, + decoration: InputDecoration( + contentPadding: const EdgeInsets.only(left: 16, top: 10, bottom: 10, right: 16), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide(width: 1, color: chatTextColor), //<-- SEE HERE + ), + hintText: 'Type your message here...', + hintStyle: TextStyle( + fontSize: 14.0, + color: chatTextColor, + ), + ), + onSubmitted: (String str) { + sendChatMessage(str); + }, + ), + ), + ), + Container( + alignment: Alignment.bottomLeft, + margin: const EdgeInsets.only(bottom: 120), + child: smallView, + ), + // CommentList(zoom: zoom, eventListener: eventListener), + changeNamePopup, + ], + )), + ], + )); + } +} + +class CallArguments { + final bool isJoin; + final String sessionName; + final String sessionPwd; + final String displayName; + final String sessionIdleTimeoutMins; + final String role; + final int callType; + + CallArguments(this.sessionName, this.sessionPwd, this.displayName, this.sessionIdleTimeoutMins, this.role, this.isJoin, this.callType); +} + +class JoinArguments { + final bool isJoin; + final String sessionName; + final String sessionPwd; + final String displayName; + final String sessionTimeout; + final String roleType; + + JoinArguments(this.isJoin, this.sessionName, this.sessionPwd, this.displayName, this.sessionTimeout, this.roleType); +} diff --git a/lib/presentation/tele_consultation/zoom/video_view.dart b/lib/presentation/tele_consultation/zoom/video_view.dart new file mode 100644 index 0000000..4c1e049 --- /dev/null +++ b/lib/presentation/tele_consultation/zoom/video_view.dart @@ -0,0 +1,258 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:flutter_zoom_videosdk/flutter_zoom_view.dart' as FlutterZoomView; +import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; + +const SHOW_TALKING_ICON_DURATION = 2000; + +class VideoView extends FlutterZoomView.ZoomView { + const VideoView({ + super.key, + required super.user, + required super.sharing, + required super.preview, + required super.focused, + required super.hasMultiCamera, + required super.multiCameraIndex, + required super.videoAspect, + required super.fullScreen, + required super.resolution, + required super.isPiPView, + }); + + @override + Widget build(BuildContext context) { + var isVideoOn = useState(false); + var isTalking = useState(false); + var isMuted = useState(false); + var isMounted = useIsMounted(); + var zoom = ZoomVideoSdk(); + var isSharing = useState(false); + user?.audioStatus?.isMuted().then((muted) => isMuted.value = muted); + + useEffect(() { + updateVideoStatus() { + if (user == null) return; + Future.microtask(() async { + if (isMounted()) { + isVideoOn.value = (await user!.videoStatus!.isOn()); + isSharing.value = sharing; + } + }); + } + + resetAudioStatus() { + isTalking.value = false; + isMuted.value = false; + } + + updateAudioStatus() async { + if (!isMounted()) return; + var talking = await user?.audioStatus?.isTalking(); + var muted = await user?.audioStatus?.isMuted(); + isMuted.value = muted!; + isTalking.value = talking!; + if (talking) { + Timer( + const Duration(milliseconds: SHOW_TALKING_ICON_DURATION), + () => { + if (isMounted()) + { + isTalking.value = false, + } + }); + } + } + + updateVideoStatus(); + return null; + }, [zoom, user]); + + ImageIcon audioStatusIcon; + if (isTalking.value) { + audioStatusIcon = const ImageIcon( + AssetImage("assets/images/png/zoom/talking@2x.png"), + ); + } else if (isMuted.value) { + audioStatusIcon = const ImageIcon( + AssetImage("assets/images/png/zoom/muted@2x.png"), + ); + } + // Pass parameters to the platform side. + final Map creationParams = {}; + creationParams.putIfAbsent("userId", () => user?.userId); + creationParams.putIfAbsent("sharing", () => sharing); + creationParams.putIfAbsent("preview", () => preview); + creationParams.putIfAbsent("focused", () => focused); + creationParams.putIfAbsent("hasMultiCamera", () => hasMultiCamera); + if (videoAspect.isEmpty) { + creationParams.putIfAbsent("videoAspect", () => VideoAspect.PanAndScan); + } else { + creationParams.putIfAbsent("videoAspect", () => videoAspect); + } + creationParams.putIfAbsent("fullScreen", () => fullScreen); + if (resolution.isNotEmpty) { + creationParams.putIfAbsent("videoAspect", () => videoAspect); + } + + if (fullScreen) { + if (sharing) { + return Container( + height: MediaQuery.of(context).size.height, + width: MediaQuery.of(context).size.width, + alignment: Alignment.center, + child: FlutterZoomView.View(creationParams: creationParams), + ); + } else if (isVideoOn.value) { + return Container( + height: MediaQuery.of(context).size.height, + width: MediaQuery.of(context).size.width, + alignment: Alignment.center, + child: FlutterZoomView.View(creationParams: creationParams), + ); + } else { + return Container( + margin: const EdgeInsets.symmetric(vertical: 0), + child: Container( + alignment: Alignment.center, + child: const Image( + image: AssetImage("assets/images/png/zoom/default-avatar.png"), + )), + ); + } + } else { + if (isVideoOn.value || sharing) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8), + height: 110, + width: 110, + child: Stack( + children: [ + Container( + height: 110, + width: 110, + decoration: BoxDecoration( + color: const Color(0xff232323), + border: Border.all( + color: const Color(0xff666666), + width: 1, + ), + borderRadius: const BorderRadius.all(Radius.circular(8)), + ), + alignment: Alignment.center, + child: FlutterZoomView.View(creationParams: creationParams), + ), + Container( + height: 110, + width: 110, + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + ), + Container( + alignment: Alignment.bottomCenter, + child: Container( + height: 20, + width: 110, + decoration: const BoxDecoration( + color: Colors.black26, + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + ), + ), + Container( + alignment: Alignment.bottomLeft, + margin: const EdgeInsets.only(left: 5), + child: Text( + user!.userName, + textAlign: TextAlign.left, + style: const TextStyle( + color: Colors.white, + fontSize: 12, + ), + ), + ), + Container( + alignment: Alignment.bottomRight, + margin: const EdgeInsets.only(right: 5, bottom: 5), + // height: 110, + // width: 110, + child: Image( + height: 12, + width: 12, + image: isMuted.value ? const AssetImage("assets/images/png/zoom/muted@2x.png") : const AssetImage("assets/images/png/zoom/talking@2x.png"), + fit: BoxFit.cover, + ), + ) + ], + ), + ); + } else { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8), + height: 110, + width: 110, + child: Stack( + children: [ + Container( + height: 110, + width: 110, + decoration: BoxDecoration( + color: const Color(0xff232323), + border: Border.all( + color: const Color(0xff666666), + width: 1, + ), + borderRadius: const BorderRadius.all(Radius.circular(8)), + ), + alignment: Alignment.center, + child: Container( + alignment: Alignment.center, + child: const Image( + height: 60, + width: 60, + image: AssetImage("assets/images/png/zoom/default-avatar.png"), + )), + ), + Align( + alignment: Alignment.bottomCenter, + child: Container( + height: 20, + width: 110, + decoration: const BoxDecoration( + color: Colors.black26, + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + ), + ), + Container( + alignment: Alignment.bottomLeft, + margin: const EdgeInsets.only(left: 5), + child: Text( + user!.userName, + textAlign: TextAlign.left, + style: const TextStyle( + color: Colors.white, + fontSize: 12, + ), + ), + ), + Container( + alignment: Alignment.bottomRight, + margin: const EdgeInsets.only(right: 5, bottom: 5), + child: Image( + height: 12, + width: 12, + image: isMuted.value ? const AssetImage("assets/images/png/zoom/muted@2x.png") : const AssetImage("assets/images/png/zoom/talking@2x.png"), + fit: BoxFit.cover, + ), + ), + ], + ), + ); + } + } + } +} diff --git a/lib/routes/app_routes.dart b/lib/routes/app_routes.dart index 36869f6..2e6b253 100644 --- a/lib/routes/app_routes.dart +++ b/lib/routes/app_routes.dart @@ -3,7 +3,7 @@ import 'package:hmg_patient_app_new/presentation/authentication/login.dart'; 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/comprehensive_checkup/comprehensive_checkup_page.dart'; -import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_page_home.dart'; +import 'package:hmg_patient_app_new/presentation/e_referral/new_e_referral.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'; @@ -11,6 +11,7 @@ import 'package:hmg_patient_app_new/presentation/symptoms_checker/organ_selector import 'package:hmg_patient_app_new/presentation/symptoms_checker/possible_conditions_screen.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/symptoms_selector_screen.dart'; import 'package:hmg_patient_app_new/presentation/symptoms_checker/triage_screen.dart'; +import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.dart'; import 'package:hmg_patient_app_new/splashPage.dart'; class AppRoutes { @@ -23,6 +24,7 @@ class AppRoutes { static const String eReferralPage = '/erReferralPage'; static const String comprehensiveCheckupPage = '/comprehensiveCheckupPage'; static const String homeHealthCarePage = '/homeHealthCarePage'; + static const String zoomCallPage = '/zoomCallPage'; // Symptoms Checker static const String organSelectorPage = '/organSelectorPage'; @@ -37,9 +39,11 @@ class AppRoutes { register: (context) => RegisterNew(), registerStepTwo: (context) => RegisterNewStep2(), medicalFilePage: (context) => MedicalFilePage(), - eReferralPage: (context) => EReferralPage(), + eReferralPage: (context) => NewReferralPage(), comprehensiveCheckupPage: (context) => ComprehensiveCheckupPage(), homeHealthCarePage: (context) => HhcProceduresPage(), + zoomCallPage: (context) => CallScreen() + homeHealthCarePage: (context) => HhcProceduresPage(), organSelectorPage: (context) => OrganSelectorPage(), symptomsCheckerScreen: (context) => SymptomsSelectorScreen(), possibleConditionsScreen: (context) => PossibleConditionsScreen(), diff --git a/lib/splashPage.dart b/lib/splashPage.dart index ba7cefd..b5b752b 100644 --- a/lib/splashPage.dart +++ b/lib/splashPage.dart @@ -4,8 +4,11 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; 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_svg/flutter_svg.dart'; import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart'; +import 'package:get_it/get_it.dart'; import 'package:hmg_patient_app_new/presentation/lab/lab_orders_page.dart'; import 'package:hmg_patient_app_new/presentation/onboarding/onboarding_screen.dart'; import 'package:hmg_patient_app_new/presentation/onboarding/splash_animation_screen.dart'; @@ -19,6 +22,9 @@ import 'package:hmg_patient_app_new/features/authentication/authentication_view_ // import 'package:hmg_patient_app_new/presentation/authantication/login.dart'; import 'package:hmg_patient_app_new/presentation/home/landing_page.dart'; import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart'; +import 'package:hmg_patient_app_new/presentation/tele_consultation/zoom/call_screen.dart'; +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/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart'; import 'package:lottie/lottie.dart'; @@ -38,6 +44,7 @@ class _SplashScreenState extends State { late AuthenticationViewModel authVm; Future initializeStuff() async { + listenerEvent(); Timer( Duration(milliseconds: 500), () async { @@ -47,22 +54,155 @@ class _SplashScreenState extends State { ); await authVm.getServicePrivilege(); Timer(Duration(seconds: 2, milliseconds: 500), () async { + bool isAppOpenedFromCall = await GetIt.instance().getBool(key: CacheConst.isAppOpenedFromCall) ?? false; + LocalNotification.init(onNotificationClick: (payload) {}); - if (await Utils.getBoolFromPrefs(CacheConst.firstLaunch)) { - Navigator.of(context).pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: OnboardingScreen()))); + if (isAppOpenedFromCall) { + navigateToTeleConsult(); } else { - Navigator.of(context).pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: LandingNavigation()))); + if (await Utils.getBoolFromPrefs(CacheConst.firstLaunch)) { + // Navigator.of(context).pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: OnboardingScreen()))); + Navigator.of(context).pushReplacement(FadePage(page: OnboardingScreen())); + } else { + // Navigator.of(context).pushReplacement(FadePage(page: SplashAnimationScreen(routeWidget: LandingNavigation()))); + Navigator.of(context).pushReplacement(FadePage(page: LandingNavigation())); + } } }); var zoom = ZoomVideoSdk(); InitConfig initConfig = InitConfig( domain: "zoom.us", - enableLog: true, + enableLog: false, ); zoom.initSdk(initConfig); } + navigateToTeleConsult() async { + String roomID = await Utils.getStringFromPrefs(CacheConst.zoomRoomID); + print('RoomID: $roomID'); + + // GetIt.instance().remove(key: CacheConst.isAppOpenedFromCall); + Utils.removeFromPrefs(CacheConst.isAppOpenedFromCall); + + 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!)), + ); + } + + Future listenerEvent() async { + print('Call Canceled : ------->'); + + try { + FlutterCallkitIncoming.onEvent.listen((event) async { + switch (event!.event) { + case Event.actionCallIncoming: + print('actionCallIncoming Event Received: ------->'); + break; + case Event.actionCallStart: + print('actionCallStart Event Received: ------->'); + break; + case Event.actionCallAccept: + print('actionCallAccept Event Received: ------->'); + FlutterCallkitIncoming.endAllCalls(); + try { + navigateToTeleConsult(); + // String roomID = await Utils.getStringFromPrefs(SharedPrefsConsts.ZOOM_ROOM_ID); + // String roomPass = await Utils.getStringFromPrefs(SharedPrefsConsts.ZOOM_ROOM_PASS); + + // print('RoomID: $roomID'); + // print('RoomPass: $roomPass'); + + // Future.delayed(const Duration(milliseconds: 3000), () async { + // // try { + // // String teleConsultURL = "https://teleconsult.meena-health.com/api/videocall/doVideoCall?roomid="; + // // await Utils.getStringFromPrefs(SharedPrefsConsts.PATIENT_MRN).then((value) { + // // teleConsultURL = teleConsultURL + value; + // // print("TeleConsult URL: $teleConsultURL"); + // // Uri uri = Uri.parse(teleConsultURL); + // // launchUrl(uri, mode: LaunchMode.externalApplication, webOnlyWindowName: "TeleConsult"); + // // }); + // + // // var cameraStatus = await Permission.camera.request(); + // // var micStatus = await Permission.microphone.request(); + // // var permissionStatus = await [Permission.microphone, Permission.camera, Permission.notification].request(); + // // if (permissionStatus[1]?.isDenied == true) { + // // await Permission.camera.request(); + // // } + // // if (permissionStatus[0]?.isDenied == true) { + // // await Permission.microphone.request(); + // // } + // + // Navigator.pushNamed( + // // context, + // navigatorKey.currentContext!, + // AppRoutes.zoomCallPage, + // // arguments: CallArguments(appointmentID, "111", "Patient", "40", "1", true, 1), + // arguments: CallArguments(roomID, roomPass, "Patient", "40", "0", true, 1), + // // arguments: CallArguments("SmallDailyStandup9875", "123", "Patient", "40", "0", false, int.parse(widget.incomingCallData!.appointmentNo!)), + // ); + // // } catch (err) { + // // print(err); + // // } + // }); + // String teleConsultURL = "https://teleconsult.meena-health.com/api/videocall/doVideoCall?roomid="; + // await Utils.getStringFromPrefs(SharedPrefsConsts.PATIENT_MRN).then((value) { + // teleConsultURL = teleConsultURL + value; + // print("TeleConsult URL: $teleConsultURL"); + // Uri uri = Uri.parse(teleConsultURL); + // launchUrl(uri, mode: LaunchMode.inAppBrowserView, webOnlyWindowName: "Test"); + // }); + // navigatorKey.currentState!.pushNamed(AppRoutes.incomingCallScreenRoute); + // await Navigator.pushNamed(context, AppRoutes.incomingCallScreenRoute).then((value) {}); + } catch (e) { + print("ERRORRRR!!! ${e.toString()}"); + // await AppSharedPreferences().setObject('call_data', data); + // var data1 = await AppSharedPreferences().getObject('call_data'); + } + break; + case Event.actionCallDecline: + print('actionCallConnected Event Received: ------->'); + await FlutterCallkitIncoming.endAllCalls(); + GetIt.instance().remove(key: CacheConst.isAppOpenedFromCall); + break; + case Event.actionCallEnded: + break; + case Event.actionCallTimeout: + break; + case Event.actionCallCallback: + break; + case Event.actionCallToggleHold: + break; + case Event.actionCallToggleMute: + break; + case Event.actionCallToggleDmtf: + break; + case Event.actionCallToggleGroup: + break; + case Event.actionCallToggleAudioSession: + break; + case Event.actionDidUpdateDevicePushTokenVoip: + break; + case Event.actionCallCustom: + break; + case Event.actionCallConnected: + print('actionCallConnected Event Received: ------->'); + await FlutterCallkitIncoming.endAllCalls(); + break; + } + }); + } on Exception catch (e) { + print(e); + print("ERRORRRR!!! ${e.toString()}"); + } + } + /// load the Privilege from service Future loadPrivilege() async { // ProjectViewModel projectProvider = Provider.of(context, listen: false); diff --git a/lib/widgets/appbar/collapsing_list_view.dart b/lib/widgets/appbar/collapsing_list_view.dart index 919e787..3e20689 100644 --- a/lib/widgets/appbar/collapsing_list_view.dart +++ b/lib/widgets/appbar/collapsing_list_view.dart @@ -119,18 +119,11 @@ class CollapsingListView extends StatelessWidget { color: AppColors.blackColor, letterSpacing: -0.5), ).expanded, - if (logout != null) - actionButton(context, t, title: "Logout".needTranslation, icon: AppAssets.logout).onPress(logout!), - if (report != null) - actionButton(context, t, title: "Report".needTranslation, icon: AppAssets.report_icon).onPress(report!), - if (history != null) - actionButton(context, t, title: "History".needTranslation, icon: AppAssets.insurance_history_icon) - .onPress(history!), - if (instructions != null) - actionButton(context, t, title: "Instructions".needTranslation, icon: AppAssets.requests).onPress(instructions!), - if (requests != null) - actionButton(context, t, title: "Requests".needTranslation, icon: AppAssets.insurance_history_icon) - .onPress(requests!), + if (logout != null) actionButton(context, t, title: "Logout".needTranslation, icon: AppAssets.logout).onPress(logout!), + if (report != null) actionButton(context, t, title: "Feedback".needTranslation, icon: AppAssets.report_icon).onPress(report!), + if (history != null) actionButton(context, t, title: "History".needTranslation, icon: AppAssets.insurance_history_icon).onPress(history!), + if (instructions != null) actionButton(context, t, title: "Instructions".needTranslation, icon: AppAssets.requests).onPress(instructions!), + if (requests != null) actionButton(context, t, title: "Requests".needTranslation, icon: AppAssets.insurance_history_icon).onPress(requests!), if (search != null) Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(search!).paddingOnly(right: 24), if (trailing != null) trailing!, ], @@ -179,7 +172,7 @@ class CollapsingListView extends StatelessWidget { style: context.dynamicTextStyle( color: AppColors.primaryRedColor, letterSpacing: -0.4, - fontSize: (14 - (2 * (1 - t))).f, + fontSize: (12 - (2 * (1 - t))).f, fontWeight: FontWeight.lerp( FontWeight.w300, FontWeight.w500, diff --git a/lib/widgets/attachment_options.dart b/lib/widgets/attachment_options.dart index 64c2485..be443f8 100644 --- a/lib/widgets/attachment_options.dart +++ b/lib/widgets/attachment_options.dart @@ -45,7 +45,7 @@ class AttachmentOptions extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SvgPicture.asset( - "assets/images/$icon", + "assets/images/svg/$icon", ), title.toText11(isBold: true), ], diff --git a/lib/widgets/chip/app_custom_chip_widget.dart b/lib/widgets/chip/app_custom_chip_widget.dart index 6904edc..8be16b7 100644 --- a/lib/widgets/chip/app_custom_chip_widget.dart +++ b/lib/widgets/chip/app_custom_chip_widget.dart @@ -22,6 +22,7 @@ class AppCustomChipWidget extends StatelessWidget { this.deleteIconColor = AppColors.textColor, this.deleteIconHasColor = false, this.padding = EdgeInsets.zero, + this.isIconPNG = false, this.onChipTap, this.labelPadding, this.onDeleteTap, @@ -42,6 +43,7 @@ class AppCustomChipWidget extends StatelessWidget { final OutlinedBorder? shape; final EdgeInsets? padding; final EdgeInsetsDirectional? labelPadding; + final bool isIconPNG; final void Function()? onChipTap; final void Function()? onDeleteTap; @@ -66,8 +68,10 @@ class AppCustomChipWidget extends StatelessWidget { child: icon.isNotEmpty ? Chip( avatar: icon.isNotEmpty - ? Utils.buildSvgWithAssets( - icon: icon, + ? isIconPNG + ? Image.asset(icon, width: iconS, height: iconS) + : Utils.buildSvgWithAssets( + icon: icon, width: iconS, height: iconS, iconColor: iconHasColor ? iconColor : null, diff --git a/lib/widgets/common_bottom_sheet.dart b/lib/widgets/common_bottom_sheet.dart index 99ff230..9312519 100644 --- a/lib/widgets/common_bottom_sheet.dart +++ b/lib/widgets/common_bottom_sheet.dart @@ -1,11 +1,65 @@ +import 'dart:io' show Platform; + 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/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/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, + {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".needTranslation, child: PrescriptionReminderView( + setReminder: (int value) async { + if (!isMultiAllowed!) { + if (onMultiDateSuccess == null) { + CalenderUtilsNew calendarUtils = CalenderUtilsNew.instance; + await calendarUtils.createOrUpdateEvent( + title: title ?? "You have appointment with Dr. ".needTranslation + doctorName, + description: description ?? "At " + appoDateFormatted + " " + appoTimeFormatted, + scheduleDateTime: dateTime, + eventId: eventId, + location: ''); + onSuccess(); + } + } else { + onMultiDateSuccess!(value); + } + }, + ), callBackFunc: () {}, isFullScreen: false); + } +} void showCommonBottomSheet(BuildContext context, {required Widget child, Function(String?)? callBackFunc, diff --git a/lib/widgets/countdown_timer.dart b/lib/widgets/countdown_timer.dart new file mode 100644 index 0000000..165a833 --- /dev/null +++ b/lib/widgets/countdown_timer.dart @@ -0,0 +1,111 @@ +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'; + +Widget buildTime(Duration duration, {bool isHomePage = false}) { + String twoDigits(int n) => n.toString().padLeft(2, '0'); + final hours = twoDigits(duration.inHours); + final minutes = twoDigits(duration.inMinutes.remainder(60)); + final seconds = twoDigits(duration.inSeconds.remainder(60)); + + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + buildTimeColumn(hours, "Hours".needTranslation), + buildTimeColumn(minutes, "Mins".needTranslation), + buildTimeColumn(seconds, "Secs".needTranslation, isLast: true), + ], + ); +} + +Widget buildTimeColumn(String time, String label, {bool isLast = false}) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Row( + children: [ + buildDigit(time[0]), + buildDigit(time[1]), + if (!isLast) buildTimeSeparator(), + ], + ), + buildLabel(label), + ], + ); +} + +Widget buildDigit(String digit) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + // margin: const EdgeInsets.symmetric(horizontal: 2), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + ), + child: ClipRect( + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 600), + switchInCurve: Curves.easeOutExpo, + switchOutCurve: Curves.easeInExpo, + transitionBuilder: (Widget child, Animation animation) { + return Stack( + children: [ + SlideTransition( + position: Tween( + begin: const Offset(0, -1), + end: const Offset(0, 1), + ).animate(CurvedAnimation( + parent: animation, + curve: Curves.easeOutCubic, + )), + child: FadeTransition( + opacity: animation, + child: child, + ), + ), + SlideTransition( + position: Tween( + begin: const Offset(0, -1), + end: const Offset(0, 0), + ).animate(CurvedAnimation( + parent: animation, + curve: Curves.bounceIn, + )), + child: FadeTransition( + opacity: animation, + child: child, + ), + ), + ], + ); + }, + child: Text( + digit, + key: ValueKey(digit), + style: TextStyle( + fontWeight: FontWeight.bold, + color: Colors.black, + fontSize: 14.f, + ), + ), + ), + ), + ); +} + +Widget buildLabel(String label) { + return label.toText12(isBold: true); +} + +Widget buildTimeSeparator() { + return const Padding( + padding: EdgeInsets.symmetric(horizontal: 2.0), + child: Text( + ":", + style: TextStyle( + color: Colors.black, + fontSize: 20, + ), + ), + ); +} diff --git a/lib/widgets/dropdown/dropdown_widget.dart b/lib/widgets/dropdown/dropdown_widget.dart index b4062e4..5ef5e58 100644 --- a/lib/widgets/dropdown/dropdown_widget.dart +++ b/lib/widgets/dropdown/dropdown_widget.dart @@ -19,7 +19,8 @@ class DropdownWidget extends StatelessWidget { final String? selectionCustomIcon; final String? leadingIcon; final Color? labelColor; - + final String? errorMessage; + final bool? hasError; const DropdownWidget( {Key? key, required this.labelText, @@ -34,7 +35,10 @@ class DropdownWidget extends StatelessWidget { this.hasSelectionCustomIcon = false, this.selectionCustomIcon, this.leadingIcon, - this.labelColor}) + this.labelColor, + this.errorMessage, + this.hasError =false + }) : super(key: key); @override @@ -42,16 +46,18 @@ class DropdownWidget extends StatelessWidget { Widget content = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, - children: [_buildLabelText(labelColor), _buildDropdown(context)], + children: [_buildLabelText(labelColor), _buildDropdown(context),], ); - return Container( + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [Container( padding: padding, alignment: Alignment.center, // This might need adjustment based on layout decoration: RoundedRectangleBorder().toSmoothCornerDecoration( color: Colors.white, borderRadius: isAllowRadius ? 15.h : null, - side: isBorderAllowed ? BorderSide(color: const Color(0xffefefef), width: 1) : null, + side: isBorderAllowed ? BorderSide(color: hasError! ? Colors.red: const Color(0xffefefef), width: 1) : null, ), child: Row( // Wrap with a Row @@ -62,9 +68,21 @@ class DropdownWidget extends StatelessWidget { SizedBox(width: 3.h), ], Expanded(child: content), + ], ), - ); + ), + if (hasError! && errorMessage != null) + Padding( + padding: EdgeInsets.only(top: 4.h, left: 12.h), // Adjust padding as needed + child: Text( + errorMessage!, + style: TextStyle( + color: Colors.red, + fontSize: 12.f, + ), + ), + )]); } Widget _buildLeadingIcon() { diff --git a/lib/widgets/image_picker.dart b/lib/widgets/image_picker.dart index 9444159..e25b117 100644 --- a/lib/widgets/image_picker.dart +++ b/lib/widgets/image_picker.dart @@ -147,6 +147,7 @@ void cameraImageAndroid(Function(String, File) image) async { if (base64Encode != null) { image(base64Encode, _image); } + } class _BottomSheet extends StatelessWidget { diff --git a/lib/widgets/map/map_utility_screen.dart b/lib/widgets/map/map_utility_screen.dart index e05c104..19823da 100644 --- a/lib/widgets/map/map_utility_screen.dart +++ b/lib/widgets/map/map_utility_screen.dart @@ -119,6 +119,7 @@ class MapUtilityScreen extends StatelessWidget { spacing: 24.h, children: [ Column( + crossAxisAlignment: CrossAxisAlignment.start, spacing: 4.h, children: [ titleString.toText21( diff --git a/lib/widgets/order_tracking/request_tracking.dart b/lib/widgets/order_tracking/request_tracking.dart index c0847f9..f07c0b1 100644 --- a/lib/widgets/order_tracking/request_tracking.dart +++ b/lib/widgets/order_tracking/request_tracking.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:hmg_patient_app_new/core/utils/size_utils.dart'; import 'package:hmg_patient_app_new/theme/colors.dart'; import 'package:hmg_patient_app_new/widgets/order_tracking/order_tracking_state.dart'; +import 'package:hmg_patient_app_new/widgets/stepper/stepper_widget.dart'; class OrderTrackingWidget extends StatelessWidget { final double? height; @@ -35,9 +36,9 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index) { if (index == 0) { - return oneProgressBar(widthOfOneState, AppColors.primaryRedColor, true); + return StepperWidget(widthOfOneState, AppColors.primaryRedColor, true, height); } else { - return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); + return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, height); } })); } @@ -46,9 +47,9 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ if(index == 0) { - return oneProgressBar(widthOfOneState, AppColors.primaryRedColor, true); + return StepperWidget(widthOfOneState, AppColors.primaryRedColor, true, height); } else { - return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); + return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, height); } }) ); @@ -57,9 +58,9 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ if(index == 1 || index == 0) { - return oneProgressBar(widthOfOneState, AppColors.primaryRedColor, index == 1 ); + return StepperWidget(widthOfOneState, AppColors.primaryRedColor, index == 1, height ); } else { - return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); + return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, height); } }) ); @@ -67,9 +68,9 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ if(index == 2 || index == 1 || index == 0) { - return oneProgressBar(widthOfOneState, AppColors.primaryRedColor, index == 2); + return StepperWidget(widthOfOneState, AppColors.primaryRedColor, index == 2, height); } else { - return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); + return StepperWidget(widthOfOneState, AppColors.greyLightColor, false, height); } }) ); @@ -77,7 +78,7 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ // if(index == 3) { - return oneProgressBar(widthOfOneState, AppColors.successLightColor, index == 3); + return StepperWidget(widthOfOneState, AppColors.successLightColor, index == 3, height); // } else { // return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); // } @@ -87,7 +88,7 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ // if(index == 3) { - return oneProgressBar(widthOfOneState, AppColors.errorColor, index == 3); + return StepperWidget(widthOfOneState, AppColors.errorColor, index == 3, height); // } else { // return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); // } @@ -97,7 +98,7 @@ class OrderTrackingWidget extends StatelessWidget { return Row( children: List.generate(4, (index){ // if(index == 3) { - return oneProgressBar(widthOfOneState, AppColors.errorColor, index == 3); + return StepperWidget(widthOfOneState, AppColors.errorColor, index == 3, height); // } else { // return oneProgressBar(widthOfOneState, AppColors.greyLightColor, false); // } @@ -106,58 +107,6 @@ class OrderTrackingWidget extends StatelessWidget { } } - Widget oneProgressBar(double width, Color color, bool hasThumb) { - return Row( - children: [ - AnimatedSize( - duration: const Duration(seconds:1), - child: SizedBox( - height: 28.h, - width: width, - child: Stack( - clipBehavior: Clip.none, - children: [ - SizedBox( - height: 28.h, - child: Container( - width: width, - height: height, - decoration: BoxDecoration( - color: color, - shape: BoxShape.rectangle, - borderRadius: BorderRadius.circular(30.h) - ), - ), - ), - Visibility( - visible: hasThumb, - child: Positioned( - top: -6.h, // move thumb above bar center - left: width - 22.h, // move to right end - child: thumb(color), - ), - ) - ], - ), - ), - ), - SizedBox(width: 8.h) - ], - ); - } - - Widget thumb(Color color) { - return Container( - width: 18.h, - height: 18.h, - padding: EdgeInsets.zero, - decoration: BoxDecoration( - color: color, - shape: BoxShape.circle, - border: Border.all(color: Colors.white, width: 2.h) - ), - ); - } } \ No newline at end of file diff --git a/lib/widgets/stepper/stepper_widget.dart b/lib/widgets/stepper/stepper_widget.dart new file mode 100644 index 0000000..5d901ac --- /dev/null +++ b/lib/widgets/stepper/stepper_widget.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:hmg_patient_app_new/core/app_export.dart'; +import 'package:hmg_patient_app_new/theme/colors.dart'; + +class StepperWidget extends StatelessWidget { + + double width = 80.w; + Color activeColor = AppColors.primaryRedColor; + bool hasThumb = true; + double? height = 4.h; + StepperWidget( this.width, this.activeColor, this.hasThumb, this.height, {super.key}); + + @override + Widget build(BuildContext context) { + return oneProgressBar(width, activeColor, hasThumb); + } + + Widget oneProgressBar(double width, Color color, bool hasThumb) { + return Row( + children: [ + AnimatedSize( + duration: const Duration(seconds: 1), + child: SizedBox( + height: 28.h, + width: width, + child: Stack( + clipBehavior: Clip.none, + children: [ + SizedBox( + height: height, + child: Container( + width: width, + height: height, + decoration: BoxDecoration( + color: color, + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(30.h) + ), + ), + ), + + Visibility( + visible: hasThumb, + child: Positioned( + top: -6.h, // move thumb above bar center + left: width - 22.h, // move to right end + child: thumb(color), + ), + ) + ], + ), + ), + ), + SizedBox(width: 8.h) + ], + ); + } + + Widget thumb(Color color) { + return Container( + width: 18.h, + height: 18.h, + padding: EdgeInsets.zero, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2.h) + ), + ); + } +} \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index 3d6604c..cd26847 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -45,6 +45,7 @@ dependencies: file_picker: ^10.3.2 local_auth: ^2.3.0 share_plus: ^11.1.0 + device_calendar_plus: ^0.3.1 device_calendar: git: https://github.com/bardram/device_calendar manage_calendar_events: ^2.0.3 @@ -59,7 +60,8 @@ 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 google_api_availability: ^5.0.1 @@ -79,6 +81,7 @@ dependencies: path_provider: ^2.0.8 open_filex: ^4.7.0 flutter_swiper_view: ^1.1.8 + flutter_callkit_incoming: ^3.0.0 location: ^8.0.1 gms_check: ^1.0.4 @@ -108,6 +111,7 @@ flutter: - assets/images/png/body_parts/female/ - assets/images/svg/ - assets/images/png/ + - assets/images/png/zoom/ - assets/animations/ - assets/animations/lottie/