commit 27e27fb70b1de26d6404c37734451a8d6caad90d Author: Sarankumar Date: Sat Apr 11 10:21:31 2026 +0530 2026-04-11 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f0d006 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..fec8952 --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + - platform: ios + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/.vscode/easycode.ignore b/.vscode/easycode.ignore new file mode 100644 index 0000000..d7cdc53 --- /dev/null +++ b/.vscode/easycode.ignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +vendor/ +cache/ +.*/ +*.min.* +*.test.* +*.spec.* +*.bundle.* +*.bundle-min.* +*.log +package-lock.json \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..47733d2 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "D:/taxglide/linux" +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..cbb7dde --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# taxglide + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..d4e0f0c --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..c908258 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..271e82c --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,71 @@ +// App-level build.gradle.kts + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + + // Add Google Services plugin for Firebase + id("com.google.gms.google-services") + + // Flutter plugin must come last + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.amrithaa.taxglide" + compileSdk = flutter.compileSdkVersion + + // Override NDK version to match Firebase requirements + ndkVersion = "27.0.12077973" + + compileOptions { + // ✅ Enable core library desugaring + isCoreLibraryDesugaringEnabled = true + + // ✅ Java 11 compatibility + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + applicationId = "com.amrithaa.taxglide" + + // Override minSdk to meet Firebase Core requirements (minimum 23) + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + getByName("release") { + // TODO: Replace with your release signing config + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} + +dependencies { + // ✅ Required for Java 8/11+ API desugaring + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") + + // Import the Firebase BoM + implementation(platform("com.google.firebase:firebase-bom:34.5.0")) + + // Firebase SDKs + implementation("com.google.firebase:firebase-analytics") + implementation("com.google.firebase:firebase-auth") + implementation("com.google.firebase:firebase-firestore") + implementation("com.google.firebase:firebase-messaging") + + // ✅ Optional: Kotlin stdlib JDK 8 for safety + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") +} diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 0000000..39bddd9 --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,29 @@ +{ + "project_info": { + "project_number": "600746935622", + "project_id": "auditpro-16b14", + "storage_bucket": "auditpro-16b14.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:600746935622:android:9c98f0c1dd408b19cad147", + "android_client_info": { + "package_name": "com.amrithaa.taxglide" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyAfTUgCMmhunZci93dqMuoeGvC5r8NpdhM" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9980072 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/taxglide/MainActivity.kt b/android/app/src/main/kotlin/com/example/taxglide/MainActivity.kt new file mode 100644 index 0000000..4a2bf19 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/taxglide/MainActivity.kt @@ -0,0 +1,5 @@ +package com.amrithaa.taxglide + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b23abb6 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..d81458d Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..1cb7aa2 --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..ef799f1 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..5e18a39 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b91e719 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..8403758 --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml b/android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml new file mode 100644 index 0000000..5f349f7 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/launcher_icon.png b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png new file mode 100644 index 0000000..6d9e9fb Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/launcher_icon.png b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png new file mode 100644 index 0000000..36ec23d Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png new file mode 100644 index 0000000..1fc333b Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png new file mode 100644 index 0000000..e894d4f Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png new file mode 100644 index 0000000..62a515a Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..360a160 --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..5fac679 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..4498b33 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,38 @@ +// Root-level build.gradle.kts + +plugins { + id("com.google.gms.google-services") apply false + id("com.android.application") apply false + id("org.jetbrains.kotlin.android") apply false +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +// Configure build directory +val customBuildDir: Directory = rootProject.layout.buildDirectory + .dir("../../build") + .get() + +rootProject.layout.buildDirectory.set(customBuildDir) + +subprojects { + val subprojectBuildDir: Directory = customBuildDir.dir(project.name) + layout.buildDirectory.set(subprojectBuildDir) +} + +subprojects { + afterEvaluate { + if (project.name != "app") { + project.evaluationDependsOn(":app") + } + } +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} \ No newline at end of file diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..223e95e --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..b7cda7b --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dcc7e10 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..d70521b --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,29 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.9.1" apply false + // START: FlutterFire Configuration + id("com.google.gms.google-services") version("4.3.15") apply false + // END: FlutterFire Configuration + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/assets/fonts/Gilroy-Black.ttf b/assets/fonts/Gilroy-Black.ttf new file mode 100644 index 0000000..3e1a57e Binary files /dev/null and b/assets/fonts/Gilroy-Black.ttf differ diff --git a/assets/fonts/Gilroy-BlackItalic.ttf b/assets/fonts/Gilroy-BlackItalic.ttf new file mode 100644 index 0000000..6f0b4c4 Binary files /dev/null and b/assets/fonts/Gilroy-BlackItalic.ttf differ diff --git a/assets/fonts/Gilroy-Bold.ttf b/assets/fonts/Gilroy-Bold.ttf new file mode 100644 index 0000000..1aea716 Binary files /dev/null and b/assets/fonts/Gilroy-Bold.ttf differ diff --git a/assets/fonts/Gilroy-BoldItalic.ttf b/assets/fonts/Gilroy-BoldItalic.ttf new file mode 100644 index 0000000..6754019 Binary files /dev/null and b/assets/fonts/Gilroy-BoldItalic.ttf differ diff --git a/assets/fonts/Gilroy-ExtraBold.ttf b/assets/fonts/Gilroy-ExtraBold.ttf new file mode 100644 index 0000000..01eb343 Binary files /dev/null and b/assets/fonts/Gilroy-ExtraBold.ttf differ diff --git a/assets/fonts/Gilroy-ExtraBoldItalic.ttf b/assets/fonts/Gilroy-ExtraBoldItalic.ttf new file mode 100644 index 0000000..86000c1 Binary files /dev/null and b/assets/fonts/Gilroy-ExtraBoldItalic.ttf differ diff --git a/assets/fonts/Gilroy-Heavy.ttf b/assets/fonts/Gilroy-Heavy.ttf new file mode 100644 index 0000000..726e371 Binary files /dev/null and b/assets/fonts/Gilroy-Heavy.ttf differ diff --git a/assets/fonts/Gilroy-HeavyItalic.ttf b/assets/fonts/Gilroy-HeavyItalic.ttf new file mode 100644 index 0000000..12a7e55 Binary files /dev/null and b/assets/fonts/Gilroy-HeavyItalic.ttf differ diff --git a/assets/fonts/Gilroy-Light.ttf b/assets/fonts/Gilroy-Light.ttf new file mode 100644 index 0000000..b08db4e Binary files /dev/null and b/assets/fonts/Gilroy-Light.ttf differ diff --git a/assets/fonts/Gilroy-LightItalic.ttf b/assets/fonts/Gilroy-LightItalic.ttf new file mode 100644 index 0000000..ea4bee4 Binary files /dev/null and b/assets/fonts/Gilroy-LightItalic.ttf differ diff --git a/assets/fonts/Gilroy-Medium.ttf b/assets/fonts/Gilroy-Medium.ttf new file mode 100644 index 0000000..06d6a94 Binary files /dev/null and b/assets/fonts/Gilroy-Medium.ttf differ diff --git a/assets/fonts/Gilroy-MediumItalic.ttf b/assets/fonts/Gilroy-MediumItalic.ttf new file mode 100644 index 0000000..9fbb898 Binary files /dev/null and b/assets/fonts/Gilroy-MediumItalic.ttf differ diff --git a/assets/fonts/Gilroy-Regular.ttf b/assets/fonts/Gilroy-Regular.ttf new file mode 100644 index 0000000..ad17f71 Binary files /dev/null and b/assets/fonts/Gilroy-Regular.ttf differ diff --git a/assets/fonts/Gilroy-RegularItalic.ttf b/assets/fonts/Gilroy-RegularItalic.ttf new file mode 100644 index 0000000..628a732 Binary files /dev/null and b/assets/fonts/Gilroy-RegularItalic.ttf differ diff --git a/assets/fonts/Gilroy-SemiBold.ttf b/assets/fonts/Gilroy-SemiBold.ttf new file mode 100644 index 0000000..cb3cbb6 Binary files /dev/null and b/assets/fonts/Gilroy-SemiBold.ttf differ diff --git a/assets/fonts/Gilroy-SemiBoldItalic.ttf b/assets/fonts/Gilroy-SemiBoldItalic.ttf new file mode 100644 index 0000000..fc82a10 Binary files /dev/null and b/assets/fonts/Gilroy-SemiBoldItalic.ttf differ diff --git a/assets/fonts/Gilroy-Thin.ttf b/assets/fonts/Gilroy-Thin.ttf new file mode 100644 index 0000000..c6daeb7 Binary files /dev/null and b/assets/fonts/Gilroy-Thin.ttf differ diff --git a/assets/fonts/Gilroy-ThinItalic.ttf b/assets/fonts/Gilroy-ThinItalic.ttf new file mode 100644 index 0000000..4bc3561 Binary files /dev/null and b/assets/fonts/Gilroy-ThinItalic.ttf differ diff --git a/assets/fonts/Gilroy-UltraLight.ttf b/assets/fonts/Gilroy-UltraLight.ttf new file mode 100644 index 0000000..adc3e33 Binary files /dev/null and b/assets/fonts/Gilroy-UltraLight.ttf differ diff --git a/assets/fonts/Gilroy-UltraLightItalic.ttf b/assets/fonts/Gilroy-UltraLightItalic.ttf new file mode 100644 index 0000000..3403fe8 Binary files /dev/null and b/assets/fonts/Gilroy-UltraLightItalic.ttf differ diff --git a/assets/images/backgroudimagesvg.svg b/assets/images/backgroudimagesvg.svg new file mode 100644 index 0000000..6dbd412 --- /dev/null +++ b/assets/images/backgroudimagesvg.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/images/backgroundimages.png b/assets/images/backgroundimages.png new file mode 100644 index 0000000..5f04d0e Binary files /dev/null and b/assets/images/backgroundimages.png differ diff --git a/assets/images/bottom_navigator.png b/assets/images/bottom_navigator.png new file mode 100644 index 0000000..4ccae97 Binary files /dev/null and b/assets/images/bottom_navigator.png differ diff --git a/assets/images/generalchatimage.png b/assets/images/generalchatimage.png new file mode 100644 index 0000000..1a04fe8 Binary files /dev/null and b/assets/images/generalchatimage.png differ diff --git a/assets/images/generalchatsvg.svg b/assets/images/generalchatsvg.svg new file mode 100644 index 0000000..2d01f8f --- /dev/null +++ b/assets/images/generalchatsvg.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/haeder_image.jpg b/assets/images/haeder_image.jpg new file mode 100644 index 0000000..170b6a8 Binary files /dev/null and b/assets/images/haeder_image.jpg differ diff --git a/assets/images/home.png b/assets/images/home.png new file mode 100644 index 0000000..1cc165a Binary files /dev/null and b/assets/images/home.png differ diff --git a/assets/images/homepagebackground.jpg b/assets/images/homepagebackground.jpg new file mode 100644 index 0000000..db70dd0 Binary files /dev/null and b/assets/images/homepagebackground.jpg differ diff --git a/assets/images/profilebanner.jpg b/assets/images/profilebanner.jpg new file mode 100644 index 0000000..666ced2 Binary files /dev/null and b/assets/images/profilebanner.jpg differ diff --git a/assets/images/taxglidelogo.png b/assets/images/taxglidelogo.png new file mode 100644 index 0000000..03a1289 Binary files /dev/null and b/assets/images/taxglidelogo.png differ diff --git a/assets/images/taxglidelogo_android.png b/assets/images/taxglidelogo_android.png new file mode 100644 index 0000000..7bfba59 Binary files /dev/null and b/assets/images/taxglidelogo_android.png differ diff --git a/assets/images/taxglidelogo_ios.png b/assets/images/taxglidelogo_ios.png new file mode 100644 index 0000000..340aedf Binary files /dev/null and b/assets/images/taxglidelogo_ios.png differ diff --git a/assets/images/taxglidelogo_white.png b/assets/images/taxglidelogo_white.png new file mode 100644 index 0000000..03a1289 Binary files /dev/null and b/assets/images/taxglidelogo_white.png differ diff --git a/assets/images/taxglidelogoauth.png b/assets/images/taxglidelogoauth.png new file mode 100644 index 0000000..9fd749d Binary files /dev/null and b/assets/images/taxglidelogoauth.png differ diff --git a/assets/images/taxglidewhitelogo.png b/assets/images/taxglidewhitelogo.png new file mode 100644 index 0000000..aaafe08 Binary files /dev/null and b/assets/images/taxglidewhitelogo.png differ diff --git a/assets/svgs/generalchat.svg b/assets/svgs/generalchat.svg new file mode 100644 index 0000000..d6e0db9 --- /dev/null +++ b/assets/svgs/generalchat.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..bef39f5 --- /dev/null +++ b/firebase.json @@ -0,0 +1 @@ +{"flutter":{"platforms":{"android":{"default":{"projectId":"auditpro-16b14","appId":"1:600746935622:android:9c98f0c1dd408b19cad147","fileOutput":"android/app/google-services.json"}},"dart":{"lib/firebase_options.dart":{"projectId":"auditpro-16b14","configurations":{"android":"1:600746935622:android:9c98f0c1dd408b19cad147","ios":"1:600746935622:ios:b8c6feb054815581cad147"}}},"ios":{"default":{"projectId":"auditpro-16b14","appId":"1:600746935622:ios:b8c6feb054815581cad147","uploadDebugSymbols":false,"fileOutput":"ios/Runner/GoogleService-Info.plist"}}}}} \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 0000000..cf07ade --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,42 @@ +platform :ios, '15.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100644 index 0000000..df776d7 --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,223 @@ +PODS: + - device_info_plus (0.0.1): + - Flutter + - DKImagePickerController/Core (4.3.9): + - DKImagePickerController/ImageDataManager + - DKImagePickerController/Resource + - DKImagePickerController/ImageDataManager (4.3.9) + - DKImagePickerController/PhotoGallery (4.3.9): + - DKImagePickerController/Core + - DKPhotoGallery + - DKImagePickerController/Resource (4.3.9) + - DKPhotoGallery (0.0.19): + - DKPhotoGallery/Core (= 0.0.19) + - DKPhotoGallery/Model (= 0.0.19) + - DKPhotoGallery/Preview (= 0.0.19) + - DKPhotoGallery/Resource (= 0.0.19) + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Core (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Preview + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Model (0.0.19): + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Preview (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Resource + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Resource (0.0.19): + - SDWebImage + - SwiftyGif + - file_picker (0.0.1): + - DKImagePickerController/PhotoGallery + - Flutter + - Firebase/CoreOnly (12.4.0): + - FirebaseCore (~> 12.4.0) + - Firebase/Messaging (12.4.0): + - Firebase/CoreOnly + - FirebaseMessaging (~> 12.4.0) + - firebase_core (4.2.1): + - Firebase/CoreOnly (= 12.4.0) + - Flutter + - firebase_messaging (16.0.4): + - Firebase/Messaging (= 12.4.0) + - firebase_core + - Flutter + - FirebaseCore (12.4.0): + - FirebaseCoreInternal (~> 12.4.0) + - GoogleUtilities/Environment (~> 8.1) + - GoogleUtilities/Logger (~> 8.1) + - FirebaseCoreInternal (12.4.0): + - "GoogleUtilities/NSData+zlib (~> 8.1)" + - FirebaseInstallations (12.4.0): + - FirebaseCore (~> 12.4.0) + - GoogleUtilities/Environment (~> 8.1) + - GoogleUtilities/UserDefaults (~> 8.1) + - PromisesObjC (~> 2.4) + - FirebaseMessaging (12.4.0): + - FirebaseCore (~> 12.4.0) + - FirebaseInstallations (~> 12.4.0) + - GoogleDataTransport (~> 10.1) + - GoogleUtilities/AppDelegateSwizzler (~> 8.1) + - GoogleUtilities/Environment (~> 8.1) + - GoogleUtilities/Reachability (~> 8.1) + - GoogleUtilities/UserDefaults (~> 8.1) + - nanopb (~> 3.30910.0) + - Flutter (1.0.0) + - flutter_local_notifications (0.0.1): + - Flutter + - flutter_secure_storage (6.0.0): + - Flutter + - gal (1.0.0): + - Flutter + - FlutterMacOS + - GoogleDataTransport (10.1.0): + - nanopb (~> 3.30910.0) + - PromisesObjC (~> 2.4) + - GoogleUtilities/AppDelegateSwizzler (8.1.0): + - GoogleUtilities/Environment + - GoogleUtilities/Logger + - GoogleUtilities/Network + - GoogleUtilities/Privacy + - GoogleUtilities/Environment (8.1.0): + - GoogleUtilities/Privacy + - GoogleUtilities/Logger (8.1.0): + - GoogleUtilities/Environment + - GoogleUtilities/Privacy + - GoogleUtilities/Network (8.1.0): + - GoogleUtilities/Logger + - "GoogleUtilities/NSData+zlib" + - GoogleUtilities/Privacy + - GoogleUtilities/Reachability + - "GoogleUtilities/NSData+zlib (8.1.0)": + - GoogleUtilities/Privacy + - GoogleUtilities/Privacy (8.1.0) + - GoogleUtilities/Reachability (8.1.0): + - GoogleUtilities/Logger + - GoogleUtilities/Privacy + - GoogleUtilities/UserDefaults (8.1.0): + - GoogleUtilities/Logger + - GoogleUtilities/Privacy + - image_picker_ios (0.0.1): + - Flutter + - nanopb (3.30910.0): + - nanopb/decode (= 3.30910.0) + - nanopb/encode (= 3.30910.0) + - nanopb/decode (3.30910.0) + - nanopb/encode (3.30910.0) + - open_filex (0.0.2): + - Flutter + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - permission_handler_apple (9.3.0): + - Flutter + - PromisesObjC (2.4.0) + - SDWebImage (5.21.7): + - SDWebImage/Core (= 5.21.7) + - SDWebImage/Core (5.21.7) + - sqflite_darwin (0.0.4): + - Flutter + - FlutterMacOS + - SwiftyGif (5.4.5) + - url_launcher_ios (0.0.1): + - Flutter + +DEPENDENCIES: + - device_info_plus (from `.symlinks/plugins/device_info_plus/ios`) + - file_picker (from `.symlinks/plugins/file_picker/ios`) + - firebase_core (from `.symlinks/plugins/firebase_core/ios`) + - firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`) + - Flutter (from `Flutter`) + - flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`) + - flutter_secure_storage (from `.symlinks/plugins/flutter_secure_storage/ios`) + - gal (from `.symlinks/plugins/gal/darwin`) + - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) + - open_filex (from `.symlinks/plugins/open_filex/ios`) + - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) + - sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`) + - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) + +SPEC REPOS: + trunk: + - DKImagePickerController + - DKPhotoGallery + - Firebase + - FirebaseCore + - FirebaseCoreInternal + - FirebaseInstallations + - FirebaseMessaging + - GoogleDataTransport + - GoogleUtilities + - nanopb + - PromisesObjC + - SDWebImage + - SwiftyGif + +EXTERNAL SOURCES: + device_info_plus: + :path: ".symlinks/plugins/device_info_plus/ios" + file_picker: + :path: ".symlinks/plugins/file_picker/ios" + firebase_core: + :path: ".symlinks/plugins/firebase_core/ios" + firebase_messaging: + :path: ".symlinks/plugins/firebase_messaging/ios" + Flutter: + :path: Flutter + flutter_local_notifications: + :path: ".symlinks/plugins/flutter_local_notifications/ios" + flutter_secure_storage: + :path: ".symlinks/plugins/flutter_secure_storage/ios" + gal: + :path: ".symlinks/plugins/gal/darwin" + image_picker_ios: + :path: ".symlinks/plugins/image_picker_ios/ios" + open_filex: + :path: ".symlinks/plugins/open_filex/ios" + path_provider_foundation: + :path: ".symlinks/plugins/path_provider_foundation/darwin" + permission_handler_apple: + :path: ".symlinks/plugins/permission_handler_apple/ios" + sqflite_darwin: + :path: ".symlinks/plugins/sqflite_darwin/darwin" + url_launcher_ios: + :path: ".symlinks/plugins/url_launcher_ios/ios" + +SPEC CHECKSUMS: + device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe + DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c + DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60 + file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be + Firebase: f07b15ae5a6ec0f93713e30b923d9970d144af3e + firebase_core: f1aafb21c14f497e5498f7ffc4dc63cbb52b2594 + firebase_messaging: c17a29984eafce4b2997fe078bb0a9e0b06f5dde + FirebaseCore: bb595f3114953664e3c1dc032f008a244147cfd3 + FirebaseCoreInternal: d7f5a043c2cd01a08103ab586587c1468047bca6 + FirebaseInstallations: ae9f4902cb5bf1d0c5eaa31ec1f4e5495a0714e2 + FirebaseMessaging: d33971b7bb252745ea6cd31ab190d1a1df4b8ed5 + Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 + flutter_local_notifications: 395056b3175ba4f08480a7c5de30cd36d69827e4 + flutter_secure_storage: 1ed9476fba7e7a782b22888f956cce43e2c62f13 + gal: baecd024ebfd13c441269ca7404792a7152fde89 + GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7 + GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1 + image_picker_ios: 7fe1ff8e34c1790d6fff70a32484959f563a928a + nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 + open_filex: 432f3cd11432da3e39f47fcc0df2b1603854eff1 + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d + PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 + SDWebImage: e9fc87c1aab89a8ab1bbd74eba378c6f53be8abf + sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0 + SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4 + url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b + +PODFILE CHECKSUM: ce2a4dd764e1c7aeed6a7cdc5e61d092b6dc6d32 + +COCOAPODS: 1.16.2 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..1f1ec88 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,778 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 1AF34DE2A69A05D5E14EDB40 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2937F78EB64278732B9642C5 /* Pods_RunnerTests.framework */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + A713CACBAB10504B0B27E6A5 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BAF70DD673429A70E5C6F058 /* Pods_Runner.framework */; }; + FE88C3412F46F73700E703C8 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = FE88C3402F46F73700E703C8 /* GoogleService-Info.plist */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 2937F78EB64278732B9642C5 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2989F063F2CBF4AAE3FB20E0 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 7E515BC6E58B804C9157A996 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BAF70DD673429A70E5C6F058 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E9C08DAAECDABD0653871E98 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + EC5F11C32DCBD2281EFC2E91 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + EEA157A1EA0DD57A78AC15C3 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + FDFD268C8965834B90C8C773 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + FE0282802F46DA91000609BC /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + FE88C3402F46F73700E703C8 /* GoogleService-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 07144859CAAB41580FAAD3BF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1AF34DE2A69A05D5E14EDB40 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A713CACBAB10504B0B27E6A5 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2C656DB2974D57E6891D7B1D /* Pods */ = { + isa = PBXGroup; + children = ( + FDFD268C8965834B90C8C773 /* Pods-Runner.debug.xcconfig */, + 2989F063F2CBF4AAE3FB20E0 /* Pods-Runner.release.xcconfig */, + E9C08DAAECDABD0653871E98 /* Pods-Runner.profile.xcconfig */, + EC5F11C32DCBD2281EFC2E91 /* Pods-RunnerTests.debug.xcconfig */, + EEA157A1EA0DD57A78AC15C3 /* Pods-RunnerTests.release.xcconfig */, + 7E515BC6E58B804C9157A996 /* Pods-RunnerTests.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 6817CCBBDA7677C5E6BC04A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + BAF70DD673429A70E5C6F058 /* Pods_Runner.framework */, + 2937F78EB64278732B9642C5 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 2C656DB2974D57E6891D7B1D /* Pods */, + 6817CCBBDA7677C5E6BC04A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + FE88C3402F46F73700E703C8 /* GoogleService-Info.plist */, + FE0282802F46DA91000609BC /* Runner.entitlements */, + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 728043871240221E58EDB821 /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 07144859CAAB41580FAAD3BF /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 37D7654EFDFF610E656C3E34 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + A0A2FA9A029E9E40E7CDB0F5 /* [CP] Embed Pods Frameworks */, + A0364D76811E0DE19C3D5E98 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + SystemCapabilities = { + com.apple.Push = { + enabled = 1; + }; + }; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + FE88C3412F46F73700E703C8 /* GoogleService-Info.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 37D7654EFDFF610E656C3E34 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 728043871240221E58EDB821 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; + A0364D76811E0DE19C3D5E98 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + A0A2FA9A029E9E40E7CDB0F5 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 2; + DEVELOPMENT_TEAM = GNH4U6HVZW; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Taxglide; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.business"; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EC5F11C32DCBD2281EFC2E91 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EEA157A1EA0DD57A78AC15C3 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7E515BC6E58B804C9157A996 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 2; + DEVELOPMENT_TEAM = GNH4U6HVZW; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Taxglide; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.business"; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 2; + DEVELOPMENT_TEAM = GNH4U6HVZW; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Taxglide; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.business"; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..13473f3 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,19 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + + if #available(iOS 10.0, *) { + UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate + } + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} + diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} 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 new file mode 100644 index 0000000..f27e8b4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png 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 new file mode 100644 index 0000000..e1a8a5f Binary files /dev/null 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 new file mode 100644 index 0000000..e7862e3 Binary files /dev/null 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 new file mode 100644 index 0000000..450d5d3 Binary files /dev/null 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 new file mode 100644 index 0000000..4b0e375 Binary files /dev/null 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 new file mode 100644 index 0000000..992bd32 Binary files /dev/null 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 new file mode 100644 index 0000000..9c83142 Binary files /dev/null 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 new file mode 100644 index 0000000..e7862e3 Binary files /dev/null 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 new file mode 100644 index 0000000..d77a497 Binary files /dev/null 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 new file mode 100644 index 0000000..316b242 Binary files /dev/null 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-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..947d9ba Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..ca818c2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..2b40be7 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..83b1e00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.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 new file mode 100644 index 0000000..316b242 Binary files /dev/null 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 new file mode 100644 index 0000000..0842b3d Binary files /dev/null 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-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..2589b6c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..d9f67a4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.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 new file mode 100644 index 0000000..3a6e558 Binary files /dev/null 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 new file mode 100644 index 0000000..010fd51 Binary files /dev/null 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 new file mode 100644 index 0000000..702a3e4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/GoogleService-Info.plist b/ios/Runner/GoogleService-Info.plist new file mode 100644 index 0000000..037abc8 --- /dev/null +++ b/ios/Runner/GoogleService-Info.plist @@ -0,0 +1,30 @@ + + + + + API_KEY + AIzaSyBnljOambzS0DdbRuDr6tvBBGvK24jEy3E + GCM_SENDER_ID + 600746935622 + PLIST_VERSION + 1 + BUNDLE_ID + com.amrithaa.taxglide + PROJECT_ID + auditpro-16b14 + STORAGE_BUCKET + auditpro-16b14.firebasestorage.app + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:600746935622:ios:b8c6feb054815581cad147 + + \ No newline at end of file diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..8f5537d --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,92 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Taxglide + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + taxglide + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + FirebaseAppDelegateProxyEnabled + + FirebaseMessagingAutoInitEnabled + + LSApplicationQueriesSchemes + + whatsapp + + LSRequiresIPhoneOS + + NSCameraUsageDescription + This app requires access to the camera to take photos of tax documents and profile pictures. + NSMicrophoneUsageDescription + This app requires access to the microphone if you record videos for tax documentation. + NSPhotoLibraryUsageDescription + This app requires access to the photo library to upload tax-related documents and profile pictures. + NSUserNotificationUsageDescription + Taxglide needs to send you notifications about your tax documents, chat updates, and important deadlines. + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UIBackgroundModes + + fetch + remote-notification + processing + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements new file mode 100644 index 0000000..903def2 --- /dev/null +++ b/ios/Runner/Runner.entitlements @@ -0,0 +1,8 @@ + + + + + aps-environment + development + + diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/auth/employee_login_screen.dart b/lib/auth/employee_login_screen.dart new file mode 100644 index 0000000..7244aca --- /dev/null +++ b/lib/auth/employee_login_screen.dart @@ -0,0 +1,287 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/comman_textformfileds.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class EmployeeLoginScreen extends ConsumerStatefulWidget { + const EmployeeLoginScreen({super.key}); + + @override + ConsumerState createState() => + _EmployeeLoginScreenState(); +} + +class _EmployeeLoginScreenState extends ConsumerState { + final ValidationPopup _validationPopup = ValidationPopup(); + final TextEditingController _mobileController = TextEditingController(); + + @override + void initState() { + super.initState(); + final args = Get.arguments; + if (args != null && args is Map) { + final mobile = args['mobile'] ?? ''; + if (mobile.isNotEmpty) { + _mobileController.text = mobile; + } + } + } + + @override + void dispose() { + _mobileController.dispose(); + super.dispose(); + } + + Future _handleLogin() async { + final mobile = _mobileController.text.trim(); + + if (!_validationPopup.validateMobileNumber(context, mobile)) { + return; + } + + await ref.read(employeeloginProvider.notifier).login(mobile); + final state = ref.read(employeeloginProvider); + + state.when( + data: (data) { + if (data['success'] == true) { + Get.toNamed(ConstRouters.employeeotp, arguments: {'mobile': mobile}); + _validationPopup.showSuccessMessage( + context, + "OTP sent successfully!", + ); + } else if (data['error'] != null) { + _validationPopup.showErrorMessage(context, data['error'].toString()); + } + }, + loading: () {}, + error: (err, _) { + _validationPopup.showErrorMessage(context, "Error: $err"); + }, + ); + } + + @override + Widget build(BuildContext context) { + final loginState = ref.watch(employeeloginProvider); + + // Initialize responsive utils + final r = ResponsiveUtils(context); + + // Responsive values + final logoWidth = r.getValue( + mobile: 120, + tablet: 141, + desktop: 160, + ); + final logoHeight = r.getValue( + mobile: 85, + tablet: 100, + desktop: 115, + ); + final titleFontSize = r.fontSize(mobile: 26, tablet: 32, desktop: 36); + final subtitleFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final termsFontSize = r.fontSize(mobile: 10.5, tablet: 11.34, desktop: 12); + final linkFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final otherLoginFontSize = r.fontSize(mobile: 12, tablet: 13, desktop: 14); + + final spacingXS = r.spacing(mobile: 10, tablet: 10, desktop: 12); + final spacingSM = r.spacing(mobile: 15, tablet: 20, desktop: 24); + final spacingMD = r.spacing(mobile: 20, tablet: 20, desktop: 24); + final spacingLG = r.spacing(mobile: 20, tablet: 22, desktop: 28); + + return Scaffold( + resizeToAvoidBottomInset: true, + body: Container( + width: double.infinity, + height: double.infinity, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + child: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: r.screenHeight), + child: IntrinsicHeight( + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Logo + Image.asset( + AppAssets.taxgildelogoauth, + width: logoWidth, + height: logoHeight, + fit: BoxFit.contain, + ), + SizedBox(height: spacingMD), + + // Login Title + Text( + "Login", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: titleFontSize, + fontWeight: FontWeight.w600, + height: 1.3, + letterSpacing: 0.01 * titleFontSize, + color: AppColors.authheading, + ), + ), + SizedBox(height: spacingMD), + + // Subtitle + Text( + "Enter your registered Mobile Number", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: subtitleFontSize, + fontWeight: FontWeight.w600, + height: 1.4, + letterSpacing: 0.03 * subtitleFontSize, + color: AppColors.authleading, + ), + ), + SizedBox(height: spacingLG), + + // Mobile Number Input + CommanTextFormField( + controller: _mobileController, + hintText: 'Enter your Mobile Number', + keyboardType: TextInputType.phone, + prefixIcon: Icons.phone_android, + ), + SizedBox(height: spacingLG), + + // Terms and Conditions + Text.rich( + TextSpan( + text: "By signing up, you agree to the ", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: termsFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authleading, + ), + children: [ + TextSpan( + text: "Terms of Service ", + style: TextStyle( + fontFamily: 'Gilroy-Bold', + fontWeight: FontWeight.w700, + fontSize: termsFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authtermsandcondition, + ), + ), + TextSpan( + text: "and ", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: termsFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authleading, + ), + ), + TextSpan( + text: "Data Processing Agreement", + style: TextStyle( + fontFamily: 'Gilroy-Bold', + fontWeight: FontWeight.w700, + fontSize: termsFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authtermsandcondition, + ), + ), + ], + ), + textAlign: TextAlign.center, + ), + + SizedBox(height: spacingLG), + + // Login Button or Loading + loginState.isLoading + ? const CircularProgressIndicator() + : CommanButton( + text: "Login", + onPressed: _handleLogin, + ), + + SizedBox(height: spacingSM), + + Text( + "Other Login", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Inter', + fontWeight: FontWeight.w500, + fontSize: otherLoginFontSize, + height: 1.8, + letterSpacing: 0.13, + color: const Color(0xFF6C7278), + ), + ), + + SizedBox(height: spacingXS), + + Text.rich( + TextSpan( + text: "User Login? ", + style: TextStyle(fontSize: linkFontSize), + children: [ + TextSpan( + text: "Click Here", + style: TextStyle( + fontSize: linkFontSize, + color: AppColors.authsignup, + fontWeight: FontWeight.bold, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed(ConstRouters.login); + }, + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/auth/employee_otp_screen.dart b/lib/auth/employee_otp_screen.dart new file mode 100644 index 0000000..1acc4cc --- /dev/null +++ b/lib/auth/employee_otp_screen.dart @@ -0,0 +1,420 @@ +import 'dart:async'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import '../router/consts_routers.dart'; + +class EmployeeOtpScreen extends ConsumerStatefulWidget { + const EmployeeOtpScreen({super.key}); + + @override + ConsumerState createState() => _EmployeeOtpScreenState(); +} + +class _EmployeeOtpScreenState extends ConsumerState { + final ValidationPopup _validationPopup = ValidationPopup(); + final int otpLength = 4; + final List _controllers = []; + final List _focusNodes = []; + String otpValue = ''; + + Timer? _timer; + int _remainingSeconds = 600; + bool _canResend = false; + + late String mobile; + + @override + void initState() { + super.initState(); + final args = Get.arguments as Map?; + mobile = args?['mobile'] ?? ''; + + for (int i = 0; i < otpLength; i++) { + _controllers.add(TextEditingController()); + _focusNodes.add(FocusNode()); + } + _startTimer(); + } + + @override + void dispose() { + _timer?.cancel(); + for (var c in _controllers) c.dispose(); + for (var f in _focusNodes) f.dispose(); + super.dispose(); + } + + void _startTimer() { + _canResend = false; + _remainingSeconds = 30; + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (_remainingSeconds > 0) { + setState(() => _remainingSeconds--); + } else { + setState(() => _canResend = true); + timer.cancel(); + } + }); + } + + String _formatTime(int seconds) { + int minutes = seconds ~/ 60; + int remainingSeconds = seconds % 60; + return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}'; + } + + Future _resendOtp() async { + if (!_canResend) return; + + for (var controller in _controllers) controller.clear(); + setState(() => otpValue = ''); + _focusNodes[0].requestFocus(); + + try { + await ref.read(employeeloginProvider.notifier).login(mobile); + final loginState = ref.read(employeeloginProvider); + loginState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "OTP has been resent successfully!", + ); + _startTimer(); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Failed to resend OTP", + ); + } + }, + loading: () {}, + error: (error, _) { + _validationPopup.showErrorMessage( + context, + "Failed to resend OTP. Please try again.", + ); + }, + ); + } catch (e) { + _validationPopup.showErrorMessage( + context, + "An error occurred. Please try again.", + ); + } + } + + Future _verifyOtp() async { + if (otpValue.length != otpLength) { + _validationPopup.showErrorMessage(context, "Please enter all OTP digits"); + return; + } + + await ref.read(employeeloginProvider.notifier).verifyOtp(mobile, otpValue); + final loginState = ref.read(employeeloginProvider); + + loginState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "OTP Verified Successfully!", + ); + Future.delayed(const Duration(seconds: 1), () { + Get.offAll(() => const MainController()); + }); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Invalid OTP. Please try again.", + ); + } + }, + loading: () {}, + error: (error, _) { + _validationPopup.showErrorMessage( + context, + "Failed to verify OTP. Please try again.", + ); + }, + ); + } + + void _onOtpChange(int index, String value) { + if (value.isNotEmpty && index < otpLength - 1) { + _focusNodes[index + 1].requestFocus(); + } else if (value.isEmpty && index > 0) { + _focusNodes[index - 1].requestFocus(); + } + setState(() { + otpValue = _controllers.map((c) => c.text).join(); + }); + } + + @override + Widget build(BuildContext context) { + final loginState = ref.watch(employeeloginProvider); + final isLoading = loginState.isLoading; + + // Initialize responsive utils + final r = ResponsiveUtils(context); + + // Responsive values + final logoWidth = r.getValue( + mobile: 120, + tablet: 141, + desktop: 160, + ); + final logoHeight = r.getValue( + mobile: 85, + tablet: 100, + desktop: 115, + ); + final titleFontSize = r.fontSize(mobile: 26, tablet: 32, desktop: 36); + final subtitleFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final mobileFontSize = r.fontSize(mobile: 12, tablet: 13, desktop: 14); + final resendFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final timerFontSize = r.fontSize(mobile: 14, tablet: 16, desktop: 18); + + final otpBoxWidth = r.getValue(mobile: 52, tablet: 60, desktop: 68); + final otpBoxHeight = r.getValue( + mobile: 48, + tablet: 56, + desktop: 64, + ); + final otpFontSize = r.fontSize(mobile: 22, tablet: 28, desktop: 32); + final otpBoxMargin = r.getValue(mobile: 5, tablet: 6, desktop: 8); + final otpBoxRadius = r.getValue(mobile: 5, tablet: 6, desktop: 8); + + final spacingXS = r.spacing(mobile: 10, tablet: 10, desktop: 12); + final spacingSM = r.spacing(mobile: 20, tablet: 20, desktop: 24); + final spacingMD = r.spacing(mobile: 22, tablet: 22, desktop: 26); + final spacingLG = r.spacing(mobile: 30, tablet: 30, desktop: 36); + + return Scaffold( + body: Stack( + children: [ + // Gradient background + Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + ), + + // Scrollable content + SingleChildScrollView( + child: SizedBox( + height: r.screenHeight, + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Logo + Image.asset( + AppAssets.taxgildelogoauth, + width: logoWidth, + height: logoHeight, + fit: BoxFit.contain, + ), + SizedBox(height: spacingSM), + + // Title + Text( + "Enter OTP", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: titleFontSize, + fontWeight: FontWeight.w600, + height: 1.3, + letterSpacing: 0.01 * titleFontSize, + color: AppColors.authheading, + ), + ), + SizedBox(height: spacingSM), + + // Subtitle + Text( + "OTP has been sent to your registered mobile number", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: subtitleFontSize, + fontWeight: FontWeight.w600, + height: 1.4, + letterSpacing: 0.03 * subtitleFontSize, + color: AppColors.authleading, + ), + ), + SizedBox(height: spacingMD), + + // Mobile + Change Number + Text.rich( + TextSpan( + text: mobile, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: mobileFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authleading, + ), + children: [ + TextSpan( + text: " ( Change Number )", + style: TextStyle( + fontFamily: 'Gilroy-ExtraBold', + fontWeight: FontWeight.w800, + fontSize: mobileFontSize, + height: 1.8, + letterSpacing: 0.04, + color: AppColors.authchange, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed( + ConstRouters.employeelogin, + arguments: {'mobile': mobile}, + ); + }, + ), + ], + ), + textAlign: TextAlign.center, + ), + SizedBox(height: spacingLG), + + // OTP Input Fields + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(otpLength, (index) { + bool isFilled = _controllers[index].text.isNotEmpty; + return Container( + margin: EdgeInsets.symmetric( + horizontal: otpBoxMargin, + ), + width: otpBoxWidth, + height: otpBoxHeight, + decoration: BoxDecoration( + color: isFilled + ? AppColors.commanbutton + : Colors.white, + borderRadius: BorderRadius.circular(otpBoxRadius), + border: Border.all( + color: const Color(0xFFDFDFDF), + ), + boxShadow: [ + BoxShadow( + color: const Color( + 0xFFBDBDBD, + ).withOpacity(0.25), + blurRadius: 7, + offset: const Offset(0, 1), + ), + ], + ), + child: Center( + child: TextField( + controller: _controllers[index], + focusNode: _focusNodes[index], + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + maxLength: 1, + enabled: !isLoading, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: otpFontSize, + letterSpacing: 0.03 * otpFontSize, + color: isFilled ? Colors.white : Colors.black, + ), + decoration: const InputDecoration( + counterText: '', + border: InputBorder.none, + ), + onChanged: (value) => + _onOtpChange(index, value), + ), + ), + ); + }), + ), + SizedBox(height: spacingXS), + + // Resend OTP + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: _canResend && !isLoading ? _resendOtp : null, + child: Text( + "Resend", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: resendFontSize, + height: 1.4, + letterSpacing: 0.02 * resendFontSize, + color: _canResend && !isLoading + ? AppColors.authchange + : Colors.grey, + ), + ), + ), + ), + SizedBox(height: spacingSM), + + // Timer + Text( + _formatTime(_remainingSeconds), + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w600, + fontSize: timerFontSize, + color: _remainingSeconds > 0 + ? AppColors.authheading + : Colors.red, + ), + ), + SizedBox(height: spacingLG), + + // Verify Button + isLoading + ? const CircularProgressIndicator() + : CommanButton(text: "Verify", onPressed: _verifyOtp), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/auth/login_screen.dart b/lib/auth/login_screen.dart new file mode 100644 index 0000000..ce980f6 --- /dev/null +++ b/lib/auth/login_screen.dart @@ -0,0 +1,343 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/comman_textformfileds.dart'; +import 'package:taxglide/consts/comman_popup.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final TextEditingController _mobileController = TextEditingController(); + final ValidationPopup _validationPopup = ValidationPopup(); + + @override + void initState() { + super.initState(); + final args = Get.arguments; + if (args != null && args is Map) { + final mobile = args['mobile'] ?? ''; + if (mobile.isNotEmpty) { + _mobileController.text = mobile; + } + } + } + + @override + void dispose() { + _mobileController.dispose(); + super.dispose(); + } + + Future _handleLogin() async { + final mobile = _mobileController.text.trim(); + + if (!_validationPopup.validateMobileNumber(context, mobile)) { + return; + } + + await ref.read(loginProvider.notifier).login(mobile); + final state = ref.read(loginProvider); + + state.when( + data: (data) { + if (data['success'] == true) { + Get.toNamed(ConstRouters.otp, arguments: {'mobile': mobile}); + _validationPopup.showSuccessMessage( + context, + "OTP sent successfully!", + ); + } else if (data['error'] != null) { + _validationPopup.showErrorMessage(context, data['error'].toString()); + } + }, + loading: () {}, + error: (err, _) { + _validationPopup.showErrorMessage(context, "Error: $err"); + }, + ); + } + + @override + Widget build(BuildContext context) { + final loginState = ref.watch(loginProvider); + final policyAsync = ref.watch(policyProvider); + final termsAsync = ref.watch(termsProvider); + + // Initialize responsive utils + final r = ResponsiveUtils(context); + + // Responsive values + final logoWidth = r.getValue( + mobile: 120, + tablet: 141, + desktop: 160, + ); + final logoHeight = r.getValue( + mobile: 85, + tablet: 100, + desktop: 115, + ); + final titleFontSize = r.fontSize(mobile: 26, tablet: 32, desktop: 36); + final subtitleFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final termsFontSize = r.fontSize(mobile: 10.5, tablet: 11.34, desktop: 12); + final signupFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final otherLoginFontSize = r.fontSize(mobile: 12, tablet: 13, desktop: 14); + + final spacingXS = r.spacing(mobile: 10, tablet: 15, desktop: 18); + final spacingSM = r.spacing(mobile: 15, tablet: 20, desktop: 24); + final spacingMD = r.spacing(mobile: 20, tablet: 22, desktop: 26); + final spacingLG = r.spacing(mobile: 20, tablet: 22, desktop: 28); + + return Scaffold( + resizeToAvoidBottomInset: true, + body: Container( + width: double.infinity, + height: double.infinity, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + child: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: r.screenHeight), + child: IntrinsicHeight( + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Logo + Image.asset( + AppAssets.taxgildelogoauth, + width: logoWidth, + height: logoHeight, + ), + SizedBox(height: spacingSM), + + // Title + Text( + "Login", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: titleFontSize, + fontWeight: FontWeight.w600, + color: AppColors.authheading, + ), + ), + SizedBox(height: spacingSM), + + // Subtitle + Text( + "Enter your Mobile Number", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: subtitleFontSize, + color: AppColors.authleading, + ), + ), + SizedBox(height: spacingLG), + + // Mobile TextField + CommanTextFormField( + controller: _mobileController, + hintText: 'Enter your Mobile Number', + keyboardType: TextInputType.phone, + prefixIcon: Icons.mobile_screen_share, + ), + SizedBox(height: spacingLG), + + // Terms and Policy + Text.rich( + TextSpan( + text: "By signing up, you agree to the ", + style: TextStyle( + fontSize: termsFontSize, + color: AppColors.authleading, + ), + children: [ + TextSpan( + text: "Terms of Service ", + style: TextStyle( + fontWeight: FontWeight.w700, + fontSize: termsFontSize, + color: AppColors.authtermsandcondition, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + termsAsync.when( + data: (terms) { + CommonInfoPopup.show( + context: context, + title: + terms.data?.title ?? + "Terms of Service", + content: + terms.data?.content ?? + "No terms found.", + ); + }, + loading: () { + _validationPopup.showErrorMessage( + context, + "Loading Terms...", + ); + }, + error: (err, _) { + _validationPopup.showErrorMessage( + context, + "Failed to load Terms", + ); + }, + ); + }, + ), + const TextSpan(text: "and "), + TextSpan( + text: "Data Processing Agreement", + style: TextStyle( + fontWeight: FontWeight.w700, + fontSize: termsFontSize, + color: AppColors.authtermsandcondition, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + policyAsync.when( + data: (policy) { + CommonInfoPopup.show( + context: context, + title: + policy.data?.title ?? + "Data Processing Agreement", + content: + policy.data?.content ?? + "No policy found.", + ); + }, + loading: () { + _validationPopup.showErrorMessage( + context, + "Loading Policy...", + ); + }, + error: (err, _) { + _validationPopup.showErrorMessage( + context, + "Failed to load Policy", + ); + }, + ); + }, + ), + ], + ), + textAlign: TextAlign.center, + ), + + SizedBox(height: spacingSM), + const Text("Or"), + SizedBox(height: spacingSM), + + // Sign up + Text.rich( + TextSpan( + text: "Didn't Have account? ", + style: TextStyle(fontSize: signupFontSize), + children: [ + TextSpan( + text: "Sign Up", + style: TextStyle( + fontSize: signupFontSize, + color: AppColors.authsignup, + fontWeight: FontWeight.bold, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed(ConstRouters.signup); + }, + ), + ], + ), + ), + SizedBox(height: spacingLG), + + // Login Button + loginState.isLoading + ? const CircularProgressIndicator() + : CommanButton( + text: "Login", + onPressed: _handleLogin, + ), + + SizedBox(height: spacingMD), + + Text( + "Other Login", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Inter', + fontWeight: FontWeight.w500, + fontSize: otherLoginFontSize, + height: 1.8, + letterSpacing: 0.13, + color: const Color(0xFF6C7278), + ), + ), + + SizedBox(height: spacingXS), + + Text.rich( + TextSpan( + text: "Staff Login? ", + style: TextStyle(fontSize: signupFontSize), + children: [ + TextSpan( + text: "Click Here", + style: TextStyle( + fontSize: signupFontSize, + color: AppColors.authsignup, + fontWeight: FontWeight.bold, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed(ConstRouters.employeelogin); + }, + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/auth/otp_screen.dart b/lib/auth/otp_screen.dart new file mode 100644 index 0000000..8ec0412 --- /dev/null +++ b/lib/auth/otp_screen.dart @@ -0,0 +1,422 @@ +import 'dart:async'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +import 'package:taxglide/view/Main_controller/main_controller.dart'; + +class OtpScreen extends ConsumerStatefulWidget { + const OtpScreen({super.key}); + + @override + ConsumerState createState() => _OtpScreenState(); +} + +class _OtpScreenState extends ConsumerState { + final ValidationPopup _validationPopup = ValidationPopup(); + final int otpLength = 4; + final List _controllers = []; + final List _focusNodes = []; + String otpValue = ''; + + Timer? _timer; + int _remainingSeconds = 600; + bool _canResend = false; + + late String mobile; + + @override + void initState() { + super.initState(); + final args = Get.arguments as Map; + mobile = args['mobile'] ?? ''; + + for (int i = 0; i < otpLength; i++) { + _controllers.add(TextEditingController()); + _focusNodes.add(FocusNode()); + } + _startTimer(); + } + + @override + void dispose() { + _timer?.cancel(); + for (var c in _controllers) c.dispose(); + for (var f in _focusNodes) f.dispose(); + super.dispose(); + } + + void _startTimer() { + _canResend = false; + _remainingSeconds = 30; + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (_remainingSeconds > 0) { + setState(() => _remainingSeconds--); + } else { + setState(() => _canResend = true); + timer.cancel(); + } + }); + } + + String _formatTime(int seconds) { + int minutes = seconds ~/ 60; + int remainingSeconds = seconds % 60; + return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}'; + } + + void _resendOtp() async { + if (!_canResend) return; + for (var controller in _controllers) controller.clear(); + setState(() => otpValue = ''); + _focusNodes[0].requestFocus(); + + try { + await ref.read(loginProvider.notifier).login(mobile); + final loginState = ref.read(loginProvider); + loginState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "OTP has been resent successfully!", + ); + _startTimer(); + for (var controller in _controllers) controller.clear(); + setState(() => otpValue = ''); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Failed to resend OTP", + ); + } + }, + loading: () {}, + error: (error, stack) { + _validationPopup.showErrorMessage( + context, + "Failed to resend OTP. Please try again.", + ); + }, + ); + } catch (e) { + _validationPopup.showErrorMessage( + context, + "An error occurred. Please try again.", + ); + } + } + + void _verifyOtp() async { + if (otpValue.length != otpLength) { + _validationPopup.showErrorMessage(context, "Please enter all OTP digits"); + return; + } + + await ref.read(loginProvider.notifier).verifyOtp(mobile, otpValue); + final loginState = ref.read(loginProvider); + + loginState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "OTP Verified Successfully!", + ); + Future.delayed(const Duration(seconds: 1), () { + Get.offAll(() => MainController()); + }); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Invalid OTP. Please try again.", + ); + } + }, + loading: () {}, + error: (error, stack) { + _validationPopup.showErrorMessage( + context, + "Failed to verify OTP. Please try again.", + ); + }, + ); + } + + void _onOtpChange(int index, String value) { + if (value.isNotEmpty && index < otpLength - 1) { + _focusNodes[index + 1].requestFocus(); + } + if (value.isEmpty && index > 0) { + _focusNodes[index - 1].requestFocus(); + } + setState(() { + otpValue = _controllers.map((c) => c.text).join(); + }); + } + + @override + Widget build(BuildContext context) { + final loginState = ref.watch(loginProvider); + final isLoading = loginState is AsyncLoading; + + // Initialize responsive utils + final r = ResponsiveUtils(context); + + // Responsive values + final logoWidth = r.getValue( + mobile: 120, + tablet: 141, + desktop: 160, + ); + final logoHeight = r.getValue( + mobile: 85, + tablet: 100, + desktop: 115, + ); + final titleFontSize = r.fontSize(mobile: 26, tablet: 32, desktop: 36); + final subtitleFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final mobileFontSize = r.fontSize(mobile: 12, tablet: 13, desktop: 14); + final resendFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final timerFontSize = r.fontSize(mobile: 14, tablet: 16, desktop: 18); + + final otpBoxWidth = r.getValue(mobile: 52, tablet: 60, desktop: 68); + final otpBoxHeight = r.getValue( + mobile: 48, + tablet: 56, + desktop: 64, + ); + final otpFontSize = r.fontSize(mobile: 22, tablet: 28, desktop: 32); + final otpBoxMargin = r.getValue(mobile: 5, tablet: 6, desktop: 8); + final otpBoxRadius = r.getValue(mobile: 5, tablet: 6, desktop: 8); + + final spacingXS = r.spacing(mobile: 10, tablet: 10, desktop: 12); + final spacingSM = r.spacing(mobile: 20, tablet: 20, desktop: 24); + final spacingMD = r.spacing(mobile: 22, tablet: 22, desktop: 26); + final spacingLG = r.spacing(mobile: 30, tablet: 30, desktop: 36); + + return Scaffold( + body: Stack( + children: [ + // Background gradient + Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + ), + + // Scrollable content + SingleChildScrollView( + child: SizedBox( + height: r.screenHeight, + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Logo + Image.asset( + AppAssets.taxgildelogoauth, + width: logoWidth, + height: logoHeight, + fit: BoxFit.contain, + ), + SizedBox(height: spacingSM), + + // Title + Text( + "Enter OTP", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: titleFontSize, + fontWeight: FontWeight.w600, + height: 1.3, + letterSpacing: 0.01 * titleFontSize, + color: AppColors.authheading, + ), + ), + SizedBox(height: spacingSM), + + // Subtitle + Text( + "OTP has been sent to your registered mobile number", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: subtitleFontSize, + fontWeight: FontWeight.w600, + height: 1.4, + letterSpacing: 0.03 * subtitleFontSize, + color: AppColors.authleading, + ), + ), + SizedBox(height: spacingMD), + + // Mobile number + Change + Text.rich( + TextSpan( + text: mobile, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: mobileFontSize, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authleading, + ), + children: [ + TextSpan( + text: " ( Change Number )", + style: TextStyle( + fontFamily: 'Gilroy-ExtraBold', + fontWeight: FontWeight.w800, + fontSize: mobileFontSize, + height: 1.8, + letterSpacing: 0.04, + color: AppColors.authchange, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed( + ConstRouters.login, + arguments: {'mobile': mobile}, + ); + }, + ), + ], + ), + textAlign: TextAlign.center, + ), + SizedBox(height: spacingLG), + + // OTP Boxes + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(otpLength, (index) { + bool isFilled = _controllers[index].text.isNotEmpty; + return Container( + margin: EdgeInsets.symmetric( + horizontal: otpBoxMargin, + ), + width: otpBoxWidth, + height: otpBoxHeight, + decoration: BoxDecoration( + color: isFilled + ? AppColors.commanbutton + : Colors.white, + borderRadius: BorderRadius.circular(otpBoxRadius), + border: Border.all( + color: const Color(0xFFDFDFDF), + ), + boxShadow: [ + BoxShadow( + color: const Color( + 0xFFBDBDBD, + ).withOpacity(0.25), + blurRadius: 7, + offset: const Offset(0, 1), + ), + ], + ), + child: Center( + child: TextField( + controller: _controllers[index], + focusNode: _focusNodes[index], + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + maxLength: 1, + enabled: !isLoading, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: otpFontSize, + letterSpacing: 0.03 * otpFontSize, + color: isFilled ? Colors.white : Colors.black, + ), + decoration: const InputDecoration( + counterText: '', + border: InputBorder.none, + ), + onChanged: (value) => + _onOtpChange(index, value), + ), + ), + ); + }), + ), + SizedBox(height: spacingXS), + + // Resend + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: _canResend && !isLoading ? _resendOtp : null, + child: Text( + "Resend", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: resendFontSize, + height: 1.4, + letterSpacing: 0.02 * resendFontSize, + color: _canResend && !isLoading + ? AppColors.authchange + : Colors.grey, + ), + ), + ), + ), + SizedBox(height: spacingSM), + + // Timer + Text( + _formatTime(_remainingSeconds), + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w600, + fontSize: timerFontSize, + color: _remainingSeconds > 0 + ? AppColors.authheading + : Colors.red, + ), + ), + SizedBox(height: spacingLG), + + // Verify Button + isLoading + ? const CircularProgressIndicator() + : CommanButton(text: "Verify", onPressed: _verifyOtp), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/auth/register_otp_screen.dart b/lib/auth/register_otp_screen.dart new file mode 100644 index 0000000..91fb48c --- /dev/null +++ b/lib/auth/register_otp_screen.dart @@ -0,0 +1,419 @@ +import 'dart:async'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; + +class RegisterOtpScreen extends ConsumerStatefulWidget { + const RegisterOtpScreen({super.key}); + + @override + ConsumerState createState() => _RegisterOtpScreenState(); +} + +class _RegisterOtpScreenState extends ConsumerState { + final ValidationPopup _validationPopup = ValidationPopup(); + final int otpLength = 4; + final List _controllers = []; + final List _focusNodes = []; + String otpValue = ''; + + // Timer variables + Timer? _timer; + int _remainingSeconds = 600; // 10 minutes = 600 seconds + bool _canResend = false; + + // Get arguments passed from signup + late String name; + late String email; + late String mobile; + + @override + void initState() { + super.initState(); + + // Get arguments from navigation + final args = Get.arguments as Map; + name = args['name'] ?? ''; + email = args['email'] ?? ''; + mobile = args['mobile'] ?? ''; + + for (int i = 0; i < otpLength; i++) { + _controllers.add(TextEditingController()); + _focusNodes.add(FocusNode()); + } + _startTimer(); + } + + @override + void dispose() { + _timer?.cancel(); + for (var c in _controllers) { + c.dispose(); + } + for (var f in _focusNodes) { + f.dispose(); + } + super.dispose(); + } + + void _startTimer() { + _canResend = false; + _remainingSeconds = 30; // Reset to 30 seconds + + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (_remainingSeconds > 0) { + setState(() { + _remainingSeconds--; + }); + } else { + setState(() { + _canResend = true; + }); + timer.cancel(); + } + }); + } + + String _formatTime(int seconds) { + int minutes = seconds ~/ 60; + int remainingSeconds = seconds % 60; + return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}'; + } + + void _resendOtp() async { + if (!_canResend) return; + for (var controller in _controllers) { + controller.clear(); + } + setState(() { + otpValue = ''; + }); + + // Move focus to first field + _focusNodes[0].requestFocus(); + try { + // Call signup API again to resend OTP + await ref.read(signupProvider.notifier).signup(name, mobile, email); + + final signupState = ref.read(signupProvider); + + signupState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "OTP has been resent successfully!", + ); + _startTimer(); + // Clear OTP fields + for (var controller in _controllers) { + controller.clear(); + } + setState(() { + otpValue = ''; + }); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Failed to resend OTP", + ); + } + }, + loading: () { + // Show loading indicator + }, + error: (error, stack) { + _validationPopup.showErrorMessage( + context, + "Failed to resend OTP. Please try again.", + ); + }, + ); + } catch (e) { + _validationPopup.showErrorMessage( + context, + "An error occurred. Please try again.", + ); + } + } + + void _verifyOtp() async { + if (otpValue.length != otpLength) { + _validationPopup.showErrorMessage(context, "Please enter all OTP digits"); + return; + } + + // Call verify OTP API for signup + await ref.read(signupProvider.notifier).verifySignupOtp(mobile, otpValue); + + final signupState = ref.read(signupProvider); + + signupState.when( + data: (result) { + if (result['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "Registration Successful!", + ); + + // Navigate to main screen after successful verification + Future.delayed(const Duration(seconds: 1), () { + Get.offAll(() => MainController()); + }); + } else { + _validationPopup.showErrorMessage( + context, + result['error'] ?? "Invalid OTP. Please try again.", + ); + } + }, + loading: () { + // Loading is handled by the provider + }, + error: (error, stack) { + _validationPopup.showErrorMessage( + context, + "Failed to verify OTP. Please try again.", + ); + }, + ); + } + + void _onOtpChange(int index, String value) { + if (value.isNotEmpty && index < otpLength - 1) { + _focusNodes[index + 1].requestFocus(); + } + if (value.isEmpty && index > 0) { + _focusNodes[index - 1].requestFocus(); + } + + setState(() { + otpValue = _controllers.map((c) => c.text).join(); + }); + } + + @override + Widget build(BuildContext context) { + final signupState = ref.watch(signupProvider); + final isLoading = signupState is AsyncLoading; + + return Scaffold( + body: Stack( + children: [ + // Background gradient + Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + ), + + // Scrollable content + SingleChildScrollView( + child: SizedBox( + height: MediaQuery.of(context).size.height, + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.asset( + AppAssets.taxgildelogoauth, + width: 141, + height: 100, + fit: BoxFit.contain, + ), + const SizedBox(height: 20), + Text( + "Enter OTP", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: 32, + fontWeight: FontWeight.w600, + height: 1.3, + letterSpacing: 0.01 * 32, + color: AppColors.authheading, + ), + ), + const SizedBox(height: 20), + Text( + "OTP has been sent to your registered mobile number", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: 14, + fontWeight: FontWeight.w600, + height: 1.4, + letterSpacing: 0.03 * 14, + color: AppColors.authleading, + ), + ), + const SizedBox(height: 22), + Text.rich( + TextSpan( + text: mobile, + style: const TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: 13, + height: 1.8, + letterSpacing: 0.01, + color: AppColors.authleading, + ), + children: [ + TextSpan( + text: " ( Change Number )", + style: const TextStyle( + fontFamily: 'Gilroy-ExtraBold', + fontWeight: FontWeight.w800, + fontSize: 13, + height: 1.8, + letterSpacing: 0.04, + color: AppColors.authchange, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + Get.offNamed( + ConstRouters.signup, + arguments: { + 'name': name, + 'email': email, + 'mobile': mobile, + }, + ); + }, + ), + ], + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 30), + + // OTP Boxes + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(otpLength, (index) { + bool isFilled = _controllers[index].text.isNotEmpty; + return Container( + margin: const EdgeInsets.symmetric(horizontal: 6), + width: 60, + height: 56, + decoration: BoxDecoration( + color: isFilled + ? AppColors.commanbutton + : Colors.white, + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: const Color(0xFFDFDFDF), + ), + boxShadow: [ + BoxShadow( + color: const Color( + 0xFFBDBDBD, + ).withOpacity(0.25), + blurRadius: 7, + offset: const Offset(0, 1), + ), + ], + ), + child: Center( + child: TextField( + controller: _controllers[index], + focusNode: _focusNodes[index], + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + maxLength: 1, + enabled: !isLoading, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: 28, + letterSpacing: 0.03 * 28, + color: isFilled ? Colors.white : Colors.black, + ), + decoration: const InputDecoration( + counterText: '', + border: InputBorder.none, + ), + onChanged: (value) => + _onOtpChange(index, value), + ), + ), + ); + }), + ), + const SizedBox(height: 10), + + // Resend OTP Button + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: _canResend && !isLoading ? _resendOtp : null, + child: Text( + "Resend", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: 14, + height: 1.4, + letterSpacing: 0.02 * 14, + color: _canResend && !isLoading + ? AppColors.authchange + : Colors.grey, + ), + ), + ), + ), + const SizedBox(height: 20), + + // Timer Display + Text( + _formatTime(_remainingSeconds), + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w600, + fontSize: 16, + color: _remainingSeconds > 0 + ? AppColors.authheading + : Colors.red, + ), + ), + const SizedBox(height: 30), + + // Verify Button + isLoading + ? const CircularProgressIndicator() + : CommanButton(text: "Verify", onPressed: _verifyOtp), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/auth/signup_screen.dart b/lib/auth/signup_screen.dart new file mode 100644 index 0000000..ec2b5b8 --- /dev/null +++ b/lib/auth/signup_screen.dart @@ -0,0 +1,329 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/comman_container_auth.dart'; +import 'package:taxglide/consts/comman_textformfileds.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class SignupScreen extends ConsumerStatefulWidget { + const SignupScreen({super.key}); + + @override + ConsumerState createState() => _SignupScreenState(); +} + +class _SignupScreenState extends ConsumerState { + final ValidationPopup _validationPopup = ValidationPopup(); + + final TextEditingController _nameController = TextEditingController(); + final TextEditingController _mobileController = TextEditingController(); + final TextEditingController _emailController = TextEditingController(); + @override + void initState() { + super.initState(); + + // Get arguments from navigation if available + final args = Get.arguments; + if (args != null && args is Map) { + _nameController.text = args['name'] ?? ''; + _emailController.text = args['email'] ?? ''; + _mobileController.text = args['mobile'] ?? ''; + } + } + + // Error state tracking + bool _nameError = false; + bool _mobileError = false; + bool _emailError = false; + + @override + Widget build(BuildContext context) { + // Listen to signup state + final signupState = ref.watch(signupProvider); + + // Handle API response + ref.listen>>(signupProvider, ( + previous, + next, + ) { + next.when( + data: (response) { + if (response.isNotEmpty) { + if (response['success'] == true) { + _validationPopup.showSuccessMessage( + context, + "Sign up successful! OTP sent to your mobile.", + ); + + // Navigate to RegisterOtpScreen with all data + Future.delayed(const Duration(milliseconds: 500), () { + Get.toNamed( + ConstRouters.registerOtp, + arguments: { + 'name': _nameController.text, + 'email': _emailController.text, + 'mobile': _mobileController.text, + }, + ); + }); + } else { + _validationPopup.showErrorMessage( + context, + response['error'] ?? 'Signup failed', + ); + } + } + }, + error: (error, stackTrace) { + _validationPopup.showErrorMessage( + context, + 'An error occurred: ${error.toString()}', + ); + }, + loading: () {}, + ); + }); + + return Scaffold( + body: Stack( + children: [ + // 🌈 Background gradient + Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF8F0), + Color(0xFFEBC894), + Color(0xFFE8DAF2), + Color(0xFFB49EF4), + ], + stops: [0.0, 0.3, 0.6, 1.0], + ), + ), + ), + + // 📜 Scrollable content + SingleChildScrollView( + child: SizedBox( + height: MediaQuery.of(context).size.height, + child: Center( + child: CommonContainerAuth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.asset( + AppAssets.taxgildelogoauth, + width: 141, + height: 100, + fit: BoxFit.contain, + ), + const SizedBox(height: 20), + + // 🟣 Title + Text( + "Sign Up", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: 32, + fontWeight: FontWeight.w600, + height: 1.3, + letterSpacing: 0.01 * 32, + color: AppColors.authheading, + ), + ), + + const SizedBox(height: 25), + + // 👤 Name Field + Align( + alignment: Alignment.centerLeft, + child: Text( + "Name*", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 14, + color: AppColors.authleading, + ), + ), + ), + const SizedBox(height: 8), + + CommanTextFormField( + hintText: 'Enter Company Name', + controller: _nameController, + hasError: _nameError, + onChanged: (value) { + if (_nameError && value.isNotEmpty) { + setState(() { + _nameError = false; + }); + } + }, + ), + + const SizedBox(height: 10), + + // 📱 Mobile Number Field + Align( + alignment: Alignment.centerLeft, + child: Text( + "Contact Number *", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 14, + color: AppColors.authleading, + ), + ), + ), + const SizedBox(height: 8), + + CommanTextFormField( + hintText: 'Enter Contact Number', + controller: _mobileController, + hasError: _mobileError, + keyboardType: TextInputType.phone, + onChanged: (value) { + if (_mobileError && value.isNotEmpty) { + setState(() { + _mobileError = false; + }); + } + }, + ), + const SizedBox(height: 10), + + // 📧 Email Field + Align( + alignment: Alignment.centerLeft, + child: Text( + "Email *", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 14, + color: AppColors.authleading, + ), + ), + ), + const SizedBox(height: 8), + + CommanTextFormField( + hintText: 'Enter Email ID', + controller: _emailController, + hasError: _emailError, + keyboardType: TextInputType.emailAddress, + onChanged: (value) { + if (_emailError && value.isNotEmpty) { + setState(() { + _emailError = false; + }); + } + }, + ), + const SizedBox(height: 30), + + // ✅ Submit Button + signupState.isLoading + ? const CircularProgressIndicator() + : CommanButton( + text: "Submit", + onPressed: () { + _handleSignup(); + }, + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } + + void _handleSignup() { + // Reset all errors first + setState(() { + _nameError = false; + _mobileError = false; + _emailError = false; + }); + + bool hasError = false; + + // Validate name + if (_nameController.text.isEmpty) { + setState(() { + _nameError = true; + }); + hasError = true; + } + + // Validate mobile + if (_mobileController.text.isEmpty) { + setState(() { + _mobileError = true; + }); + hasError = true; + } else if (!_validationPopup.validateMobileNumber( + context, + _mobileController.text, + )) { + setState(() { + _mobileError = true; + }); + hasError = true; + } + + // Validate email - NOW WITH FORMAT CHECK + if (_emailController.text.isEmpty) { + setState(() { + _emailError = true; + }); + hasError = true; + } else if (!_validationPopup.validateEmail( + context, + _emailController.text, + )) { + setState(() { + _emailError = true; + }); + hasError = true; + } + + // Show error message if any field has error + if (hasError) { + _validationPopup.showErrorMessage( + context, + "Please fill all required fields correctly", + ); + return; + } + + // All validations passed - call API + ref + .read(signupProvider.notifier) + .signup( + _nameController.text, + _mobileController.text, + _emailController.text, + ); + } + + @override + void dispose() { + _nameController.dispose(); + _mobileController.dispose(); + _emailController.dispose(); + super.dispose(); + } +} diff --git a/lib/consts/app_asstes.dart b/lib/consts/app_asstes.dart new file mode 100644 index 0000000..924c214 --- /dev/null +++ b/lib/consts/app_asstes.dart @@ -0,0 +1,12 @@ +class AppAssets { + static const String taxgildelogo = 'assets/images/taxglidelogo.png'; + static const String taxgildelogoauth = 'assets/images/taxglidelogoauth.png'; + static const String homepageheader = 'assets/images/haeder_image.jpg'; + static const String profilebanner = 'assets/images/profilebanner.jpg'; + static const String backgroundimages = 'assets/images/backgroundimages.png'; + static const String back = "assets/images/homepagebackground.jpg"; + static const String image = "assets/images/home.png"; + static const String generalchatimage = "assets/images/generalchatimage.png"; + static const String maincontroller = "assets/images/taxglidewhitelogo.png"; + static const String generalchatsvg = "assets/images/backgroudimagesvg.svg"; +} diff --git a/lib/consts/app_colors.dart b/lib/consts/app_colors.dart new file mode 100644 index 0000000..837f61d --- /dev/null +++ b/lib/consts/app_colors.dart @@ -0,0 +1,17 @@ +import 'dart:ui'; + +class AppColors { + static const Color backgroundgrainetflashtop = Color(0xFFEBC894); + static const Color backgroundgrainetflashbottom = Color(0xFFB49EF4); + static const Color authheading = Color(0xFF111827); + static const Color authleading = Color(0xFF6C7278); + static const Color authtermsandcondition = Color(0xFFC9861D); + static const Color authsignup = Color(0xFF4DA526); + static const Color authchange = Color(0xFFFF0004); + static const Color commanbutton = Color(0xFF5F297B); + static const Color homepagekycdetails = Color(0xFF239F5B); + static const Color homepagekycdetailsorange = Color(0xFFF68945); + static const Color homepageserivcetext = Color(0xFF3F3F3F); + static const Color black = Color(0xFF000000); + static const Color white = Color(0xFFFFFFFF); +} diff --git a/lib/consts/comman_button.dart b/lib/consts/comman_button.dart new file mode 100644 index 0000000..da96dd8 --- /dev/null +++ b/lib/consts/comman_button.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; +import 'package:taxglide/consts/app_colors.dart'; + +class CommanButton extends StatelessWidget { + final String text; + final VoidCallback onPressed; + final String? backgroundImage; // optional bg image + final Widget? prefixIcon; // optional prefix icon + + const CommanButton({ + super.key, + required this.text, + required this.onPressed, + this.backgroundImage, + this.prefixIcon, + }); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + height: 57, + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(8), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + color: AppColors.commanbutton, // base color (visible always) + + image: backgroundImage != null + ? DecorationImage( + image: AssetImage(backgroundImage!), + fit: BoxFit.cover, + + // 🔥 THIS MAKES BOTH IMAGE + COLOR VISIBLE + colorFilter: ColorFilter.mode( + AppColors.commanbutton.withOpacity(0.5), + BlendMode.srcATop, + ), + ) + : null, + ), + child: Center( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (prefixIcon != null) ...[ + prefixIcon!, + const SizedBox(width: 8), + ], + Text( + text, + style: const TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: 16, + height: 1.4, + letterSpacing: 0.03 * 16, + color: Colors.white, + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/consts/comman_container_auth.dart b/lib/consts/comman_container_auth.dart new file mode 100644 index 0000000..af96c23 --- /dev/null +++ b/lib/consts/comman_container_auth.dart @@ -0,0 +1,31 @@ +// ignore_for_file: use_super_parameters + +import 'package:flutter/material.dart'; + +class CommonContainerAuth extends StatelessWidget { + final Widget child; + + const CommonContainerAuth({Key? key, required this.child}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + margin: const EdgeInsets.only(left: 16, right: 16), + padding: const EdgeInsets.only(top: 31, right: 18, bottom: 31, left: 18), + decoration: BoxDecoration( + color: const Color(0x99FFFFFF), // #FFFFFF with 60% opacity (99 in hex) + border: Border.all(color: Colors.white, width: 2), + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: child, + ); + } +} diff --git a/lib/consts/comman_dropdown.dart b/lib/consts/comman_dropdown.dart new file mode 100644 index 0000000..87c1935 --- /dev/null +++ b/lib/consts/comman_dropdown.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; +import 'package:dropdown_button2/dropdown_button2.dart'; +import 'package:dropdown_textfield/dropdown_textfield.dart'; + +class CommanDropdown extends StatefulWidget { + final List items; + final String? value; + final Function(String?) onChanged; + final String hint; + final bool useTextFieldType; + + const CommanDropdown({ + Key? key, + required this.items, + this.value, + required this.onChanged, + this.hint = 'Select an option', + this.useTextFieldType = false, + }) : super(key: key); + + @override + State createState() => _CommanDropdownState(); +} + +class _CommanDropdownState extends State { + @override + Widget build(BuildContext context) { + if (widget.useTextFieldType) { + return Container( + width: double.infinity, + height: 56, + decoration: _boxDecoration(), + child: DropDownTextField( + textFieldDecoration: const InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 16), + ), + clearOption: false, + dropDownList: widget.items + .map((e) => DropDownValueModel(name: e, value: e)) + .toList(), + dropDownItemCount: widget.items.length > 6 ? 6 : widget.items.length, + // dropdownHeight: 200, // Limit the dropdown height + isEnabled: true, + onChanged: (value) { + widget.onChanged(value?.value); + }, + ), + ); + } else { + return Container( + width: double.infinity, + height: 56, + decoration: _boxDecoration(), + padding: const EdgeInsets.symmetric(horizontal: 0), + child: DropdownButtonHideUnderline( + child: DropdownButton2( + value: widget.value, + isExpanded: true, + hint: Text(widget.hint, style: const TextStyle(color: Colors.grey)), + items: widget.items + .map( + (item) => DropdownMenuItem( + value: item, + child: Text(item, style: const TextStyle(fontSize: 14)), + ), + ) + .toList(), + onChanged: widget.onChanged, + buttonStyleData: const ButtonStyleData(height: 56), + iconStyleData: const IconStyleData( + icon: Icon(Icons.arrow_drop_down), + ), + dropdownStyleData: DropdownStyleData( + maxHeight: 300, // Limit dropdown menu height + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6)), + ), + menuItemStyleData: const MenuItemStyleData( + height: 48, // Set individual item height + ), + ), + ), + ); + } + } + + BoxDecoration _boxDecoration() { + return BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFFDFDFDF), width: 1), + boxShadow: [ + BoxShadow( + color: const Color(0x40BDBDBD), + blurRadius: 7, + offset: const Offset(0, 1), + ), + ], + ); + } +} diff --git a/lib/consts/comman_image_box.dart b/lib/consts/comman_image_box.dart new file mode 100644 index 0000000..fbe3343 --- /dev/null +++ b/lib/consts/comman_image_box.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; + +class CommanImageBox extends StatelessWidget { + final VoidCallback onTap; + final String text; + final IconData icon; + + const CommanImageBox({ + super.key, + required this.onTap, + this.text = 'Upload Image', + this.icon = Icons.cloud_upload_outlined, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: Container( + width: double.infinity, + height: 117, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFCFCFCF), width: 1), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + offset: const Offset(0, 1), + blurRadius: 7, + ), + ], + ), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 32, color: const Color(0xFF5F297B)), + const SizedBox(height: 8), + Text( + text, + style: const TextStyle( + fontSize: 14, + color: Color(0xFF5F297B), + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/consts/comman_popup.dart b/lib/consts/comman_popup.dart new file mode 100644 index 0000000..5d867fe --- /dev/null +++ b/lib/consts/comman_popup.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; + +class CommonInfoPopup { + /// 🔹 Show a reusable popup dialog + static void show({ + required BuildContext context, + required String title, + required String content, + }) { + final ScrollController scrollController = ScrollController(); + + showDialog( + context: context, + barrierDismissible: true, + builder: (BuildContext ctx) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(18), + ), + backgroundColor: Colors.white, + titlePadding: const EdgeInsets.fromLTRB(20, 20, 20, 10), + contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 10), + title: Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-Bold', + fontSize: 18, + fontWeight: FontWeight.w700, + color: Colors.black87, + ), + ), + content: ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 300), + child: ScrollbarTheme( + data: ScrollbarThemeData( + thumbColor: WidgetStateProperty.all( + const Color(0xFF6A4BFC), + ), // 💜 Custom scrollbar color + trackColor: WidgetStateProperty.all(Colors.transparent), + radius: const Radius.circular(8), + thickness: WidgetStateProperty.all(4), + ), + child: Scrollbar( + controller: scrollController, + thumbVisibility: true, + child: SingleChildScrollView( + controller: scrollController, + child: Text( + content, + textAlign: TextAlign.justify, + style: const TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 14, + height: 1.6, + color: Colors.black54, + ), + ), + ), + ), + ), + ), + actionsPadding: const EdgeInsets.only(right: 10, bottom: 8), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), + child: const Text( + "Close", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: 14, + color: Color(0xFF6A4BFC), + ), + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/consts/comman_serivce.dart b/lib/consts/comman_serivce.dart new file mode 100644 index 0000000..ec976f4 --- /dev/null +++ b/lib/consts/comman_serivce.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/model/serivce_list_model.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import 'package:taxglide/view/screens/serivce_request_screen.dart'; + +class CommonServiceItem extends StatelessWidget { + final ServiceListModel service; + final int sourceTabIndex; // ✅ New param to know from where user clicked + + const CommonServiceItem({ + super.key, + required this.service, + required this.sourceTabIndex, + }); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + GestureDetector( + onTap: () { + Get.offAll( + () => MainController( + child: ServiceRequestScreen( + id: service.id, + service: service.service, + icon: service.icon, + ), + initialIndex: sourceTabIndex, // 0 for Home, 1 for Services + sourceTabIndex: + sourceTabIndex, // to remember where it came from + ), + ); + }, + child: Container( + width: 110, + height: 84, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFE1E1E1), width: 1), + boxShadow: const [ + BoxShadow( + color: Color(0x66757575), + offset: Offset(0, 1), + blurRadius: 7.3, + ), + ], + ), + padding: const EdgeInsets.all(8), + child: Center( + child: Image.network( + service.icon, + width: 42, + height: 42, + fit: BoxFit.contain, + ), + ), + ), + ), + const SizedBox(height: 16), + Text( + service.service, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 13, + height: 1.3, + letterSpacing: 0.02, + color: AppColors.homepageserivcetext, + ), + ), + ], + ); + } +} diff --git a/lib/consts/comman_textformfileds.dart b/lib/consts/comman_textformfileds.dart new file mode 100644 index 0000000..03a14b4 --- /dev/null +++ b/lib/consts/comman_textformfileds.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:flutter/services.dart'; + +class CommanTextFormField extends StatelessWidget { + final String? hintText; + final TextEditingController? controller; + final TextInputType? keyboardType; + final bool obscureText; + final bool readOnly; + final String? Function(String?)? validator; + final IconData? prefixIcon; + final bool hasError; + final Function(String)? onChanged; + final FocusNode? focusNode; + final VoidCallback? onTap; + + /// ✅ NEW + final List? inputFormatters; + final TextCapitalization textCapitalization; + + const CommanTextFormField({ + Key? key, + this.hintText, + this.controller, + this.keyboardType, + this.obscureText = false, + this.readOnly = false, + this.validator, + this.prefixIcon, + this.hasError = false, + this.onChanged, + this.focusNode, + this.onTap, + + /// ✅ DEFAULTS + this.inputFormatters, + this.textCapitalization = TextCapitalization.none, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + height: 56, + child: TextFormField( + focusNode: focusNode, + controller: controller, + keyboardType: keyboardType, + obscureText: obscureText, + validator: validator, + onChanged: onChanged, + onTap: onTap, + readOnly: readOnly, + + /// ✅ APPLIED HERE + inputFormatters: inputFormatters, + textCapitalization: textCapitalization, + + cursorColor: readOnly ? Colors.transparent : AppColors.authleading, + decoration: InputDecoration( + hintText: hintText, + filled: true, + fillColor: readOnly ? const Color(0xFFF6F6F6) : Colors.white, + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 16, + ), + prefixIcon: prefixIcon != null + ? Icon(prefixIcon, color: AppColors.authleading) + : null, + hintStyle: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: 11.31, + height: 1.4, + letterSpacing: 0.03, + color: hasError + ? Colors.red.withOpacity(0.6) + : Colors.grey.shade500, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide( + color: hasError + ? Colors.red + : readOnly + ? Colors.grey.shade300 + : const Color(0xFFDFDFDF), + width: 1, + ), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide( + color: hasError + ? Colors.red + : readOnly + ? Colors.grey.shade300 + : const Color(0xFFDFDFDF), + width: 1, + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide( + color: hasError + ? Colors.red + : readOnly + ? Colors.grey.shade400 + : Colors.blue, + width: 1, + ), + ), + ), + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: 11.31, + height: 1.4, + letterSpacing: 0.03, + color: readOnly ? Colors.grey.shade600 : AppColors.authleading, + ), + ), + ); + } +} diff --git a/lib/consts/comman_webscoket.dart b/lib/consts/comman_webscoket.dart new file mode 100644 index 0000000..23642f0 --- /dev/null +++ b/lib/consts/comman_webscoket.dart @@ -0,0 +1,240 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// Common WebSocket for user-based communication (not chatId-based) +class CommonWebSocketService { + static final CommonWebSocketService _instance = + CommonWebSocketService._internal(); + factory CommonWebSocketService() => _instance; + CommonWebSocketService._internal(); + + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Timer? _pingTimer; + Timer? _reconnectTimer; + + bool _isConnected = false; + bool _isIntentionalClose = false; + int _reconnectAttempts = 0; + + static const int _maxReconnectAttempts = 5; + static const Duration _reconnectDelay = Duration(seconds: 3); + + // Callbacks + Function(Map)? onMessageReceived; + Function()? onConnected; + Function()? onDisconnected; + Function(dynamic error)? onError; + + String? _userId; + String? _wsUrl; + + /// Check connection status + bool get isConnected => _isConnected; + + /// Current user ID + String? get currentUserId => _userId; + + /// Connect WS using LOCAL USER ID + Future connect({ + required String userId, + String baseUrl = "wss://taxglide.amrithaa.net:443/reverb", + String appKey = "2yj0lyzc9ylw2h03ts6i", + }) async { + try { + await disconnect(); + + _userId = userId; + _wsUrl = "$baseUrl/app/$appKey?protocol=7&client=js&version=1.0"; + _isIntentionalClose = false; + _reconnectAttempts = 0; + + await _establishConnection(); + } catch (e) { + debugPrint("❌ Connection error: $e"); + onError?.call(e); + _scheduleReconnect(); + } + } + + Future _establishConnection() async { + try { + debugPrint("🔌 Connecting to: $_wsUrl"); + + _channel = WebSocketChannel.connect(Uri.parse(_wsUrl!)); + + _subscription = _channel!.stream.listen( + _handleMessage, + onError: _handleError, + onDone: _handleDisconnection, + cancelOnError: false, + ); + + await Future.delayed(const Duration(milliseconds: 500)); + + _isConnected = true; + _reconnectAttempts = 0; + debugPrint("✅ WebSocket connected"); + + _subscribeToUserChannel(); + _startPingTimer(); + onConnected?.call(); + } catch (e) { + debugPrint("❌ Failed to establish connection: $e"); + _isConnected = false; + rethrow; + } + } + + /// Handle incoming messages + void _handleMessage(dynamic data) { + try { + debugPrint("📨 Received: $data"); + final Map message = json.decode(data); + + if (message['event'] == 'pusher:ping') { + _sendPong(); + return; + } + + if (message['event'] == 'pusher:connection_established') { + debugPrint("🔗 Pusher connection established"); + return; + } + + if (message['event'] == 'pusher_internal:subscription_succeeded') { + debugPrint("✅ User channel subscribed"); + return; + } + + if (message['event'] != null && + !message['event'].toString().startsWith('pusher')) { + onMessageReceived?.call(message); + } + } catch (e) { + debugPrint("❌ Error parsing message: $e"); + onError?.call(e); + } + } + + void _handleError(dynamic error) { + debugPrint("❌ WebSocket error: $error"); + _isConnected = false; + onError?.call(error); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + void _handleDisconnection() { + debugPrint("🔌 Disconnected"); + _isConnected = false; + _stopPingTimer(); + onDisconnected?.call(); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + /// Subscribe to USER CHANNEL + void _subscribeToUserChannel() { + if (_userId == null) return; + + final subscribeMessage = { + 'event': 'pusher:subscribe', + 'data': {'channel': 'user-chat-notification.$_userId'}, + }; + + _sendMessage(subscribeMessage); + debugPrint("📡 Subscribing to user.$_userId"); + } + + void _sendPong() { + final pong = {'event': 'pusher:pong', 'data': {}}; + _sendMessage(pong); + } + + void _startPingTimer() { + _pingTimer?.cancel(); + _pingTimer = Timer.periodic(const Duration(seconds: 30), (timer) { + if (_isConnected) debugPrint("💓 WS heartbeat"); + }); + } + + void _stopPingTimer() { + _pingTimer?.cancel(); + _pingTimer = null; + } + + void _scheduleReconnect() { + if (_isIntentionalClose) return; + if (_reconnectAttempts >= _maxReconnectAttempts) { + onError?.call( + "Failed to reconnect after $_maxReconnectAttempts attempts", + ); + return; + } + + _reconnectTimer?.cancel(); + _reconnectAttempts++; + + debugPrint( + "🔄 Retry $_reconnectAttempts in ${_reconnectDelay.inSeconds}s...", + ); + + _reconnectTimer = Timer(_reconnectDelay, () async { + if (!_isIntentionalClose && _wsUrl != null && _userId != null) { + await _establishConnection(); + } + }); + } + + /// Send message + void _sendMessage(Map message) { + if (!_isConnected || _channel == null) { + debugPrint("⚠️ Cannot send: Not connected"); + return; + } + + try { + final jsonMsg = json.encode(message); + _channel!.sink.add(jsonMsg); + debugPrint("📤 Sent: $jsonMsg"); + } catch (e) { + debugPrint("❌ Send error: $e"); + } + } + + /// Send event to backend + void sendEvent({ + required String eventName, + required Map data, + }) { + final msg = { + 'event': eventName, + 'data': data, + 'channel': 'user-chat-notification.$_userId', + }; + _sendMessage(msg); + } + + Future disconnect() async { + _isIntentionalClose = true; + _reconnectTimer?.cancel(); + _stopPingTimer(); + + await _subscription?.cancel(); + await _channel?.sink.close(); + + _channel = null; + _subscription = null; + _isConnected = false; + _userId = null; + + debugPrint("🔌 WS disconnected intentionally"); + } +} diff --git a/lib/consts/details_webscokect.dart b/lib/consts/details_webscokect.dart new file mode 100644 index 0000000..4d13843 --- /dev/null +++ b/lib/consts/details_webscokect.dart @@ -0,0 +1,240 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// Common WebSocket for user-based communication (not chatId-based) +class DetailsWebscokect { + static final DetailsWebscokect _instance = + DetailsWebscokect._internal(); + factory DetailsWebscokect() => _instance; + DetailsWebscokect._internal(); + + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Timer? _pingTimer; + Timer? _reconnectTimer; + + bool _isConnected = false; + bool _isIntentionalClose = false; + int _reconnectAttempts = 0; + + static const int _maxReconnectAttempts = 5; + static const Duration _reconnectDelay = Duration(seconds: 3); + + // Callbacks + Function(Map)? onMessageReceived; + Function()? onConnected; + Function()? onDisconnected; + Function(dynamic error)? onError; + + String? _userId; + String? _wsUrl; + + /// Check connection status + bool get isConnected => _isConnected; + + /// Current user ID + String? get currentUserId => _userId; + + /// Connect WS using LOCAL USER ID + Future connect({ + required String userId, + String baseUrl = "wss://taxglide.amrithaa.net:443/reverb", + String appKey = "2yj0lyzc9ylw2h03ts6i", + }) async { + try { + await disconnect(); + + _userId = userId; + _wsUrl = "$baseUrl/app/$appKey?protocol=7&client=js&version=1.0"; + _isIntentionalClose = false; + _reconnectAttempts = 0; + + await _establishConnection(); + } catch (e) { + debugPrint("❌ Connection error: $e"); + onError?.call(e); + _scheduleReconnect(); + } + } + + Future _establishConnection() async { + try { + debugPrint("🔌 Connecting to: $_wsUrl"); + + _channel = WebSocketChannel.connect(Uri.parse(_wsUrl!)); + + _subscription = _channel!.stream.listen( + _handleMessage, + onError: _handleError, + onDone: _handleDisconnection, + cancelOnError: false, + ); + + await Future.delayed(const Duration(milliseconds: 500)); + + _isConnected = true; + _reconnectAttempts = 0; + debugPrint("✅ WebSocket connected"); + + _subscribeToUserChannel(); + _startPingTimer(); + onConnected?.call(); + } catch (e) { + debugPrint("❌ Failed to establish connection: $e"); + _isConnected = false; + rethrow; + } + } + + /// Handle incoming messages + void _handleMessage(dynamic data) { + try { + debugPrint("📨 Received: $data"); + final Map message = json.decode(data); + + if (message['event'] == 'pusher:ping') { + _sendPong(); + return; + } + + if (message['event'] == 'pusher:connection_established') { + debugPrint("🔗 Pusher connection established"); + return; + } + + if (message['event'] == 'pusher_internal:subscription_succeeded') { + debugPrint("✅ User channel subscribed"); + return; + } + + if (message['event'] != null && + !message['event'].toString().startsWith('pusher')) { + onMessageReceived?.call(message); + } + } catch (e) { + debugPrint("❌ Error parsing message: $e"); + onError?.call(e); + } + } + + void _handleError(dynamic error) { + debugPrint("❌ WebSocket error: $error"); + _isConnected = false; + onError?.call(error); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + void _handleDisconnection() { + debugPrint("🔌 Disconnected"); + _isConnected = false; + _stopPingTimer(); + onDisconnected?.call(); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + /// Subscribe to USER CHANNEL + void _subscribeToUserChannel() { + if (_userId == null) return; + + final subscribeMessage = { + 'event': 'pusher:subscribe', + 'data': {'channel': 'user-chat-notification.$_userId'}, + }; + + _sendMessage(subscribeMessage); + debugPrint("📡 Subscribing to user.$_userId"); + } + + void _sendPong() { + final pong = {'event': 'pusher:pong', 'data': {}}; + _sendMessage(pong); + } + + void _startPingTimer() { + _pingTimer?.cancel(); + _pingTimer = Timer.periodic(const Duration(seconds: 30), (timer) { + if (_isConnected) debugPrint("💓 WS heartbeat"); + }); + } + + void _stopPingTimer() { + _pingTimer?.cancel(); + _pingTimer = null; + } + + void _scheduleReconnect() { + if (_isIntentionalClose) return; + if (_reconnectAttempts >= _maxReconnectAttempts) { + onError?.call( + "Failed to reconnect after $_maxReconnectAttempts attempts", + ); + return; + } + + _reconnectTimer?.cancel(); + _reconnectAttempts++; + + debugPrint( + "🔄 Retry $_reconnectAttempts in ${_reconnectDelay.inSeconds}s...", + ); + + _reconnectTimer = Timer(_reconnectDelay, () async { + if (!_isIntentionalClose && _wsUrl != null && _userId != null) { + await _establishConnection(); + } + }); + } + + /// Send message + void _sendMessage(Map message) { + if (!_isConnected || _channel == null) { + debugPrint("⚠️ Cannot send: Not connected"); + return; + } + + try { + final jsonMsg = json.encode(message); + _channel!.sink.add(jsonMsg); + debugPrint("📤 Sent: $jsonMsg"); + } catch (e) { + debugPrint("❌ Send error: $e"); + } + } + + /// Send event to backend + void sendEvent({ + required String eventName, + required Map data, + }) { + final msg = { + 'event': eventName, + 'data': data, + 'channel': 'user-chat-notification.$_userId', + }; + _sendMessage(msg); + } + + Future disconnect() async { + _isIntentionalClose = true; + _reconnectTimer?.cancel(); + _stopPingTimer(); + + await _subscription?.cancel(); + await _channel?.sink.close(); + + _channel = null; + _subscription = null; + _isConnected = false; + _userId = null; + + debugPrint("🔌 WS disconnected intentionally"); + } +} diff --git a/lib/consts/download_helper.dart b/lib/consts/download_helper.dart new file mode 100644 index 0000000..c9590ce --- /dev/null +++ b/lib/consts/download_helper.dart @@ -0,0 +1,539 @@ +import 'dart:io'; +import 'package:dio/dio.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:open_filex/open_filex.dart'; +import 'package:gal/gal.dart'; + +class DownloadHelper { + static const String API_BASE_URL = "https://www.taxglide.amrithaa.net/api/"; + + /// Request storage permission based on Android version + static Future requestStoragePermission() async { + if (!Platform.isAndroid) return true; + + try { + final androidInfo = await DeviceInfoPlugin().androidInfo; + final sdkInt = androidInfo.version.sdkInt; + + print("📱 Android SDK: $sdkInt"); + + // Android 13+ (API 33+) + if (sdkInt >= 33) { + final photoStatus = await Permission.photos.request(); + final videoStatus = await Permission.videos.request(); + + print("✅ Android 13+ - Media permissions requested"); + return photoStatus.isGranted || videoStatus.isGranted; + } + + // Android 11-12 (API 30-32) + if (sdkInt >= 30) { + if (await Permission.manageExternalStorage.isGranted) { + return true; + } + + var status = await Permission.manageExternalStorage.request(); + if (status.isGranted) return true; + + status = await Permission.storage.request(); + return status.isGranted; + } + + // Android 10 and below (API 29 and below) + final status = await Permission.storage.request(); + return status.isGranted; + } catch (e) { + print("❌ Permission error: $e"); + return false; + } + } + + /// ⭐ NEW: Get TaxGlide folder in PUBLIC Downloads + static Future getTaxGlideFolder() async { + try { + await requestStoragePermission(); + + if (Platform.isAndroid) { + // Use public Downloads folder for all Android versions + final publicTaxGlide = Directory( + '/storage/emulated/0/Download/TaxGlide', + ); + + if (!await publicTaxGlide.exists()) { + await publicTaxGlide.create(recursive: true); + print( + "✅ TaxGlide folder created in public Downloads: ${publicTaxGlide.path}", + ); + } + + return publicTaxGlide; + } else { + // iOS - use app documents + final baseDirectory = await getApplicationDocumentsDirectory(); + final taxGlideFolder = Directory('${baseDirectory.path}/TaxGlide'); + + if (!await taxGlideFolder.exists()) { + await taxGlideFolder.create(recursive: true); + } + + return taxGlideFolder; + } + } catch (e) { + print("❌ Error creating TaxGlide folder: $e"); + // Fallback to app-specific storage if public storage fails + final fallbackDir = await getExternalStorageDirectory(); + final taxGlideFolder = Directory('${fallbackDir!.path}/TaxGlide'); + + if (!await taxGlideFolder.exists()) { + await taxGlideFolder.create(recursive: true); + print("⚠️ Using app-specific storage as fallback"); + } + + return taxGlideFolder; + } + } + + /// ⭐ Get Received folder in PUBLIC Downloads + static Future getReceivedFolder() async { + final taxGlideFolder = await getTaxGlideFolder(); + final receivedFolder = Directory('${taxGlideFolder.path}/Received'); + + if (!await receivedFolder.exists()) { + await receivedFolder.create(recursive: true); + print("✅ Received folder created: ${receivedFolder.path}"); + } + + return receivedFolder; + } + + /// ⭐ Get Send folder in PUBLIC Downloads + static Future getSendFolder() async { + final taxGlideFolder = await getTaxGlideFolder(); + final sendFolder = Directory('${taxGlideFolder.path}/Send'); + + if (!await sendFolder.exists()) { + await sendFolder.create(recursive: true); + print("✅ Send folder created: ${sendFolder.path}"); + } + + return sendFolder; + } + + /// Save file to Gallery (for images/videos only) + static Future saveToGallery(String filePath) async { + try { + final file = File(filePath); + if (!await file.exists()) { + print("❌ File does not exist: $filePath"); + return false; + } + + final fileName = filePath.split('/').last; + + // Request permissions + final hasPermission = await requestStoragePermission(); + if (!hasPermission) { + print("⚠️ No permission to save to gallery"); + return false; + } + + // Only save images/videos to Gallery + if (isImageFile(filePath)) { + await Gal.putImage(filePath, album: 'TaxGlide'); + print("✅ Image saved to Gallery: $fileName"); + return true; + } else if (isVideoFile(filePath)) { + await Gal.putVideo(filePath, album: 'TaxGlide'); + print("✅ Video saved to Gallery: $fileName"); + return true; + } + + return false; + } catch (e) { + print("❌ Error saving to gallery: $e"); + return false; + } + } + + /// Build download URL + static String buildDownloadUrl(String filePath) { + if (filePath.startsWith('http://') || filePath.startsWith('https://')) { + return filePath; + } + return '${API_BASE_URL}chat/download/$filePath'; + } + + /// Check if file exists in Received folder + static Future checkFileExistsInReceived(String url) async { + try { + final fileName = url.contains('/') + ? url.split('/').last.split('?').first + : url.split('?').first; + + final receivedFolder = await getReceivedFolder(); + final filePath = '${receivedFolder.path}/$fileName'; + final file = File(filePath); + + if (await file.exists()) { + print("✅ File already exists in Received: $filePath"); + return filePath; + } + return null; + } catch (e) { + print("❌ Error checking file existence: $e"); + return null; + } + } + + /// Backward compatibility + static Future checkFileExists(String url) async { + return await checkFileExistsInReceived(url); + } + + /// ⭐ Download file to Received folder (now in public Downloads) and Gallery + static Future> downloadFileToReceived(String url) async { + try { + final fullUrl = buildDownloadUrl(url); + print("🔗 Downloading from: $fullUrl"); + + // Check if file already exists + final existingFilePath = await checkFileExistsInReceived(fullUrl); + if (existingFilePath != null) { + print("📂 File already exists, opening it..."); + await openDownloadedFile(existingFilePath); + return { + 'filePath': existingFilePath, + 'isNewDownload': false, + 'success': true, + }; + } + + // Request permissions + await requestStoragePermission(); + + // Get filename and prepare save path + String fileName = fullUrl.split('/').last.split('?').first; + fileName = fileName.replaceAll(RegExp(r'[^\w\s\-\.]'), '_'); + + final receivedFolder = await getReceivedFolder(); + final savePath = "${receivedFolder.path}/$fileName"; + + print("Download Started: Downloading $fileName..."); + + // Download file to Received folder (now in public Downloads) + Dio dio = Dio(); + await dio.download( + fullUrl, + savePath, + onReceiveProgress: (received, total) { + if (total != -1) { + final progress = (received / total * 100).toStringAsFixed(0); + print("📊 Download progress: $progress%"); + } + }, + ); + + // Also save images/videos to Gallery + bool savedToGallery = false; + try { + savedToGallery = await saveToGallery(savePath); + } catch (e) { + print("⚠️ Could not save to gallery: $e"); + } + + if (savedToGallery) { + print( + "Download Complete: $fileName saved to Gallery & Downloads/TaxGlide/Received", + ); + } else { + print( + "Download Complete: $fileName saved to Downloads/TaxGlide/Received", + ); + } + + print("✅ File downloaded to: $savePath"); + + // Open the downloaded file + await openDownloadedFile(savePath); + + return { + 'filePath': savePath, + 'isNewDownload': true, + 'success': true, + 'savedToGallery': savedToGallery, + }; + } catch (e) { + print("❌ Download error: $e"); + print("Download Failed: Error: ${e.toString()}"); + return {'success': false, 'error': e.toString()}; + } + } + + /// Backward compatibility + static Future> downloadFile(String url) async { + return await downloadFileToReceived(url); + } + + /// ⭐ Save file to Send folder (now in public Downloads) + static Future saveToSendFolder(File file) async { + try { + if (!await file.exists()) { + throw Exception("Source file does not exist: ${file.path}"); + } + + final sendFolder = await getSendFolder(); + final originalFileName = file.path.split('/').last; + final timestamp = DateTime.now().millisecondsSinceEpoch; + final fileName = '${timestamp}_$originalFileName'; + final savePath = '${sendFolder.path}/$fileName'; + + final savedFile = await file.copy(savePath); + + print("✅ File saved to Send folder (Downloads/TaxGlide/Send): $savePath"); + + // Also save images/videos to Gallery + try { + await saveToGallery(savePath); + } catch (e) { + print("⚠️ Could not save to gallery: $e"); + } + + return savedFile.path; + } catch (e) { + print("❌ Error saving to Send folder: $e"); + print("⚠️ Using original file path: ${file.path}"); + return file.path; + } + } + + /// Save multiple files to Send folder + static Future> saveMultipleToSendFolder(List files) async { + List savedFiles = []; + + for (File file in files) { + try { + final savedPath = await saveToSendFolder(file); + savedFiles.add(File(savedPath)); + } catch (e) { + print("❌ Error saving file: ${file.path}, using original"); + savedFiles.add(file); + } + } + + return savedFiles; + } + + /// Open file with appropriate viewer + static Future openDownloadedFile(String path) async { + print("🔓 Opening file: $path"); + + try { + final file = File(path); + if (!await file.exists()) { + print("❌ File not found at $path"); + print("Error: File not found"); + return; + } + + final result = await OpenFilex.open(path); + + if (result.type != ResultType.done) { + print("⚠️ Could not open file: ${result.message}"); + print("Notice: File saved but no app found to open it"); + } + } catch (e) { + print("❌ Error opening file: $e"); + print("Error: Could not open file"); + } + } + + /// Get all files from Send folder + static Future> getSentFiles() async { + try { + final sendFolder = await getSendFolder(); + if (await sendFolder.exists()) { + return sendFolder.listSync().whereType().toList()..sort( + (a, b) => b.lastModifiedSync().compareTo(a.lastModifiedSync()), + ); + } + return []; + } catch (e) { + print("❌ Error getting sent files: $e"); + return []; + } + } + + /// Get all files from Received folder + static Future> getReceivedFiles() async { + try { + final receivedFolder = await getReceivedFolder(); + if (await receivedFolder.exists()) { + return receivedFolder.listSync().whereType().toList()..sort( + (a, b) => b.lastModifiedSync().compareTo(a.lastModifiedSync()), + ); + } + return []; + } catch (e) { + print("❌ Error getting received files: $e"); + return []; + } + } + + /// Delete a file + static Future deleteFile(String filePath) async { + try { + final file = File(filePath); + if (await file.exists()) { + await file.delete(); + print("✅ File deleted: $filePath"); + print("File Deleted: File removed successfully"); + return true; + } + return false; + } catch (e) { + print("❌ Error deleting file: $e"); + return false; + } + } + + /// Clear all files from Send folder + static Future clearSendFolder() async { + try { + final files = await getSentFiles(); + for (final file in files) { + await file.delete(); + } + print("✅ Send folder cleared: ${files.length} files deleted"); + } catch (e) { + print("❌ Error clearing Send folder: $e"); + } + } + + /// Clear all files from Received folder + static Future clearReceivedFolder() async { + try { + final files = await getReceivedFiles(); + for (final file in files) { + await file.delete(); + } + print("✅ Received folder cleared: ${files.length} files deleted"); + } catch (e) { + print("❌ Error clearing Received folder: $e"); + } + } + + /// Get file size in human-readable format + static Future getFileSize(File file) async { + try { + final bytes = await file.length(); + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) { + return '${(bytes / 1024).toStringAsFixed(2)} KB'; + } + if (bytes < 1024 * 1024 * 1024) { + return '${(bytes / (1024 * 1024)).toStringAsFixed(2)} MB'; + } + return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB'; + } catch (e) { + return 'Unknown'; + } + } + + /// Get file extension + static String getFileExtension(String path) { + return path.split('.').last.toLowerCase(); + } + + /// Check if file is image + static bool isImageFile(String path) { + final ext = getFileExtension(path); + return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].contains(ext); + } + + /// Check if file is document + static bool isDocumentFile(String path) { + final ext = getFileExtension(path); + return [ + 'pdf', + 'doc', + 'docx', + 'xls', + 'xlsx', + 'txt', + 'ppt', + 'pptx', + 'rtf', + 'odt', + ].contains(ext); + } + + /// Check if file is video + static bool isVideoFile(String path) { + final ext = getFileExtension(path); + return ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].contains(ext); + } + + /// Check if file is audio + static bool isAudioFile(String path) { + final ext = getFileExtension(path); + return ['mp3', 'wav', 'aac', 'flac', 'ogg', 'm4a', 'wma'].contains(ext); + } + + /// Get file icon based on type + static String getFileIcon(String path) { + if (isImageFile(path)) return '🖼️'; + if (isVideoFile(path)) return '🎥'; + if (isAudioFile(path)) return '🎵'; + if (isDocumentFile(path)) { + final ext = getFileExtension(path); + if (ext == 'pdf') return '📄'; + if (['doc', 'docx'].contains(ext)) return '📝'; + if (['xls', 'xlsx'].contains(ext)) return '📊'; + if (['ppt', 'pptx'].contains(ext)) return '📽️'; + } + return '📎'; + } + + /// Get storage info + static Future> getStorageInfo() async { + try { + final taxGlideFolder = await getTaxGlideFolder(); + final sentFiles = await getSentFiles(); + final receivedFiles = await getReceivedFiles(); + + int totalSentSize = 0; + int totalReceivedSize = 0; + + for (final file in sentFiles) { + totalSentSize += await file.length(); + } + + for (final file in receivedFiles) { + totalReceivedSize += await file.length(); + } + + return { + 'taxGlidePath': taxGlideFolder.path, + 'sentFiles': sentFiles.length.toString(), + 'receivedFiles': receivedFiles.length.toString(), + 'sentSize': _formatBytes(totalSentSize), + 'receivedSize': _formatBytes(totalReceivedSize), + 'totalSize': _formatBytes(totalSentSize + totalReceivedSize), + }; + } catch (e) { + print("❌ Error getting storage info: $e"); + return {}; + } + } + + static String _formatBytes(int bytes) { + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(2)} KB'; + if (bytes < 1024 * 1024 * 1024) { + return '${(bytes / (1024 * 1024)).toStringAsFixed(2)} MB'; + } + return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB'; + } +} diff --git a/lib/consts/fcm_token.dart b/lib/consts/fcm_token.dart new file mode 100644 index 0000000..fffeb35 --- /dev/null +++ b/lib/consts/fcm_token.dart @@ -0,0 +1,139 @@ +import 'dart:io'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/material.dart'; + +/// 🔥 FCM Token Manager - Force regenerates token on logout/login +class FcmTokenManager { + static final FcmTokenManager _instance = FcmTokenManager._internal(); + factory FcmTokenManager() => _instance; + FcmTokenManager._internal(); + + final FirebaseMessaging _messaging = FirebaseMessaging.instance; + + /// 🔑 Get current FCM token + Future getCurrentToken() async { + try { + if (Platform.isIOS) { + final apns = await _messaging.getAPNSToken(); + if (apns == null) { + debugPrint('⚠️ APIs Token missing on iOS - Skipping FCM getToken'); + return null; + } + } + + debugPrint('🔄 Getting current FCM token...'); + final token = await _messaging.getToken(); + debugPrint('✅ Current FCM Token: $token'); + return token; + } catch (e) { + debugPrint('❌ Error getting FCM token: $e'); + return null; + } + } + + /// 🔄 Force regenerate FCM token (deletes old and creates new) + /// Call this BEFORE login to ensure fresh token + /// 🔄 Force regenerate FCM token (deletes old and creates new) + Future regenerateToken() async { + try { + if (Platform.isIOS) { + final apns = await _messaging.getAPNSToken(); + if (apns == null) { + debugPrint( + '⚠️ APIs Token missing on iOS - Cannot regenerate FCM token', + ); + return null; + } + } + + debugPrint('🔄 Starting FCM token regeneration...'); + + // Step 1: Get old token + String? oldToken; + try { + oldToken = await _messaging.getToken(); + debugPrint('📋 OLD FCM Token: $oldToken'); + } catch (e) { + debugPrint('⚠️ Could not get old token: $e'); + } + + // Step 2: Delete the old token + try { + debugPrint('🗑️ Deleting old FCM token...'); + await _messaging.deleteToken(); + debugPrint('✅ Old token deleted'); + } catch (e) { + debugPrint('⚠️ Error deleting old token: $e'); + } + + // Step 3: Wait + await Future.delayed(const Duration(milliseconds: 800)); + + // Step 4: Request permission + await _messaging.requestPermission(alert: true, badge: true, sound: true); + + // Step 5: Generate new token + debugPrint('🔄 Generating new FCM token...'); + final newToken = await _messaging.getToken(); + + if (newToken != null) { + debugPrint('✅ NEW FCM Token: $newToken'); + } else { + debugPrint('⚠️ Failed to generate new token'); + } + + return newToken; + } catch (e) { + debugPrint('❌ Error regenerating FCM token: $e'); + return null; + } + } + + /// 🗑️ Delete FCM token (call on logout) + Future deleteToken() async { + try { + if (Platform.isIOS) { + final apns = await _messaging.getAPNSToken(); + if (apns == null) return false; + } + + // Print token before deletion + final currentToken = await _messaging.getToken(); + debugPrint('📋 Current FCM Token (before delete): $currentToken'); + + debugPrint('🗑️ Deleting FCM token...'); + await _messaging.deleteToken(); + debugPrint('✅ FCM token deleted successfully'); + + return true; + } catch (e) { + debugPrint('❌ Error deleting FCM token: $e'); + return false; + } + } + + /// 📡 Listen to token refresh events + void listenToTokenRefresh(Function(String) onTokenRefreshed) { + _messaging.onTokenRefresh.listen((newToken) { + debugPrint('🔔 FCM Token auto-refreshed by Firebase: $newToken'); + onTokenRefreshed(newToken); + }); + } + + /// 🔄 Reset and get fresh token (comprehensive reset) + Future resetAndGetFreshToken() async { + try { + // Delete existing token + await deleteToken(); + + // Wait longer to ensure complete reset + await Future.delayed(const Duration(seconds: 1)); + + // Regenerate + return await regenerateToken(); + } catch (e) { + debugPrint('❌ Error in resetAndGetFreshToken: $e'); + return null; + } + } +} diff --git a/lib/consts/home_page_headers.dart b/lib/consts/home_page_headers.dart new file mode 100644 index 0000000..e24b2cd --- /dev/null +++ b/lib/consts/home_page_headers.dart @@ -0,0 +1,262 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/view/screens/notification_screen.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +final serviceSearchProvider = StateProvider((ref) => ""); + +class HomePageHeader extends ConsumerWidget { + final String userName; + + const HomePageHeader({super.key, required this.userName}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final screenWidth = MediaQuery.of(context).size.width; + final screenHeight = MediaQuery.of(context).size.height; + + final headerHeight = screenHeight * 0.21; + final profileSize = screenWidth * 0.14; + final iconSize = screenWidth * 0.07; + final horizontalPadding = screenWidth * 0.04; + final searchBoxHeight = screenHeight * 0.07; + + final welcomeFontSize = screenWidth * 0.035; + final userFontSize = screenWidth * 0.045; + final initialFontSize = screenWidth * 0.045; + + // 🔴 Fetch Notification Count + final notifCountAsync = ref.watch(notificationCountProvider); + // 🔴 Fetch Profile Data for Image + final profileAsync = ref.watch(profileProvider); + + return Stack( + clipBehavior: Clip.none, + children: [ + // Background Header + ClipRRect( + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(20), + bottomRight: Radius.circular(20), + ), + child: Image.asset( + AppAssets.homepageheader, + width: double.infinity, + height: headerHeight, + fit: BoxFit.cover, + ), + ), + + // Profile + Welcome + Notification Icon + Positioned( + top: headerHeight * 0.15, + left: horizontalPadding, + right: horizontalPadding, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Profile Avatar + profileAsync.when( + data: (profileModel) { + final String? logoUrl = profileModel.data?.logo; + if (logoUrl != null && logoUrl.isNotEmpty) { + return Container( + width: profileSize, + height: profileSize, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + image: DecorationImage( + image: NetworkImage(logoUrl), + fit: BoxFit.cover, + ), + ), + ); + } + // Fallback to initial + return Container( + width: profileSize, + height: profileSize, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.black.withOpacity(0.8), + border: Border.all(color: Colors.white, width: 2), + ), + child: Center( + child: Text( + userName.isNotEmpty ? userName[0].toUpperCase() : "M", + style: TextStyle( + color: Colors.white, + fontSize: initialFontSize, + fontWeight: FontWeight.bold, + ), + ), + ), + ); + }, + loading: () => Container( + width: profileSize, + height: profileSize, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.grey[300], + border: Border.all(color: Colors.white, width: 2), + ), + ), + error: (e, st) => Container( + width: profileSize, + height: profileSize, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.black.withOpacity(0.8), + border: Border.all(color: Colors.white, width: 2), + ), + child: Center( + child: Text( + userName.isNotEmpty ? userName[0].toUpperCase() : "M", + style: TextStyle( + color: Colors.white, + fontSize: initialFontSize, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + + SizedBox(width: screenWidth * 0.03), + + // Welcome & Username + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Welcome to TaxGlide", + style: TextStyle( + color: Colors.black, + fontSize: welcomeFontSize, + fontWeight: FontWeight.w400, + ), + ), + Text( + userName, + style: TextStyle( + color: Colors.black, + fontSize: userFontSize, + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + + // Notifications with Badge + GestureDetector( + onTap: () => Get.to(NotificationScreen()), + child: Stack( + clipBehavior: Clip.none, + children: [ + Container( + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.black, + ), + padding: EdgeInsets.all(screenWidth * 0.025), + child: Icon( + Icons.notifications, + color: Colors.white, + size: iconSize, + ), + ), + + // 🔴 Notification Badge + Positioned( + right: -2, + top: -2, + child: notifCountAsync.when( + loading: () => const SizedBox.shrink(), + error: (e, st) => const SizedBox.shrink(), + data: (count) { + if (count.count == 0) { + return const SizedBox.shrink(); + } + return Container( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + ), + child: Text( + count.count.toString(), + style: const TextStyle( + fontSize: 10, + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ), + ); + }, + ), + ), + ], + ), + ), + ], + ), + ), + + // Search Bar + Positioned( + top: headerHeight - (searchBoxHeight * 0.6), + left: screenWidth * 0.05, + right: screenWidth * 0.05, + child: Container( + height: searchBoxHeight, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(50), + border: Border.all(color: const Color(0xFFE4E4E4), width: 1), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.15), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: TextField( + textAlign: TextAlign.start, // ✅ Start (left) alignment + style: TextStyle(fontSize: screenWidth * 0.04), + onChanged: (value) { + ref.read(serviceSearchProvider.notifier).state = value; + }, + decoration: InputDecoration( + hintText: "Search services...", + hintStyle: TextStyle( + color: Colors.grey, + fontSize: screenWidth * 0.04, + ), + prefixIcon: Icon( + Icons.search, + color: Colors.black54, + size: screenWidth * 0.06, + ), + border: InputBorder.none, + + // ✅ Only vertical center + contentPadding: EdgeInsets.symmetric( + vertical: searchBoxHeight * 0.3, + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/consts/image_permission.dart b/lib/consts/image_permission.dart new file mode 100644 index 0000000..241909d --- /dev/null +++ b/lib/consts/image_permission.dart @@ -0,0 +1,651 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:get/get.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:taxglide/consts/comman_image_box.dart'; +import 'package:taxglide/consts/comman_textformfileds.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:path/path.dart' as path; + +/// A reusable helper class for image picking with safe permission handling. +class ImagePickerHelper { + static final ImagePicker _picker = ImagePicker(); + static bool _isPicking = false; + + /// Request permission depending on platform and SDK version + static Future _requestPermission( + BuildContext context, + ImageSource source, + ) async { + try { + Permission permission; + String name; + + if (source == ImageSource.camera) { + permission = Permission.camera; + name = 'Camera'; + } else { + if (Platform.isAndroid) { + final info = await DeviceInfoPlugin().androidInfo; + if (info.version.sdkInt >= 33) { + permission = Permission.photos; + name = 'Photos'; + } else { + permission = Permission.storage; + name = 'Storage'; + } + } else { + permission = Permission.photos; // iOS gallery + name = 'Gallery'; + } + } + + var status = await permission.status; + if (status.isGranted || status.isLimited) return true; + + // On iOS, if already denied, request() won't show anything. + // On Android, permanently denied also won't show anything. + if (status.isPermanentlyDenied || (Platform.isIOS && status.isDenied)) { + await _showSettingsDialog(context, name); + return false; + } + + // Now request permission + status = await permission.request(); + + if (status.isGranted || status.isLimited) { + return true; + } else { + // If user denied it just now, or it was already denied (iOS) + await _showSettingsDialog(context, name); + return false; + } + } catch (e) { + debugPrint('Permission request failed: $e'); + return Platform.isIOS; + } + } + + static Future _showSettingsDialog( + BuildContext context, + String name, + ) async { + final openSettings = + await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text('$name Permission Required'), + content: Text( + 'Allow Taxglide to access your $name to capture and upload files easily. You can enable this in the app settings.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Go to Settings'), + ), + ], + ), + ) ?? + false; + if (openSettings) await openAppSettings(); + } + + /// Pick single image safely + static Future pickSingleImage({ + required BuildContext context, + required void Function(File?) onImageSelected, + required void Function(String?) setError, + }) async { + if (_isPicking) return; + _isPicking = true; + + try { + // Ask user: Camera or Gallery + final source = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + title: const Text('Select Image Source'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.camera_alt, color: Colors.blue), + title: const Text('Camera'), + onTap: () => Navigator.pop(ctx, ImageSource.camera), + ), + ListTile( + leading: const Icon(Icons.photo, color: Colors.blue), + title: const Text('Gallery'), + onTap: () => Navigator.pop(ctx, ImageSource.gallery), + ), + ], + ), + ), + ); + + if (source == null) { + _isPicking = false; + return; + } + + // Permission check + final hasPermission = await _requestPermission(context, source); + if (!hasPermission) { + _isPicking = false; + return; + } + + // Image selection + final pickedFile = await _picker.pickImage(source: source); + if (pickedFile != null) { + onImageSelected(File(pickedFile.path)); + setError(null); + } + } catch (e) { + debugPrint('Image pick error: $e'); + Get.snackbar( + "Error", + "Failed to pick image: $e", + backgroundColor: Colors.red, + colorText: Colors.white, + ); + } finally { + _isPicking = false; + } + } + + /// 🔥 NEW: Pick Image or PDF + static Future pickImageOrPdf({ + required BuildContext context, + required void Function(File?) onFileSelected, + required void Function(String?) setError, + }) async { + if (_isPicking) return; + _isPicking = true; + + try { + // Ask user: Camera, Gallery, or PDF + final choice = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + title: const Text('Select File Source'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.camera_alt, color: Colors.blue), + title: const Text('Camera'), + onTap: () => Navigator.pop(ctx, 'camera'), + ), + ListTile( + leading: const Icon(Icons.photo, color: Colors.blue), + title: const Text('Gallery (Image)'), + onTap: () => Navigator.pop(ctx, 'gallery'), + ), + ListTile( + leading: const Icon(Icons.picture_as_pdf, color: Colors.red), + title: const Text('Select PDF'), + onTap: () => Navigator.pop(ctx, 'pdf'), + ), + ], + ), + ), + ); + + if (choice == null) { + _isPicking = false; + return; + } + + if (choice == 'pdf') { + // Pick PDF using file_picker + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['pdf'], + ); + + if (result != null && result.files.single.path != null) { + final file = File(result.files.single.path!); + + // Check file size (max 10MB) + final fileSizeInBytes = await file.length(); + final fileSizeInMB = fileSizeInBytes / (1024 * 1024); + + if (fileSizeInMB > 10) { + Get.snackbar( + "Error", + "PDF file size should not exceed 10MB", + backgroundColor: Colors.red, + colorText: Colors.white, + ); + _isPicking = false; + return; + } + + onFileSelected(file); + setError(null); + } + } else { + // Pick Image (Camera or Gallery) + final source = choice == 'camera' + ? ImageSource.camera + : ImageSource.gallery; + + // Permission check + final hasPermission = await _requestPermission(context, source); + if (!hasPermission) { + _isPicking = false; + return; + } + + // Image selection + final pickedFile = await _picker.pickImage(source: source); + if (pickedFile != null) { + onFileSelected(File(pickedFile.path)); + setError(null); + } + } + } catch (e) { + debugPrint('File pick error: $e'); + Get.snackbar( + "Error", + "Failed to pick file: $e", + backgroundColor: Colors.red, + colorText: Colors.white, + ); + } finally { + _isPicking = false; + } + } +} + +class LabeledTextField extends StatelessWidget { + final GlobalKey fieldKey; + final String label; + final String keyName; + final String hint; + final TextEditingController controller; + final FocusNode focusNode; + final TextInputType keyboardType; + final Map errors; + final Function(String) onChanged; + final bool readOnly; + + /// ✅ ADD THESE + final List? inputFormatters; + final TextCapitalization textCapitalization; + + const LabeledTextField({ + super.key, + required this.fieldKey, + required this.label, + required this.keyName, + required this.hint, + required this.controller, + required this.focusNode, + required this.errors, + required this.onChanged, + this.readOnly = false, + this.keyboardType = TextInputType.text, + + /// ✅ DEFAULT VALUES + this.inputFormatters, + this.textCapitalization = TextCapitalization.none, + }); + + @override + Widget build(BuildContext context) { + return Padding( + key: fieldKey, + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + height: 1.3, + letterSpacing: 0.64, + color: Colors.black, + ), + ), + const SizedBox(height: 8), + + /// ✅ PASS FORMATTERS & CAPITALIZATION HERE + CommanTextFormField( + controller: controller, + hintText: hint, + keyboardType: keyboardType, + focusNode: focusNode, + hasError: errors[keyName] != null, + onChanged: onChanged, + readOnly: readOnly, + inputFormatters: inputFormatters, + textCapitalization: textCapitalization, + ), + + if (errors[keyName] != null) + Padding( + padding: const EdgeInsets.only(top: 4, left: 6), + child: Text( + errors[keyName]!, + style: const TextStyle(color: Colors.red, fontSize: 12), + ), + ), + ], + ), + ); + } +} + +// 🔥 Updated SingleImageSectionField with URL support (Image only - for Logo) +class SingleImageSectionField extends StatelessWidget { + final GlobalKey imageKey; + final String title; + final File? imageFile; + final String? imageUrl; + final String? errorText; + final Function(String?) setError; + final Function(File?) onImageSelected; + final VoidCallback onImageRemoved; + + const SingleImageSectionField({ + super.key, + required this.imageKey, + required this.title, + required this.imageFile, + required this.imageUrl, + required this.errorText, + required this.setError, + required this.onImageSelected, + required this.onImageRemoved, + }); + + @override + Widget build(BuildContext context) { + final hasImage = imageFile != null || imageUrl != null; + + return Padding( + key: imageKey, + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + height: 1.3, + letterSpacing: 0.64, + color: Colors.black, + ), + ), + const SizedBox(height: 8), + CommanImageBox( + onTap: () => ImagePickerHelper.pickSingleImage( + context: context, + onImageSelected: onImageSelected, + setError: setError, + ), + text: hasImage ? 'Change Image' : 'Upload Image', + ), + if (errorText != null) + Padding( + padding: const EdgeInsets.only(top: 4, left: 6), + child: Text( + errorText!, + style: const TextStyle(color: Colors.red, fontSize: 12), + ), + ), + + if (hasImage) + Container( + margin: const EdgeInsets.only(top: 10), + child: Stack( + children: [ + Container( + width: 120, + height: 120, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade300), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: imageFile != null + ? Image.file(imageFile!, fit: BoxFit.cover) + : CachedNetworkImage( + imageUrl: imageUrl!, + fit: BoxFit.cover, + placeholder: (context, url) => const Center( + child: CircularProgressIndicator(), + ), + errorWidget: (context, url, error) => + const Icon(Icons.error, color: Colors.red), + ), + ), + ), + Positioned( + right: 0, + top: 0, + child: GestureDetector( + onTap: onImageRemoved, + child: Container( + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.2), + blurRadius: 4, + ), + ], + ), + padding: const EdgeInsets.all(4), + child: const Icon( + Icons.close, + color: Colors.white, + size: 18, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +// 🔥 NEW: File Section Field (Supports both Image and PDF) +class FileUploadSectionField extends StatelessWidget { + final GlobalKey fileKey; + final String title; + final File? fileData; + final String? fileUrl; + final String? errorText; + final Function(String?) setError; + final Function(File?) onFileSelected; + final VoidCallback onFileRemoved; + + const FileUploadSectionField({ + super.key, + required this.fileKey, + required this.title, + required this.fileData, + required this.fileUrl, + required this.errorText, + required this.setError, + required this.onFileSelected, + required this.onFileRemoved, + }); + + bool _isPdfFile(String? filePath) { + if (filePath == null) return false; + return path.extension(filePath).toLowerCase() == '.pdf'; + } + + bool _isImageFile(String? filePath) { + if (filePath == null) return false; + final ext = path.extension(filePath).toLowerCase(); + return ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'].contains(ext); + } + + @override + Widget build(BuildContext context) { + final hasFile = fileData != null || fileUrl != null; + final isPdf = _isPdfFile(fileData?.path ?? fileUrl); + final isImage = _isImageFile(fileData?.path ?? fileUrl); + + return Padding( + key: fileKey, + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + height: 1.3, + letterSpacing: 0.64, + color: Colors.black, + ), + ), + const SizedBox(height: 8), + CommanImageBox( + onTap: () => ImagePickerHelper.pickImageOrPdf( + context: context, + onFileSelected: onFileSelected, + setError: setError, + ), + text: hasFile ? 'Change File' : 'Upload Image/PDF', + ), + if (errorText != null) + Padding( + padding: const EdgeInsets.only(top: 4, left: 6), + child: Text( + errorText!, + style: const TextStyle(color: Colors.red, fontSize: 12), + ), + ), + + // Display file preview + if (hasFile) + Container( + margin: const EdgeInsets.only(top: 10), + child: Stack( + children: [ + Container( + width: 120, + height: 120, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade300), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: isPdf + // Show PDF icon + ? Container( + color: Colors.red.shade50, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.picture_as_pdf, + size: 48, + color: Colors.red.shade700, + ), + const SizedBox(height: 8), + Text( + 'PDF', + style: TextStyle( + color: Colors.red.shade700, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ) + : isImage && fileData != null + // Show local image + ? Image.file(fileData!, fit: BoxFit.cover) + : isImage && fileUrl != null + // Show network image + ? CachedNetworkImage( + imageUrl: fileUrl!, + fit: BoxFit.cover, + placeholder: (context, url) => const Center( + child: CircularProgressIndicator(), + ), + errorWidget: (context, url, error) => + const Icon(Icons.error, color: Colors.red), + ) + // Unknown file type + : Container( + color: Colors.grey.shade100, + child: const Icon( + Icons.insert_drive_file, + size: 48, + color: Colors.grey, + ), + ), + ), + ), + Positioned( + right: 0, + top: 0, + child: GestureDetector( + onTap: onFileRemoved, + child: Container( + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.2), + blurRadius: 4, + ), + ], + ), + padding: const EdgeInsets.all(4), + child: const Icon( + Icons.close, + color: Colors.white, + size: 18, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/consts/local_store.dart b/lib/consts/local_store.dart new file mode 100644 index 0000000..9b3babf --- /dev/null +++ b/lib/consts/local_store.dart @@ -0,0 +1,102 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +class LocalStore { + // Secure storage instance + final _storage = const FlutterSecureStorage(); + + /// -------------------------------------------------------- + /// 🔐 SAVE LOGIN / SIGNUP DATA + /// -------------------------------------------------------- + Future saveLoginData(Map data) async { + final token = data['access_token'] ?? ''; + final role = data['role'] ?? ''; + + // Keep existing FCM token (do not overwrite) + String? existingFcmToken = await _storage.read(key: 'fcm_token'); + + // Save token & role + await _storage.write(key: 'access_token', value: token.toString()); + await _storage.write(key: 'role', value: role.toString()); + + // ⭐ Save general_chat_id if available + if (data['general_chat_id'] != null) { + await _storage.write( + key: 'general_chat_id', + value: data['general_chat_id'].toString(), + ); + } + + // ⭐ Save USER ID if available + if (data['user'] != null && data['user']['id'] != null) { + await _storage.write( + key: 'user_id', + value: data['user']['id'].toString(), + ); + } + + // ⭐ If root level ID exists (not in your JSON but future-safe) + if (data['id'] != null) { + await _storage.write(key: 'main_id', value: data['id'].toString()); + } + + // ⭐ Save/Persist FCM token safely + if (existingFcmToken != null && existingFcmToken.isNotEmpty) { + // Keep old FCM + await _storage.write(key: 'fcm_token', value: existingFcmToken); + } else if (data['fcm_token'] != null && + data['fcm_token'].toString().isNotEmpty) { + // Save new FCM token + await _storage.write( + key: 'fcm_token', + value: data['fcm_token'].toString(), + ); + } + } + + /// -------------------------------------------------------- + /// 🔥 SAVE FCM TOKEN ALONE + /// -------------------------------------------------------- + Future saveFcmToken(String token) async { + await _storage.write(key: 'fcm_token', value: token); + } + + /// -------------------------------------------------------- + /// 🔍 GETTERS + /// -------------------------------------------------------- + Future getToken() async { + return await _storage.read(key: 'access_token'); + } + + Future getRole() async { + return await _storage.read(key: 'role'); + } + + Future getGeneralChatId() async { + return await _storage.read(key: 'general_chat_id'); + } + + Future getUserId() async { + return await _storage.read(key: 'user_id'); + } + + Future getMainId() async { + return await _storage.read(key: 'main_id'); + } + + /// -------------------------------------------------------- + /// 🧹 CLEAR ALL (OPTIONAL KEEP FCM TOKEN) + /// -------------------------------------------------------- + Future clearAll({bool keepFcm = true}) async { + if (keepFcm) { + // Preserve FCM token + String? fcmToken = await _storage.read(key: 'fcm_token'); + await _storage.deleteAll(); + if (fcmToken != null) { + await _storage.write(key: 'fcm_token', value: fcmToken); + } + } else { + // Full wipe + await _storage.deleteAll(); + } + } +} diff --git a/lib/consts/notification_webscoket.dart b/lib/consts/notification_webscoket.dart new file mode 100644 index 0000000..23c8002 --- /dev/null +++ b/lib/consts/notification_webscoket.dart @@ -0,0 +1,328 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/foundation.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/services/notification_service.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class NotificationWebSocket { + static final NotificationWebSocket _instance = + NotificationWebSocket._internal(); + factory NotificationWebSocket() => _instance; + NotificationWebSocket._internal(); + + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Timer? _reconnectTimer; + + bool _isConnected = false; + bool _isIntentionalClose = false; + + String? _userId; + String? _wsUrl; + ProviderContainer? _container; + + int _reconnectAttempts = 0; + static const int _maxReconnectAttempts = 10; + + /// ChatId the user is currently VIEWING. + String? _activeChatId; + + /// ChatId whose `chat.` channel we are subscribed to on this WS. + String? _subscribedChatChannelId; + + // ─────────────────────────── Public API ──────────────────────────────────── + + /// Call from LiveChatScreen.initState(). + void setActiveChatId(String chatId) { + _activeChatId = chatId; + debugPrint('NotificationWS: viewing chat $chatId'); + _subscribeToChatChannel(chatId); + } + + /// Call from LiveChatScreen.dispose() + void clearActiveChatId() { + debugPrint('NotificationWS: left chat $_activeChatId'); + _activeChatId = null; + } + + /// Subscribe to a chat channel for updates. + void watchChatChannel(String chatId) { + debugPrint('Eye NotificationWS: watchChatChannel($chatId)'); + _subscribeToChatChannel(chatId); + } + + /// Connect (or skip if already connected for the same user). + Future connect({ + required String userId, + required ProviderContainer container, + String baseUrl = 'wss://taxglide.amrithaa.net:443/reverb', + String appKey = '2yj0lyzc9ylw2h03ts6i', + }) async { + if (_isConnected && _userId == userId) { + debugPrint('⚡ NotificationWS: already connected for user $userId'); + return; + } + + await disconnect(); + + _userId = userId; + _container = container; + _wsUrl = '$baseUrl/app/$appKey?protocol=7&client=js&version=1.0'; + _isIntentionalClose = false; + _reconnectAttempts = 0; + + _openSocket(); + } + + // ──────────────────────── Socket lifecycle ────────────────────────────────── + + void _openSocket() { + try { + debugPrint('🔌 NotificationWS connecting…'); + _channel = WebSocketChannel.connect(Uri.parse(_wsUrl!)); + + _subscription = _channel!.stream.listen( + _handleMessage, + onError: _handleError, + onDone: _handleDone, + ); + + _isConnected = true; + + _subscribeToUserChannel(); + + // Re-subscribe to chat channel after reconnect if we had one before. + final chatId = _subscribedChatChannelId; + if (chatId != null) { + _sendRaw({ + 'event': 'pusher:subscribe', + 'data': {'channel': 'chat.$chatId'}, + }); + debugPrint('📡 NotificationWS: re-subscribed to chat.$chatId'); + } + } catch (e) { + debugPrint('❌ NotificationWS connect error: $e'); + _isConnected = false; + _scheduleReconnect(); + } + } + + void _subscribeToUserChannel() { + if (_userId == null) return; + _sendRaw({ + 'event': 'pusher:subscribe', + 'data': {'channel': 'user-chat-notification.$_userId'}, + }); + debugPrint( + '📡 NotificationWS: subscribed to user-chat-notification.$_userId', + ); + } + + void _subscribeToChatChannel(String chatId) { + if (_subscribedChatChannelId == chatId) return; // already subscribed + + // Unsubscribe previous chat channel + if (_subscribedChatChannelId != null) { + _sendRaw({ + 'event': 'pusher:unsubscribe', + 'data': {'channel': 'chat.$_subscribedChatChannelId'}, + }); + debugPrint( + '📡 NotificationWS: unsubscribed from chat.$_subscribedChatChannelId', + ); + } + + _subscribedChatChannelId = chatId; + _sendRaw({ + 'event': 'pusher:subscribe', + 'data': {'channel': 'chat.$chatId'}, + }); + debugPrint('📡 NotificationWS: subscribed to chat.$chatId'); + } + + // ──────────────────────── Message handler ────────────────────────────────── + + void _handleMessage(dynamic raw) { + debugPrint('🔔 NotificationWS raw: $raw'); + + try { + final msg = jsonDecode(raw) as Map; + final event = msg['event']?.toString() ?? ''; + + // ── Pusher connection established → re-subscribe ────────────────────── + if (event == 'pusher:connection_established') { + debugPrint('🔗 NotificationWS: connection established'); + _subscribeToUserChannel(); + final chatId = _subscribedChatChannelId; + if (chatId != null) { + _sendRaw({ + 'event': 'pusher:subscribe', + 'data': {'channel': 'chat.$chatId'}, + }); + } + return; + } + + // ── Skip all other Pusher internal events ───────────────────────────── + if (event.startsWith('pusher')) return; + if (event.startsWith('pusher_internal')) return; + + // ── Refresh Riverpod badge count ────────────────────────────────────── + try { + _container?.read(notificationTriggerProvider.notifier).state++; + } catch (_) {} + + // ── Determine which chat this message belongs to ────────────────────── + String? incomingChatId; + final channelStr = msg['channel']?.toString() ?? ''; + if (channelStr.startsWith('chat.')) { + incomingChatId = channelStr.split('.').last; + } + + // ── Parse the payload ───────────────────────────────────────────────── + final rawData = msg['data']; + if (rawData == null) return; + + dynamic data; + try { + data = rawData is String ? jsonDecode(rawData) : rawData; + } catch (_) { + data = rawData; + } + + // Flatten list → use first element + if (data is List && data.isNotEmpty) { + data = data[0]; + } + + if (data is! Map) { + debugPrint('⚠️ NotificationWS: unrecognised data format, skipping'); + return; + } + + final dataMap = Map.from(data); + debugPrint('🔔 NotificationWS data keys: ${dataMap.keys.toList()}'); + + // ── Skip ping-only payloads {status, reload} ────────────────────────── + // The backend first fires a lightweight notification-trigger event that + // only contains `status` and `reload`. There is nothing to display yet; + // the full message list arrives in the next event on the same channel. + final onlyStatusReload = + dataMap.containsKey('status') && + dataMap.containsKey('reload') && + !dataMap.containsKey('message') && + !dataMap.containsKey('chat_by'); + if (onlyStatusReload) { + debugPrint('🔔 NotificationWS: reload ping received, badge refreshed'); + return; + } + + // ── Skip user's own messages ────────────────────────────────────────── + final chatBy = dataMap['chat_by']?.toString().toLowerCase() ?? ''; + if (chatBy == 'user' || chatBy == 'customer') { + debugPrint('🔕 NotificationWS: own message, skipping'); + return; + } + + // ── Extract routing info if needed for internal state ───────────── + final String? page = + dataMap['page']?.toString() ?? dataMap['type']?.toString(); + final String? pageId = + dataMap['page_id']?.toString() ?? dataMap['pageId']?.toString(); + + if (page == null || page.isEmpty || pageId == null || pageId.isEmpty) { + // Chat Notification fallback + incomingChatId ??= + dataMap['chat_id']?.toString() ?? + dataMap['chatId']?.toString() ?? + (dataMap['parent_tag'] != null && dataMap['parent_tag'] is Map + ? dataMap['parent_tag']['id']?.toString() + : null) ?? + dataMap['id']?.toString(); + + if (incomingChatId != null && incomingChatId != '0') { + _subscribeToChatChannel(incomingChatId); + } + } + + // ── Show Foreground Notification ───────────────────────────────────── + // Only show if it's NOT a message for the currently active chat screen. + // Pass incomingChatId as the dedup tag so that if FCM already fired a + // notification for this same chat, this one *replaces* it on Android + // instead of showing a second notification. + if (incomingChatId != _activeChatId) { + // Prefer the sender name from dataMap for the title. + final String senderTitle = + dataMap['sender_name']?.toString() ?? + dataMap['name']?.toString() ?? + dataMap['chat_by']?.toString() ?? + 'New Message'; + + final RemoteMessage fcmLikeMessage = RemoteMessage( + data: dataMap, + notification: RemoteNotification( + title: senderTitle, + body: dataMap['message']?.toString() ?? 'You have a new message', + ), + ); + + Get.find().showForegroundNotification( + fcmLikeMessage, + tag: incomingChatId, // dedup key – same chat collapses into 1 notif + ); + } + } catch (e, st) { + debugPrint('❌ NotificationWS _handleMessage error: $e\n$st'); + } + } + + void _sendRaw(Map message) { + try { + _channel?.sink.add(jsonEncode(message)); + } catch (e) { + debugPrint('❌ NotificationWS send error: $e'); + } + } + + // ──────────────────────── Reconnect ──────────────────────────────────────── + + void _handleError(dynamic error) { + debugPrint('❌ NotificationWS error: $error'); + _isConnected = false; + _scheduleReconnect(); + } + + void _handleDone() { + debugPrint('🔌 NotificationWS: connection closed'); + _isConnected = false; + if (!_isIntentionalClose) _scheduleReconnect(); + } + + void _scheduleReconnect() { + if (_isIntentionalClose || _reconnectAttempts >= _maxReconnectAttempts) { + return; + } + _reconnectAttempts++; + final delay = Duration(seconds: _reconnectAttempts * 2); + debugPrint( + '🔄 NotificationWS: reconnect #$_reconnectAttempts in ${delay.inSeconds}s', + ); + _reconnectTimer = Timer(delay, () { + if (!_isIntentionalClose) _openSocket(); + }); + } + + Future disconnect() async { + _isIntentionalClose = true; + _reconnectTimer?.cancel(); + await _subscription?.cancel(); + await _channel?.sink.close(); + _isConnected = false; + _subscribedChatChannelId = null; + debugPrint('🔌 NotificationWS: disconnected'); + } +} diff --git a/lib/consts/responsive_helper.dart b/lib/consts/responsive_helper.dart new file mode 100644 index 0000000..d2f2cf2 --- /dev/null +++ b/lib/consts/responsive_helper.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; + +/// Responsive utility class for all screens +class ResponsiveUtils { + final BuildContext context; + + ResponsiveUtils(this.context); + + // Get screen width + double get screenWidth => MediaQuery.of(context).size.width; + + // Get screen height + double get screenHeight => MediaQuery.of(context).size.height; + + // Device type checks + bool get isMobile => screenWidth < 600; + bool get isTablet => screenWidth >= 600 && screenWidth < 900; + bool get isDesktop => screenWidth >= 900; + + // Responsive width percentage + double widthPercent(double percent) => screenWidth * (percent / 100); + + // Responsive height percentage + double heightPercent(double percent) => screenHeight * (percent / 100); + + // Responsive font size + double fontSize({required double mobile, double? tablet, double? desktop}) { + if (isDesktop && desktop != null) return desktop; + if (isTablet && tablet != null) return tablet; + return mobile; + } + + // Responsive spacing + double spacing({required double mobile, double? tablet, double? desktop}) { + if (isDesktop && desktop != null) return desktop; + if (isTablet && tablet != null) return tablet; + return mobile; + } + + // Responsive padding + EdgeInsets padding({ + required double mobile, + double? tablet, + double? desktop, + }) { + final value = spacing(mobile: mobile, tablet: tablet, desktop: desktop); + return EdgeInsets.all(value); + } + + // Responsive horizontal padding + EdgeInsets horizontalPadding({ + required double mobile, + double? tablet, + double? desktop, + }) { + final value = spacing(mobile: mobile, tablet: tablet, desktop: desktop); + return EdgeInsets.symmetric(horizontal: value); + } + + // Responsive vertical padding + EdgeInsets verticalPadding({ + required double mobile, + double? tablet, + double? desktop, + }) { + final value = spacing(mobile: mobile, tablet: tablet, desktop: desktop); + return EdgeInsets.symmetric(vertical: value); + } + + // Responsive border radius + double borderRadius({ + required double mobile, + double? tablet, + double? desktop, + }) { + if (isDesktop && desktop != null) return desktop; + if (isTablet && tablet != null) return tablet; + return mobile; + } + + // Card width for list items + double cardWidth({ + double mobilePercent = 70, + double tabletPercent = 45, + double desktopPercent = 30, + }) { + if (isDesktop) return widthPercent(desktopPercent); + if (isTablet) return widthPercent(tabletPercent); + return widthPercent(mobilePercent); + } + + // Get value based on screen size + T getValue({required T mobile, T? tablet, T? desktop}) { + if (isDesktop && desktop != null) return desktop; + if (isTablet && tablet != null) return tablet; + return mobile; + } +} + +/// Extension on BuildContext for easy access +extension ResponsiveExtension on BuildContext { + ResponsiveUtils get responsive => ResponsiveUtils(this); + + // Quick access methods + double get screenWidth => MediaQuery.of(this).size.width; + double get screenHeight => MediaQuery.of(this).size.height; + bool get isMobile => screenWidth < 600; + bool get isTablet => screenWidth >= 600 && screenWidth < 900; + bool get isDesktop => screenWidth >= 900; +} diff --git a/lib/consts/validation_popup.dart b/lib/consts/validation_popup.dart new file mode 100644 index 0000000..ee0259e --- /dev/null +++ b/lib/consts/validation_popup.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; + +class ValidationPopup { + // Show SnackBar + void _showSnackBar(BuildContext context, String msg, {bool isError = false}) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + duration: const Duration(seconds: 2), + backgroundColor: isError + ? Colors.red + : AppColors.commanbutton, // 🔴 Error red + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + elevation: 6, + margin: const EdgeInsets.symmetric(horizontal: 70, vertical: 25), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + content: SizedBox( + width: 200, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Image.asset(AppAssets.taxgildelogoauth, height: 18, width: 18), + const SizedBox(width: 8), + Expanded( + child: Text( + msg, + style: const TextStyle(color: Colors.white, fontSize: 12), + overflow: TextOverflow.ellipsis, + maxLines: 2, + ), + ), + ], + ), + ), + ), + ); + } + + // Validate Mobile Number + bool validateMobileNumber(BuildContext context, String mobileNumber) { + // Check if empty + if (mobileNumber.isEmpty) { + _showSnackBar(context, "Please enter mobile number", isError: true); + return false; + } + + // Remove spaces and special characters + String cleanNumber = mobileNumber.replaceAll(RegExp(r'[^\d]'), ''); + + // Check if contains only digits + if (!RegExp(r'^[0-9]+$').hasMatch(cleanNumber)) { + _showSnackBar( + context, + "Mobile number must contain only digits", + isError: true, + ); + return false; + } + + // Check length (Indian mobile numbers are 10 digits) + if (cleanNumber.length != 10) { + _showSnackBar(context, "Mobile number must be 10 digits", isError: true); + return false; + } + + // Check if starts with valid digit (6-9 for Indian numbers) + if (!RegExp(r'^[6-9]').hasMatch(cleanNumber)) { + _showSnackBar( + context, + "Mobile number must start with 6, 7, 8, or 9", + isError: true, + ); + return false; + } + + // All validations passed + return true; + } + + // Add this method to your ValidationPopup class + bool validateEmail(BuildContext context, String email) { + // Email regex pattern + final emailRegex = RegExp( + r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', + ); + + if (!emailRegex.hasMatch(email)) { + showErrorMessage(context, "Please enter a valid email address"); + return false; + } + return true; + } + + // Show success message + void showSuccessMessage(BuildContext context, String msg) { + _showSnackBar(context, msg, isError: false); + } + + // Show error message + void showErrorMessage(BuildContext context, String msg) { + _showSnackBar(context, msg, isError: true); + } +} diff --git a/lib/controller/api_consts.dart b/lib/controller/api_consts.dart new file mode 100644 index 0000000..c1ded75 --- /dev/null +++ b/lib/controller/api_consts.dart @@ -0,0 +1,30 @@ +class ConstsApi { + static const String baseUrl = "https://www.taxglide.amrithaa.net"; + + static const String login = "$baseUrl/api/otp/sms/request"; + static const String verifyOtp = "$baseUrl/api/otp/sms/verify"; + static const String signup = "$baseUrl/api/register"; + static const String terms = "$baseUrl/api/get_terms_conditions"; + static const String policy = "$baseUrl/api/get_privacy_policy"; + static const String getprofile = "$baseUrl/api/get_profile"; + static const String employeelogin = "$baseUrl/api/otp/employee/sms/request"; + static const String serivcelist = "$baseUrl/api/get_services_list"; + static const String conturystate = "$baseUrl/api/kyc_master"; + static const String city = "$baseUrl/api/state_based_districts"; + static const String kycupdate = "$baseUrl/api/profile_update"; + static const String serivcerequest = "$baseUrl/api/service_register"; + static const String serivcehistory = "$baseUrl/api/get_service_requests_list"; + static const String serivcedetails = + "$baseUrl/api/get_service_request_detail"; + static const String logout = "$baseUrl/api/logout"; + static const String chatList = "$baseUrl/api/chat"; + static const String sendChatMessage = "$baseUrl/api/chat/message/send"; + static const String stafflist = "$baseUrl/api/get_employee_list"; + static const String count = "$baseUrl/api/chat/un_read_message_count"; + static const String chatdocument = "$baseUrl/api/chat/document_lists"; + static const String notificationList = "$baseUrl/api/notification/lists"; + static const String notificationcount = + "$baseUrl/api/notification/un_read_count"; + static const String dashboard = "$baseUrl/api/get_dashboard_data"; + static const String proformaaccept = "$baseUrl/api/proforma/accept"; +} diff --git a/lib/controller/api_contoller.dart b/lib/controller/api_contoller.dart new file mode 100644 index 0000000..c2c702d --- /dev/null +++ b/lib/controller/api_contoller.dart @@ -0,0 +1,536 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:taxglide/controller/api_consts.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/model/chat_model.dart'; +import 'package:taxglide/model/chat_profile_model.dart'; +import 'package:taxglide/model/city_model.dart'; +import 'package:taxglide/model/count_model.dart'; +import 'package:taxglide/model/country_model.dart'; +import 'package:taxglide/model/dash_board_model.dart'; +import 'package:taxglide/model/detail_model.dart'; +import 'package:taxglide/model/employeeprofile_model.dart'; +import 'package:taxglide/model/login_model.dart'; +import 'package:taxglide/model/notification_model.dart'; +import 'package:taxglide/model/notificationcount_model.dart'; +import 'package:taxglide/model/profile_get_model.dart'; +import 'package:taxglide/model/serivce_list_model.dart'; +import 'package:taxglide/model/service_list_history_model.dart'; +import 'package:taxglide/model/signup_model.dart'; +import 'package:taxglide/model/staff_model.dart'; +import 'package:taxglide/model/terms_model.dart'; + +final apiRepositoryProvider = Provider((ref) => ApiRepository()); + +//login controller +final loginProvider = + StateNotifierProvider>>( + (ref) => LoginNotifier(ref.read(apiRepositoryProvider)), + ); + +class LoginNotifier extends StateNotifier>> { + final ApiRepository _apiRepository; + + LoginNotifier(this._apiRepository) : super(const AsyncValue.data({})); + + Future login(String mobile) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final model = LoginModel(mobile: mobile); + final result = await _apiRepository.loginUser(model); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } + + Future verifyOtp(String mobile, String otp) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final model = LoginModel(mobile: mobile, otp: otp); + final result = await _apiRepository.verifyOtp(model); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } +} + +//signup controller +final signupProvider = + StateNotifierProvider>>( + (ref) => SignupNotifier(ref.read(apiRepositoryProvider)), + ); + +class SignupNotifier extends StateNotifier>> { + final ApiRepository _apiRepository; + + SignupNotifier(this._apiRepository) : super(const AsyncValue.data({})); + + Future signup(String name, String contactNumber, String email) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final model = SignupModel( + name: name, + contactNumber: contactNumber, + email: email, + ); + final result = await _apiRepository.signupUser(model); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } + + // Verify OTP for signup + Future verifySignupOtp(String mobile, String otp) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final result = await _apiRepository.verifySignupOtp(mobile, otp); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } + + // Reset state + void reset() { + state = const AsyncValue.data({}); + } +} + +final employeeloginProvider = + StateNotifierProvider< + EmployeeLoginNotifier, + AsyncValue> + >((ref) => EmployeeLoginNotifier(ref.read(apiRepositoryProvider))); + +class EmployeeLoginNotifier + extends StateNotifier>> { + final ApiRepository _apiRepository; + + EmployeeLoginNotifier(this._apiRepository) : super(const AsyncValue.data({})); + + Future login(String mobile) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final result = await _apiRepository.employeeLogin(mobile); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } + + Future verifyOtp(String mobile, String otp) async { + if (!mounted) return; + state = const AsyncValue.loading(); + try { + final model = LoginModel(mobile: mobile, otp: otp); + final result = await _apiRepository.verifyOtp(model); + if (mounted) state = AsyncValue.data(result); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } +} + +final termsProvider = FutureProvider((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchTermsAndConditions(); +}); +final dashboardProvider = FutureProvider((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchDashboard(); +}); + +final policyProvider = FutureProvider((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchpolicy(); +}); +final profileProvider = FutureProvider((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchProfile(); +}); +final employeeProfileProvider = FutureProvider(( + ref, +) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchEmployeeProfile(); +}); + +final serviceHistoryNotifierProvider = + StateNotifierProvider.family< + ServiceHistoryNotifier, + AsyncValue, + String + >((ref, type) { + return ServiceHistoryNotifier(ref: ref, type: type); + }); + +class ServiceHistoryNotifier + extends StateNotifier> { + final Ref ref; + final String type; + + String? fromDate; + String? toDate; + + ServiceHistoryNotifier({required this.ref, required this.type}) + : super(const AsyncValue.loading()) { + fetchServiceHistory(); + } + + Future fetchServiceHistory() async { + try { + if (!mounted) return; + state = const AsyncValue.loading(); + + final repo = ref.read(apiRepositoryProvider); + + final result = await repo.fetchServiceHistory( + type, + fromDate: fromDate, + toDate: toDate, + ); + + if (!mounted) return; + state = AsyncValue.data(result); + } catch (e, st) { + if (!mounted) return; + state = AsyncValue.error(e, st); + } + } + + // ✅ APPLY FILTER + void applyDateFilter({String? from, String? to}) { + fromDate = from; + toDate = to; + fetchServiceHistory(); + } + + // ✅ CLEAR FILTER + void clearFilter() { + fromDate = null; + toDate = null; + fetchServiceHistory(); + } + + // ✅ MANUAL REFRESH + Future refresh() async { + await fetchServiceHistory(); + } +} + +final countProvider = FutureProvider.family(( + ref, + type, +) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchCount(type); +}); +final notificationTriggerProvider = StateProvider((ref) => 0); + +// 🔥 fetch notification count API +final notificationCountProvider = + FutureProvider.autoDispose((ref) async { + ref.watch(notificationTriggerProvider); // listen for refresh trigger + + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchNotificationCount(); + }); + +final serviceDetailProvider = FutureProvider.family(( + ref, + id, +) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchServiceDetail(id); +}); +final chatDocumentProvider = FutureProvider.family(( + ref, + id, +) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchChatDocuments(id); +}); + +final serviceListProvider = FutureProvider>((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchServiceList(); +}); +final staffListProvider = FutureProvider>((ref) async { + final repo = ref.read(apiRepositoryProvider); + return await repo.fetchStaffList(); +}); +final notificationProvider = StateNotifierProvider.family + .autoDispose< + NotificationNotifier, + AsyncValue>, + int + >((ref, page) { + return NotificationNotifier(ref: ref, page: page); + }); + +// ---------------- NOTIFIER -------------------- + +class NotificationNotifier + extends StateNotifier>> { + final Ref ref; + final int page; + + NotificationNotifier({required this.ref, required this.page}) + : super(const AsyncValue.loading()) { + fetchNotifications(); + } + + Future fetchNotifications() async { + if (!mounted) return; + try { + state = const AsyncValue.loading(); + + final List notifications = await ApiRepository() + .fetchNotificationList(page: page); + + if (mounted) state = AsyncValue.data(notifications); + } catch (e, st) { + if (mounted) state = AsyncValue.error(e, st); + } + } +} + +final chatMessagesProvider = + StateNotifierProvider.family< + ChatMessagesNotifier, + AsyncValue>, + int + >((ref, chatId) { + return ChatMessagesNotifier(ref: ref, chatId: chatId); + }); + +class ChatMessagesNotifier + extends StateNotifier>> { + final Ref ref; + final int chatId; + + int _currentPage = 1; + bool _hasNextPage = true; + bool _isFetching = false; + bool _isInitialLoad = true; + + final List _messages = []; + + ChatMessagesNotifier({required this.ref, required this.chatId}) + : super(const AsyncLoading()) { + loadMessages(); + } + + /// ⭐ Getter to expose hasNextPage + bool get hasNextPage => _hasNextPage; + + /// Load paginated messages (used for scroll pagination) + Future loadMessages() async { + if (_isFetching || !_hasNextPage || !mounted) return; + + _isFetching = true; + + try { + print("📥 Loading page $_currentPage for chat $chatId"); + + final result = await ref + .read(apiRepositoryProvider) + .fetchChatMessages(chatId: chatId, page: _currentPage); + + if (result.isEmpty) { + print("✅ No more messages - pagination complete"); + _hasNextPage = false; + } else { + print("✅ Loaded ${result.length} messages from page $_currentPage"); + + if (_isInitialLoad) { + // ⭐ FIX: On initial load, sort messages in ascending order (oldest first, newest last) + result.sort((a, b) { + final dateA = + DateTime.tryParse(a.createdAt ?? '') ?? DateTime(1970); + final dateB = + DateTime.tryParse(b.createdAt ?? '') ?? DateTime(1970); + return dateA.compareTo(dateB); + }); + _messages.clear(); + _messages.addAll(result); + } else { + // ⭐ FIX: On pagination load, insert older messages at beginning + // Make sure pagination result is sorted in ascending order + result.sort((a, b) { + final dateA = + DateTime.tryParse(a.createdAt ?? '') ?? DateTime(1970); + final dateB = + DateTime.tryParse(b.createdAt ?? '') ?? DateTime(1970); + return dateA.compareTo(dateB); + }); + _messages.insertAll(0, result); + } + + _currentPage++; + if (mounted) state = AsyncData(List.from(_messages)); + } + + if (_isInitialLoad && result.isNotEmpty) { + _isInitialLoad = false; + } + } catch (e, st) { + print("❌ Error loading messages: $e"); + if (mounted) state = AsyncError(e, st); + } finally { + _isFetching = false; + } + } + + /// ⭐ Refresh chat (pull to refresh or after sending message) + /// This is a SMOOTH refresh that doesn't show loading screen + Future refresh() async { + print("🔄 Refreshing chat..."); + + try { + // ⭐ Get the latest messages from page 1 + final result = await ref + .read(apiRepositoryProvider) + .fetchChatMessages(chatId: chatId, page: 1); + + if (result.isNotEmpty) { + // Sort in ascending order + result.sort((a, b) { + final dateA = DateTime.tryParse(a.createdAt ?? '') ?? DateTime(1970); + final dateB = DateTime.tryParse(b.createdAt ?? '') ?? DateTime(1970); + return dateA.compareTo(dateB); + }); + + // ⭐ Check if we have any new messages + final lastMessageId = _messages.isNotEmpty ? _messages.last.id : -1; + final latestMessageId = result.last.id; + + if (latestMessageId != lastMessageId) { + // ⭐ New messages found - merge them smoothly + print("✅ Found new messages, updating list"); + + // Add only new messages that don't exist in current list + for (var newMsg in result) { + final exists = _messages.any((m) => m.id == newMsg.id); + if (!exists) { + _messages.add(newMsg); + } + } + + // Sort the entire list + _messages.sort((a, b) { + final dateA = + DateTime.tryParse(a.createdAt ?? '') ?? DateTime(1970); + final dateB = + DateTime.tryParse(b.createdAt ?? '') ?? DateTime(1970); + return dateA.compareTo(dateB); + }); + + if (mounted) state = AsyncData(List.from(_messages)); + } else { + print("✅ No new messages"); + } + } + } catch (e) { + print("❌ Error refreshing: $e"); + // Don't throw error, just continue with existing messages + } + } + + /// ⭐ Hard refresh (for pull to refresh gesture) + Future hardRefresh() async { + print("🔄 Hard refreshing chat..."); + _currentPage = 1; + _hasNextPage = true; + _messages.clear(); + _isInitialLoad = true; + if (mounted) state = const AsyncLoading(); + await loadMessages(); + } + + /// Add new message to list (socket or send API) + void addNewMessage(MessageModel msg) { + print("➕ Adding new message: ${msg.message} (ID: ${msg.id})"); + + // ⭐ DEDUPLICATION: Avoid adding the same message twice + // 1. Check if ID already exists + final existingIndex = _messages.indexWhere((m) => m.id == msg.id); + if (existingIndex != -1) { + print("♻️ Message ID ${msg.id} already exists, updating instead"); + _messages[existingIndex] = msg; + if (mounted) state = AsyncData(List.from(_messages)); + return; + } + + // 2. Check if this is a server confirmation of an optimistic message + // Optimistic messages have large positive IDs from DateTime.now().millisecondsSinceEpoch + // OR content match for very recent messages + final optimisticIndex = _messages.indexWhere( + (m) => + // Match by content and sender if it's a very recent "local" message + (m.id > 1000000000000 && + m.message == msg.message && + m.chatBy == msg.chatBy), + ); + + if (optimisticIndex != -1) { + print("🔄 Replacing optimistic message with server version"); + _messages[optimisticIndex] = msg; + } else { + // ⭐ Add at the END (newest messages at bottom) + _messages.add(msg); + } + + if (mounted) state = AsyncData(List.from(_messages)); + } + + /// Update existing message (e.g., delivery status, read status) + void updateMessage(MessageModel updatedMsg) { + final index = _messages.indexWhere((m) => m.id == updatedMsg.id); + if (index != -1) { + _messages[index] = updatedMsg; + if (mounted) state = AsyncData(List.from(_messages)); + } + } + + /// Delete a message + void deleteMessage(int messageId) { + _messages.removeWhere((m) => m.id == messageId); + if (mounted) state = AsyncData(List.from(_messages)); + } +} + +// ✅ Provider for fetching both country and state data +final countryAndStatesProvider = FutureProvider((ref) async { + final repo = ref.read(apiRepositoryProvider); + try { + final model = await repo.fetchCountryAndStates(ConstsApi.conturystate); + ref.keepAlive(); // Keep cached until manually disposed + return model; + } catch (e) { + print('❌ Error in countryAndStatesProvider: $e'); + throw e; + } +}); +final fetchCityProvider = FutureProvider.family(( + ref, + stateId, +) async { + final repo = ref.read(apiRepositoryProvider); + try { + final cityModel = await repo.fetchCityByState(ConstsApi.city, stateId); + ref.keepAlive(); + return cityModel; + } catch (e) { + print('❌ Error in fetchCityProvider: $e'); + throw e; + } +}); diff --git a/lib/controller/api_repository.dart b/lib/controller/api_repository.dart new file mode 100644 index 0000000..2ff9546 --- /dev/null +++ b/lib/controller/api_repository.dart @@ -0,0 +1,1143 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:http/http.dart' as http; +import 'package:path/path.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/controller/api_consts.dart'; +import 'package:taxglide/model/chat_model.dart'; +import 'package:taxglide/model/chat_profile_model.dart'; +import 'package:taxglide/model/city_model.dart'; +import 'package:taxglide/model/count_model.dart'; +import 'package:taxglide/model/country_model.dart'; +import 'package:taxglide/model/dash_board_model.dart'; +import 'package:taxglide/model/detail_model.dart'; +import 'package:taxglide/model/employeeprofile_model.dart'; +import 'package:taxglide/model/login_model.dart'; +import 'package:taxglide/model/notification_model.dart'; +import 'package:taxglide/model/notificationcount_model.dart'; +import 'package:taxglide/model/profile_get_model.dart'; +import 'package:taxglide/model/serivce_list_model.dart'; +import 'package:taxglide/model/service_list_history_model.dart'; +import 'package:taxglide/model/signup_model.dart'; +import 'package:taxglide/model/staff_model.dart'; +import 'package:taxglide/model/terms_model.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class ApiRepository { + final LocalStore _localStore = LocalStore(); + final FirebaseMessaging _messaging = FirebaseMessaging.instance; + + // 🔹 Common headers without token (for login/signup) + Map get _baseHeaders => { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + }; + + // 🔹 Authorized headers with token + Future> _authorizedHeaders() async { + final token = await _localStore.getToken(); + return { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + 'Accept': 'application/json', + }; + } + + /// 🔑 Get fresh FCM token on-demand (not from storage) + Future _getFreshFcmToken() async { + try { + debugPrint('🔄 Generating fresh FCM token...'); + final token = await _messaging.getToken(); + debugPrint('✅ FCM Token generated: $token'); + return token; + } catch (e) { + debugPrint('❌ Error getting FCM token: $e'); + return null; + } + } + + Future> _regenerateFcmToken() async { + try { + // 📌 Print old token BEFORE deleting + final oldToken = await _messaging.getToken(); + debugPrint('📋 OLD FCM Token (before delete): $oldToken'); + + debugPrint('🔄 Deleting old FCM token...'); + + // Delete the current token + await _messaging.deleteToken(); + debugPrint('🗑️ Old FCM token deleted'); + + // Wait for Firebase to process the deletion + await Future.delayed(const Duration(milliseconds: 800)); + + // Request permission again (important for iOS) + await _messaging.requestPermission(); + + // Generate new tokens + debugPrint('🔄 Requesting new tokens...'); + final newToken = await _messaging.getToken(); + final apnsToken = await _messaging.getAPNSToken(); + + debugPrint('✅ NEW FCM Token: $newToken'); + debugPrint('✅ NEW APNS Token: $apnsToken'); + + // Compare tokens + if (oldToken == newToken) { + debugPrint('⚠️ WARNING: Old and New tokens are SAME!'); + } else { + debugPrint('✅ SUCCESS: New token is DIFFERENT from old token'); + } + + return {'fcm_token': newToken, 'apns_token': apnsToken}; + } catch (e) { + debugPrint('❌ Error regenerating tokens: $e'); + return {'fcm_token': null, 'apns_token': null}; + } + } + + // 🔐 Centralized token expiry handler + Future _handleUnauthorized() async { + debugPrint('🔐 Token expired - Auto logout'); + await _localStore.clearAll(); + Get.offAllNamed(ConstRouters.login); + Get.snackbar( + 'Session Expired', + 'Please login again', + snackPosition: SnackPosition.BOTTOM, + backgroundColor: Colors.red, + colorText: Colors.white, + duration: const Duration(seconds: 3), + ); + } + + // 🔹 Wrapper to handle token expiry for all authenticated requests + Future _makeAuthenticatedRequest( + Future Function() request, + ) async { + try { + final response = await request(); + + if (response.statusCode == 401 || response.statusCode == 403) { + await _handleUnauthorized(); + throw Exception('Unauthorized - Token expired'); + } + + return response; + } catch (e) { + rethrow; + } + } + + // 🔹 LOGIN API - sends OTP + Future> loginUser(LoginModel model) async { + try { + final params = model.toJsonMobile(); + final uri = Uri.parse(ConstsApi.login).replace( + queryParameters: params.map( + (key, value) => MapEntry(key, value.toString()), + ), + ); + + final response = await http.post(uri, headers: _baseHeaders); + final data = jsonDecode(response.body); + + if (response.statusCode == 200 || response.statusCode == 201) { + return {'success': true, 'data': data}; + } else { + return {'success': false, 'error': _extractErrorMessage(data)}; + } + } catch (e) { + return { + 'success': false, + 'error': 'Connection error. Please check your internet.', + }; + } + } + + // 🔹 VERIFY OTP (LOGIN) - ✅ Regenerates FCM token + Future> verifyOtp(LoginModel model) async { + try { + final params = model.toJsonOtp(); + + // ✅ Regenerate FCM and APNS tokens on every login + final tokens = await _regenerateFcmToken(); + final fcmToken = tokens['fcm_token']; + final apnsToken = tokens['apns_token']; + + if (fcmToken != null && fcmToken.isNotEmpty) { + params['fcm_token'] = fcmToken; + } + if (apnsToken != null && apnsToken.isNotEmpty) { + params['apns_token'] = apnsToken; + } + + if (params['fcm_token'] == null) { + debugPrint('⚠️ Failed to generate FCM token, trying fallback...'); + final fallbackToken = await _getFreshFcmToken(); + if (fallbackToken != null && fallbackToken.isNotEmpty) { + params['fcm_token'] = fallbackToken; + } + } + + final uri = Uri.parse(ConstsApi.verifyOtp).replace( + queryParameters: params.map( + (key, value) => MapEntry(key, value.toString()), + ), + ); + + final response = await http.post(uri, headers: _baseHeaders); + final data = jsonDecode(response.body); + + if (response.statusCode == 200 || response.statusCode == 201) { + await _localStore.saveLoginData(data); + return {'success': true, 'data': data}; + } else { + return {'success': false, 'error': _extractErrorMessage(data)}; + } + } catch (e) { + return { + 'success': false, + 'error': 'Connection error. Please check your internet.', + }; + } + } + + // 🔹 EMPLOYEE LOGIN + Future> employeeLogin(String mobile) async { + try { + final uri = Uri.parse( + ConstsApi.employeelogin, + ).replace(queryParameters: {'mobile': mobile}); + + final response = await http.post(uri, headers: _baseHeaders); + final data = jsonDecode(response.body); + + if (response.statusCode == 200 || response.statusCode == 201) { + return {'success': true, 'data': data}; + } else { + return {'success': false, 'error': _extractErrorMessage(data)}; + } + } catch (e) { + return { + 'success': false, + 'error': 'Connection error. Please check your internet.', + }; + } + } + + // 🔹 SIGNUP API + Future> signupUser(SignupModel model) async { + try { + final params = model.toJson(); + final uri = Uri.parse(ConstsApi.signup).replace( + queryParameters: params.map( + (key, value) => MapEntry(key, value.toString()), + ), + ); + + final response = await http.post(uri, headers: _baseHeaders); + final data = jsonDecode(response.body); + + if (response.statusCode == 200 || response.statusCode == 201) { + return {'success': true, 'data': data}; + } else { + return {'success': false, 'error': _extractErrorMessage(data)}; + } + } catch (e) { + return { + 'success': false, + 'error': 'Connection error. Please check your internet.', + }; + } + } + + // 🔹 VERIFY OTP (SIGNUP) - ✅ Regenerates FCM token + Future> verifySignupOtp( + String mobile, + String otp, + ) async { + try { + // ✅ Regenerate FCM and APNS tokens on signup + final tokens = await _regenerateFcmToken(); + final fcmToken = tokens['fcm_token']; + final apnsToken = tokens['apns_token']; + + final params = {'mobile': mobile, 'otp': otp}; + + if (fcmToken != null && fcmToken.isNotEmpty) { + params['fcm_token'] = fcmToken; + } + if (apnsToken != null && apnsToken.isNotEmpty) { + params['apns_token'] = apnsToken; + } + + if (params['fcm_token'] == null) { + debugPrint('⚠️ Failed to generate FCM token, trying fallback...'); + final fallbackToken = await _getFreshFcmToken(); + if (fallbackToken != null && fallbackToken.isNotEmpty) { + params['fcm_token'] = fallbackToken; + } + } + + final uri = Uri.parse( + ConstsApi.verifyOtp, + ).replace(queryParameters: params); + + final response = await http.post(uri, headers: _baseHeaders); + final data = jsonDecode(response.body); + + if (response.statusCode == 200 || response.statusCode == 201) { + await _localStore.saveLoginData(data); + return {'success': true, 'data': data}; + } else { + return {'success': false, 'error': _extractErrorMessage(data)}; + } + } catch (e) { + return { + 'success': false, + 'error': 'Connection error. Please check your internet.', + }; + } + } + + // 🔹 FETCH TERMS & CONDITIONS + Future fetchTermsAndConditions() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.terms), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return TermsModel.fromJson(data); + } else { + throw Exception('Failed to fetch terms and conditions'); + } + } + + // 🔹 FETCH DASHBOARD + Future fetchDashboard() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.dashboard), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return DashBoardModel.fromJson(data); + } else { + throw Exception('Failed to fetch dashboard'); + } + } + + // 🔹 FETCH POLICY + Future fetchpolicy() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.policy), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return TermsModel.fromJson(data); + } else { + throw Exception('Failed to fetch Policy'); + } + } + + // 🔹 FETCH PROFILE + Future fetchProfile() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.getprofile), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return ProfileGetModel.fromJson(data); + } else { + throw Exception('Failed to fetch Profile'); + } + } + + // 🔹 FETCH EMPLOYEE PROFILE + Future fetchEmployeeProfile() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.getprofile), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return EmployeeProfileModel.fromJson(data); + } else { + throw Exception('Failed to fetch Employee Profile'); + } + } + + // 🔹 FETCH SERVICE HISTORY + Future fetchServiceHistory( + String type, { + String? fromDate, + String? toDate, + }) async { + final uri = Uri.parse(ConstsApi.serivcehistory).replace( + queryParameters: { + 'type': type, + if (fromDate != null) 'from_date': fromDate, + if (toDate != null) 'to_date': toDate, + }, + ); + + final response = await _makeAuthenticatedRequest(() async { + return await http.get(uri, headers: await _authorizedHeaders()); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return ServiceListHistoryModel.fromJson(data); + } else { + throw Exception('Failed to fetch Service History'); + } + } + + // 🔹 FETCH COUNT + Future fetchCount(String type) async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse("${ConstsApi.count}?chat_id=$type"), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return CountModel.fromJson(data); + } else { + throw Exception('Failed to fetch count'); + } + } + + // 🔹 FETCH NOTIFICATION COUNT + Future fetchNotificationCount() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.notificationcount), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return NotificationCountModel.fromJson(data); + } else { + throw Exception('Failed to fetch notification count'); + } + } + + // 🔹 FETCH SERVICE DETAIL + Future fetchServiceDetail(int id) async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse("${ConstsApi.serivcedetails}?service_request_id=$id"), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return DetailModel.fromJson(data); + } else { + throw Exception('Failed to fetch Service Detail'); + } + } + + // 🔹 FETCH CHAT DOCUMENTS + Future fetchChatDocuments(int id) async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse("${ConstsApi.chatdocument}?chat_id=$id"), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + return ChatProfileModel.fromJson(data); + } else { + throw Exception('Failed to fetch Chat Documents'); + } + } + + // 🔹 FETCH SERVICE LIST + Future> fetchServiceList() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.serivcelist), + headers: await _authorizedHeaders(), + ); + }); + + debugPrint("📡 Status Code: ${response.statusCode}"); + debugPrint("📡 Response: ${response.body}"); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final List list = data['data'] ?? []; + return list.map((e) => ServiceListModel.fromJson(e)).toList(); + } + + throw Exception('Failed to fetch service list'); + } + + // 🔹 FETCH STAFF LIST + Future> fetchStaffList() async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(ConstsApi.stafflist), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final List list = data['data'] ?? []; + return list.map((e) => StaffModel.fromJson(e)).toList(); + } else { + throw Exception('Failed to fetch staff list'); + } + } + + // 🔹 FETCH NOTIFICATION LIST + Future> fetchNotificationList({ + required int page, + }) async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse("${ConstsApi.notificationList}?page=$page"), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final List list = data['data'] ?? []; + return list.map((e) => NotificationModel.fromJson(e)).toList(); + } else { + throw Exception('Failed to fetch notifications'); + } + } + + // 🔹 FETCH CHAT MESSAGES + Future> fetchChatMessages({ + required int chatId, + required int page, + }) async { + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse("${ConstsApi.chatList}/$chatId/messages?page=$page"), + headers: await _authorizedHeaders(), + ); + }); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final messages = data["messages"]["data"] ?? []; + return List.from( + messages.map((e) => MessageModel.fromJson(e)), + ); + } else { + throw Exception("Failed to fetch chat messages → ${response.statusCode}"); + } + } + + // 🔹 FETCH COUNTRY AND STATES + Future fetchCountryAndStates(String url) async { + try { + debugPrint('🌐 Fetching Country & States from: $url'); + + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(url), + headers: await _authorizedHeaders(), + ); + }); + + debugPrint('📡 API Status: ${response.statusCode}'); + debugPrint('📡 API Body: ${response.body}'); + + if (response.statusCode == 200) { + final jsonBody = jsonDecode(response.body); + final model = CountryModel.fromJson(jsonBody); + debugPrint( + '✅ Countries: ${model.countriesData?.length ?? 0}, States: ${model.statesData?.length ?? 0}', + ); + return model; + } else { + final error = jsonDecode(response.body); + throw Exception(error['message'] ?? 'Failed to fetch data'); + } + } catch (e) { + debugPrint('❌ fetchCountryAndStates Error: $e'); + throw Exception('Error fetching country & state data: $e'); + } + } + + // 🔹 FETCH CITY BY STATE + Future fetchCityByState(String url, int stateId) async { + try { + final fullUrl = "$url?state_id=$stateId"; + debugPrint('🌐 Fetching Cities (Districts) from: $fullUrl'); + + final response = await _makeAuthenticatedRequest(() async { + return await http.get( + Uri.parse(fullUrl), + headers: await _authorizedHeaders(), + ); + }); + + debugPrint('📡 City API Status: ${response.statusCode}'); + debugPrint('📡 City API Body: ${response.body}'); + + if (response.statusCode == 200) { + final jsonBody = jsonDecode(response.body); + final model = CityModel.fromJson(jsonBody); + debugPrint('✅ Districts fetched: ${model.districtsData?.length ?? 0}'); + return model; + } else { + final error = jsonDecode(response.body); + throw Exception(error['message'] ?? 'Failed to fetch city data'); + } + } catch (e) { + debugPrint('❌ fetchCityByState Error: $e'); + throw Exception('Error fetching city data: $e'); + } + } + + // 🔹 KYC FORM UPDATE + Future kycFormUpdate({ + File? logo, + File? panFile, + File? gstFile, + File? incorporationFile, + required int countryId, + required int stateId, + required int cityId, + required String companyPincode, + required String companyAddress, + required String panNumber, + required String gstNumber, + required String tanNumber, + required String cinNumber, + required String yearOfIncorporation, + required String address, + }) async { + try { + final token = await _localStore.getToken(); + final uri = Uri.parse(ConstsApi.kycupdate); + + var request = http.MultipartRequest('POST', uri) + ..headers.addAll({ + 'Authorization': 'Bearer $token', + 'Accept': 'application/json', + 'Connection': 'keep-alive', + }) + ..fields.addAll({ + 'country_id': countryId.toString(), + 'state_id': stateId.toString(), + 'district_id': cityId.toString(), + 'company_pincode': companyPincode, + 'company_address': companyAddress, + 'pan_number': panNumber, + 'gst_number': gstNumber, + 'tan_number': tanNumber, + 'cin': cinNumber, + 'year_of_incorporation': yearOfIncorporation, + 'address': address, + }); + + await Future.wait([ + _addFileIfExists(request, logo, 'logo'), + _addFileIfExists(request, panFile, 'pan_file'), + _addFileIfExists(request, gstFile, 'gst_file'), + _addFileIfExists(request, incorporationFile, 'incorporation_file'), + ]); + + final streamedResponse = await request.send().timeout( + const Duration(seconds: 60), + onTimeout: () { + throw TimeoutException('Request timed out after 60 seconds'); + }, + ); + + final response = await http.Response.fromStream(streamedResponse); + + // Handle token expiry + if (response.statusCode == 401 || response.statusCode == 403) { + await _handleUnauthorized(); + throw Exception('Unauthorized - Token expired'); + } + + if (response.statusCode == 200) { + debugPrint('✅ KYC update success'); + return; + } + + final decoded = _safeJsonDecode(response.body); + + if (response.statusCode == 422) { + throw _formatValidationErrors(decoded); + } else { + final message = + decoded?['message'] ?? decoded?['error'] ?? 'Something went wrong'; + throw {'error': message.toString()}; + } + } on SocketException { + throw {'error': 'No internet connection. Please check your network.'}; + } on TimeoutException { + throw {'error': 'Request timed out. Please try again.'}; + } on FormatException { + throw {'error': 'Invalid server response. Please try again.'}; + } catch (e) { + if (e is Map) rethrow; + debugPrint('❌ KYC update error: $e'); + throw {'error': 'Failed to update KYC: ${e.toString()}'}; + } + } + + // 🔹 SEND CHAT MESSAGE + Future sendChatMessage({ + required int chatId, + required String messages, + int? tagId, + List? files, + }) async { + try { + final token = await _localStore.getToken(); + final uri = Uri.parse(ConstsApi.sendChatMessage); + + var request = http.MultipartRequest('POST', uri) + ..headers.addAll({ + 'Authorization': 'Bearer $token', + 'Accept': 'application/json', + }) + ..fields.addAll({'chat_id': chatId.toString(), 'message': messages}); + + if (tagId != null && tagId > 0) { + request.fields['tag_id'] = tagId.toString(); + } + + if (files != null && files.isNotEmpty) { + for (int i = 0; i < files.length; i++) { + request.files.add( + await http.MultipartFile.fromPath( + 'file[$i]', + files[i].path, + filename: files[i].path.split('/').last, + ), + ); + } + } + + final streamedResponse = await request.send(); + final response = await http.Response.fromStream(streamedResponse); + + // Handle token expiry + if (response.statusCode == 401 || response.statusCode == 403) { + await _handleUnauthorized(); + throw Exception('Unauthorized - Token expired'); + } + + final decoded = _safeJsonDecode(response.body); + + if (response.statusCode == 200) { + debugPrint("✅ Chat message sent successfully"); + return; + } + + if (response.statusCode == 422) { + throw _formatValidationErrors(decoded); + } else { + final message = + decoded?['message'] ?? decoded?['error'] ?? 'Something went wrong'; + throw {'error': message.toString()}; + } + } catch (e) { + debugPrint('❌ Chat send error: $e'); + if (e is Map) rethrow; + throw {'error': 'Failed to send message: ${e.toString()}'}; + } + } + + // 🔹 UPDATE SERVICE REQUEST + Future updateServiceRequest({ + required int serviceId, + required String message, + List? documents, + }) async { + try { + final token = await _localStore.getToken(); + final uri = Uri.parse(ConstsApi.serivcerequest); + + var request = http.MultipartRequest('POST', uri) + ..headers.addAll({ + 'Authorization': 'Bearer $token', + 'Accept': 'application/json', + 'Connection': 'keep-alive', + }) + ..fields.addAll({ + 'service_id': serviceId.toString(), + 'message': message, + }); + + if (documents != null && documents.isNotEmpty) { + for (int i = 0; i < documents.length; i++) { + final file = documents[i]; + final fileName = file.path.split('/').last; + request.files.add( + await http.MultipartFile.fromPath( + 'documents[$i]', + file.path, + filename: fileName, + ), + ); + } + } + + final streamedResponse = await request.send().timeout( + const Duration(seconds: 60), + onTimeout: () { + throw TimeoutException('Request timed out after 60 seconds'); + }, + ); + + final response = await http.Response.fromStream(streamedResponse); + + // Handle token expiry + if (response.statusCode == 401 || response.statusCode == 403) { + await _handleUnauthorized(); + throw Exception('Unauthorized - Token expired'); + } + + if (response.statusCode == 200) { + debugPrint('✅ Service request updated successfully'); + return; + } + + final decoded = _safeJsonDecode(response.body); + if (response.statusCode == 422) { + throw _formatValidationErrors(decoded); + } else { + final message = + decoded?['message'] ?? decoded?['error'] ?? 'Something went wrong'; + throw {'error': message.toString()}; + } + } on SocketException { + throw {'error': 'No internet connection. Please check your network.'}; + } on TimeoutException { + throw {'error': 'Request timed out. Please try again.'}; + } on FormatException { + throw {'error': 'Invalid server response. Please try again.'}; + } catch (e) { + if (e is Map) rethrow; + debugPrint('❌ Service request update error: $e'); + throw {'error': 'Failed to update service request: ${e.toString()}'}; + } + } + + Future proformaaccept({required int proformaId}) async { + try { + final token = await _localStore.getToken(); + final uri = Uri.parse(ConstsApi.proformaaccept); + + var request = http.MultipartRequest('POST', uri) + ..headers.addAll({ + 'Authorization': 'Bearer $token', + 'Accept': 'application/json', + 'Connection': 'keep-alive', + }) + ..fields.addAll({ + 'id': proformaId.toString(), // ✅ FIXED + }); + + final streamedResponse = await request.send().timeout( + const Duration(seconds: 60), + onTimeout: () { + throw TimeoutException('Request timed out after 60 seconds'); + }, + ); + + final response = await http.Response.fromStream(streamedResponse); + + if (response.statusCode == 401 || response.statusCode == 403) { + await _handleUnauthorized(); + throw Exception('Unauthorized - Token expired'); + } + + if (response.statusCode == 200) { + debugPrint('✅ Proforma accepted successfully'); + return; + } + + final decoded = _safeJsonDecode(response.body); + if (response.statusCode == 422) { + throw _formatValidationErrors(decoded); + } else { + final message = + decoded?['message'] ?? decoded?['error'] ?? 'Something went wrong'; + throw {'error': message.toString()}; + } + } on SocketException { + throw {'error': 'No internet connection. Please check your network.'}; + } on TimeoutException { + throw {'error': 'Request timed out. Please try again.'}; + } on FormatException { + throw {'error': 'Invalid server response. Please try again.'}; + } catch (e) { + if (e is Map) rethrow; + debugPrint('❌ Proforma accept error: $e'); + throw {'error': 'Failed to accept proforma: ${e.toString()}'}; + } + } + + // 🔹 LOGOUT - ✅ Deletes FCM token + Future logout() async { + try { + final token = await _localStore.getToken(); + + if (token == null || token.isEmpty) { + debugPrint('⚠️ No token found — clearing data and deleting FCM token'); + await _messaging.deleteToken(); + await _localStore.clearAll(keepFcm: false); + return; + } + + final uri = Uri.parse(ConstsApi.logout); + debugPrint('📡 Logging out from: $uri'); + + final request = http.Request('POST', uri) + ..headers.addAll({ + 'Authorization': 'Bearer $token', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Connection': 'keep-alive', + }); + + final streamedResponse = await request.send().timeout( + const Duration(seconds: 30), + onTimeout: () => + throw TimeoutException('Logout request timed out after 30 seconds'), + ); + + final response = await http.Response.fromStream(streamedResponse); + + debugPrint('📡 Logout Status Code: ${response.statusCode}'); + debugPrint('📦 Logout Body: ${response.body}'); + + final decoded = _safeJsonDecode(response.body); + + if (response.statusCode == 200) { + final message = decoded?['message'] ?? 'Logout successful'; + debugPrint('✅ $message'); + } else if (response.statusCode == 401) { + debugPrint('⚠️ Token expired or unauthorized. Clearing storage.'); + } else { + final message = decoded?['message'] ?? 'Logout failed'; + debugPrint('⚠️ $message'); + } + } on SocketException { + debugPrint('❌ No internet connection'); + } on TimeoutException { + debugPrint('❌ Request timed out'); + } catch (e, stack) { + debugPrint('❌ Logout error: $e'); + debugPrint('🧩 Stack trace: $stack'); + } finally { + // ✅ ALWAYS delete FCM token and clear data on logout + try { + debugPrint('🗑️ Deleting FCM token on logout...'); + await _messaging.deleteToken(); + debugPrint('✅ FCM token deleted successfully'); + } catch (e) { + debugPrint('⚠️ Error deleting FCM token: $e'); + } + + await _localStore.clearAll(keepFcm: false); + debugPrint('✅ Local storage cleared'); + } + } + + // Helper methods remain the same... + Map? _safeJsonDecode(String body) { + try { + return jsonDecode(body) as Map?; + } catch (e) { + debugPrint('⚠️ JSON decode error: $e'); + return null; + } + } + + String _extractErrorMessage( + dynamic data, [ + String defaultMsg = 'Operation failed', + ]) { + if (data is! Map) return defaultMsg; + + if (data['status'] == 'error') { + if (data['errors'] is Map) { + final errors = data['errors'] as Map; + final firstErrorKey = errors.keys.first; + final errorList = errors[firstErrorKey]; + + if (errorList is List && errorList.isNotEmpty) { + return errorList.first.toString(); + } else if (errorList is String) { + return errorList; + } + } else if (data['errors'] is List && + (data['errors'] as List).isNotEmpty) { + final firstError = (data['errors'] as List).first; + if (firstError is String) { + return firstError; + } else if (firstError is Map && firstError['message'] != null) { + return firstError['message']; + } + } + } + + return data['message'] ?? + data['error'] ?? + data['msg'] ?? + data['detail'] ?? + defaultMsg; + } + + // Additional helper methods (fetchProfile, fetchServiceHistory, etc.) remain unchanged + // ... (include all other methods from your original code) +} + +// 🔹 HELPER: Add file if exists +Future _addFileIfExists( + http.MultipartRequest request, + File? file, + String fieldName, +) async { + if (file == null) return; + + try { + if (!file.existsSync()) { + debugPrint('⚠️ File not found: ${file.path}'); + return; + } + + request.files.add( + await http.MultipartFile.fromPath( + fieldName, + file.path, + filename: basename(file.path), + ), + ); + } catch (e) { + debugPrint('⚠️ Error adding file $fieldName: $e'); + } +} + +// // 🔹 HELPER: Safe JSON decode +// Map? _safeJsonDecode(String body) { +// try { +// return jsonDecode(body) as Map?; +// } catch (e) { +// debugPrint('⚠️ JSON decode error: $e'); +// return null; +// } +// } + +// // 🔹 HELPER: Extract error message from API response +// String _extractErrorMessage( +// dynamic data, [ +// String defaultMsg = 'Operation failed', +// ]) { +// if (data is! Map) return defaultMsg; + +// // Check if status is error +// if (data['status'] == 'error') { +// // Handle errors object with field-specific errors +// if (data['errors'] is Map) { +// final errors = data['errors'] as Map; +// final firstErrorKey = errors.keys.first; +// final errorList = errors[firstErrorKey]; + +// if (errorList is List && errorList.isNotEmpty) { +// return errorList.first.toString(); +// } else if (errorList is String) { +// return errorList; +// } +// } +// // Handle errors as List +// else if (data['errors'] is List && (data['errors'] as List).isNotEmpty) { +// final firstError = (data['errors'] as List).first; +// if (firstError is String) { +// return firstError; +// } else if (firstError is Map && firstError['message'] != null) { +// return firstError['message']; +// } +// } +// } + +// // Fallback to other common error formats +// return data['message'] ?? +// data['error'] ?? +// data['msg'] ?? +// data['detail'] ?? +// defaultMsg; +// } + +// 🔹 HELPER: Format validation errors +Map _formatValidationErrors(Map? decoded) { + if (decoded == null) return {'error': 'Validation failed'}; + + final rawErrors = + (decoded['errors'] ?? decoded['error'] ?? {}) as Map; + + final Map formattedErrors = {}; + + rawErrors.forEach((key, value) { + if (value is List && value.isNotEmpty) { + formattedErrors[key] = value.first.toString(); + } else if (value is String) { + formattedErrors[key] = value; + } else { + formattedErrors[key] = 'Invalid input'; + } + }); + + return formattedErrors.isNotEmpty + ? formattedErrors + : {'error': 'Validation failed'}; +} + +// ⚡ Optimized HTTP Client for better performance +class OptimizedHttpClient { + static final http.Client _client = http.Client(); + + static http.Client get client => _client; + + static void dispose() { + _client.close(); + } +} diff --git a/lib/firebase_options.dart b/lib/firebase_options.dart new file mode 100644 index 0000000..c39f6b8 --- /dev/null +++ b/lib/firebase_options.dart @@ -0,0 +1,88 @@ +// File generated by FlutterFire CLI. +// ignore_for_file: type=lint +import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, kIsWeb, TargetPlatform; + +/// Default [FirebaseOptions] for use with your Firebase apps. +/// +/// Example: +/// ```dart +/// import 'firebase_options.dart'; +/// // ... +/// await Firebase.initializeApp( +/// options: DefaultFirebaseOptions.currentPlatform, +/// ); +/// ``` +class DefaultFirebaseOptions { + static FirebaseOptions get currentPlatform { + if (kIsWeb) { + return web; + } + switch (defaultTargetPlatform) { + case TargetPlatform.android: + return android; + case TargetPlatform.iOS: + return ios; + case TargetPlatform.macOS: + return macos; + case TargetPlatform.windows: + return windows; + case TargetPlatform.linux: + throw UnsupportedError( + 'DefaultFirebaseOptions have not been configured for linux - ' + 'you can reconfigure this by running the FlutterFire CLI again.', + ); + default: + throw UnsupportedError( + 'DefaultFirebaseOptions are not supported for this platform.', + ); + } + } + + static const FirebaseOptions web = FirebaseOptions( + apiKey: 'AIzaSyCSsZ4AGPvVs1wzpGFe5QL62bvPc4ki6E0', + appId: '1:355745714219:web:45eae1bcbd26aee5815a6e', + messagingSenderId: '355745714219', + projectId: 'taxglide-bd535', + authDomain: 'taxglide-bd535.firebaseapp.com', + storageBucket: 'taxglide-bd535.firebasestorage.app', + measurementId: 'G-2VQB1FS2MV', + ); + + static const FirebaseOptions android = FirebaseOptions( + apiKey: 'AIzaSyAfTUgCMmhunZci93dqMuoeGvC5r8NpdhM', + appId: '1:600746935622:android:9c98f0c1dd408b19cad147', + messagingSenderId: '600746935622', + projectId: 'auditpro-16b14', + storageBucket: 'auditpro-16b14.firebasestorage.app', + ); + + static const FirebaseOptions ios = FirebaseOptions( + apiKey: 'AIzaSyBnljOambzS0DdbRuDr6tvBBGvK24jEy3E', + appId: '1:600746935622:ios:b8c6feb054815581cad147', + messagingSenderId: '600746935622', + projectId: 'auditpro-16b14', + storageBucket: 'auditpro-16b14.firebasestorage.app', + iosBundleId: 'com.amrithaa.taxglide', + ); + + static const FirebaseOptions macos = FirebaseOptions( + apiKey: 'AIzaSyCKZwHVfE0Ih5kSUx-mOD25F2tAFeAL18w', + appId: '1:355745714219:ios:4948c6a82d1b7570815a6e', + messagingSenderId: '355745714219', + projectId: 'taxglide-bd535', + storageBucket: 'taxglide-bd535.firebasestorage.app', + iosBundleId: 'com.amrithaa.taxglide', + ); + + static const FirebaseOptions windows = FirebaseOptions( + apiKey: 'AIzaSyCSsZ4AGPvVs1wzpGFe5QL62bvPc4ki6E0', + appId: '1:355745714219:web:1d46121a7639ff32815a6e', + messagingSenderId: '355745714219', + projectId: 'taxglide-bd535', + authDomain: 'taxglide-bd535.firebaseapp.com', + storageBucket: 'taxglide-bd535.firebasestorage.app', + measurementId: 'G-14E4NG37P2', + ); +} \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..744ad4a --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,239 @@ +import 'dart:io'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:permission_handler/permission_handler.dart'; + +import 'firebase_options.dart'; +import 'package:taxglide/router/router.dart'; +import 'package:taxglide/services/notification_service.dart'; + +final GlobalKey rootScaffoldMessengerKey = + GlobalKey(); + +/// --------------------------------------------------------------------------- +/// 🚨 BACKGROUND HANDLER - Must be top-level function (outside main) +/// This handles notifications when app is CLOSED/TERMINATED +/// --------------------------------------------------------------------------- +@pragma('vm:entry-point') +Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { + await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); + debugPrint("📩 Background Notification Received!"); +} + +Future main() async { + try { + WidgetsFlutterBinding.ensureInitialized(); + + // 1. Initialize Firebase first (required) + debugPrint("🔥 Initializing Firebase..."); + await Firebase.initializeApp( + options: DefaultFirebaseOptions.currentPlatform, + ); + debugPrint("✅ Firebase Initialized"); + + // ✅ Register background handler as early as possible + FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); + + // 2. Fetch initial FCM message (terminated → tapped notification) + RemoteMessage? initialMessage; + try { + debugPrint("📩 Fetching initial message..."); + initialMessage = await FirebaseMessaging.instance + .getInitialMessage() + .timeout( + const Duration(seconds: 2), + onTimeout: () { + debugPrint("⚠️ Firebase getInitialMessage timed out!"); + return null; + }, + ); + debugPrint("📥 Initial message fetched: ${initialMessage != null}"); + } catch (e) { + debugPrint("⚠️ Could not fetch initial message: $e"); + } + + Get.put( + NotificationService(initialMessage), + permanent: true, + ); + + // 3. Initialize local notifications plugin (must happen before runApp) + await initLocalNotifications(); + + // 4. Start the app + debugPrint("🚀 Calling runApp..."); + runApp(const ProviderScope(child: TaxglideApp())); + + // 4. Run FCM/permission setup in background (non-blocking) + _runBackgroundTasks(); + } catch (e, stack) { + debugPrint("❌ CRITICAL BOOT ERROR: $e"); + debugPrint(stack.toString()); + runApp(const ProviderScope(child: TaxglideApp())); + } +} + +/// Helper to run non-critical startup tasks without blocking the UI +Future _runBackgroundTasks() async { + try { + FirebaseMessaging messaging = FirebaseMessaging.instance; + + // Request permissions (Non-blocking) + await messaging.requestPermission( + alert: true, + badge: true, + sound: true, + provisional: false, + ); + + // Request notification permission for Android 13+ + if (Platform.isAndroid) { + await Permission.notification.request(); + } + + // Setup messaging (tokens, etc) + await _setupMessaging(messaging); + + // On iOS, set alert to true – we show foreground FCM messages naturally. + await messaging.setForegroundNotificationPresentationOptions( + alert: true, + badge: true, + sound: true, + ); + + // Set up FCM foreground listener + _setupFcmListeners(); + + // Other plugins + await _initializePlugins(); + + debugPrint("✅ All background initializations complete"); + } catch (e) { + debugPrint("⚠️ Background task failed: $e"); + } +} + +void _setupFcmListeners() { + FirebaseMessaging.onMessage.listen((RemoteMessage message) async { + debugPrint( + "🔔 Foreground FCM received! Notification block: ${message.notification}", + ); + debugPrint("🔍 Foreground FCM Data block: ${message.data}"); + + // Show custom in-app notification for Android (since system doesn't show it in foreground) + // On iOS, setForegroundNotificationPresentationOptions handles this. + if (Platform.isAndroid) { + // Pass a dedup tag (chat/page id) so that if the WebSocket fires for the + // same event, the second notification replaces the first instead of + // showing a double notification. + final String? dedupTag = + message.data['page_id']?.toString() ?? + message.data['chat_id']?.toString() ?? + message.data['id']?.toString(); + Get.find().showForegroundNotification( + message, + tag: dedupTag, + ); + } + }); + + // Background tap + FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { + debugPrint("📥 Notification tapped from background!"); + Get.find().handleNavigation(message.data); + }); +} + +/// --------------------------------------------------------------------------- +/// Non-blocking Messaging Setup +/// --------------------------------------------------------------------------- +Future _setupMessaging(FirebaseMessaging messaging) async { + if (Platform.isIOS) { + debugPrint("🍎 iOS Detected: Requesting notification permissions..."); + NotificationSettings settings = await messaging.requestPermission( + alert: true, + badge: true, + sound: true, + ); + + if (settings.authorizationStatus == AuthorizationStatus.authorized) { + debugPrint("✅ User granted notification permissions"); + } else if (settings.authorizationStatus == + AuthorizationStatus.provisional) { + debugPrint("✅ User granted provisional notification permissions"); + } else { + debugPrint( + "❌ User declined or has not accepted notification permissions", + ); + } + + // Checking for APNS token - essential for FCM on iOS + String? apnsToken = await messaging.getAPNSToken(); + + if (apnsToken == null) { + debugPrint("⏳ APNS Token not ready. Retrying (Max 10s)..."); + // Simulators will stay null here. Physical devices might take a few seconds. + for (int i = 0; i < 10; i++) { + await Future.delayed(const Duration(seconds: 1)); + apnsToken = await messaging.getAPNSToken(); + if (apnsToken != null) { + debugPrint("✅ APNS Token received after retry"); + break; + } + } + } + + if (apnsToken != null) { + debugPrint("✅ APNS Token: $apnsToken"); + } else { + debugPrint( + "⚠️ APNS Token is NULL. " + "IMPORTANT: Push notifications require a PHYSICAL DEVICE and valid Xcode Push Capability. " + "Tokens are NOT available on Simulators.", + ); + return; + } + } + + // FCM Token generation is now handled EXCLUSIVELY during OTP verification in ApiRepository. +} + +/// --------------------------------------------------------------------------- +/// Plugin Initializer +/// --------------------------------------------------------------------------- +Future _initializePlugins() async { + try { + await FilePicker.platform.clearTemporaryFiles(); + debugPrint("✅ Plugins initialized"); + } catch (e) { + debugPrint("⚠️ Plugin init failed: $e"); + } +} + +class TaxglideApp extends StatefulWidget { + const TaxglideApp({super.key}); + + @override + State createState() => _TaxglideAppState(); +} + +class _TaxglideAppState extends State { + @override + Widget build(BuildContext context) { + return GetMaterialApp( + title: 'Taxglide App', + debugShowCheckedModeBanner: false, + scaffoldMessengerKey: rootScaffoldMessengerKey, + initialRoute: '/splash', + getPages: AppRoutes.routes, + theme: ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), + ), + ); + } +} diff --git a/lib/model/chat_model.dart b/lib/model/chat_model.dart new file mode 100644 index 0000000..1cd1f01 --- /dev/null +++ b/lib/model/chat_model.dart @@ -0,0 +1,242 @@ +// ------------------------------------------------------------ +// CHAT MODEL +// ------------------------------------------------------------ +class ChatModel { + final bool status; + final List messages; + + final String? chatStatus; + final int? draw; + final int? recordsTotal; + final int? recordsFiltered; + + final String? profile; + final String? name; + final String? role; + + final List userUploadedDocuments; + final List adminUploadedDocuments; + + ChatModel({ + required this.status, + required this.messages, + this.chatStatus, + this.draw, + this.recordsTotal, + this.recordsFiltered, + this.profile, + this.name, + this.role, + required this.userUploadedDocuments, + required this.adminUploadedDocuments, + }); + + factory ChatModel.fromJson(Map json) { + final msg = json["messages"]; + + return ChatModel( + status: json['status'] ?? false, + + messages: (msg?['data'] != null && msg['data'] is List) + ? List.from( + msg['data'].map((x) => MessageModel.fromJson(x)), + ) + : [], + + chatStatus: msg?['status'], + draw: msg?['draw'], + recordsTotal: msg?['recordsTotal'], + recordsFiltered: msg?['recordsFiltered'], + + profile: msg?['profile'], + name: msg?['name'], + role: msg?['role'], + + userUploadedDocuments: + (msg?['user_uploaded_documents'] != null && + msg['user_uploaded_documents'] is List) + ? List.from( + msg['user_uploaded_documents'].map( + (x) => DocumentModel.fromJson(x), + ), + ) + : [], + + adminUploadedDocuments: + (msg?['admin_uploaded_documents'] != null && + msg['admin_uploaded_documents'] is List) + ? List.from( + msg['admin_uploaded_documents'].map( + (x) => DocumentModel.fromJson(x), + ), + ) + : [], + ); + } +} + +// ------------------------------------------------------------ +// MESSAGE MODEL +// ------------------------------------------------------------ +class MessageModel { + final int id; + final String chatBy; + final String message; + final String type; + final int isDelivered; + final int isRead; + + final String? createdAt; + final String? readAt; + final String? time; + + final int userId; + final int? tagId; + final String? fileName; + + final List uploadedDocuments; + final UserModel? user; + final ParentTagModel? parentTag; + final List documents; + + MessageModel({ + required this.id, + required this.chatBy, + required this.message, + required this.type, + required this.isDelivered, + required this.isRead, + this.createdAt, + this.readAt, + this.time, + required this.userId, + this.tagId, + this.fileName, + required this.uploadedDocuments, + this.user, + this.parentTag, + required this.documents, + }); + + factory MessageModel.fromJson(Map json) { + return MessageModel( + id: json['id'] ?? 0, + chatBy: json['chat_by'] ?? "", + message: json['message'] ?? "", + type: json['type'] ?? "", + isDelivered: json['is_delivered'] ?? 0, + isRead: json['is_read'] ?? 0, + + createdAt: json['created_at'], + readAt: json['read_at'], + time: json['time'], + + userId: json['user_id'] ?? 0, + tagId: json['tag_id'], + fileName: json['file_name'], + + uploadedDocuments: + (json['uploaded_documents'] != null && + json['uploaded_documents'] is List) + ? List.from( + json['uploaded_documents'].map((x) => DocumentModel.fromJson(x)), + ) + : [], + + documents: (json['documents'] != null && json['documents'] is List) + ? List.from( + json['documents'].map((x) => DocumentModel.fromJson(x)), + ) + : [], + + user: json['user'] != null ? UserModel.fromJson(json['user']) : null, + parentTag: json['parent_tag'] != null + ? ParentTagModel.fromJson(json['parent_tag']) + : null, + ); + } +} + +// ------------------------------------------------------------ +// DOCUMENT MODEL +// ------------------------------------------------------------ +class DocumentModel { + final String filePath; + final String fileName; + final String fileType; + final int? id; + final String? type; + + DocumentModel({ + this.id, + required this.filePath, + required this.fileName, + required this.fileType, + this.type, + }); + + factory DocumentModel.fromJson(Map json) { + return DocumentModel( + id: json['id'], + filePath: json['file_path'] ?? "", + fileName: json['file_name'] ?? "", + fileType: json['file_type'] ?? "", + type: json['type'], + ); + } +} + +// ------------------------------------------------------------ +// USER MODEL +// ------------------------------------------------------------ +class UserModel { + final int id; + final String name; + final String role; + final String? profilePicture; + final Map? profile; + + UserModel({ + required this.id, + required this.name, + required this.role, + this.profilePicture, + this.profile, + }); + + factory UserModel.fromJson(Map json) { + return UserModel( + id: json['id'] ?? 0, + name: json['name'] ?? "", + role: json['role'] ?? "", + profilePicture: json['profile_picture'], + profile: json['profile'], + ); + } +} + +// ------------------------------------------------------------ +// PARENT TAG MODEL +// ------------------------------------------------------------ +class ParentTagModel { + final int id; + final String message; + final String type; + final String? fileName; + + ParentTagModel({ + required this.id, + required this.message, + required this.type, + this.fileName, + }); + + factory ParentTagModel.fromJson(Map json) { + return ParentTagModel( + id: json['id'] ?? 0, + message: json['message'] ?? "", + type: json['type'] ?? "", + fileName: json['file_name'], + ); + } +} diff --git a/lib/model/chat_profile_model.dart b/lib/model/chat_profile_model.dart new file mode 100644 index 0000000..972762a --- /dev/null +++ b/lib/model/chat_profile_model.dart @@ -0,0 +1,80 @@ +import 'dart:convert'; + +ChatProfileModel chatProfileModelFromJson(String str) => + ChatProfileModel.fromJson(json.decode(str)); + +String chatProfileModelToJson(ChatProfileModel data) => + json.encode(data.toJson()); + +class ChatProfileModel { + final bool status; + final String profile; + final String name; + final String role; + final List userUploadedDocuments; + final List adminUploadedDocuments; + + ChatProfileModel({ + required this.status, + required this.profile, + required this.name, + required this.role, + required this.userUploadedDocuments, + required this.adminUploadedDocuments, + }); + + factory ChatProfileModel.fromJson(Map json) => + ChatProfileModel( + status: json["status"] ?? false, + profile: json["profile"] ?? "", + name: json["name"] ?? "", + role: json["role"] ?? "", + userUploadedDocuments: json["userUploadedDocuments"] == null + ? [] + : List.from( + json["userUploadedDocuments"] + .map((x) => ChatDocument.fromJson(x)), + ), + adminUploadedDocuments: json["adminUploadedDocuments"] == null + ? [] + : List.from( + json["adminUploadedDocuments"] + .map((x) => ChatDocument.fromJson(x)), + ), + ); + + Map toJson() => { + "status": status, + "profile": profile, + "name": name, + "role": role, + "userUploadedDocuments": + userUploadedDocuments.map((x) => x.toJson()).toList(), + "adminUploadedDocuments": + adminUploadedDocuments.map((x) => x.toJson()).toList(), + }; +} + +class ChatDocument { + final String fileName; + final String filePath; + final String fileType; + + ChatDocument({ + required this.fileName, + required this.filePath, + required this.fileType, + }); + + factory ChatDocument.fromJson(Map json) => ChatDocument( + fileName: json["file_name"] ?? "", + filePath: json["file_path"] ?? "", + fileType: json["file_type"] ?? "", + ); + + Map toJson() => { + "file_name": fileName, + "file_path": filePath, + "file_type": fileType, + }; +} diff --git a/lib/model/city_model.dart b/lib/model/city_model.dart new file mode 100644 index 0000000..da40244 --- /dev/null +++ b/lib/model/city_model.dart @@ -0,0 +1,72 @@ +class CityModel { + final bool? status; + final List? districtsData; + + CityModel({this.status, this.districtsData}); + + factory CityModel.fromJson(Map json) { + return CityModel( + status: json['status'], + districtsData: json['districts_data'] != null + ? List.from( + json['districts_data'].map((x) => DistrictData.fromJson(x)), + ) + : [], + ); + } + + Map toJson() { + return { + 'status': status, + 'districts_data': districtsData?.map((x) => x.toJson()).toList(), + }; + } +} + +class DistrictData { + final int? id; + final String? districtName; + final int? active; + final int? stateId; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + DistrictData({ + this.id, + this.districtName, + this.active, + this.stateId, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory DistrictData.fromJson(Map json) { + return DistrictData( + id: json['id'], + districtName: json['district_name'], + active: json['active'], + stateId: json['state_id'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'district_name': districtName, + 'active': active, + 'state_id': stateId, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} diff --git a/lib/model/count_model.dart b/lib/model/count_model.dart new file mode 100644 index 0000000..0d7f08b --- /dev/null +++ b/lib/model/count_model.dart @@ -0,0 +1,23 @@ +class CountModel { + final bool status; + final int count; + + CountModel({ + required this.status, + required this.count, + }); + + factory CountModel.fromJson(Map json) { + return CountModel( + status: json['status'] ?? false, + count: json['count'] ?? 0, + ); + } + + Map toJson() { + return { + 'status': status, + 'count': count, + }; + } +} diff --git a/lib/model/country_model.dart b/lib/model/country_model.dart new file mode 100644 index 0000000..6b6cf61 --- /dev/null +++ b/lib/model/country_model.dart @@ -0,0 +1,129 @@ +class CountryModel { + final bool? status; + final List? countriesData; + final List? statesData; + + CountryModel({ + this.status, + this.countriesData, + this.statesData, + }); + + factory CountryModel.fromJson(Map json) { + return CountryModel( + status: json['status'], + countriesData: json['countries_data'] != null + ? List.from( + json['countries_data'].map((x) => CountryData.fromJson(x))) + : [], + statesData: json['states_data'] != null + ? List.from( + json['states_data'].map((x) => StateData.fromJson(x))) + : [], + ); + } + + Map toJson() { + return { + 'status': status, + 'countries_data': countriesData?.map((x) => x.toJson()).toList(), + 'states_data': statesData?.map((x) => x.toJson()).toList(), + }; + } +} + +class CountryData { + final int? id; + final String? countryCode; + final String? countryName; + final int? active; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + CountryData({ + this.id, + this.countryCode, + this.countryName, + this.active, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory CountryData.fromJson(Map json) { + return CountryData( + id: json['id'], + countryCode: json['country_code'], + countryName: json['country_name'], + active: json['active'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'country_code': countryCode, + 'country_name': countryName, + 'active': active, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} + +class StateData { + final int? id; + final String? stateName; + final int? active; + final int? countryId; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + StateData({ + this.id, + this.stateName, + this.active, + this.countryId, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory StateData.fromJson(Map json) { + return StateData( + id: json['id'], + stateName: json['state_name'], + active: json['active'], + countryId: json['country_id'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'state_name': stateName, + 'active': active, + 'country_id': countryId, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} diff --git a/lib/model/dash_board_model.dart b/lib/model/dash_board_model.dart new file mode 100644 index 0000000..576a263 --- /dev/null +++ b/lib/model/dash_board_model.dart @@ -0,0 +1,193 @@ +class DashBoardModel { + final String status; + final bool isKycCompleted; + final List serviceLists; + final String userName; + final String companyName; + final int generalChatId; + final List reviews; + final ServiceRequestList serviceRequestLists; + final List imageSlider; + + DashBoardModel({ + required this.status, + required this.isKycCompleted, + required this.serviceLists, + required this.userName, + required this.companyName, + required this.generalChatId, + required this.imageSlider, + required this.reviews, + required this.serviceRequestLists, + }); + + factory DashBoardModel.fromJson(Map json) { + return DashBoardModel( + status: json['status'] ?? '', + isKycCompleted: json['is_kyc_completed'] ?? false, + serviceLists: + (json['service_lists'] as List?) + ?.map((e) => ServiceList.fromJson(e)) + .toList() ?? + [], + imageSlider: (json['imageSlider'] as List) + .map((e) => ImageSlider.fromJson(e)) + .toList(), + userName: json['user_name'] ?? '', + companyName: json['company_name'] ?? '', + generalChatId: json['general_chat_id'] ?? 0, + reviews: + (json['reviews'] as List?) + ?.map((e) => Review.fromJson(e)) + .toList() ?? + [], + serviceRequestLists: ServiceRequestList.fromJson( + json['service_request_lists'] ?? {}, + ), + ); + } +} + +// --------------------------------------------------------------- +// SERVICE LIST MODEL +// --------------------------------------------------------------- +class ServiceList { + final int id; + final String service; + final String icon; + + ServiceList({required this.id, required this.service, required this.icon}); + + factory ServiceList.fromJson(Map json) { + return ServiceList( + id: json['id'] ?? 0, + service: json['service'] ?? '', + icon: json['icon'] ?? '', + ); + } +} + +class ImageSlider { + final String image; + + ImageSlider({required this.image}); + + factory ImageSlider.fromJson(Map json) { + return ImageSlider(image: json['image'] ?? ''); + } +} + +// --------------------------------------------------------------- +// REVIEW MODEL +// --------------------------------------------------------------- +class Review { + final int id; + final String name; + final String about; + final String content; + final int rating; + + Review({ + required this.id, + required this.name, + required this.about, + required this.content, + required this.rating, + }); + + factory Review.fromJson(Map json) { + return Review( + id: json['id'] ?? 0, + name: json['name'] ?? '', + about: json['about'] ?? '', + content: json['content'] ?? '', + rating: json['rating'] ?? 0, + ); + } +} + +// --------------------------------------------------------------- +// SERVICE REQUEST LIST WRAPPER +// --------------------------------------------------------------- +class ServiceRequestList { + final String status; + final int recordsTotal; + final int recordsFiltered; + final List data; + + ServiceRequestList({ + required this.status, + required this.recordsTotal, + required this.recordsFiltered, + required this.data, + }); + + factory ServiceRequestList.fromJson(Map json) { + return ServiceRequestList( + status: json['status'] ?? '', + recordsTotal: json['recordsTotal'] ?? 0, + recordsFiltered: json['recordsFiltered'] ?? 0, + data: + (json['data'] as List?) + ?.map((e) => ServiceRequestItem.fromJson(e)) + .toList() ?? + [], + ); + } +} + +// --------------------------------------------------------------- +// SERVICE REQUEST ITEM +// --------------------------------------------------------------- +class ServiceRequestItem { + final int id; + final String name; + final String logo; + final String email; + final String mobile; + final String paymentStatus; + final num paymentAmount; + final String status; + final String service; + final String message; + final String createdDate; + final String createdTime; + final int actions; + final int? chatId; + + ServiceRequestItem({ + required this.id, + required this.name, + required this.logo, + required this.email, + required this.mobile, + required this.paymentStatus, + required this.paymentAmount, + required this.status, + required this.service, + required this.message, + required this.createdDate, + required this.createdTime, + required this.actions, + required this.chatId, + }); + + factory ServiceRequestItem.fromJson(Map json) { + return ServiceRequestItem( + id: json['id'] ?? 0, + name: json['name'] ?? '', + logo: json['logo'] ?? '', + email: json['email'] ?? '', + mobile: json['mobile'] ?? '', + paymentStatus: json['payment_status'] ?? '', + paymentAmount: json['payment_amount'] ?? 0, + status: json['status'] ?? '', + service: json['service'] ?? '', + message: json['message'] ?? '', + createdDate: json['created_date'] ?? '', + createdTime: json['created_time'] ?? '', + actions: json['actions'] ?? 0, + chatId: json['chat_id'], + ); + } +} diff --git a/lib/model/detail_model.dart b/lib/model/detail_model.dart new file mode 100644 index 0000000..d394c63 --- /dev/null +++ b/lib/model/detail_model.dart @@ -0,0 +1,235 @@ +import 'dart:convert'; + +/// ------------------------------ +/// JSON Helpers +/// ------------------------------ + +DetailModel detailModelFromJson(String str) => + DetailModel.fromJson(json.decode(str)); + +String detailModelToJson(DetailModel data) => json.encode(data.toJson()); + +/// ------------------------------ +/// Root Model +/// ------------------------------ + +class DetailModel { + final String? status; + final DetailData? data; + + DetailModel({this.status, this.data}); + + factory DetailModel.fromJson(Map json) => DetailModel( + status: json["status"], + data: json["data"] == null ? null : DetailData.fromJson(json["data"]), + ); + + Map toJson() => {"status": status, "data": data?.toJson()}; +} + +/// ------------------------------ +/// Detail Data Model +/// ------------------------------ + +class DetailData { + final int? id; + final int? firmId; + final String? dueDate; + + final String? service; + final String? serviceStatus; + + final String? paymentStatus; + final String? paidStatus; + final String? paymentDate; + final String? paymentAmount; + + final String? invoice; + final String? invoiceNumber; + + final String? proforma; + final int? proformaId; + final String? proformaNumber; + final String? proformastatus; + final String? createdDate; + final String? createdTime; + final String? createdBy; + + final String? message; + final String? completedDate; + final String? paidBy; + + final List userUploadedDocuments; + final List userHandoverDocuments; + + final String? chatId; + final String? completedChatId; + + DetailData({ + this.id, + this.firmId, + this.dueDate, + this.service, + this.proformastatus, + this.serviceStatus, + this.paymentStatus, + this.paidStatus, + this.paymentDate, + this.paymentAmount, + this.invoice, + this.invoiceNumber, + this.proforma, + this.proformaId, + this.proformaNumber, + this.createdDate, + this.createdTime, + this.createdBy, + this.message, + this.completedDate, + this.paidBy, + required this.userUploadedDocuments, + required this.userHandoverDocuments, + this.chatId, + this.completedChatId, + }); + + factory DetailData.fromJson(Map json) => DetailData( + id: json["id"], + firmId: json["firm_id"], + dueDate: json["due_date"], + + service: json["service"], + serviceStatus: json["service_status"], + + paymentStatus: json["payment_status"], + proformastatus: json["proforma_status"], + paidStatus: json["paid_status"], + paymentDate: json["payment_date"], + paymentAmount: json["payment_amount"]?.toString(), + + invoice: json["invoice"], + invoiceNumber: json["invoice_number"], + + proforma: json["proforma"], + proformaId: json["proforma_id"], + proformaNumber: json["proforma_number"], + + createdDate: json["created_date"], + createdTime: json["created_time"], + createdBy: json["created_by"], + + message: json["message"], + completedDate: json["completed_date"], + paidBy: json["paid_by"], + + userUploadedDocuments: json["user_uploaded_documents"] == null + ? [] + : List.from( + json["user_uploaded_documents"].map( + (x) => UserUploadedDocument.fromJson(x), + ), + ), + + userHandoverDocuments: json["user_handover_documents"] == null + ? [] + : List.from( + json["user_handover_documents"].map( + (x) => UserHandoverDocument.fromJson(x), + ), + ), + + chatId: json["chat_id"]?.toString(), + completedChatId: json["completed_chat_id"]?.toString(), + ); + + Map toJson() => { + "id": id, + "firm_id": firmId, + "due_date": dueDate, + "service": service, + "service_status": serviceStatus, + "payment_status": paymentStatus, + "paid_status": paidStatus, + "payment_date": paymentDate, + "payment_amount": paymentAmount, + "invoice": invoice, + "proforma_status": proformastatus, + "invoice_number": invoiceNumber, + "proforma": proforma, + "proforma_id": proformaId, + "proforma_number": proformaNumber, + "created_date": createdDate, + "created_time": createdTime, + "created_by": createdBy, + "message": message, + "completed_date": completedDate, + "paid_by": paidBy, + "user_uploaded_documents": userUploadedDocuments + .map((x) => x.toJson()) + .toList(), + "user_handover_documents": userHandoverDocuments + .map((x) => x.toJson()) + .toList(), + "chat_id": chatId, + "completed_chat_id": completedChatId, + }; +} + +/// ------------------------------ +/// User Uploaded Document +/// ------------------------------ + +class UserUploadedDocument { + final int? id; + final String? filePath; + final String? fileName; + final String? uploadedBy; + final bool? viewable; + + UserUploadedDocument({ + this.id, + this.filePath, + this.fileName, + this.uploadedBy, + this.viewable, + }); + + factory UserUploadedDocument.fromJson(Map json) => + UserUploadedDocument( + id: json["id"], + filePath: json["file_path"], + fileName: json["file_name"], + uploadedBy: json["uploaded_by"], + viewable: json["viewable"], + ); + + Map toJson() => { + "id": id, + "file_path": filePath, + "file_name": fileName, + "uploaded_by": uploadedBy, + "viewable": viewable, + }; +} + +/// ------------------------------ +/// User Handover Document +/// ------------------------------ + +class UserHandoverDocument { + final String? filePath; + final String? fileName; + + UserHandoverDocument({this.filePath, this.fileName}); + + factory UserHandoverDocument.fromJson(Map json) => + UserHandoverDocument( + filePath: json["file_path"], + fileName: json["file_name"], + ); + + Map toJson() => { + "file_path": filePath, + "file_name": fileName, + }; +} diff --git a/lib/model/employeeprofile_model.dart b/lib/model/employeeprofile_model.dart new file mode 100644 index 0000000..3fa647e --- /dev/null +++ b/lib/model/employeeprofile_model.dart @@ -0,0 +1,85 @@ +class EmployeeProfileModel { + final bool status; + final EmployeeData? data; + + EmployeeProfileModel({required this.status, this.data}); + + factory EmployeeProfileModel.fromJson(Map json) { + return EmployeeProfileModel( + status: json['status'] ?? false, + data: json['data'] != null ? EmployeeData.fromJson(json['data']) : null, + ); + } + + Map toJson() { + return {'status': status, 'data': data?.toJson()}; + } +} + +class EmployeeData { + final int id; + final String name; + final String mobile; + final String email; + final int status; + final int generalChat; + final int createService; + final Company? company; + + EmployeeData({ + required this.id, + required this.name, + required this.mobile, + required this.email, + required this.status, + required this.generalChat, + required this.createService, + this.company, + }); + + factory EmployeeData.fromJson(Map json) { + return EmployeeData( + id: json['id'] ?? 0, + name: json['name'] ?? '', + mobile: json['mobile'] ?? '', + email: json['email'] ?? '', + status: json['status'] ?? 0, + generalChat: json['general_chat'] ?? 0, + createService: json['create_service'] ?? 0, + company: json['company'] != null + ? Company.fromJson(json['company']) + : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'mobile': mobile, + 'email': email, + 'status': status, + 'general_chat': generalChat, + 'create_service': createService, + 'company': company?.toJson(), + }; + } +} + +class Company { + final String? companyName; + final String? companyLogo; + + Company({this.companyName, this.companyLogo}); + + factory Company.fromJson(Map json) { + return Company( + companyName: json['company_name'], + companyLogo: json['company_logo'], + ); + } + + Map toJson() { + return {'company_name': companyName, 'company_logo': companyLogo}; + } +} diff --git a/lib/model/login_model.dart b/lib/model/login_model.dart new file mode 100644 index 0000000..0f61e7e --- /dev/null +++ b/lib/model/login_model.dart @@ -0,0 +1,23 @@ +// login_model.dart + +class LoginModel { + String? mobile; + String? otp; + + LoginModel({this.mobile, this.otp}); + + // For sending mobile number to request OTP + Map toJsonMobile() { + return {'mobile': mobile}; + } + + // For sending mobile + OTP for verification + Map toJsonOtp() { + return {'mobile': mobile, 'otp': otp}; + } + + // Response from API + factory LoginModel.fromJson(Map json) { + return LoginModel(mobile: json['mobile'], otp: json['otp']); + } +} diff --git a/lib/model/notification_model.dart b/lib/model/notification_model.dart new file mode 100644 index 0000000..8368a92 --- /dev/null +++ b/lib/model/notification_model.dart @@ -0,0 +1,79 @@ +class NotificationResponse { + final String status; + final int? draw; + final int recordsTotal; + final int recordsFiltered; + final List data; + + NotificationResponse({ + required this.status, + required this.draw, + required this.recordsTotal, + required this.recordsFiltered, + required this.data, + }); + + factory NotificationResponse.fromJson(Map json) { + return NotificationResponse( + status: json['status'] ?? '', + draw: json['draw'], + recordsTotal: json['recordsTotal'] ?? 0, + recordsFiltered: json['recordsFiltered'] ?? 0, + data: (json['data'] as List? ?? []) + .map((e) => NotificationModel.fromJson(e)) + .toList(), + ); + } + + Map toJson() { + return { + "status": status, + "draw": draw, + "recordsTotal": recordsTotal, + "recordsFiltered": recordsFiltered, + "data": data.map((e) => e.toJson()).toList(), + }; + } +} + +// ------------------------------------------------------------- + +class NotificationModel { + final int id; + final String title; + final String description; + final int? pageId; + final String page; + final String createdAt; // Keeping as string because format is custom + + NotificationModel({ + required this.id, + required this.title, + required this.description, + required this.pageId, + required this.page, + required this.createdAt, + }); + + factory NotificationModel.fromJson(Map json) { + return NotificationModel( + id: json['id'] ?? 0, + title: json['tittle'] ?? '', // API spelled as "tittle" + description: json['description'] ?? '', + pageId: json['page_id'], + page: json['page'] ?? '', + createdAt: json['created_at'] ?? '', + ); + } + + Map toJson() { + return { + "id": id, + "tittle": title, + "description": description, + "page_id": pageId, + "page": page, + "created_at": createdAt, + }; + } +} diff --git a/lib/model/notificationcount_model.dart b/lib/model/notificationcount_model.dart new file mode 100644 index 0000000..f47a6d8 --- /dev/null +++ b/lib/model/notificationcount_model.dart @@ -0,0 +1,17 @@ +class NotificationCountModel { + final bool status; + final int count; + + NotificationCountModel({required this.status, required this.count}); + + factory NotificationCountModel.fromJson(Map json) { + return NotificationCountModel( + status: json['status'] ?? false, + count: json['count'] ?? 0, + ); + } + + Map toJson() { + return {'status': status, 'count': count}; + } +} diff --git a/lib/model/profile_get_model.dart b/lib/model/profile_get_model.dart new file mode 100644 index 0000000..073cd0a --- /dev/null +++ b/lib/model/profile_get_model.dart @@ -0,0 +1,313 @@ +class ProfileGetModel { + final bool status; + final ProfileData? data; + + ProfileGetModel({required this.status, this.data}); + + factory ProfileGetModel.fromJson(Map json) { + return ProfileGetModel( + status: json['status'] ?? false, + data: json['data'] != null ? ProfileData.fromJson(json['data']) : null, + ); + } + + Map toJson() { + return {'status': status, 'data': data?.toJson()}; + } +} + +class ProfileData { + final int? id; + final String? companyName; + final String? companyEmail; + final String? companyMobile; + final String? companyAddress; + final String? companyPincode; + final String? panNumber; + final String? gstNumber; + final String? tanNumber; + final String? cin; + final int? yearOfIncorporation; + final String? logo; + final String? panFile; + final String? gstFile; + final String? incorporationFile; + final int? active; + final int? createdBy; + final int? updatedBy; + final String? createdAt; + final String? updatedAt; + final int? countryId; + final int? stateId; + final int? districtId; + final String? countryName; + final String? stateName; + final String? districtName; + final String? name; + final String? email; + final String? mobile; + final int? userId; + final Country? country; + final StateData? state; + final District? district; + + ProfileData({ + this.id, + this.companyName, + this.companyEmail, + this.companyMobile, + this.companyAddress, + this.companyPincode, + this.panNumber, + this.gstNumber, + this.tanNumber, + this.cin, + this.yearOfIncorporation, + this.logo, + this.panFile, + this.gstFile, + this.incorporationFile, + this.active, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + this.countryId, + this.stateId, + this.districtId, + this.countryName, + this.stateName, + this.districtName, + this.name, + this.email, + this.mobile, + this.userId, + this.country, + this.state, + this.district, + }); + + factory ProfileData.fromJson(Map json) { + return ProfileData( + id: json['id'], + companyName: json['company_name'], + companyEmail: json['company_email'], + companyMobile: json['company_mobile'], + companyAddress: json['company_address'], + companyPincode: json['company_pincode'], + panNumber: json['pan_number'], + gstNumber: json['gst_number'], + tanNumber: json['tan_number'], + cin: json['cin'], + yearOfIncorporation: json['year_of_incorporation'], + logo: json['logo'], + panFile: json['pan_file'], + gstFile: json['gst_file'], + incorporationFile: json['incorporation_file'], + active: json['active'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + countryId: json['country_id'], + stateId: json['state_id'], + districtId: json['district_id'], + countryName: json['country_name'], + stateName: json['state_name'], + districtName: json['district_name'], + name: json['name'], + email: json['email'], + mobile: json['mobile'], + userId: json['user_id'], + country: json['country'] != null + ? Country.fromJson(json['country']) + : null, + state: json['state'] != null ? StateData.fromJson(json['state']) : null, + district: json['district'] != null + ? District.fromJson(json['district']) + : null, + ); + } + + Map toJson() { + return { + 'id': id, + 'company_name': companyName, + 'company_email': companyEmail, + 'company_mobile': companyMobile, + 'company_address': companyAddress, + 'company_pincode': companyPincode, + 'pan_number': panNumber, + 'gst_number': gstNumber, + 'tan_number': tanNumber, + 'cin': cin, + 'year_of_incorporation': yearOfIncorporation, + 'logo': logo, + 'pan_file': panFile, + 'gst_file': gstFile, + 'incorporation_file': incorporationFile, + 'active': active, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + 'country_id': countryId, + 'state_id': stateId, + 'district_id': districtId, + 'country_name': countryName, + 'state_name': stateName, + 'district_name': districtName, + 'name': name, + 'email': email, + 'mobile': mobile, + 'user_id': userId, + 'country': country?.toJson(), + 'state': state?.toJson(), + 'district': district?.toJson(), + }; + } +} + +class Country { + final int? id; + final String? countryCode; + final String? countryName; + final int? active; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + Country({ + this.id, + this.countryCode, + this.countryName, + this.active, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory Country.fromJson(Map json) { + return Country( + id: json['id'], + countryCode: json['country_code'], + countryName: json['country_name'], + active: json['active'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'country_code': countryCode, + 'country_name': countryName, + 'active': active, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} + +class StateData { + final int? id; + final String? stateName; + final int? active; + final int? countryId; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + StateData({ + this.id, + this.stateName, + this.active, + this.countryId, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory StateData.fromJson(Map json) { + return StateData( + id: json['id'], + stateName: json['state_name'], + active: json['active'], + countryId: json['country_id'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'state_name': stateName, + 'active': active, + 'country_id': countryId, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} + +class District { + final int? id; + final String? districtName; + final int? active; + final int? stateId; + final dynamic createdBy; + final dynamic updatedBy; + final String? createdAt; + final String? updatedAt; + + District({ + this.id, + this.districtName, + this.active, + this.stateId, + this.createdBy, + this.updatedBy, + this.createdAt, + this.updatedAt, + }); + + factory District.fromJson(Map json) { + return District( + id: json['id'], + districtName: json['district_name'], + active: json['active'], + stateId: json['state_id'], + createdBy: json['created_by'], + updatedBy: json['updated_by'], + createdAt: json['created_at'], + updatedAt: json['updated_at'], + ); + } + + Map toJson() { + return { + 'id': id, + 'district_name': districtName, + 'active': active, + 'state_id': stateId, + 'created_by': createdBy, + 'updated_by': updatedBy, + 'created_at': createdAt, + 'updated_at': updatedAt, + }; + } +} diff --git a/lib/model/serivce_list_model.dart b/lib/model/serivce_list_model.dart new file mode 100644 index 0000000..9067c66 --- /dev/null +++ b/lib/model/serivce_list_model.dart @@ -0,0 +1,43 @@ +class ServiceListModel { + final int id; + final String service; + final String icon; + + ServiceListModel({ + required this.id, + required this.service, + required this.icon, + }); + + factory ServiceListModel.fromJson(Map json) { + return ServiceListModel( + id: json['id'] ?? 0, + service: json['service'] ?? '', + icon: json['icon'] ?? '', + ); + } + + Map toJson() { + return {'id': id, 'service': service, 'icon': icon}; + } +} + +class ServiceListResponse { + final String status; + final List data; + + ServiceListResponse({required this.status, required this.data}); + + factory ServiceListResponse.fromJson(Map json) { + return ServiceListResponse( + status: json['status'] ?? '', + data: (json['data'] as List) + .map((e) => ServiceListModel.fromJson(e)) + .toList(), + ); + } + + Map toJson() { + return {'status': status, 'data': data.map((e) => e.toJson()).toList()}; + } +} diff --git a/lib/model/service_list_history_model.dart b/lib/model/service_list_history_model.dart new file mode 100644 index 0000000..f6a8451 --- /dev/null +++ b/lib/model/service_list_history_model.dart @@ -0,0 +1,91 @@ +class ServiceListHistoryModel { + final String? status; + final dynamic draw; + final int? recordsTotal; + final int? recordsFiltered; + final List? data; + + ServiceListHistoryModel({ + this.status, + this.draw, + this.recordsTotal, + this.recordsFiltered, + this.data, + }); + + factory ServiceListHistoryModel.fromJson(Map json) { + return ServiceListHistoryModel( + status: json['status'] as String?, + draw: json['draw'], + recordsTotal: json['recordsTotal'] is int + ? json['recordsTotal'] + : int.tryParse(json['recordsTotal']?.toString() ?? ''), + recordsFiltered: json['recordsFiltered'] is int + ? json['recordsFiltered'] + : int.tryParse(json['recordsFiltered']?.toString() ?? ''), + data: (json['data'] as List?) + ?.map((e) => ServiceHistoryData.fromJson(e)) + .toList(), + ); + } + + Map toJson() { + return { + 'status': status, + 'draw': draw, + 'recordsTotal': recordsTotal, + 'recordsFiltered': recordsFiltered, + 'data': data?.map((e) => e.toJson()).toList(), + }; + } +} + +class ServiceHistoryData { + final int? id; + final String? paymentStatus; + final String? paymentAmount; + final String? status; + final String? service; + final String? message; + final String? createdDate; + final String? createdTime; + + ServiceHistoryData({ + this.id, + this.paymentStatus, + this.paymentAmount, + this.status, + this.service, + this.message, + this.createdDate, + this.createdTime, + }); + + factory ServiceHistoryData.fromJson(Map json) { + return ServiceHistoryData( + id: json['id'] is int + ? json['id'] + : int.tryParse(json['id']?.toString() ?? ''), + paymentStatus: json['payment_status']?.toString(), + paymentAmount: json['payment_amount']?.toString(), + status: json['status']?.toString(), + service: json['service']?.toString(), + message: json['message']?.toString(), + createdDate: json['created_date']?.toString(), + createdTime: json['created_time']?.toString(), + ); + } + + Map toJson() { + return { + 'id': id, + 'payment_status': paymentStatus, + 'payment_amount': paymentAmount, + 'status': status, + 'service': service, + 'message': message, + 'created_date': createdDate, + 'created_time': createdTime, + }; + } +} diff --git a/lib/model/signup_model.dart b/lib/model/signup_model.dart new file mode 100644 index 0000000..4df9370 --- /dev/null +++ b/lib/model/signup_model.dart @@ -0,0 +1,25 @@ +class SignupModel { + final String email; + final String name; + final String contactNumber; + + SignupModel({ + required this.email, + required this.name, + required this.contactNumber, + }); + + // Convert JSON to SignupModel + factory SignupModel.fromJson(Map json) { + return SignupModel( + email: json['email'] ?? '', + name: json['name'] ?? '', + contactNumber: json['mobile'] ?? '', + ); + } + + // Convert SignupModel to JSON + Map toJson() { + return {'email': email, 'name': name, 'mobile': contactNumber}; + } +} diff --git a/lib/model/staff_model.dart b/lib/model/staff_model.dart new file mode 100644 index 0000000..287b707 --- /dev/null +++ b/lib/model/staff_model.dart @@ -0,0 +1,47 @@ +class StaffResponse { + final String status; + final List data; + + StaffResponse({required this.status, required this.data}); + + factory StaffResponse.fromJson(Map json) { + return StaffResponse( + status: json['status'] ?? '', + data: (json['data'] as List) + .map((item) => StaffModel.fromJson(item)) + .toList(), + ); + } +} + +class StaffModel { + final int id; + final String name; + final String mobile; + final String email; + final int status; + final int generalChat; + final int createService; + + StaffModel({ + required this.id, + required this.name, + required this.mobile, + required this.email, + required this.status, + required this.generalChat, + required this.createService, + }); + + factory StaffModel.fromJson(Map json) { + return StaffModel( + id: json['id'] ?? 0, + name: json['name'] ?? '', + mobile: json['mobile'] ?? '', + email: json['email'] ?? '', + status: json['status'] ?? 0, + generalChat: json['general_chat'] ?? 0, + createService: json['create_service'] ?? 0, + ); + } +} diff --git a/lib/model/terms_model.dart b/lib/model/terms_model.dart new file mode 100644 index 0000000..89e4f67 --- /dev/null +++ b/lib/model/terms_model.dart @@ -0,0 +1,35 @@ +class TermsModel { + final bool status; + final TermsData? data; + + TermsModel({required this.status, this.data}); + + factory TermsModel.fromJson(Map json) { + return TermsModel( + status: json['status'] ?? false, + data: json['data'] != null ? TermsData.fromJson(json['data']) : null, + ); + } + + Map toJson() { + return {'status': status, 'data': data?.toJson()}; + } +} + +class TermsData { + final String? title; + final String? content; + + TermsData({this.title, this.content}); + + factory TermsData.fromJson(Map json) { + return TermsData( + title: json['title'] ?? '', + content: json['content'] ?? '', + ); + } + + Map toJson() { + return {'title': title, 'content': content}; + } +} diff --git a/lib/router/consts_routers.dart b/lib/router/consts_routers.dart new file mode 100644 index 0000000..2ae30dc --- /dev/null +++ b/lib/router/consts_routers.dart @@ -0,0 +1,16 @@ +class ConstRouters { + static const String splash = '/splash'; + static const String login = '/login'; + static const String signup = '/signup'; + static const String otp = '/otp'; + static const String registerOtp = '/registerOtp'; + static const String terms = '/terms'; + static const String policy = '/policy'; + static const String employeelogin = '/employeelogin'; + static const String employeeotp = '/employeeotp'; + static const String kycdetails = '/kycdetails'; + static const String kycdetailslist = '/kycdetailslist'; + static const String servicerequest = '/servicerequest'; + static const String staff = '/staff'; + static const String employeekycdetailslist = '/employeekycdetailslist'; +} diff --git a/lib/router/router.dart b/lib/router/router.dart new file mode 100644 index 0000000..c021869 --- /dev/null +++ b/lib/router/router.dart @@ -0,0 +1,54 @@ +import 'package:get/get.dart'; +import 'package:taxglide/auth/employee_login_screen.dart'; +import 'package:taxglide/auth/employee_otp_screen.dart'; +import 'package:taxglide/auth/login_screen.dart'; +import 'package:taxglide/auth/otp_screen.dart'; +import 'package:taxglide/auth/register_otp_screen.dart'; +import 'package:taxglide/auth/signup_screen.dart'; +import 'package:taxglide/router/consts_routers.dart'; +import 'package:taxglide/view/flash_screen.dart'; +import 'package:taxglide/view/screens/profile/employee_profile/employee_profile_list.dart'; +import 'package:taxglide/view/screens/profile/kyc_detail_screen.dart'; +import 'package:taxglide/view/screens/profile/kyc_details_list.dart'; +import 'package:taxglide/view/screens/profile/policy_screen.dart'; +import 'package:taxglide/view/screens/profile/staff_list_screen.dart'; +import 'package:taxglide/view/screens/profile/terms_and_condition_screen.dart'; + +class AppRoutes { + static final routes = [ + // Flash / Splash Screen + GetPage(name: ConstRouters.splash, page: () => const FlashScreen()), + GetPage(name: ConstRouters.login, page: () => const LoginScreen()), + GetPage( + name: ConstRouters.employeelogin, + page: () => const EmployeeLoginScreen(), + ), + GetPage(name: ConstRouters.signup, page: () => const SignupScreen()), + GetPage( + name: ConstRouters.registerOtp, + page: () => const RegisterOtpScreen(), + ), + + GetPage(name: ConstRouters.otp, page: () => const OtpScreen()), + GetPage( + name: ConstRouters.employeeotp, + page: () => const EmployeeOtpScreen(), + ), + GetPage( + name: ConstRouters.terms, + page: () => const TermsAndConditionScreen(), + ), + GetPage(name: ConstRouters.kycdetails, page: () => const KycDetailScreen()), + + GetPage( + name: ConstRouters.kycdetailslist, + page: () => const KycDetailsList(), + ), + GetPage( + name: ConstRouters.employeekycdetailslist, + page: () => const EmployeeProfileList(), + ), + GetPage(name: ConstRouters.policy, page: () => const PolicyScreen()), + GetPage(name: ConstRouters.staff, page: () => const StaffListScreen()), + ]; +} diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart new file mode 100644 index 0000000..5ef7a2c --- /dev/null +++ b/lib/services/notification_service.dart @@ -0,0 +1,254 @@ +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import 'package:taxglide/view/screens/history/detail_screen.dart'; +import 'package:taxglide/view/screens/notification_screen.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +// ───────────────────────────────────────────────────────────────────────────── +// Local Notifications setup (singleton plugin instance) +// ───────────────────────────────────────────────────────────────────────────── + +final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = + FlutterLocalNotificationsPlugin(); + +/// Android notification channel used for all foreground chat/app notifications. +const AndroidNotificationChannel _channel = AndroidNotificationChannel( + 'taxglide_foreground', // id + 'TaxGlide Notifications', // name shown in system settings + description: 'Foreground notifications for TaxGlide', + importance: Importance.high, + playSound: true, + enableVibration: true, +); + +/// Call once in main() after Firebase.initializeApp(). +Future initLocalNotifications() async { + const initSettings = InitializationSettings( + android: AndroidInitializationSettings('@mipmap/launcher_icon'), + iOS: DarwinInitializationSettings(), + ); + + await flutterLocalNotificationsPlugin.initialize( + initSettings, + onDidReceiveNotificationResponse: (NotificationResponse response) { + // Notification tapped while app is open – handled inside NotificationService. + debugPrint('🔔 Local notification tapped: payload=${response.payload}'); + Get.find().handleNavigationFromPayload( + response.payload, + ); + }, + ); + + // Create the Android channel (no-op on iOS). + await flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin + >() + ?.createNotificationChannel(_channel); + + debugPrint('✅ LocalNotifications initialized'); +} + +// ───────────────────────────────────────────────────────────────────────────── +// NotificationService +// ───────────────────────────────────────────────────────────────────────────── + +class NotificationService extends GetxController { + final RemoteMessage? initialMessage; + NotificationService(this.initialMessage); + + /// Running notification ID counter so multiple notifications can stack. + int _notifId = 0; + + /// Shows a native Android system notification for a foreground message. + /// Works from any context – WebSocket callbacks, FCM listeners, etc. + /// + /// [tag] is used as a deduplication key: if two sources (FCM + WebSocket) + /// fire for the same chat/event, passing the same tag means Android will + /// *replace* the first notification instead of showing a second one. + void showForegroundNotification(RemoteMessage message, {String? tag}) { + final String title = + message.notification?.title ?? + message.data['title']?.toString() ?? + 'New Notification'; + final String body = + message.notification?.body ?? + message.data['body']?.toString() ?? + 'You have a new update'; + + // Build a simple payload string so tapping routes correctly. + final String? type = message.data['type']?.toString(); + final String? id = + message.data['page_id']?.toString() ?? message.data['id']?.toString(); + final String payload = (type != null && id != null) ? '$type:$id' : ''; + + // Use the tag as dedup key; fall back to an incrementing ID so unrelated + // notifications still stack correctly. + final int notifId = tag != null ? tag.hashCode.abs() % 100000 : _notifId++; + + debugPrint( + '🔔 NotificationService: showing local notification ' + '[id=$notifId tag=$tag title=$title]', + ); + + flutterLocalNotificationsPlugin.show( + notifId, + title, + body, + NotificationDetails( + android: AndroidNotificationDetails( + _channel.id, + _channel.name, + channelDescription: _channel.description, + importance: Importance.high, + priority: Priority.high, + icon: '@mipmap/launcher_icon', + playSound: true, + enableVibration: true, + styleInformation: BigTextStyleInformation(body), + tag: tag, // same tag → replaces instead of duplicating + ), + iOS: const DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ), + ), + payload: payload, + ); + } + + // ── Navigation helpers ────────────────────────────────────────────────────── + + /// Called when a local notification is tapped (payload = "type:id"). + void handleNavigationFromPayload(String? payload) { + if (payload == null || payload.isEmpty) { + _safeNavigate(() => Get.offAll(() => MainController())); + return; + } + final parts = payload.split(':'); + final type = parts.isNotEmpty ? parts[0] : null; + final idStr = parts.length > 1 ? parts[1] : null; + handleNavigation({'type': type, 'id': idStr}); + } + + Future handleNavigation(Map data) async { + final LocalStore localStore = LocalStore(); + + try { + // ── Auth check ────────────────────────────────────────────────────────── + final String? token = await localStore.getToken(); + if (token == null || token.isEmpty || token == 'null') { + debugPrint('🔒 No valid token → Login'); + _safeNavigate(() => Get.offAllNamed(ConstRouters.login)); + return; + } + + // Support both 'page'+'page_id' and 'type'+'id' payload formats. + final String? type = data['page']?.toString() ?? data['type']?.toString(); + final String? idStr = + data['page_id']?.toString() ?? + data['pageId']?.toString() ?? + data['id']?.toString(); + + if (type == null || type.isEmpty) { + debugPrint('⚠️ Invalid notification data: type is empty'); + _safeNavigate(() => Get.offAll(() => MainController())); + return; + } + + debugPrint('📍 Notification nav → type=$type id=$idStr'); + + if (type == 'chat') { + final int chatId = int.tryParse(idStr ?? '') ?? 0; + if (chatId == 0) { + _safeNavigate(() => Get.offAll(() => MainController())); + return; + } + debugPrint('💬 Navigating to Chat $chatId'); + _safeNavigate(() { + try { + if (Get.isDialogOpen ?? false) Get.back(); + if (Get.isBottomSheetOpen ?? false) Get.back(); + Navigator.of(Get.context!).popUntil((route) { + return route.isFirst || + route.settings.name == '/splash' || + route.settings.name == '/MainController'; + }); + } catch (_) {} + Future.delayed(const Duration(milliseconds: 200), () { + if (Get.currentRoute == '/LiveChatScreen') { + Get.off( + () => LiveChatScreen(chatid: chatId, fileid: '0'), + preventDuplicates: false, + ); + } else { + Get.to( + () => LiveChatScreen(chatid: chatId, fileid: '0'), + preventDuplicates: false, + ); + } + }); + }); + } else if (type == 'service') { + final int serviceId = int.tryParse(idStr ?? '') ?? 0; + if (serviceId == 0) { + _safeNavigate(() => Get.offAll(() => MainController())); + return; + } + debugPrint('📋 Navigating to Service $serviceId'); + _safeNavigate( + () => Get.offAll( + () => MainController( + initialIndex: 2, + child: DetailScreen(id: serviceId, sourceTabIndex: 2), + ), + ), + ); + } else { + debugPrint("❓ Unknown type '$type' → NotificationScreen"); + _safeNavigate(() { + Get.offAll(() => const MainController()); + Future.delayed( + const Duration(milliseconds: 300), + () => Get.to(() => const NotificationScreen()), + ); + }); + } + } catch (e) { + debugPrint('❌ Error handling notification nav: $e'); + try { + final String? token = await localStore.getToken(); + if (token != null && token.isNotEmpty && token != 'null') { + _safeNavigate(() => Get.offAll(() => MainController())); + } else { + _safeNavigate(() => Get.offAllNamed(ConstRouters.login)); + } + } catch (_) { + _safeNavigate(() => Get.offAllNamed(ConstRouters.login)); + } + } + } + + void _safeNavigate(Function action) { + if (Get.key.currentState != null) { + action(); + return; + } + int attempts = 0; + Future.doWhile(() async { + await Future.delayed(const Duration(milliseconds: 100)); + attempts++; + if (Get.key.currentState != null) { + action(); + return false; + } + return attempts < 20; + }); + } +} diff --git a/lib/view/Mahi_chat/chat_profile_screen.dart b/lib/view/Mahi_chat/chat_profile_screen.dart new file mode 100644 index 0000000..5a86000 --- /dev/null +++ b/lib/view/Mahi_chat/chat_profile_screen.dart @@ -0,0 +1,373 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/consts/download_helper.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +import 'package:photo_view/photo_view.dart'; + +class ChatProfileScreen extends ConsumerWidget { + final int chatid; + + const ChatProfileScreen({super.key, required this.chatid}); + + // Helper function to check if document is valid + bool _isValidDocument(dynamic doc) { + // Check if fileName exists and is not empty + final hasFileName = + doc.fileName != null && doc.fileName.toString().trim().isNotEmpty; + + // Check if filePath exists and is not empty + final hasFilePath = + doc.filePath != null && doc.filePath.toString().trim().isNotEmpty; + + // Return true only if both fileName and filePath exist + return hasFileName && hasFilePath; + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final result = ref.watch(chatDocumentProvider(chatid)); + + return Scaffold( + appBar: PreferredSize( + preferredSize: const Size.fromHeight(240), + child: AppBar( + automaticallyImplyLeading: true, + backgroundColor: Colors.transparent, + elevation: 0, + centerTitle: true, + title: const Text( + "Profile", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w400, + fontSize: 20, + height: 1.4, + letterSpacing: 0.6, + color: Colors.black, + ), + ), + + flexibleSpace: result.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, st) => Center(child: Text(e.toString())), + data: (data) { + return Container( + width: double.infinity, + height: 282, + padding: const EdgeInsets.only(top: 100, bottom: 20), + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: const Color(0xFFDEDEDE), + width: 1, + ), + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircleAvatar( + radius: 45, + backgroundImage: NetworkImage(data.profile), + ), + const SizedBox(height: 12), + Text( + data.name, + style: Theme.of(context).textTheme.titleLarge!.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text( + data.role, + style: TextStyle(fontSize: 16, color: Colors.grey[700]), + ), + ], + ), + ); + }, + ), + ), + ), + + body: result.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, st) => Center(child: Text(e.toString())), + data: (data) { + // Filter out invalid documents + final senderList = data.userUploadedDocuments + .where((doc) => _isValidDocument(doc)) + .toList(); + + final receiverList = data.adminUploadedDocuments + .where((doc) => _isValidDocument(doc)) + .toList(); + + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ---------------- Shared by Taxglide ---------------- + const Text( + "Shared By Taxglide", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + fontSize: 20, + height: 1.4, + letterSpacing: 0.6, + color: Colors.black, + ), + ), + + const SizedBox(height: 10), + + receiverList.isEmpty + ? const Text("No documents from Taxglide") + : SizedBox( + height: 110, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: receiverList.length, + separatorBuilder: (_, __) => + const SizedBox(width: 12), + itemBuilder: (_, index) { + final doc = receiverList[index]; + final isImage = DownloadHelper.isImageFile( + doc.filePath, + ); + final isPdf = + DownloadHelper.getFileExtension(doc.filePath) == + 'pdf'; + + return GestureDetector( + onTap: () { + if (isImage) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ImagePreviewScreen( + imageUrl: doc.filePath, + ), + ), + ); + } else if (isPdf) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => PdfPreviewScreen( + pdfUrl: doc.filePath, + fileName: doc.fileName, + ), + ), + ); + } + }, + child: Container( + width: 100, + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.grey.shade300, + ), + ), + child: Column( + children: [ + Expanded( + child: isImage + ? ClipRRect( + borderRadius: + BorderRadius.circular(8), + child: Image.network( + doc.filePath, + width: 100, + fit: BoxFit.cover, + ), + ) + : isPdf + ? const Icon( + Icons.picture_as_pdf, + size: 40, + color: Colors.red, + ) + : const Icon( + Icons.insert_drive_file, + size: 40, + color: Colors.blue, + ), + ), + ], + ), + ), + ); + }, + ), + ), + + const SizedBox(height: 30), + + // ---------------- Shared by Client ---------------- + const Text( + "Shared By Client", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + fontSize: 20, + height: 1.4, + letterSpacing: 0.6, + color: Colors.black, + ), + ), + const SizedBox(height: 10), + + senderList.isEmpty + ? const Text("No documents from Client") + : SizedBox( + height: 110, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: senderList.length, + separatorBuilder: (_, __) => + const SizedBox(width: 12), + itemBuilder: (_, index) { + final doc = senderList[index]; + final isImage = DownloadHelper.isImageFile( + doc.filePath, + ); + final isPdf = + DownloadHelper.getFileExtension(doc.filePath) == + 'pdf'; + + return GestureDetector( + onTap: () async { + if (isImage) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ImagePreviewScreen( + imageUrl: doc.filePath, + ), + ), + ); + } else { + await DownloadHelper.downloadFile( + doc.filePath, + ); + } + }, + child: Container( + width: 100, + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.grey.shade300, + ), + ), + child: Column( + children: [ + Expanded( + child: isImage + ? ClipRRect( + borderRadius: + BorderRadius.circular(8), + child: Image.network( + doc.filePath, + width: 100, + fit: BoxFit.cover, + ), + ) + : isPdf + ? const Icon( + Icons.picture_as_pdf, + size: 40, + color: Colors.red, + ) + : const Icon( + Icons.insert_drive_file, + size: 40, + color: Colors.blue, + ), + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ); + }, + ), + ); + } +} + +class ImagePreviewScreen extends StatelessWidget { + final String imageUrl; + + const ImagePreviewScreen({super.key, required this.imageUrl}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: Center( + child: PhotoView( + imageProvider: NetworkImage(imageUrl), + backgroundDecoration: const BoxDecoration(color: Colors.black), + ), + ), + ); + } +} + +class PdfPreviewScreen extends StatelessWidget { + final String pdfUrl; + final String fileName; + + const PdfPreviewScreen({ + super.key, + required this.pdfUrl, + required this.fileName, + }); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(fileName), + backgroundColor: Colors.white, + foregroundColor: Colors.black, + ), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.picture_as_pdf, size: 80, color: Colors.red), + const SizedBox(height: 20), + Text( + fileName, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500), + textAlign: TextAlign.center, + ), + const SizedBox(height: 10), + const Text( + "PDF Preview not available", + style: TextStyle(color: Colors.grey), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/Mahi_chat/comman_input_button.dart b/lib/view/Mahi_chat/comman_input_button.dart new file mode 100644 index 0000000..eb7ccf5 --- /dev/null +++ b/lib/view/Mahi_chat/comman_input_button.dart @@ -0,0 +1,569 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:taxglide/consts/download_helper.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart'; + +// ⭐⭐⭐ CHAT INPUT BOX WITH FILE TAG SUPPORT ⭐⭐⭐ +class ChatInputBox extends ConsumerStatefulWidget { + final int chatId; + final VoidCallback? onMessageSent; + + const ChatInputBox(this.chatId, {Key? key, this.onMessageSent}) + : super(key: key); + + @override + ConsumerState createState() => _ChatInputBoxState(); +} + +class _ChatInputBoxState extends ConsumerState { + final TextEditingController messageCtrl = TextEditingController(); + final ImagePicker picker = ImagePicker(); + + List selectedFiles = []; + bool _isSending = false; + + @override + void initState() { + super.initState(); + _requestPermissions(); + } + + // ⭐ Request storage permissions + Future _requestPermissions() async { + await DownloadHelper.requestStoragePermission(); + } + + void showPickerMenu() { + showModalBottomSheet( + context: context, + backgroundColor: Colors.white, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(15)), + ), + builder: (context) { + return SafeArea( + bottom: true, + child: SizedBox( + height: 220, + child: Column( + children: [ + const SizedBox(height: 10), + ListTile( + leading: const Icon(Icons.photo_camera, size: 28), + title: const Text("Camera", style: TextStyle(fontSize: 17)), + onTap: pickFromCamera, + ), + ListTile( + leading: const Icon(Icons.photo_library, size: 28), + title: const Text("Gallery", style: TextStyle(fontSize: 17)), + onTap: pickFromGallery, + ), + ListTile( + leading: const Icon(Icons.attach_file, size: 28), + title: const Text("Files", style: TextStyle(fontSize: 17)), + onTap: pickDocuments, + ), + const SizedBox(height: 10), + ], + ), + ), + ); + }, + ); + } + + Future pickFromCamera() async { + Navigator.pop(context); + + try { + var status = await Permission.camera.status; + + // Handle cases where we cannot show the system dialog again + // Skip strict blocks on iOS Simulator by just trying to launch picker + if (!Platform.isIOS || status.isGranted || status.isLimited) { + if (status.isPermanentlyDenied || (Platform.isIOS && status.isDenied)) { + status = await Permission.camera.request(); + if (!status.isGranted && !status.isLimited) { + _showPermissionDialog("Camera"); + return; + } + } + } + + final XFile? image = await picker.pickImage( + source: ImageSource.camera, + maxWidth: 1920, + maxHeight: 1080, + imageQuality: 85, + ); + + if (image != null) { + setState(() => selectedFiles.add(File(image.path))); + } + } catch (e) { + debugPrint("❌ Camera error: $e"); + // If it's a simulator, it will throw an error since there is no camera + if (Platform.isIOS && e.toString().contains("camera not available")) { + _showErrorSnackbar("Camera not available on iOS Simulator"); + } else { + _showErrorSnackbar("Failed to capture image"); + } + } + } + + Future pickFromGallery() async { + Navigator.pop(context); + + try { + var status = await Permission.photos.status; + + if (status.isPermanentlyDenied || (Platform.isIOS && status.isDenied)) { + status = await Permission.photos.request(); + if (!status.isGranted && !status.isLimited && !Platform.isIOS) { + _showPermissionDialog("Photos"); + return; + } + } + + final List? images = await picker.pickMultiImage( + maxWidth: 1920, + maxHeight: 1080, + imageQuality: 85, + ); + + if (images != null && images.isNotEmpty) { + setState(() { + selectedFiles.addAll(images.map((e) => File(e.path))); + }); + } + } catch (e) { + print("❌ Gallery error: $e"); + _showErrorSnackbar("Failed to pick images"); + } + } + + Future pickDocuments() async { + Navigator.pop(context); + + try { + FilePickerResult? result = await FilePicker.platform.pickFiles( + allowMultiple: true, + type: FileType.any, + ); + + if (result != null && result.files.isNotEmpty) { + setState(() { + selectedFiles.addAll( + result.paths.where((e) => e != null).map((e) => File(e!)), + ); + }); + } + } catch (e) { + print("❌ File picker error: $e"); + _showErrorSnackbar("Failed to pick files"); + } + } + + void _showPermissionDialog(String permissionName) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("$permissionName Permission Required"), + content: Text( + "Allow Taxglide to access your $permissionName to capture and upload files easily. You can enable this in the app settings.", + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Cancel"), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + openAppSettings(); + }, + child: const Text("Go to Settings"), + ), + ], + ), + ); + } + + void _showErrorSnackbar(String message) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + backgroundColor: Colors.red, + content: Text(message), + duration: const Duration(seconds: 2), + ), + ); + } + + void removeFile(int index) { + setState(() { + selectedFiles.removeAt(index); + }); + } + + String getFileName(String path) { + return path.split('/').last; + } + + IconData getFileIcon(String path) { + final ext = path.split('.').last.toLowerCase(); + + if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) { + return Icons.image; + } else if (ext == 'pdf') { + return Icons.picture_as_pdf; + } else if (['doc', 'docx'].contains(ext)) { + return Icons.description; + } else if (['xls', 'xlsx'].contains(ext)) { + return Icons.table_chart; + } else { + return Icons.insert_drive_file; + } + } + + Future sendMessage() async { + if (_isSending) return; // Prevent double-tap + + String text = messageCtrl.text.trim(); + + if (text.isEmpty && selectedFiles.isEmpty) return; + + // ⭐ Get the tagged message + final taggedMessage = ref.read(taggedMessageProvider); + final tagId = taggedMessage?.id ?? 0; + + setState(() => _isSending = true); + + // Show loading dialog + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => WillPopScope( + onWillPop: () async => false, + child: const Center( + child: Card( + child: Padding( + padding: EdgeInsets.all(20), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text("Sending message..."), + ], + ), + ), + ), + ), + ), + ); + + try { + List filesToUpload = []; + + // ⭐⭐⭐ Save files to Send folder + if (selectedFiles.isNotEmpty) { + print("📤 Saving ${selectedFiles.length} files to Send folder..."); + + for (File file in selectedFiles) { + try { + // Try to save to Send folder, fallback to original if fails + final savedPath = await DownloadHelper.saveToSendFolder(file); + filesToUpload.add(File(savedPath)); + } catch (e) { + print("⚠️ Could not save file, using original: $e"); + filesToUpload.add(file); + } + } + + print("✅ Files prepared for upload: ${filesToUpload.length}"); + } + + // Send message with files + await ApiRepository().sendChatMessage( + chatId: widget.chatId, + messages: text, + tagId: tagId, + files: filesToUpload, + ); + + // Refresh chat messages + await ref.read(chatMessagesProvider(widget.chatId).notifier).refresh(); + ref.invalidate(chatDocumentProvider); + print("✅ Message sent successfully with tagId: $tagId"); + + // Close loading dialog + if (mounted) Navigator.pop(context); + + // Clear input + if (mounted) { + setState(() { + messageCtrl.clear(); + selectedFiles.clear(); + _isSending = false; + }); + } + + // Clear the tagged message + ref.read(taggedMessageProvider.notifier).state = null; + + // Notify parent to scroll to bottom + if (widget.onMessageSent != null) { + widget.onMessageSent!(); + } + } catch (e) { + print("❌ Error sending message: $e"); + + // Close loading dialog + if (mounted) Navigator.pop(context); + + setState(() => _isSending = false); + + // Show error message + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + backgroundColor: Colors.red, + content: Row( + children: [ + const Icon(Icons.error_outline, color: Colors.white), + const SizedBox(width: 8), + Expanded( + child: Text( + "Failed to send: ${e.toString()}", + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + duration: const Duration(seconds: 4), + action: SnackBarAction( + label: "Retry", + textColor: Colors.white, + onPressed: sendMessage, + ), + ), + ); + } + } + } + + @override + Widget build(BuildContext context) { + final taggedMessage = ref.watch(taggedMessageProvider); + + return SafeArea( + bottom: true, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + color: Colors.white, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // ⭐⭐⭐ SELECTED FILES PREVIEW (like WhatsApp) + if (selectedFiles.isNotEmpty) + Container( + height: 100, + margin: const EdgeInsets.only(bottom: 10), + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: selectedFiles.length, + itemBuilder: (context, index) { + final file = selectedFiles[index]; + final isImage = DownloadHelper.isImageFile(file.path); + + return Container( + width: 80, + margin: const EdgeInsets.only(right: 8), + decoration: BoxDecoration( + border: Border.all(color: Colors.grey[300]!), + borderRadius: BorderRadius.circular(8), + ), + child: Stack( + children: [ + // File preview + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: isImage + ? Image.file( + file, + width: 80, + height: 100, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) { + return const Center( + child: Icon(Icons.broken_image), + ); + }, + ) + : Center( + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Icon( + getFileIcon(file.path), + size: 30, + color: Colors.grey[600], + ), + const SizedBox(height: 4), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 4, + ), + child: Text( + getFileName(file.path), + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 9), + ), + ), + ], + ), + ), + ), + + // Remove button + Positioned( + top: 2, + right: 2, + child: GestureDetector( + onTap: () => removeFile(index), + child: Container( + padding: const EdgeInsets.all(2), + decoration: const BoxDecoration( + color: Colors.black54, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.close, + size: 16, + color: Colors.white, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + + // Input Row + Row( + children: [ + Expanded( + child: Container( + constraints: const BoxConstraints( + minHeight: 62, + maxHeight: 150, + ), + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: const Color(0xFFCACACA)), + boxShadow: const [ + BoxShadow( + color: Colors.black26, + offset: Offset(0, 4), + blurRadius: 7.8, + ), + ], + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + controller: messageCtrl, + maxLines: null, + minLines: 1, + keyboardType: TextInputType.multiline, + textInputAction: TextInputAction.newline, + decoration: InputDecoration( + hintText: taggedMessage != null + ? "Reply to ${taggedMessage.user?.name ?? 'message'}" + : "Send your message", + border: InputBorder.none, + contentPadding: const EdgeInsets.symmetric( + vertical: 12, + ), + ), + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: _isSending ? null : showPickerMenu, + child: Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Icon( + Icons.attach_file, + size: 26, + color: _isSending ? Colors.grey : Colors.black, + ), + ), + ), + ], + ), + ), + ), + + const SizedBox(width: 10), + + GestureDetector( + onTap: _isSending ? null : sendMessage, + child: Container( + height: 46, + width: 46, + decoration: BoxDecoration( + color: _isSending ? Colors.grey : const Color(0xFF08710C), + shape: BoxShape.circle, + ), + child: Center( + child: _isSending + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2, + ), + ) + : const Icon( + Icons.send, + color: Colors.white, + size: 22, + ), + ), + ), + ), + ], + ), + ], + ), + ), + ); + } + + @override + void dispose() { + messageCtrl.dispose(); + super.dispose(); + } +} diff --git a/lib/view/Mahi_chat/downloadchat.dart b/lib/view/Mahi_chat/downloadchat.dart new file mode 100644 index 0000000..fa05cc3 --- /dev/null +++ b/lib/view/Mahi_chat/downloadchat.dart @@ -0,0 +1,323 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:taxglide/consts/download_helper.dart'; + +class DownloadsScreen extends StatefulWidget { + const DownloadsScreen({super.key}); + + @override + State createState() => _DownloadsScreenState(); +} + +class _DownloadsScreenState extends State + with SingleTickerProviderStateMixin { + late TabController _tabController; + + List sentFiles = []; + List receivedFiles = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + _loadFiles(); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + Future _loadFiles() async { + setState(() { + isLoading = true; + }); + + try { + final sent = await DownloadHelper.getSentFiles(); + final received = await DownloadHelper.getReceivedFiles(); + + setState(() { + sentFiles = sent; + receivedFiles = received; + isLoading = false; + }); + } catch (e) { + print("Error loading files: $e"); + setState(() { + isLoading = false; + }); + } + } + + Future _deleteFile(String filePath, bool isSent) async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text("Delete File"), + content: const Text("Are you sure you want to delete this file?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + style: TextButton.styleFrom(foregroundColor: Colors.red), + child: const Text("Delete"), + ), + ], + ), + ); + + if (confirmed == true) { + final success = await DownloadHelper.deleteFile(filePath); + + if (success) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("File deleted successfully"), + backgroundColor: Colors.green, + ), + ); + _loadFiles(); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Failed to delete file"), + backgroundColor: Colors.red, + ), + ); + } + } + } + + String _getFileName(String path) { + return path.split('/').last; + } + + String _getFileSize(File file) { + final bytes = file.lengthSync(); + if (bytes < 1024) return "$bytes B"; + if (bytes < 1024 * 1024) return "${(bytes / 1024).toStringAsFixed(1)} KB"; + return "${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB"; + } + + IconData _getFileIcon(String path) { + final ext = path.split('.').last.toLowerCase(); + + if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) { + return Icons.image; + } else if (ext == 'pdf') { + return Icons.picture_as_pdf; + } else if (['doc', 'docx'].contains(ext)) { + return Icons.description; + } else if (['xls', 'xlsx'].contains(ext)) { + return Icons.table_chart; + } else { + return Icons.insert_drive_file; + } + } + + Color _getFileIconColor(String path) { + final ext = path.split('.').last.toLowerCase(); + + if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) { + return Colors.blue; + } else if (ext == 'pdf') { + return Colors.red; + } else if (['doc', 'docx'].contains(ext)) { + return Colors.indigo; + } else if (['xls', 'xlsx'].contains(ext)) { + return Colors.green; + } else { + return Colors.grey; + } + } + + Widget _buildFileList(List files, bool isSent) { + if (isLoading) { + return const Center(child: CircularProgressIndicator()); + } + + if (files.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + isSent ? Icons.upload_file : Icons.download, + size: 80, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + isSent ? "No sent files" : "No downloaded files", + style: TextStyle( + fontSize: 18, + color: Colors.grey[600], + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 8), + Text( + isSent + ? "Files you upload will appear here" + : "Downloaded files will appear here", + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + ), + ], + ), + ); + } + + return RefreshIndicator( + onRefresh: _loadFiles, + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: files.length, + itemBuilder: (context, index) { + final file = files[index]; + final fileName = _getFileName(file.path); + final fileSize = _getFileSize(file); + final isImage = DownloadHelper.isImageFile(file.path); + + return Card( + margin: const EdgeInsets.only(bottom: 12), + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + child: InkWell( + onTap: () => DownloadHelper.openDownloadedFile(file.path), + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + // File icon or image preview + Container( + width: 50, + height: 50, + decoration: BoxDecoration( + color: _getFileIconColor(file.path).withOpacity(0.1), + borderRadius: BorderRadius.circular(8), + ), + child: isImage + ? ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.file(file, fit: BoxFit.cover), + ) + : Icon( + _getFileIcon(file.path), + size: 30, + color: _getFileIconColor(file.path), + ), + ), + + const SizedBox(width: 12), + + // File info + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + fileName, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 4), + Text( + fileSize, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ], + ), + ), + + const SizedBox(width: 8), + + // Delete button + IconButton( + icon: const Icon(Icons.delete_outline), + color: Colors.red, + onPressed: () => _deleteFile(file.path, isSent), + ), + ], + ), + ), + ), + ); + }, + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text( + "Downloads", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + elevation: 1, + foregroundColor: Colors.black, + bottom: TabBar( + controller: _tabController, + labelColor: const Color(0xFF630A73), + unselectedLabelColor: Colors.grey, + indicatorColor: const Color(0xFF630A73), + tabs: [ + Tab( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.upload, size: 18), + const SizedBox(width: 6), + Text("Sent (${sentFiles.length})"), + ], + ), + ), + Tab( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.download, size: 18), + const SizedBox(width: 6), + Text("Received (${receivedFiles.length})"), + ], + ), + ), + ], + ), + ), + body: TabBarView( + controller: _tabController, + children: [ + _buildFileList(sentFiles, true), + _buildFileList(receivedFiles, false), + ], + ), + floatingActionButton: FloatingActionButton( + onPressed: _loadFiles, + backgroundColor: const Color(0xFF630A73), + child: const Icon(Icons.refresh, color: Colors.white), + ), + ); + } +} diff --git a/lib/view/Mahi_chat/file_images_screen.dart b/lib/view/Mahi_chat/file_images_screen.dart new file mode 100644 index 0000000..2c8a24a --- /dev/null +++ b/lib/view/Mahi_chat/file_images_screen.dart @@ -0,0 +1,690 @@ +// ⭐⭐⭐ UPDATED SWIPEABLE MESSAGE BUBBLE WITH IMAGE GRID VIEWER ⭐⭐⭐ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:taxglide/consts/download_helper.dart'; +import 'package:taxglide/model/chat_model.dart'; + +class SwipeableMessageBubble extends StatefulWidget { + final MessageModel message; + final DateTime msgDate; + final String Function(DateTime) formatTime; + final Widget Function(int, int) buildTick; + final VoidCallback onSwipe; + final Function(int?)? onParentTagTap; + final Function(List imageUrls, int initialIndex)? + onImageTap; // 🖼️ NEW + + const SwipeableMessageBubble({ + super.key, + required this.message, + required this.msgDate, + required this.formatTime, + required this.buildTick, + required this.onSwipe, + this.onParentTagTap, + this.onImageTap, // 🖼️ NEW + }); + + @override + State createState() => SwipeableMessageBubbleState(); +} + +class SwipeableMessageBubbleState extends State + with SingleTickerProviderStateMixin { + double _dragExtent = 0; + late AnimationController _controller; + late Animation _animation; + final Map _downloadingFiles = {}; + final Map _downloadedFiles = {}; + bool _isHighlighted = false; + + void highlight() { + if (!mounted) return; + // Reset first to ensure it re-triggers if already highlighted + setState(() => _isHighlighted = false); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + setState(() => _isHighlighted = true); + Future.delayed(const Duration(milliseconds: 1500), () { + if (mounted) setState(() => _isHighlighted = false); + }); + }); + } + + @override + void initState() { + super.initState(); + _controller = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 200), + ); + _animation = Tween(begin: 0, end: 0).animate(_controller) + ..addListener(() { + setState(() { + _dragExtent = _animation.value; + }); + }); + + _checkDownloadedFiles(); + } + + Future _checkDownloadedFiles() async { + for (var doc in widget.message.uploadedDocuments) { + final existingPath = await DownloadHelper.checkFileExistsInReceived( + doc.filePath, + ); + if (existingPath != null && mounted) { + setState(() { + _downloadedFiles[doc.fileName] = true; + }); + } + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _handleDragUpdate(DragUpdateDetails details) { + if (!mounted) return; + + final isUserMessage = widget.message.chatBy == "user"; + final delta = details.primaryDelta ?? 0; + + if ((isUserMessage && delta < 0) || (!isUserMessage && delta > 0)) { + setState(() { + _dragExtent += delta; + _dragExtent = _dragExtent.clamp( + isUserMessage ? -80.0 : 0.0, + isUserMessage ? 0.0 : 80.0, + ); + }); + } + } + + void _handleDragEnd(DragEndDetails details) { + if (!mounted) return; + + final threshold = 60.0; + + if (_dragExtent.abs() > threshold) { + widget.onSwipe(); + } + + _animation = Tween( + begin: _dragExtent, + end: 0, + ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut)); + + _controller.reset(); + _controller.forward(); + } + + // 🖼️ NEW: Handle image tap - open grid viewer + void _handleImageTap(int tappedIndex) { + if (widget.onImageTap == null) return; + + // Get all image URLs from uploaded documents + final imageUrls = widget.message.uploadedDocuments + .where((doc) => DownloadHelper.isImageFile(doc.fileName)) + .map((doc) => doc.filePath) + .toList(); + + if (imageUrls.isNotEmpty) { + widget.onImageTap!(imageUrls, tappedIndex); + } + } + + Future _handleFileView(String url, String fileName) async { + if (!mounted) return; + + try { + print("👁️ Opening file: $fileName"); + + final existingPath = await DownloadHelper.checkFileExistsInReceived(url); + + if (existingPath != null) { + await DownloadHelper.openDownloadedFile(existingPath); + } else { + final sendFolder = await DownloadHelper.getSendFolder(); + final localPath = '${sendFolder.path}/$fileName'; + final file = File(localPath); + + if (await file.exists()) { + await DownloadHelper.openDownloadedFile(localPath); + } else { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("File not found locally"), + backgroundColor: Colors.orange, + duration: Duration(seconds: 2), + ), + ); + } + } + } + } catch (e) { + print("❌ View error: $e"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Could not open file: $e"), + backgroundColor: Colors.red, + ), + ); + } + } + } + + Future _handleFileDownload(String url, String fileName) async { + if (!mounted) return; + + setState(() { + _downloadingFiles[fileName] = true; + }); + + try { + print("🔗 Downloading from: $url"); + final result = await DownloadHelper.downloadFileToReceived(url); + + if (!mounted) return; + + if (result['success'] == true) { + setState(() { + _downloadedFiles[fileName] = true; + }); + + if (mounted) { + if (result['isNewDownload'] == false) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Opening $fileName"), + backgroundColor: Colors.green, + duration: const Duration(seconds: 1), + ), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Downloaded $fileName"), + backgroundColor: Colors.green, + duration: const Duration(seconds: 1), + ), + ); + } + } + } + } catch (e) { + print("❌ Download error: $e"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Download failed: $e"), + backgroundColor: Colors.red, + ), + ); + } + } finally { + if (mounted) { + setState(() { + _downloadingFiles[fileName] = false; + }); + } + } + } + + Future _handleDownloadedFileView(String url, String fileName) async { + if (!mounted) return; + + try { + final existingPath = await DownloadHelper.checkFileExistsInReceived(url); + if (existingPath != null) { + await DownloadHelper.openDownloadedFile(existingPath); + } + } catch (e) { + print("❌ View error: $e"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Could not open file: $e"), + backgroundColor: Colors.red, + ), + ); + } + } + } + + @override + Widget build(BuildContext context) { + final isUserMessage = widget.message.chatBy == "user"; + final hasDocuments = widget.message.uploadedDocuments.isNotEmpty; + + print("💬 Building message bubble:"); + print(" - ID: ${widget.message.id}"); + print(" - chatBy: ${widget.message.chatBy}"); + print( + " - uploadedDocuments count: ${widget.message.uploadedDocuments.length}", + ); + + return Stack( + children: [ + if (_dragExtent.abs() > 10) + Positioned( + right: isUserMessage ? 20 : null, + left: isUserMessage ? null : 20, + top: 0, + bottom: 0, + child: Center( + child: Icon( + Icons.reply_rounded, + color: Colors.grey[600], + size: 24, + ), + ), + ), + GestureDetector( + onHorizontalDragUpdate: _handleDragUpdate, + onHorizontalDragEnd: _handleDragEnd, + child: Transform.translate( + offset: Offset(_dragExtent, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.message.user != null) + Padding( + padding: const EdgeInsets.only(left: 5, right: 5), + child: Align( + alignment: isUserMessage + ? Alignment.centerRight + : Alignment.centerLeft, + child: Text( + widget.message.user!.name, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), + ), + ), + if (widget.message.parentTag != null) + GestureDetector( + onTap: () { + if (widget.onParentTagTap != null) { + widget.onParentTagTap!( + widget.message.parentTag?.id ?? widget.message.tagId, + ); + } + }, + child: Align( + alignment: isUserMessage + ? Alignment.centerRight + : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.only( + bottom: 4, + left: 5, + right: 5, + ), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.60, + ), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.05), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: const Color(0xFF630A73).withOpacity(0.3), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 3, + height: 30, + decoration: BoxDecoration( + color: const Color(0xFF630A73), + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.message.parentTag!.type == "file") + Row( + children: [ + Icon( + Icons.insert_drive_file, + size: 14, + color: Colors.grey[600], + ), + const SizedBox(width: 4), + Expanded( + child: Text( + widget + .message + .parentTag! + .fileName ?? + "File", + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Colors.grey[700], + ), + ), + ), + ], + ), + Text( + widget.message.parentTag!.message, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + Align( + alignment: isUserMessage + ? Alignment.centerRight + : Alignment.centerLeft, + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.70, + ), + child: Container( + margin: const EdgeInsets.symmetric(vertical: 6), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 14, + ), + decoration: BoxDecoration( + color: _isHighlighted + ? Colors.green.withOpacity(0.2) + : (isUserMessage + ? const Color(0xFFFFF8E2) + : Colors.white), + border: Border.all( + color: _isHighlighted + ? Colors.green.withOpacity(0.5) + : (isUserMessage + ? const Color(0xFFF9D9C8) + : const Color(0xFFE2E2E2)), + ), + borderRadius: BorderRadius.circular(10), + boxShadow: isUserMessage + ? [] + : const [ + BoxShadow( + color: Color(0x40979797), + blurRadius: 3.6, + offset: Offset(0, 1), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ⭐⭐⭐ DISPLAY uploadedDocuments WITH IMAGE GRID SUPPORT + if (hasDocuments) + ...widget.message.uploadedDocuments.asMap().entries.map(( + entry, + ) { + final index = entry.key; + final doc = entry.value; + final isImage = DownloadHelper.isImageFile( + doc.fileName, + ); + final isDownloading = + _downloadingFiles[doc.fileName] ?? false; + final isDownloaded = + _downloadedFiles[doc.fileName] ?? false; + + // 🖼️ Calculate image index (only count images before this one) + final imageIndex = widget + .message + .uploadedDocuments + .sublist(0, index) + .where( + (d) => + DownloadHelper.isImageFile(d.fileName), + ) + .length; + + return GestureDetector( + onTap: isImage + ? () => + _handleImageTap( + imageIndex, + ) // 🖼️ Open grid viewer + : (isUserMessage + ? () => _handleFileView( + doc.filePath, + doc.fileName, + ) + : null), + child: Container( + margin: const EdgeInsets.only(bottom: 8), + child: isImage + ? Stack( + children: [ + ClipRRect( + borderRadius: + BorderRadius.circular(8), + child: Image.network( + doc.filePath, + width: 150, + height: 100, + fit: BoxFit.cover, + errorBuilder: + (context, error, stack) { + return Container( + width: 200, + height: 150, + color: Colors.grey[300], + child: const Center( + child: Icon( + Icons.broken_image, + ), + ), + ); + }, + ), + ), + // ⭐ Download/View icon for receiver messages + if (!isUserMessage) + Positioned( + top: 8, + right: 8, + child: GestureDetector( + onTap: isDownloading + ? null + : isDownloaded + ? () => + _handleDownloadedFileView( + doc.filePath, + doc.fileName, + ) + : () => + _handleFileDownload( + doc.filePath, + doc.fileName, + ), + child: Container( + padding: + const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.black + .withOpacity(0.6), + shape: BoxShape.circle, + ), + child: isDownloading + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: + AlwaysStoppedAnimation< + Color + >( + Colors + .white, + ), + ), + ) + : Icon( + isDownloaded + ? Icons + .visibility + : Icons + .download, + color: Colors.white, + size: 20, + ), + ), + ), + ), + ], + ) + : Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.grey[100], + borderRadius: BorderRadius.circular( + 8, + ), + border: Border.all( + color: Colors.grey[300]!, + ), + ), + child: Row( + children: [ + Icon( + Icons.insert_drive_file, + color: Colors.grey[600], + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + doc.fileName, + style: const TextStyle( + fontSize: 13, + fontWeight: + FontWeight.w600, + ), + ), + Text( + doc.fileType + .toUpperCase(), + style: TextStyle( + fontSize: 11, + color: Colors.grey[600], + ), + ), + ], + ), + ), + GestureDetector( + onTap: isDownloading + ? null + : () => isUserMessage + ? _handleFileView( + doc.filePath, + doc.fileName, + ) + : isDownloaded + ? _handleDownloadedFileView( + doc.filePath, + doc.fileName, + ) + : _handleFileDownload( + doc.filePath, + doc.fileName, + ), + child: isDownloading + ? const SizedBox( + width: 20, + height: 20, + child: + CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : Icon( + isUserMessage + ? Icons.open_in_new + : isDownloaded + ? Icons.visibility + : Icons.download, + color: Colors.grey[600], + size: 20, + ), + ), + ], + ), + ), + ), + ); + }).toList(), + if (widget.message.message.isNotEmpty) + Text( + widget.message.message, + style: const TextStyle(fontSize: 15), + ), + const SizedBox(height: 3), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text( + widget.formatTime(widget.msgDate), + style: TextStyle( + fontSize: 11, + color: Colors.grey[700], + ), + ), + const SizedBox(width: 4), + widget.buildTick( + widget.message.isDelivered, + widget.message.isRead, + ), + ], + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ], + ); + } +} diff --git a/lib/view/Mahi_chat/live_chat_screen.dart b/lib/view/Mahi_chat/live_chat_screen.dart new file mode 100644 index 0000000..5404749 --- /dev/null +++ b/lib/view/Mahi_chat/live_chat_screen.dart @@ -0,0 +1,1004 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:flutter_riverpod/legacy.dart'; +import 'package:get/get.dart'; + +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/notification_webscoket.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +import 'package:taxglide/model/chat_model.dart'; +import 'package:taxglide/view/Mahi_chat/chat_profile_screen.dart'; +import 'package:taxglide/view/Mahi_chat/comman_input_button.dart'; +import 'package:taxglide/view/Mahi_chat/file_images_screen.dart'; + +import 'package:taxglide/view/Mahi_chat/webscoket.dart'; + +// ⭐ Provider to hold the tagged message +final taggedMessageProvider = StateProvider((ref) => null); + +// ⭐ Global key map to track message positions (if you want from outside) +final messageKeysProvider = StateProvider>((ref) => {}); + +class LiveChatScreen extends ConsumerStatefulWidget { + final int chatid; + final String? fileid; + const LiveChatScreen({super.key, required this.chatid, required this.fileid}); + + @override + ConsumerState createState() => _LiveChatScreenState(); +} + +class _LiveChatScreenState extends ConsumerState + with AutomaticKeepAliveClientMixin, WidgetsBindingObserver { + @override + bool get wantKeepAlive => true; + + final ScrollController scrollController = ScrollController(); + final ChatWebSocketService _wsService = ChatWebSocketService(); + + bool showScrollButton = false; + bool userIsReading = false; + bool _isPaginationLoading = false; + bool _hasNewMessage = false; + bool _isOtherUserTyping = false; + Timer? _typingTimeoutTimer; + + // For reply scroll - FIXED: Use unique key per message + final Map _messageKeys = {}; + + // ⭐⭐⭐ Key variables for smooth pagination + final double _paginationTriggerOffset = 300; // Start loading 300px before top + + @override + void initState() { + super.initState(); + + WidgetsBinding.instance.addObserver(this); + + // ✅ Tell the global notification WS that we are viewing this chat, + // so it suppresses banner notifications for this specific chat. + NotificationWebSocket().setActiveChatId(widget.chatid.toString()); + + _initializeWebSocket(); + + scrollController.addListener(_handleScroll); + + // Refresh immediately in background if already loaded + Future.microtask(() { + final currentState = ref.read(chatMessagesProvider(widget.chatid)); + if (currentState is AsyncData) { + ref.read(chatMessagesProvider(widget.chatid).notifier).refresh(); + } + }); + } + + // ⭐ WhatsApp-like Smooth Pagination Logic + void _handleScroll() { + if (!scrollController.hasClients) return; + + double position = scrollController.position.pixels; + double maxExtent = scrollController.position.maxScrollExtent; + + // In a reversed list, maxExtent is the "top" (older messages) + if (position >= maxExtent - _paginationTriggerOffset && + !_isPaginationLoading) { + _triggerPagination(); + } + + // Show scroll to bottom button + // In a reversed list, bottom is 0 + if (position > 100) { + if (!showScrollButton) { + setState(() => showScrollButton = true); + } + } else { + if (showScrollButton) { + setState(() => showScrollButton = false); + } + } + } + + // ⭐ Simplified pagination for reversed list + Future _triggerPagination() async { + final notifier = ref.read(chatMessagesProvider(widget.chatid).notifier); + if (!notifier.hasNextPage || _isPaginationLoading) return; + + setState(() => _isPaginationLoading = true); + + try { + await notifier.loadMessages(); // Prepends older messages naturally + } catch (e) { + debugPrint("❌ Pagination error: $e"); + } finally { + if (mounted) setState(() => _isPaginationLoading = false); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + super.didChangeAppLifecycleState(state); + + debugPrint("📱 App Lifecycle State: $state"); + + if (state == AppLifecycleState.resumed) { + debugPrint("🔄 App resumed - checking for new messages"); + + if (_hasNewMessage) { + _silentRefresh(); + _hasNewMessage = false; + } + } + } + + Future _silentRefresh() async { + try { + debugPrint("🔄 Starting silent refresh..."); + + await ref.read(chatMessagesProvider(widget.chatid).notifier).refresh(); + + debugPrint("✅ Silent refresh completed"); + + // In a reversed list, new messages are at 0. No manual scroll needed. + // The reverse: true property handles this naturally. + if (mounted) { + setState(() {}); + } + } catch (e) { + debugPrint("❌ Error during silent refresh: $e"); + } + } + + Future _initializeWebSocket() async { + try { + _wsService.onMessageReceived = (Map message) async { + debugPrint("📨 WebSocket message received: $message"); + + try { + final event = message['event'] as String?; + + if (event == 'message.sent' || event == 'message.received') { + debugPrint("🔔 New message detected!"); + + if (WidgetsBinding.instance.lifecycleState == + AppLifecycleState.resumed) { + debugPrint("✅ Screen active - refreshing now"); + await _silentRefresh(); + } else { + debugPrint("⏳ Screen not active - will refresh on resume"); + _hasNewMessage = true; + } + // ℹ️ Notification banner is handled centrally in NotificationWebSocket. + // No need to show it here – it is already suppressed for this chat. + } + + if (event == 'client-typing') { + debugPrint("⌨️ Typing event received: ${message['data']}"); + _handleTypingEvent(message['data']); + } + } catch (e) { + debugPrint("❌ Error handling WebSocket message: $e"); + } + }; + + _wsService.onConnected = () { + debugPrint("✅ WebSocket Connected"); + }; + + _wsService.onDisconnected = () { + debugPrint("🔌 WebSocket Disconnected"); + }; + + _wsService.onError = (error) { + debugPrint("❌ WebSocket Error: $error"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Connection error: $error"), + backgroundColor: Colors.red, + duration: const Duration(seconds: 2), + ), + ); + } + }; + + await _wsService.connect(chatId: widget.chatid.toString()); + } catch (e) { + debugPrint("❌ Error initializing WebSocket: $e"); + } + } + + @override + void dispose() { + // ✅ Clear active chat so notifications resume when user leaves this screen. + NotificationWebSocket().clearActiveChatId(); + WidgetsBinding.instance.removeObserver(this); + _wsService.disconnect(); + scrollController.dispose(); + super.dispose(); + } + + void _handleTypingEvent(dynamic data) { + try { + Map dataMap; + if (data is String) { + dataMap = json.decode(data); + } else if (data is Map) { + dataMap = Map.from(data); + } else { + return; + } + + final bool isTyping = dataMap['is_typing'] == true; + + setState(() { + _isOtherUserTyping = isTyping; + }); + + // Auto-clear typing status after 5 seconds of no update + _typingTimeoutTimer?.cancel(); + if (_isOtherUserTyping) { + _typingTimeoutTimer = Timer(const Duration(seconds: 5), () { + if (mounted) { + setState(() { + _isOtherUserTyping = false; + }); + } + }); + } + } catch (e) { + debugPrint("❌ Error parsing typing data: $e"); + } + } + + void scrollToBottom({bool animated = false}) { + // In a reversed list, bottom is pixels: 0 + if (!scrollController.hasClients) return; + + if (animated) { + scrollController.animateTo( + 0, + duration: const Duration(milliseconds: 400), + curve: Curves.easeOutCubic, + ); + } else { + scrollController.jumpTo(0); + } + } + + // ⭐ FIXED: Use stable key that doesn't change with pagination + bool scrollToMessage(String messageKey) { + final key = _messageKeys[messageKey]; + + if (key != null && key.currentContext != null) { + Scrollable.ensureVisible( + key.currentContext!, + duration: const Duration(milliseconds: 500), + curve: Curves.easeInOut, + alignment: 0.3, + ); + + // Trigger highlight animation + if (key is GlobalKey) { + key.currentState?.highlight(); + } else { + final state = key.currentContext! + .findAncestorStateOfType(); + state?.highlight(); + } + return true; + } + return false; + } + + // ⭐ NEW: Search and scroll to message that might not be loaded yet + Future _scrollToMissingMessage(int tagId) async { + final notifier = ref.read(chatMessagesProvider(widget.chatid).notifier); + + // Check if it exists in locally loaded messages first + final currentMessages = + ref.read(chatMessagesProvider(widget.chatid)).value ?? []; + final existingIndex = currentMessages.indexWhere((m) => m.id == tagId); + + if (existingIndex != -1) { + final targetMsg = currentMessages[existingIndex]; + final keyString = _getMessageKeyString(targetMsg); + + // 1. Try direct scroll + if (scrollToMessage(keyString)) return; + + // 2. If not rendered, perform a smooth animation to force it + final reversedIndex = (currentMessages.length - 1 - existingIndex); + final targetOffset = reversedIndex * 150.0; // Estimated position + + await scrollController.animateTo( + targetOffset, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + scrollToMessage(keyString); + return; + } + + // --- If NOT in memory, paginate silently (no full-screen loader) --- + try { + bool found = false; + int maxRetries = 20; + + while (!found && maxRetries > 0) { + final messages = + ref.read(chatMessagesProvider(widget.chatid)).value ?? []; + final index = messages.indexWhere((m) => m.id == tagId); + + if (index != -1) { + final targetMsg = messages[index]; + final keyString = _getMessageKeyString(targetMsg); + + final reversedIndex = (messages.length - 1 - index); + final targetOffset = reversedIndex * 150.0; + + await scrollController.animateTo( + targetOffset, + duration: const Duration(milliseconds: 400), + curve: Curves.easeOut, + ); + + // Retry highlight after animation + for (int retry = 0; retry < 3; retry++) { + await Future.delayed(Duration(milliseconds: 100 + (retry * 100))); + if (scrollToMessage(keyString)) { + found = true; + break; + } + } + if (found) break; + } + + if (!notifier.hasNextPage) break; + await notifier.loadMessages(); + maxRetries--; + } + + if (!found && mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Could not find the original message")), + ); + } + } catch (e) { + debugPrint("❌ Error searching for message: $e"); + } + } + + // ⭐ FIXED: Generate unique string key for each message + GlobalKey _getKeyForMessage(String messageKey) { + if (!_messageKeys.containsKey(messageKey)) { + _messageKeys[messageKey] = GlobalKey(); + } + return _messageKeys[messageKey] as GlobalKey; + } + + // ⭐ FIXED: Generate stable key from message data + String _getMessageKeyString(MessageModel msg) { + // Unique features: ID, type, and creation time + final id = msg.id; + final createdAt = msg.createdAt ?? ''; + final message = + msg.message.hashCode; // Add message hash for extra uniqueness + return 'msg_${id}_${createdAt}_$message'; + } + + String formatMessageDate(DateTime date) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final msgDay = DateTime(date.year, date.month, date.day); + + if (msgDay == today) return "Today"; + if (msgDay == today.subtract(const Duration(days: 1))) return "Yesterday"; + return "${date.day}-${date.month}-${date.year}"; + } + + String formatTime(DateTime time) { + final hour = time.hour % 12 == 0 ? 12 : time.hour % 12; + final minute = time.minute.toString().padLeft(2, '0'); + final period = time.hour >= 12 ? "PM" : "AM"; + return "$hour:$minute $period"; + } + + Widget buildTick(int isDelivered, int isRead) { + if (isRead == 1) { + return const Icon(Icons.done_all, size: 16, color: Colors.blue); + } else if (isDelivered == 1) { + return const Icon(Icons.done_all, size: 16, color: Colors.grey); + } else { + return const Icon(Icons.check, size: 16, color: Colors.grey); + } + } + + // 🖼️ NEW: Show Image Grid Dialog + void _showImageGridDialog(List imageUrls, int initialIndex) { + showDialog( + context: context, + barrierColor: Colors.black87, + builder: (context) => + ImageGridViewer(imageUrls: imageUrls, initialIndex: initialIndex), + ); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + final chatAsync = ref.watch(chatMessagesProvider(widget.chatid)); + final taggedMessage = ref.watch(taggedMessageProvider); + + return Scaffold( + appBar: AppBar( + title: Text( + (widget.fileid != null && + widget.fileid.toString().isNotEmpty && + widget.fileid.toString() != "0") + ? 'File ID : ${widget.fileid.toString()}' + : "Live Chat", + style: const TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + elevation: 1, + foregroundColor: Colors.black, + centerTitle: true, + actions: [ + Padding( + padding: const EdgeInsets.only(right: 12), + child: GestureDetector( + onTap: () { + Get.to(ChatProfileScreen(chatid: widget.chatid)); + }, + child: Container( + width: 37.446807861328125, + height: 40, + decoration: BoxDecoration( + color: const Color(0xFFFAFAFA), + borderRadius: BorderRadius.circular(6.81), + border: Border.all( + color: const Color(0xFF1E780C), + width: 0.85, + ), + ), + child: const Icon(Icons.person, color: Color(0xFF1E780C)), + ), + ), + ), + ], + ), + body: Stack( + children: [ + Container( + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + ), + Column( + children: [ + Expanded( + child: chatAsync.when( + loading: () => const Center(child: SizedBox.shrink()), + error: (e, _) => Center(child: Text(e.toString())), + data: (messages) { + final seenKeys = {}; + final uniqueMessages = messages.where((msg) { + final key = _getMessageKeyString(msg); + if (seenKeys.contains(key)) return false; + seenKeys.add(key); + return true; + }).toList(); + + final reversedMessages = uniqueMessages.reversed.toList(); + + return Stack( + children: [ + ListView.builder( + controller: scrollController, + reverse: true, // ⭐ Index 0 is now at the bottom + physics: const ClampingScrollPhysics(), + cacheExtent: + 1000, // ⭐ Help with deep scrolling visibility + padding: const EdgeInsets.only( + left: 15, + right: 15, + top: 15, + bottom: 15, + ), + itemCount: reversedMessages.length, + itemBuilder: (context, index) { + final msg = reversedMessages[index]; + final msgDate = DateTime.parse(msg.createdAt!); + + // In reversed list, header shows if previous message (index+1) has different date + final showDateHeader = + index == reversedMessages.length - 1 || + formatMessageDate( + DateTime.parse( + reversedMessages[index + 1].createdAt!, + ), + ) != + formatMessageDate(msgDate); + + // ⭐ FIXED: Use stable key (no index dependency) + final messageKeyString = _getMessageKeyString(msg); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (showDateHeader) + Padding( + padding: const EdgeInsets.symmetric( + vertical: 10, + ), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 5, + ), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.06), + borderRadius: BorderRadius.circular( + 12, + ), + ), + child: Text( + formatMessageDate(msgDate), + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ), + SwipeableMessageBubble( + message: msg, + msgDate: msgDate, + formatTime: formatTime, + buildTick: buildTick, + onSwipe: () { + ref + .read( + taggedMessageProvider.notifier, + ) + .state = + msg; + }, + onParentTagTap: (tagId) { + if (tagId == null) return; + + // ALWAYS call _scrollToMissingMessage now as it handles both + // local smooth scroll and remote paginate search correctly. + _scrollToMissingMessage(tagId); + }, + // 🖼️ NEW: Pass image grid callback + onImageTap: (imageUrls, initialIndex) { + _showImageGridDialog( + imageUrls, + initialIndex, + ); + }, + key: _getKeyForMessage(messageKeyString), + ), + ], + ); + }, + ), + // ⭐⭐⭐ Subtle loading indicator at top + if (_isPaginationLoading) + Positioned( + top: 5, + left: 0, + right: 0, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 6, + ), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.9), + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 4, + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + SizedBox(width: 8), + Text( + "Loading...", + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ), + ), + ], + ); + }, + ), + ), + if (taggedMessage != null) + GestureDetector( + onTap: () { + if (taggedMessage != null) { + // ⭐ FIXED: Need to find the message in the list to get proper key + final chatAsync = ref.read( + chatMessagesProvider(widget.chatid), + ); + chatAsync.whenData((messages) { + _scrollToMissingMessage(taggedMessage.id); + }); + } + }, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 15, + vertical: 8, + ), + decoration: BoxDecoration( + color: Colors.grey[200], + border: Border(top: BorderSide(color: Colors.grey[300]!)), + ), + child: Row( + children: [ + Container( + width: 4, + height: 50, + decoration: BoxDecoration( + color: const Color(0xFF630A73), + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + taggedMessage.user?.name ?? "Unknown", + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + color: Color(0xFF630A73), + ), + ), + const SizedBox(height: 2), + if (taggedMessage.type == "file" && + taggedMessage.fileName != null) + Row( + children: [ + Icon( + Icons.attach_file, + size: 14, + color: Colors.grey[600], + ), + const SizedBox(width: 4), + Expanded( + child: Text( + taggedMessage.fileName!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ), + ], + ) + else + Text( + taggedMessage.message, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.close, size: 20), + padding: EdgeInsets.zero, + onPressed: () { + ref.read(taggedMessageProvider.notifier).state = + null; + }, + ), + ], + ), + ), + ), + if (_isOtherUserTyping) + Padding( + padding: const EdgeInsets.only(left: 20, bottom: 5), + child: Row( + children: [ + const SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Color(0xFF1E780C), + ), + ), + const SizedBox(width: 8), + Text( + "Typing...", + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ), + ChatInputBox( + widget.chatid, + onMessageSent: () { + setState(() { + userIsReading = false; + }); + scrollToBottom(animated: true); + }, + ), + ], + ), + if (showScrollButton) + Positioned( + bottom: 150, + right: 20, + child: FloatingActionButton( + heroTag: "scrollBtn", + backgroundColor: Colors.green, + mini: true, + onPressed: () { + scrollToBottom(animated: true); + }, + child: const Icon(Icons.arrow_downward, color: Colors.white), + ), + ), + ], + ), + ); + } +} + +// 🖼️ NEW: Image Grid Viewer Widget +class ImageGridViewer extends StatefulWidget { + final List imageUrls; + final int initialIndex; + + const ImageGridViewer({ + Key? key, + required this.imageUrls, + required this.initialIndex, + }) : super(key: key); + + @override + State createState() => _ImageGridViewerState(); +} + +class _ImageGridViewerState extends State { + late PageController _pageController; + late int _currentIndex; + + @override + void initState() { + super.initState(); + _currentIndex = widget.initialIndex; + _pageController = PageController(initialPage: widget.initialIndex); + } + + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: Colors.transparent, + insetPadding: EdgeInsets.zero, + child: Container( + width: double.infinity, + height: double.infinity, + color: Colors.black87, + child: Stack( + children: [ + // Main Image Viewer + PageView.builder( + controller: _pageController, + onPageChanged: (index) { + setState(() { + _currentIndex = index; + }); + }, + itemCount: widget.imageUrls.length, + itemBuilder: (context, index) { + return Center( + child: InteractiveViewer( + minScale: 0.5, + maxScale: 4.0, + child: Image.network( + widget.imageUrls[index], + fit: BoxFit.contain, + loadingBuilder: (context, child, loadingProgress) { + if (loadingProgress == null) return child; + return Center( + child: CircularProgressIndicator( + value: loadingProgress.expectedTotalBytes != null + ? loadingProgress.cumulativeBytesLoaded / + loadingProgress.expectedTotalBytes! + : null, + color: Colors.white, + ), + ); + }, + errorBuilder: (context, error, stackTrace) { + return const Center( + child: Icon( + Icons.broken_image, + color: Colors.white54, + size: 64, + ), + ); + }, + ), + ), + ); + }, + ), + + // Close Button + Positioned( + top: 40, + right: 20, + child: IconButton( + icon: const Icon(Icons.close, color: Colors.white, size: 30), + onPressed: () => Navigator.pop(context), + ), + ), + + // Image Counter + Positioned( + top: 50, + left: 0, + right: 0, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + decoration: BoxDecoration( + color: Colors.black54, + borderRadius: BorderRadius.circular(20), + ), + child: Text( + '${_currentIndex + 1} / ${widget.imageUrls.length}', + style: const TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ), + + // Thumbnail Grid at Bottom + Positioned( + bottom: 20, + left: 0, + right: 0, + child: Container( + height: 80, + child: ListView.builder( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 20), + itemCount: widget.imageUrls.length, + itemBuilder: (context, index) { + final isSelected = index == _currentIndex; + return GestureDetector( + onTap: () { + _pageController.animateToPage( + index, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + }, + child: Container( + width: 112.8125, + height: 66.88169860839844, + margin: const EdgeInsets.only(right: 10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: isSelected + ? Colors.white + : Colors.transparent, + width: 3, + ), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(6), + child: Image.network( + widget.imageUrls[index], + fit: BoxFit.cover, + loadingBuilder: (context, child, loadingProgress) { + if (loadingProgress == null) return child; + return Container( + color: Colors.grey[800], + child: const Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white54, + ), + ), + ), + ); + }, + errorBuilder: (context, error, stackTrace) { + return Container( + color: Colors.grey[800], + child: const Icon( + Icons.broken_image, + color: Colors.white54, + size: 24, + ), + ); + }, + ), + ), + ), + ); + }, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/Mahi_chat/webscoket.dart b/lib/view/Mahi_chat/webscoket.dart new file mode 100644 index 0000000..da9517a --- /dev/null +++ b/lib/view/Mahi_chat/webscoket.dart @@ -0,0 +1,296 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// WebSocket service for real-time chat communication +class ChatWebSocketService { + static final ChatWebSocketService _instance = + ChatWebSocketService._internal(); + factory ChatWebSocketService() => _instance; + ChatWebSocketService._internal(); + + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Timer? _pingTimer; + Timer? _reconnectTimer; + + bool _isConnected = false; + bool _isIntentionalClose = false; + int _reconnectAttempts = 0; + static const int _maxReconnectAttempts = 5; + static const Duration _reconnectDelay = Duration(seconds: 3); + + // Callbacks + Function(Map)? onMessageReceived; + Function()? onConnected; + Function()? onDisconnected; + Function(dynamic error)? onError; + + String? _currentChatId; + String? _wsUrl; + + /// Check if WebSocket is currently connected + bool get isConnected => _isConnected; + + /// Get current chat ID + String? get currentChatId => _currentChatId; + + /// Connect to WebSocket for a specific chat + Future connect({ + required String chatId, + String baseUrl = "wss://taxglide.amrithaa.net:443/reverb", + String appKey = "2yj0lyzc9ylw2h03ts6i", + }) async { + try { + // Close existing connection if any + await disconnect(); + + _currentChatId = chatId; + _wsUrl = "$baseUrl/app/$appKey?protocol=7&client=js&version=1.0"; + _isIntentionalClose = false; + _reconnectAttempts = 0; + + await _establishConnection(); + } catch (e) { + debugPrint("❌ Connection error: $e"); + onError?.call(e); + _scheduleReconnect(); + } + } + + /// Establish WebSocket connection + Future _establishConnection() async { + try { + debugPrint("🔌 Connecting to: $_wsUrl"); + + _channel = WebSocketChannel.connect(Uri.parse(_wsUrl!)); + + // Listen to messages + _subscription = _channel!.stream.listen( + _handleMessage, + onError: _handleError, + onDone: _handleDisconnection, + cancelOnError: false, + ); + + // Wait a bit for connection to establish + await Future.delayed(const Duration(milliseconds: 500)); + + _isConnected = true; + _reconnectAttempts = 0; + debugPrint("✅ WebSocket connected"); + + // Subscribe to chat channel + _subscribeToChannel(); + + // Start ping timer + _startPingTimer(); + + onConnected?.call(); + } catch (e) { + debugPrint("❌ Failed to establish connection: $e"); + _isConnected = false; + rethrow; + } + } + + /// Handle incoming messages + void _handleMessage(dynamic data) { + try { + debugPrint("📨 Received: $data"); + + final Map message = json.decode(data); + + // Handle Pusher ping + if (message['event'] == 'pusher:ping') { + _sendPong(); + return; + } + + // Handle connection established + if (message['event'] == 'pusher:connection_established') { + debugPrint("🔗 Connection established"); + return; + } + + // Handle subscription succeeded + if (message['event'] == 'pusher_internal:subscription_succeeded') { + debugPrint("✅ Subscribed to chat.${_currentChatId}"); + return; + } + + // Handle custom events (your chat messages) + if (message['event'] != null && + !message['event'].toString().startsWith('pusher')) { + onMessageReceived?.call(message); + } + } catch (e) { + debugPrint("❌ Error parsing message: $e"); + onError?.call(e); + } + } + + /// Handle WebSocket errors + void _handleError(dynamic error) { + debugPrint("❌ WebSocket error: $error"); + _isConnected = false; + onError?.call(error); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + /// Handle disconnection + void _handleDisconnection() { + debugPrint("🔌 WebSocket disconnected"); + _isConnected = false; + _stopPingTimer(); + onDisconnected?.call(); + + if (!_isIntentionalClose) { + _scheduleReconnect(); + } + } + + /// Subscribe to chat channel + void _subscribeToChannel() { + if (_currentChatId == null) return; + + final subscribeMessage = { + 'event': 'pusher:subscribe', + 'data': {'channel': 'chat.$_currentChatId'}, + }; + + _sendMessage(subscribeMessage); + debugPrint("📡 Subscribing to chat.$_currentChatId"); + } + + /// Send pong response to ping + void _sendPong() { + final pongMessage = {'event': 'pusher:pong', 'data': {}}; + _sendMessage(pongMessage); + debugPrint("🏓 Pong sent"); + } + + /// Start periodic ping timer + void _startPingTimer() { + _pingTimer?.cancel(); + _pingTimer = Timer.periodic(const Duration(seconds: 30), (timer) { + if (_isConnected) { + // Server will send ping, we just respond with pong + debugPrint("💓 Heartbeat check"); + } + }); + } + + /// Stop ping timer + void _stopPingTimer() { + _pingTimer?.cancel(); + _pingTimer = null; + } + + /// Schedule reconnection attempt + void _scheduleReconnect() { + if (_isIntentionalClose) return; + if (_reconnectAttempts >= _maxReconnectAttempts) { + debugPrint("❌ Max reconnection attempts reached"); + onError?.call( + "Failed to reconnect after $_maxReconnectAttempts attempts", + ); + return; + } + + _reconnectTimer?.cancel(); + _reconnectAttempts++; + + debugPrint( + "🔄 Scheduling reconnect attempt $_reconnectAttempts in ${_reconnectDelay.inSeconds}s", + ); + + _reconnectTimer = Timer(_reconnectDelay, () async { + if (!_isIntentionalClose && _wsUrl != null && _currentChatId != null) { + debugPrint("🔄 Attempting to reconnect..."); + try { + await _establishConnection(); + } catch (e) { + debugPrint("❌ Reconnect failed: $e"); + _scheduleReconnect(); + } + } + }); + } + + /// Send a message through WebSocket + void _sendMessage(Map message) { + if (_channel == null || !_isConnected) { + debugPrint("⚠️ Cannot send message: Not connected"); + return; + } + + try { + final jsonMessage = json.encode(message); + _channel!.sink.add(jsonMessage); + debugPrint("📤 Sent: $jsonMessage"); + } catch (e) { + debugPrint("❌ Error sending message: $e"); + onError?.call(e); + } + } + + /// Send a custom event to the channel + void sendEvent({ + required String eventName, + required Map data, + }) { + final message = { + 'event': eventName, + 'data': data, + 'channel': 'chat.$_currentChatId', + }; + _sendMessage(message); + } + + /// Disconnect from WebSocket + Future disconnect() async { + _isIntentionalClose = true; + _reconnectTimer?.cancel(); + _stopPingTimer(); + + await _subscription?.cancel(); + await _channel?.sink.close(); + + _channel = null; + _subscription = null; + _isConnected = false; + _currentChatId = null; + + debugPrint("🔌 WebSocket disconnected intentionally"); + } + + /// Switch to a different chat channel + Future switchChannel(String newChatId) async { + if (newChatId == _currentChatId) return; + + debugPrint("🔄 Switching from chat.$_currentChatId to chat.$newChatId"); + + // Unsubscribe from current channel + if (_currentChatId != null) { + final unsubscribeMessage = { + 'event': 'pusher:unsubscribe', + 'data': {'channel': 'chat.$_currentChatId'}, + }; + _sendMessage(unsubscribeMessage); + } + + // Update chat ID and subscribe to new channel + _currentChatId = newChatId; + _subscribeToChannel(); + } + + /// Dispose and cleanup + void dispose() { + disconnect(); + } +} diff --git a/lib/view/Main_controller/comman_chat_box.dart b/lib/view/Main_controller/comman_chat_box.dart new file mode 100644 index 0000000..fbe97a1 --- /dev/null +++ b/lib/view/Main_controller/comman_chat_box.dart @@ -0,0 +1,179 @@ +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/comman_webscoket.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/consts/notification_webscoket.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +class CommanChatBox extends ConsumerStatefulWidget { + final String? chatId; + + const CommanChatBox({super.key, this.chatId}); + + @override + ConsumerState createState() => _CommanChatBoxState(); +} + +class _CommanChatBoxState extends ConsumerState { + bool _isWebSocketInitialized = false; + + @override + void initState() { + super.initState(); + _initializeWebSocket(); + } + + /// ✅ Initialize WebSocket on widget load + Future _initializeWebSocket() async { + if (_isWebSocketInitialized) return; + + try { + final String? userId = await LocalStore().getUserId(); + if (userId != null && userId.isNotEmpty) { + final wsService = CommonWebSocketService(); + + // Setup message handler to refresh count + wsService.onMessageReceived = (message) { + debugPrint("📨 WebSocket message received: $message"); + _refreshCount(); + }; + + // Connect WebSocket + await wsService.connect(userId: userId); + _isWebSocketInitialized = true; + debugPrint("✅ WebSocket initialized for chat box"); + + // ✅ Subscribe NotificationWebSocket to the chat channel early + // so notifications arrive from ANY screen, not just the chat screen. + final String chatId = + widget.chatId ?? await LocalStore().getGeneralChatId() ?? '0'; + if (chatId != '0' && chatId.isNotEmpty) { + NotificationWebSocket().watchChatChannel(chatId); + debugPrint( + "👁 CommanChatBox: watching chat channel $chatId for notifications", + ); + } + } + } catch (e) { + debugPrint("❌ Failed to initialize WebSocket: $e"); + } + } + + /// ✅ Refresh count provider + void _refreshCount() { + try { + final chatId = widget.chatId ?? "0"; + // Invalidate the count provider to trigger API call + ref.invalidate(countProvider(chatId)); + debugPrint("🔄 Count refreshed for chatId: $chatId"); + } catch (e) { + debugPrint("❌ Error refreshing count: $e"); + } + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: widget.chatId != null + ? Future.value(widget.chatId) + : LocalStore().getGeneralChatId(), + builder: (context, snapshot) { + if (!snapshot.hasData) { + return const SizedBox(); + } + + final id = snapshot.data ?? "0"; + final countAsync = ref.watch(countProvider(id)); + + return Positioned( + right: 20, + bottom: 120, + child: Stack( + clipBehavior: Clip.none, + children: [ + // Main Chat Button + GestureDetector( + onTap: () async { + int cid = int.tryParse(id) ?? 0; + + ref.invalidate(chatMessagesProvider); + + // Navigate to chat screen + Get.to(() => LiveChatScreen(chatid: cid, fileid: '0'))?.then(( + _, + ) { + ref.read(notificationTriggerProvider.notifier).state++; + }); + }, + child: Container( + width: 53, + height: 53, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFBD49F7), Color(0xFF630A73)], + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.2, + offset: const Offset(0, 1), + ), + ], + ), + child: Container( + margin: const EdgeInsets.all(3), + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: Image.asset(AppAssets.generalchatimage), + ), + ), + ), + + // 🔴 Count Badge + Positioned( + right: -2, + top: -2, + child: countAsync.when( + loading: () => const SizedBox(), + error: (_, __) => const SizedBox(), + data: (data) { + if (data.count == 0) return const SizedBox(); + return Container( + padding: const EdgeInsets.all(5), + decoration: const BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + ), + child: Text( + data.count.toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + ); + }, + ), + ), + ], + ), + ); + }, + ); + } + + @override + void dispose() { + // Don't disconnect WebSocket here as it's shared across app + super.dispose(); + } +} diff --git a/lib/view/Main_controller/main_controller.dart b/lib/view/Main_controller/main_controller.dart new file mode 100644 index 0000000..606534d --- /dev/null +++ b/lib/view/Main_controller/main_controller.dart @@ -0,0 +1,451 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/controller/api_contoller.dart'; // ✅ Needed for providers +import 'package:taxglide/view/Main_controller/comman_chat_box.dart'; +import 'package:taxglide/view/screens/history/serivces_status_screen.dart' + show ServicesStatusScreen; +import 'package:taxglide/view/screens/home_screen.dart'; +import 'package:taxglide/view/screens/list_service_screen.dart'; +import 'package:taxglide/view/screens/profile/employee_profile/employee_profile_screen.dart'; +import 'package:taxglide/view/screens/profile/profile_screen.dart'; + +class MainController extends ConsumerStatefulWidget { + final Widget? child; // Optional child (like ServiceRequestScreen) + final int? initialIndex; // Which tab to show initially + final int? sourceTabIndex; // Source tab (Home=0, Services=1) + + const MainController({ + Key? key, + this.child, + this.initialIndex, + this.sourceTabIndex, + }) : super(key: key); + + @override + ConsumerState createState() => _MainControllerState(); +} + +class _MainControllerState extends ConsumerState { + int currentIndex = 0; + DateTime? lastBackPressed; + String? userRole; + + /// 📌 Bottom bar labels + final List _labels = [ + 'Home', + 'Services', + 'Service Details', + 'Profile', + ]; + + /// 📌 Screens list + List _screens = []; + + @override + void initState() { + super.initState(); + currentIndex = widget.initialIndex ?? 0; + _loadRole(); + } + + /// 🔹 Load user role from local storage + Future _loadRole() async { + userRole = await LocalStore().getRole(); // "employee" or "user" + _initScreens(); + setState(() {}); + } + + /// 🔹 Initialize screens based on role + void _initScreens() { + _screens = [ + const HomeScreen(), + ListServiceScreen(key: UniqueKey()), + ServicesStatusScreen(), + _getProfileScreen(), // ✅ role based + ]; + } + + /// 🔹 Role based profile screen + Widget _getProfileScreen() { + if (userRole == "employee") { + return const EmployeeProfileScreen(); // 👈 employee profile + } + return const ProfileScreen(); // 👈 normal user profile + } + + /// 🔄 Change tab index + void setBottomBarIndex(int index) { + setState(() { + currentIndex = index; + }); + _refreshTab(index); + } + + /// ✅ Refresh API data based on the current tab + void _refreshTab(int index) { + final container = ProviderScope.containerOf(context, listen: false); + + switch (index) { + case 0: + // 🔁 Refresh Home screen APIs + container.refresh(profileProvider); + container.refresh(serviceListProvider); + ref.invalidate(chatMessagesProvider); + ref.invalidate(notificationCountProvider); + ref.invalidate(dashboardProvider); + break; + case 1: + // 🔁 Refresh ListServiceScreen APIs + container.refresh(serviceListProvider); + ref.invalidate(chatMessagesProvider); + ref.invalidate(dashboardProvider); + break; + case 2: + // 🔁 Refresh Service Status APIs + try { + ref.invalidate(serviceHistoryNotifierProvider); + ref.invalidate(serviceDetailProvider); + ref.invalidate(chatMessagesProvider); + ref.invalidate(dashboardProvider); + } catch (_) {} + break; + case 3: + // 🔁 Refresh Profile screen APIs + ref.invalidate(chatMessagesProvider); + container.refresh(profileProvider); + ref.invalidate(staffListProvider); + ref.invalidate(dashboardProvider); + break; + } + } + + /// ✅ Handle Back button presses + Future _onWillPop() async { + // If inside ServiceRequestScreen → go back to originating tab + if (widget.child != null) { + Get.offAll( + () => MainController(initialIndex: widget.sourceTabIndex ?? 0), + ); + return false; + } + + // If not in Home tab, go back to Home + if (currentIndex != 0) { + setState(() => currentIndex = 0); + return false; + } + + // Double back press to exit + DateTime now = DateTime.now(); + if (lastBackPressed == null || + now.difference(lastBackPressed!) > const Duration(seconds: 2)) { + lastBackPressed = now; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Press back again to exit"), + duration: Duration(seconds: 2), + ), + ); + return false; + } + + await SystemNavigator.pop(); + return true; + } + + @override + Widget build(BuildContext context) { + final Size size = MediaQuery.of(context).size; + + // ✅ Show loading while screens are being initialized + if (_screens.isEmpty) { + return const Scaffold(body: Center(child: CircularProgressIndicator())); + } + + final Widget mainContent = widget.child ?? _screens[currentIndex]; + final dashboardAsync = ref.watch(dashboardProvider); + + return WillPopScope( + onWillPop: _onWillPop, + child: Scaffold( + backgroundColor: Colors.white.withAlpha(55), + body: Stack( + children: [ + mainContent, + + /// ✅ Bottom Navigation Bar + Positioned( + bottom: 0, + left: 0, + child: SafeArea( + top: false, + child: Container( + width: size.width, + height: 80, + child: Stack( + clipBehavior: Clip.none, + children: [ + CustomPaint( + size: Size(size.width, 80), + painter: BNBCustomPainter(), + ), + Center( + heightFactor: 0.6, + child: GestureDetector( + onTap: () {}, + child: CustomPaint( + painter: PentagonPainter( + color: const Color(0xFF61277A), + ), + child: Container( + width: 70, + height: 70, + alignment: Alignment.center, + child: Image.asset( + AppAssets.maincontroller, + color: Colors.white, + fit: BoxFit.contain, + height: 40, + width: 40, + ), + ), + ), + ), + ), + SizedBox( + width: size.width, + height: 80, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _buildNavItem(Icons.home, 0, _labels[0]), + _buildNavItem(Icons.list_alt_sharp, 1, _labels[1]), + SizedBox(width: size.width * 0.20), + _buildNavItem(Icons.history_edu, 2, _labels[2]), + _buildNavItem(Icons.person_2, 3, _labels[3]), + ], + ), + ), + ], + ), + ), + ), + ), + dashboardAsync.when( + data: (dashboard) { + final int? chatIdInt = dashboard.generalChatId; + + if (chatIdInt == null || chatIdInt == 0) { + return const SizedBox(); // ❌ No chat box + } + + return CommanChatBox( + chatId: chatIdInt.toString(), // ✅ INT → STRING + ); + }, + loading: () => const SizedBox(), + error: (e, _) => const SizedBox(), + ), + ], + ), + ), + ); + } + + /// ✅ Navigation Logic with Refresh + Widget _buildNavItem(IconData icon, int index, String label) { + bool isSelected = currentIndex == index; + + return GestureDetector( + onTap: () { + // 🔹 If inside ServiceRequestScreen + if (widget.child != null) { + if (widget.initialIndex == index) return; + + if (widget.sourceTabIndex == 0 && index == 1) { + Get.offAll(() => const MainController(initialIndex: 1)); + return; + } + + if (widget.sourceTabIndex == 1 && index == 1) return; + + Get.offAll(() => MainController(initialIndex: index)); + return; + } + + // 🔹 If same tab tapped again → refresh + if (currentIndex == index) { + _refreshTab(index); + return; + } + + // 🔹 Switch to a different tab + setBottomBarIndex(index); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: isSelected + ? Border.all(color: const Color(0xFF61277A), width: 2) + : null, + ), + child: Icon( + icon, + color: isSelected + ? const Color(0xFF61277A) + : const Color(0xFF6C7278), + size: isSelected ? 19.5 : 20.8, + ), + ), + if (isSelected) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + label, + style: const TextStyle( + color: Color(0xFF61277A), + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ); + } +} + +/// ✅ Custom Curved Bottom Navigation Painter +class BNBCustomPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + Paint paint = Paint() + ..color = Colors.white + ..style = PaintingStyle.fill; + + Path path = Path(); + path.moveTo(0, 20); + path.quadraticBezierTo(size.width * 0.20, 0, size.width * 0.35, 0); + path.quadraticBezierTo(size.width * 0.40, 0, size.width * 0.40, 20); + path.arcToPoint( + Offset(size.width * 0.60, 20), + radius: const Radius.circular(20.0), + clockwise: false, + ); + path.quadraticBezierTo(size.width * 0.60, 0, size.width * 0.65, 0); + path.quadraticBezierTo(size.width * 0.80, 0, size.width, 20); + path.lineTo(size.width, size.height); + path.lineTo(0, size.height); + path.close(); + + canvas.drawShadow(path, Colors.black.withOpacity(0.2), 5, true); + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) => false; +} + +/// ✅ Pentagon Button Painter +/// ✅ Pentagon Button Painter +class PentagonPainter extends CustomPainter { + final Color color; + final double cornerRadius; + + PentagonPainter({ + required this.color, + this.cornerRadius = 8.0, // Adjust this value for more/less rounding + }); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.fill; + + final double w = size.width; + final double cx = w / 2; + final double cy = size.height / 2; + final double r = w / 2; + + // Calculate pentagon vertices + List vertices = []; + for (int i = 0; i < 5; i++) { + double angle = (72 * i - 90) * math.pi / 180; + double x = cx + r * 0.95 * math.cos(angle); + double y = cy + r * 0.95 * math.sin(angle); + vertices.add(Offset(x, y)); + } + + // Create path with rounded corners + final path = Path(); + + for (int i = 0; i < vertices.length; i++) { + final current = vertices[i]; + final next = vertices[(i + 1) % vertices.length]; + final prev = vertices[(i - 1 + vertices.length) % vertices.length]; + + // Calculate direction vectors + final toCurrent = Offset(current.dx - prev.dx, current.dy - prev.dy); + final toNext = Offset(next.dx - current.dx, next.dy - current.dy); + + // Normalize and scale by corner radius + final lengthToCurrent = math.sqrt( + toCurrent.dx * toCurrent.dx + toCurrent.dy * toCurrent.dy, + ); + final lengthToNext = math.sqrt( + toNext.dx * toNext.dx + toNext.dy * toNext.dy, + ); + + final normalizedToCurrent = Offset( + toCurrent.dx / lengthToCurrent, + toCurrent.dy / lengthToCurrent, + ); + final normalizedToNext = Offset( + toNext.dx / lengthToNext, + toNext.dy / lengthToNext, + ); + + // Points before and after the corner + final beforeCorner = Offset( + current.dx - normalizedToCurrent.dx * cornerRadius, + current.dy - normalizedToCurrent.dy * cornerRadius, + ); + final afterCorner = Offset( + current.dx + normalizedToNext.dx * cornerRadius, + current.dy + normalizedToNext.dy * cornerRadius, + ); + + if (i == 0) { + path.moveTo(beforeCorner.dx, beforeCorner.dy); + } else { + path.lineTo(beforeCorner.dx, beforeCorner.dy); + } + + // Draw rounded corner using quadratic bezier + path.quadraticBezierTo( + current.dx, + current.dy, + afterCorner.dx, + afterCorner.dy, + ); + } + path.close(); + + canvas.drawShadow(path, Colors.black.withOpacity(0.3), 4, true); + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) => false; +} diff --git a/lib/view/flash_screen.dart b/lib/view/flash_screen.dart new file mode 100644 index 0000000..e9d3241 --- /dev/null +++ b/lib/view/flash_screen.dart @@ -0,0 +1,204 @@ +import 'dart:ui'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/services/notification_service.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; + +import 'package:taxglide/view/screens/history/detail_screen.dart' + show DetailScreen; + +import 'package:firebase_messaging/firebase_messaging.dart'; + +import 'Mahi_chat/live_chat_screen.dart'; + +class FlashScreen extends ConsumerStatefulWidget { + const FlashScreen({super.key}); + + @override + ConsumerState createState() => _FlashScreenState(); +} + +class _FlashScreenState extends ConsumerState { + final LocalStore _localStore = LocalStore(); + + @override + void initState() { + super.initState(); + _navigateNext(); + } + + Future _navigateNext() async { + try { + await Future.delayed(const Duration(seconds: 3)); + + if (!mounted) return; + + String? token; + String? role; + + try { + token = await _localStore.getToken(); + role = await _localStore.getRole(); + } catch (e) { + debugPrint("⚠️ Error reading stored data: $e"); + // Clear corrupted data + await _localStore.clearAll(); + } + + if (!mounted) return; + + // Check if token and role are valid + if (token != null && + token.isNotEmpty && + token != 'null' && + role != null && + role.isNotEmpty && + role != 'null') { + debugPrint("✅ User logged in → Checking for initial notification"); + + try { + // Trigger notification refresh + ref.read(notificationTriggerProvider.notifier).state++; + ref.invalidate(chatMessagesProvider); + + // ✅ Check if app was opened from notification (terminated state) + final notificationService = Get.find(); + RemoteMessage? initialMessage = notificationService.initialMessage; + + if (initialMessage != null) { + debugPrint("📥 Processing initial notification"); + await _handleInitialNotification(initialMessage.data); + } else { + // Navigate to main controller normally + Get.offAll(() => MainController()); + } + } catch (e) { + debugPrint("⚠️ Error checking initial notification: $e"); + // If no initial notification or error, go to MainController + Get.offAll(() => MainController()); + } + } else { + debugPrint("🔒 No valid login data → Navigating to Login"); + // Clear any invalid stored data + await _localStore.clearAll(); + Get.offNamed(ConstRouters.login); + } + } catch (e) { + debugPrint("❌ Critical error in splash screen: $e"); + // Fallback: always go to login if there's any error + if (mounted) { + await _localStore.clearAll(); + Get.offNamed(ConstRouters.login); + } + } + } + + /// Handle notification when app was opened from terminated state + Future _handleInitialNotification(Map data) async { + String? type = data['type']; + String? idStr = data['id']?.toString(); + + if (type == null || idStr == null) { + debugPrint("⚠️ Invalid initial notification data"); + Get.offAll(() => MainController()); + return; + } + + debugPrint("📍 Initial notification type: $type, ID: $idStr"); + + if (type == 'chat') { + // Navigate to chat + Get.offAll(() => MainController()); + await Future.delayed(const Duration(milliseconds: 300)); + Get.to(() => LiveChatScreen(chatid: int.parse(idStr), fileid: '0')); + } else if (type == 'service') { + // Navigate to service detail + int serviceId = int.tryParse(idStr) ?? 0; + Get.offAll( + () => MainController( + initialIndex: 2, + child: DetailScreen(id: serviceId, sourceTabIndex: 2), + ), + ); + } else { + // Unknown type + Get.offAll(() => MainController()); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFFFF8F0), + body: Stack( + children: [ + // Background gradient + Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFFFF8F0), Color(0xFFF5F0FF)], + ), + ), + ), + + // Top blur circle + Positioned( + top: -431, + left: -256, + child: Container( + width: 582, + height: 582, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.backgroundgrainetflashtop.withOpacity(0.9), + ), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 368.3, sigmaY: 368.3), + child: Container(color: Colors.transparent), + ), + ), + ), + + // Bottom blur circle + Positioned( + top: 638, + left: 149, + child: Container( + width: 934, + height: 934, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.backgroundgrainetflashbottom.withOpacity(0.94), + ), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 591.0, sigmaY: 591.0), + child: Container(color: Colors.transparent), + ), + ), + ), + + // Center logo + Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Image.asset( + AppAssets.taxgildelogo, + width: 361.09, + height: 333.94, + fit: BoxFit.contain, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/view/screens/history/completed_live_chat_screen.dart b/lib/view/screens/history/completed_live_chat_screen.dart new file mode 100644 index 0000000..1507e14 --- /dev/null +++ b/lib/view/screens/history/completed_live_chat_screen.dart @@ -0,0 +1,696 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/model/chat_model.dart'; +import 'package:taxglide/view/Mahi_chat/chat_profile_screen.dart'; +import 'package:taxglide/view/Mahi_chat/file_images_screen.dart'; +import 'package:taxglide/view/Mahi_chat/webscoket.dart'; + +// ⭐ Provider to hold the tagged message +final taggedMessageProvider = StateProvider((ref) => null); + +// ⭐ Global key map to track message positions (if you want from outside) +final messageKeysProvider = StateProvider>((ref) => {}); + +class CompletedLiveChatScreen extends ConsumerStatefulWidget { + final int chatid; + final String? fileid; + const CompletedLiveChatScreen({ + super.key, + required this.chatid, + required this.fileid, + }); + + @override + ConsumerState createState() => + _CompletedLiveChatScreenState(); +} + +class _CompletedLiveChatScreenState + extends ConsumerState + with AutomaticKeepAliveClientMixin, WidgetsBindingObserver { + bool get wantKeepAlive => true; + + final ScrollController scrollController = ScrollController(); + final ChatWebSocketService _wsService = ChatWebSocketService(); + + bool showScrollButton = false; + bool userIsReading = false; + bool _isInitialLoad = true; + bool _isPaginationLoading = false; + bool _hasNewMessage = false; + + // For reply scroll - FIXED: Use unique key per message + final Map _messageKeys = {}; + + // ⭐⭐⭐ Key variables for smooth pagination + final double _paginationTriggerOffset = 300; // Start loading 300px before top + + @override + void initState() { + super.initState(); + + WidgetsBinding.instance.addObserver(this); + + _initializeWebSocket(); + + scrollController.addListener(_handleScroll); + } + + // ⭐⭐⭐ Enhanced scroll handler with early pagination trigger + void _handleScroll() { + if (!scrollController.hasClients) return; + + double position = scrollController.position.pixels; + double bottom = scrollController.position.maxScrollExtent; + double top = scrollController.position.minScrollExtent; + + // ⭐⭐⭐ EARLY PAGINATION: Load before reaching exact top + if (position <= top + _paginationTriggerOffset && !_isPaginationLoading) { + _triggerPagination(); + } + + // Show scroll to bottom button + if (position < bottom - 50) { + if (!userIsReading) { + setState(() { + userIsReading = true; + showScrollButton = true; + }); + } + } else { + if (userIsReading) { + setState(() { + userIsReading = false; + showScrollButton = false; + }); + } + } + } + + // ⭐⭐⭐ Smooth pagination with scroll position preservation (NO JUMP TO BOTTOM) + Future _triggerPagination() async { + final notifier = ref.read(chatMessagesProvider(widget.chatid).notifier); + if (!notifier.hasNextPage) return; + if (_isPaginationLoading) return; + if (!scrollController.hasClients) return; + + setState(() { + _isPaginationLoading = true; + // userIsReading remains true while scrolling old messages + }); + + // Save current scroll metrics BEFORE loading more messages + final double beforeMaxExtent = scrollController.position.maxScrollExtent; + final double currentOffset = scrollController.position.pixels; + + try { + await notifier.loadMessages(); // This should prepend older messages + + // Restore scroll position after new messages loaded + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !scrollController.hasClients) return; + + final double afterMaxExtent = scrollController.position.maxScrollExtent; + final double diff = afterMaxExtent - beforeMaxExtent; + + // Keep user at same visual message position + final double newOffset = currentOffset + diff; + + scrollController.jumpTo( + newOffset.clamp( + scrollController.position.minScrollExtent, + scrollController.position.maxScrollExtent, + ), + ); + + if (mounted) { + setState(() { + _isPaginationLoading = false; + }); + } + }); + } catch (e) { + debugPrint("❌ Pagination error: $e"); + if (mounted) { + setState(() { + _isPaginationLoading = false; + }); + } + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + super.didChangeAppLifecycleState(state); + + debugPrint("📱 App Lifecycle State: $state"); + + if (state == AppLifecycleState.resumed) { + debugPrint("🔄 App resumed - checking for new messages"); + + if (_hasNewMessage) { + _silentRefresh(); + _hasNewMessage = false; + } + } + } + + Future _silentRefresh() async { + try { + debugPrint("🔄 Starting silent refresh..."); + + await ref.read(chatMessagesProvider(widget.chatid).notifier).refresh(); + + debugPrint("✅ Silent refresh completed"); + + // Only auto-scroll to bottom on new messages if user is NOT reading old ones + if (!userIsReading && mounted) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (scrollController.hasClients) { + scrollController.animateTo( + scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + }); + } + } catch (e) { + debugPrint("❌ Error during silent refresh: $e"); + } + } + + Future _initializeWebSocket() async { + try { + _wsService.onMessageReceived = (Map message) async { + debugPrint("📨 WebSocket message received: $message"); + + try { + final event = message['event'] as String?; + + if (event == 'message.sent' || event == 'message.received') { + debugPrint("🔔 New message detected!"); + + if (WidgetsBinding.instance.lifecycleState == + AppLifecycleState.resumed) { + debugPrint("✅ Screen active - refreshing now"); + await _silentRefresh(); + } else { + debugPrint("⏳ Screen not active - will refresh on resume"); + _hasNewMessage = true; + } + } + } catch (e) { + debugPrint("❌ Error handling WebSocket message: $e"); + } + }; + + _wsService.onConnected = () { + debugPrint("✅ WebSocket Connected"); + }; + + _wsService.onDisconnected = () { + debugPrint("🔌 WebSocket Disconnected"); + }; + + _wsService.onError = (error) { + debugPrint("❌ WebSocket Error: $error"); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Connection error: $error"), + backgroundColor: Colors.red, + duration: const Duration(seconds: 2), + ), + ); + } + }; + + await _wsService.connect(chatId: widget.chatid.toString()); + } catch (e) { + debugPrint("❌ Error initializing WebSocket: $e"); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _wsService.disconnect(); + scrollController.dispose(); + super.dispose(); + } + + void scrollToBottom({bool animated = false}) { + if (!scrollController.hasClients) return; + + setState(() { + _isPaginationLoading = false; + userIsReading = false; + }); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!scrollController.hasClients) return; + + if (animated) { + scrollController + .animateTo( + scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 400), + curve: Curves.easeOutCubic, + ) + .then((_) { + Future.delayed(const Duration(milliseconds: 50), () { + if (scrollController.hasClients && mounted) { + scrollController.jumpTo( + scrollController.position.maxScrollExtent, + ); + } + }); + }); + } else { + scrollController.jumpTo(scrollController.position.maxScrollExtent); + + Future.delayed(const Duration(milliseconds: 10), () { + if (scrollController.hasClients && mounted) { + scrollController.jumpTo(scrollController.position.maxScrollExtent); + } + }); + } + }); + } + + // ⭐ FIXED: Use unique string key instead of int + void scrollToMessage(String messageKey) { + final key = _messageKeys[messageKey]; + + if (key != null && key.currentContext != null) { + Scrollable.ensureVisible( + key.currentContext!, + duration: const Duration(milliseconds: 500), + curve: Curves.easeInOut, + alignment: 0.3, + ); + } + } + + // ⭐ FIXED: Generate unique string key for each message + GlobalKey _getKeyForMessage(String messageKey) { + if (!_messageKeys.containsKey(messageKey)) { + _messageKeys[messageKey] = GlobalKey(); + } + return _messageKeys[messageKey]!; + } + + // ⭐ FIXED: Generate unique key string from message + String _getMessageKeyString(MessageModel msg, int index) { + // Use combination of ID, index, and document count for uniqueness + final id = msg.id; + final docCount = msg.uploadedDocuments.length; + final createdAt = msg.createdAt ?? ''; + return 'msg_${id}_${index}_${docCount}_$createdAt'; + } + + String formatMessageDate(DateTime date) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final msgDay = DateTime(date.year, date.month, date.day); + + if (msgDay == today) return "Today"; + if (msgDay == today.subtract(const Duration(days: 1))) return "Yesterday"; + return "${date.day}-${date.month}-${date.year}"; + } + + String formatTime(DateTime time) { + final hour = time.hour % 12 == 0 ? 12 : time.hour % 12; + final minute = time.minute.toString().padLeft(2, '0'); + final period = time.hour >= 12 ? "PM" : "AM"; + return "$hour:$minute $period"; + } + + Widget buildTick(int isDelivered, int isRead) { + if (isRead == 1) { + return const Icon(Icons.done_all, size: 16, color: Colors.blue); + } else if (isDelivered == 1) { + return const Icon(Icons.done_all, size: 16, color: Colors.grey); + } else { + return const Icon(Icons.check, size: 16, color: Colors.grey); + } + } + + @override + Widget build(BuildContext context) { + super.build(context); + + final chatAsync = ref.watch(chatMessagesProvider(widget.chatid)); + final taggedMessage = ref.watch(taggedMessageProvider); + + return Scaffold( + appBar: AppBar( + title: Text( + (widget.fileid != null && + widget.fileid.toString().isNotEmpty && + widget.fileid.toString() != "0") + ? 'File ID : ${widget.fileid.toString()}' + : "Live Chat", + style: const TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + elevation: 1, + foregroundColor: Colors.black, + centerTitle: true, + + actions: [ + Padding( + padding: const EdgeInsets.only(right: 12), // ✅ Right end spacing + child: GestureDetector( + onTap: () { + Get.to(ChatProfileScreen(chatid: widget.chatid)); + }, + child: Container( + width: 37.446807861328125, + height: 40, + decoration: BoxDecoration( + color: const Color(0xFFFAFAFA), + borderRadius: BorderRadius.circular(6.81), + border: Border.all( + color: const Color(0xFF1E780C), + width: 0.85, + ), + ), + child: const Icon(Icons.person, color: Color(0xFF1E780C)), + ), + ), + ), + ], + ), + + body: Stack( + children: [ + Container( + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + ), + Column( + children: [ + Expanded( + child: chatAsync.when( + loading: () => const Center(child: SizedBox.shrink()), + error: (e, _) => Center(child: Text(e.toString())), + data: (messages) { + // ✅ Only first load scrolls to bottom, NOT during pagination / scroll up + if (_isInitialLoad && !_isPaginationLoading) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (scrollController.hasClients && mounted) { + scrollController.jumpTo( + scrollController.position.maxScrollExtent, + ); + } + }); + _isInitialLoad = false; + } + + return Stack( + children: [ + ListView.builder( + controller: scrollController, + physics: const ClampingScrollPhysics(), + padding: const EdgeInsets.only( + left: 15, + right: 15, + top: 15, + bottom: 15, + ), + itemCount: messages.length, + itemBuilder: (context, index) { + final msg = messages[index]; + final msgDate = DateTime.parse(msg.createdAt!); + + final showDateHeader = + index == 0 || + formatMessageDate( + DateTime.parse( + messages[index - 1].createdAt!, + ), + ) != + formatMessageDate(msgDate); + + // ⭐ FIXED: Generate unique key string + final messageKeyString = _getMessageKeyString( + msg, + index, + ); + + return Column( + key: _getKeyForMessage(messageKeyString), + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (showDateHeader) + Padding( + padding: const EdgeInsets.symmetric( + vertical: 10, + ), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 5, + ), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.06), + borderRadius: BorderRadius.circular( + 12, + ), + ), + child: Text( + formatMessageDate(msgDate), + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ), + SwipeableMessageBubble( + message: msg, + msgDate: msgDate, + formatTime: formatTime, + buildTick: buildTick, + onSwipe: () { + ref + .read( + taggedMessageProvider.notifier, + ) + .state = + msg; + }, + onParentTagTap: (tagId) { + if (tagId != null) { + // ⭐ FIXED: Find the message key string for the tagId + final tagIndex = messages.indexWhere( + (m) => m.id == tagId, + ); + if (tagIndex != -1) { + final taggedMsg = messages[tagIndex]; + final tagKeyString = + _getMessageKeyString( + taggedMsg, + tagIndex, + ); + scrollToMessage(tagKeyString); + } + } + }, + // ⭐ FIXED: Use messageKeyString as ValueKey + key: ValueKey(messageKeyString), + ), + ], + ); + }, + ), + // ⭐⭐⭐ Subtle loading indicator at top + if (_isPaginationLoading) + Positioned( + top: 5, + left: 0, + right: 0, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 6, + ), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.9), + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 4, + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + SizedBox(width: 8), + Text( + "Loading...", + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ), + ), + ], + ); + }, + ), + ), + if (taggedMessage != null) + GestureDetector( + onTap: () { + if (taggedMessage != null) { + // ⭐ FIXED: Need to find the message in the list to get proper key + final chatAsync = ref.read( + chatMessagesProvider(widget.chatid), + ); + chatAsync.whenData((messages) { + final tagIndex = messages.indexWhere( + (m) => m.id == taggedMessage.id, + ); + if (tagIndex != -1) { + final tagKeyString = _getMessageKeyString( + taggedMessage, + tagIndex, + ); + scrollToMessage(tagKeyString); + } + }); + } + }, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 15, + vertical: 8, + ), + decoration: BoxDecoration( + color: Colors.grey[200], + border: Border(top: BorderSide(color: Colors.grey[300]!)), + ), + child: Row( + children: [ + Container( + width: 4, + height: 50, + decoration: BoxDecoration( + color: const Color(0xFF630A73), + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + taggedMessage.user?.name ?? "Unknown", + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + color: Color(0xFF630A73), + ), + ), + const SizedBox(height: 2), + if (taggedMessage.type == "file" && + taggedMessage.fileName != null) + Row( + children: [ + Icon( + Icons.attach_file, + size: 14, + color: Colors.grey[600], + ), + const SizedBox(width: 4), + Expanded( + child: Text( + taggedMessage.fileName!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ), + ], + ) + else + Text( + taggedMessage.message, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.close, size: 20), + padding: EdgeInsets.zero, + onPressed: () { + ref.read(taggedMessageProvider.notifier).state = + null; + }, + ), + ], + ), + ), + ), + ], + ), + if (showScrollButton) + Positioned( + bottom: 150, + right: 20, + child: FloatingActionButton( + heroTag: "scrollBtn", + backgroundColor: Colors.green, + mini: true, + onPressed: () { + scrollToBottom(animated: true); + }, + child: const Icon(Icons.arrow_downward, color: Colors.white), + ), + ), + ], + ), + ); + } +} diff --git a/lib/view/screens/history/detail_screen.dart b/lib/view/screens/history/detail_screen.dart new file mode 100644 index 0000000..3cefffe --- /dev/null +++ b/lib/view/screens/history/detail_screen.dart @@ -0,0 +1,1893 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/details_webscokect.dart'; +import 'package:taxglide/consts/download_helper.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/model/detail_model.dart'; +import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import 'package:taxglide/view/screens/history/completed_live_chat_screen.dart'; + +class DetailScreen extends ConsumerStatefulWidget { + final int id; + final int? sourceTabIndex; + const DetailScreen({super.key, required this.id, this.sourceTabIndex}); + + @override + ConsumerState createState() => _DetailScreenState(); +} + +class _DetailScreenState extends ConsumerState { + Map _downloadingFiles = {}; // Track each file separately + bool _isDownloadingInvoice = false; + String? _downloadedInvoicePath; + + bool _isWebSocketInitialized = false; // Add this flag + + @override + void initState() { + super.initState(); + _initializeWebSocket(); // Initialize WebSocket + } + + // Add this method + Future _initializeWebSocket() async { + if (_isWebSocketInitialized) return; + + try { + String? userId = await LocalStore().getUserId(); + if (userId != null && userId.isNotEmpty) { + final wsService = DetailsWebscokect(); + + // Setup message handler to refresh count + wsService.onMessageReceived = (message) { + debugPrint("📨 WebSocket message received: $message"); + + // Refresh count when message arrives + _refreshCount(); + }; + + // Connect WebSocket + await wsService.connect(userId: userId); + _isWebSocketInitialized = true; + + debugPrint("✅ WebSocket initialized for detail screen"); + } + } catch (e) { + debugPrint("❌ Failed to initialize WebSocket: $e"); + } + } + + // Add this method to refresh count + void _refreshCount() { + // Get the chatId from the detail model + final detailAsync = ref.read(serviceDetailProvider(widget.id)); + + detailAsync.whenData((detailModel) { + final chatId = detailModel.data?.chatId; + if (chatId != null && chatId.isNotEmpty) { + // Invalidate the count provider to trigger refresh + ref.invalidate(countProvider(chatId)); + debugPrint("🔄 Count refreshed for chatId: $chatId"); + } + }); + } + + @override + void dispose() { + // Optionally disconnect WebSocket when leaving screen + // DetailsWebscokect().disconnect(); + super.dispose(); + } + + Future _handleDownload(String url) async { + if (_downloadingFiles[url] == true) return; + + setState(() { + _downloadingFiles[url] = true; + }); + + try { + // Check if file exists, if yes open it, if no download it + final result = await DownloadHelper.downloadFile(url); + + // No snackbar for downloads - only notification will show + // For existing files (view mode), no messages shown at all + + // If there's an error, still show it + if (mounted && result['success'] == false) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error: ${result['error']}'), + backgroundColor: Colors.red, + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red), + ); + } + } finally { + if (mounted) { + setState(() { + _downloadingFiles[url] = false; + }); + } + } + } + + Future _handleInvoiceDownload(String invoiceUrl) async { + if (_isDownloadingInvoice) return; + + // Check if already downloaded + final existingPath = await DownloadHelper.checkFileExists(invoiceUrl); + if (existingPath != null) { + setState(() { + _downloadedInvoicePath = existingPath; + }); + // Open the existing file + await DownloadHelper.openDownloadedFile(existingPath); + return; + } + + setState(() { + _isDownloadingInvoice = true; + }); + + try { + final result = await DownloadHelper.downloadFile(invoiceUrl); + + if (mounted && result['success'] == true) { + setState(() { + _downloadedInvoicePath = result['filePath']; + }); + } else if (mounted && result['success'] == false) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Download failed: ${result['error']}'), + backgroundColor: Colors.red, + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red), + ); + } + } finally { + if (mounted) { + setState(() { + _isDownloadingInvoice = false; + }); + } + } + } + + Widget _buildInvoiceDownloadButton(String? invoiceUrl, double width) { + if (invoiceUrl == null || invoiceUrl.isEmpty) { + return SizedBox( + width: double.infinity, + height: 57, + child: ElevatedButton.icon( + onPressed: null, + icon: const Icon(Icons.error_outline, color: Colors.white, size: 22), + label: Text( + "Invoice Not Available", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: width * 0.045, + height: 1.3, + letterSpacing: 0.04 * 17.64, + color: Colors.white, + ), + ), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.grey, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6), + ), + disabledBackgroundColor: Colors.grey, + ), + ), + ); + } + + return FutureBuilder( + future: DownloadHelper.checkFileExists(invoiceUrl), + builder: (context, snapshot) { + final isAlreadyDownloaded = + snapshot.data != null || _downloadedInvoicePath != null; + + return SizedBox( + width: double.infinity, + height: 57, + child: ElevatedButton.icon( + onPressed: _isDownloadingInvoice + ? null + : () => _handleInvoiceDownload(invoiceUrl), + icon: _isDownloadingInvoice + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : Icon( + isAlreadyDownloaded + ? Icons.visibility + : Icons.download_rounded, + color: Colors.white, + size: 22, + ), + label: Text( + _isDownloadingInvoice + ? "Downloading..." + : isAlreadyDownloaded + ? "View Invoice" + : "Download Invoice", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: width * 0.045, + height: 1.3, + letterSpacing: 0.04 * 17.64, + color: Colors.white, + ), + ), + style: ElevatedButton.styleFrom( + backgroundColor: isAlreadyDownloaded + ? const Color(0xFF0C5A78) + : const Color(0xFF1E780C), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6), + ), + elevation: 7.8, + shadowColor: const Color(0x66000000), + disabledBackgroundColor: Colors.grey, + ), + ), + ); + }, + ); + } + + Widget _buildProformaDownloadButton(String? proforma) { + final bool isDisabled = proforma == null || proforma.isEmpty; + + return FutureBuilder( + future: isDisabled ? null : DownloadHelper.checkFileExists(proforma), + builder: (context, snapshot) { + final bool isDownloaded = snapshot.data != null; + + return GestureDetector( + onTap: isDisabled + ? null + : () async { + if (isDownloaded) { + /// 👀 View Proforma (OPEN LOCAL FILE) + await DownloadHelper.openDownloadedFile(snapshot.data!); + } else { + /// ⬇️ Download Proforma + await _handleInvoiceDownload(proforma); + } + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + /// 🔵 Icon + Container( + width: 38.45, + height: 38.45, + decoration: const BoxDecoration( + color: Color(0xFF4000FF), + shape: BoxShape.circle, + ), + child: Icon( + isDownloaded ? Icons.visibility : Icons.download_rounded, + color: Colors.white, + size: 22, + ), + ), + + const SizedBox(width: 5), + + /// 🔤 Text + Text( + isDisabled + ? "Proforma Not Available" + : isDownloaded + ? "View Proforma" + : "Download Proforma", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 12, + height: 1.3, + letterSpacing: 0.04 * 14.47, + color: isDisabled ? Colors.grey : const Color(0xFF4000FF), + ), + ), + ], + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + final width = size.width; + final height = size.height; + final validationPopup = ValidationPopup(); + + final detailAsync = ref.watch(serviceDetailProvider(widget.id)); + + return Scaffold( + body: Container( + height: height, + width: width, + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + child: SafeArea( + child: detailAsync.when( + loading: () => const Center( + child: CircularProgressIndicator(color: Colors.deepPurple), + ), + error: (e, _) => Center( + child: Text( + "Error: $e", + style: const TextStyle( + color: Colors.red, + fontSize: 16, + fontFamily: 'Gilroy-Medium', + ), + ), + ), + data: (DetailModel detailModel) { + final data = detailModel.data; + if (data == null) { + return const Center(child: Text("No details found")); + } + final countAsync = data.chatId != null && data.chatId!.isNotEmpty + ? ref.watch(countProvider(data.chatId!)) + : null; + return SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// 🔹 Custom App Bar + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 21, + ), + child: SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + // ✅ Center Title + Text( + "Service Details", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.055, + color: const Color(0xFF111827), + ), + ), + + // ✅ Left Back Icon + Positioned( + left: 0, + child: GestureDetector( + onTap: () { + final targetTab = widget.sourceTabIndex ?? 0; + Get.offAll( + () => + MainController(initialIndex: targetTab), + ); + }, + child: const Icon( + Icons.arrow_back_ios_rounded, + color: Color(0xFF111827), + ), + ), + ), + + if (data.serviceStatus == 'Completed') + Positioned( + right: 0, + child: GestureDetector( + onTap: () { + Get.to( + () => CompletedLiveChatScreen( + fileid: data.id.toString(), + chatid: + int.tryParse( + data.completedChatId ?? '0', + ) ?? + 0, + ), + )?.then((_) { + ref + .read( + notificationTriggerProvider + .notifier, + ) + .state++; + ref.invalidate(chatMessagesProvider); + }); + }, + child: Container( + width: 39.0, + height: 39.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + border: Border.all( + color: const Color(0xFF055976), + width: 0.8, + ), + ), + child: const Icon( + Icons.message_rounded, + size: 18, + ), + ), + ), + ), + ], + ), + ), + ), + + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 16, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Detailed Information", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.047, + height: 1.4, + letterSpacing: 0.03 * 20, + ), + textAlign: TextAlign.center, + ), + + if (data.serviceStatus == 'Waiting for Admin' || + data.serviceStatus == 'Payment Pending' || + data.serviceStatus == 'Cancelled') + Container( + width: width * 0.3, + height: height * 0.04, + decoration: BoxDecoration( + color: const Color(0xFFFFE8E8), + borderRadius: BorderRadius.circular(5.52), + border: Border.all( + color: const Color(0xFFFFD7D7), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: Center( + child: Text( + data.serviceStatus.toString(), + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: width * 0.029, + color: const Color(0xFFFF0F0F), + ), + ), + ), + ), + + // 🔹 In Progress Badge + if (data.serviceStatus == 'In Progress') + Container( + width: width * 0.25, + height: height * 0.042, + decoration: BoxDecoration( + color: const Color(0xFFEAFAE6), + borderRadius: BorderRadius.circular(6.21), + border: Border.all( + color: const Color(0xFFDDFFDD), + width: 2.07, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 8.08, + offset: const Offset(0, 4.14), + ), + ], + ), + child: Center( + child: Text( + data.serviceStatus.toString(), + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: width * 0.032, + letterSpacing: 0.03, + color: const Color(0xFF12800C), + ), + ), + ), + ), + + // 🔹 Completed Badge + if (data.serviceStatus == 'Completed') + Container( + width: width * 0.23, + height: height * 0.038, + decoration: BoxDecoration( + color: const Color(0xFFFAF7E6), + borderRadius: BorderRadius.circular(5.52), + border: Border.all( + color: const Color(0xFFFFE9DD), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: Center( + child: Text( + data.serviceStatus.toString(), + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: width * 0.029, + letterSpacing: 0.03, + color: const Color(0xFFFF630F), + ), + ), + ), + ), + ], + ), + ), + if (data.serviceStatus == "Completed") ...[ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 20, + horizontal: 20, + ), + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: const Color(0xFFE1E1E1), + width: 1, + ), + boxShadow: const [ + BoxShadow( + color: Color(0x66757575), + blurRadius: 15, + offset: Offset(0, 1), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Task Final Report", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.042, + height: 1.4, + letterSpacing: 0.03 * 16, + color: const Color(0xFF111827), + ), + textAlign: TextAlign.start, + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + text: TextSpan( + children: [ + TextSpan( + text: 'Date: ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: data.createdDate ?? "-", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + ), + const SizedBox(width: 10), + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + text: TextSpan( + children: [ + TextSpan( + text: 'Payment : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: data.paymentStatus ?? "-", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 15), + if (data.userHandoverDocuments.isNotEmpty) + SizedBox( + height: 100, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: + data.userHandoverDocuments.length, + itemBuilder: (context, index) { + final doc = + data.userHandoverDocuments[index]; + final filePath = doc.filePath ?? ''; + final isImage = + filePath.toLowerCase().endsWith( + '.jpg', + ) || + filePath.toLowerCase().endsWith( + '.jpeg', + ) || + filePath.toLowerCase().endsWith( + '.png', + ) || + filePath.toLowerCase().endsWith( + '.gif', + ) || + filePath.toLowerCase().endsWith( + '.webp', + ); + final isPdf = filePath + .toLowerCase() + .endsWith('.pdf'); + + final isDownloadingThis = + _downloadingFiles[filePath] == true; + + return Padding( + padding: const EdgeInsets.only( + right: 10, + ), + child: GestureDetector( + onTap: () => + _handleDownload(filePath), + child: Container( + height: 90, + width: 90, + decoration: BoxDecoration( + borderRadius: + BorderRadius.circular(8), + color: const Color(0xFFF5F5F5), + boxShadow: [ + BoxShadow( + color: Colors.black + .withOpacity(0.05), + blurRadius: 3, + offset: const Offset(0, 2), + ), + ], + ), + child: Stack( + children: [ + ClipRRect( + borderRadius: + BorderRadius.circular( + 8, + ), + child: isImage + ? Image.network( + filePath, + width: 90, + height: 90, + fit: BoxFit.cover, + errorBuilder: + ( + context, + error, + stackTrace, + ) { + return const Center( + child: Icon( + Icons + .broken_image, + color: Colors + .grey, + ), + ); + }, + ) + : isPdf + ? const Center( + child: Icon( + Icons + .picture_as_pdf, + color: Colors.red, + size: 50, + ), + ) + : const Center( + child: Icon( + Icons + .insert_drive_file, + color: + Colors.grey, + size: 50, + ), + ), + ), + Center( + child: Container( + width: 56.12, + height: 56.12, + decoration: BoxDecoration( + color: Colors.white + .withOpacity(0.37), + borderRadius: + BorderRadius.circular( + 8, + ), + ), + child: Center( + child: Container( + width: 36.66, + height: 36.66, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.circular( + 6, + ), + boxShadow: const [ + BoxShadow( + color: Colors + .black12, + blurRadius: 4, + offset: Offset( + 0, + 2, + ), + ), + ], + ), + child: + isDownloadingThis + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: + 2, + color: Colors + .deepPurple, + ), + ) + : FutureBuilder< + String? + >( + future: + DownloadHelper.checkFileExists( + filePath, + ), + builder: + ( + context, + snapshot, + ) { + final fileExists = + snapshot.data != + null; + return Icon( + fileExists + ? Icons.visibility + : Icons.download, + color: + Colors.black87, + size: + 20, + ); + }, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ); + }, + ), + ) + else + const SizedBox.shrink(), + ], + ), + ), + ), + ), + ], + Column( + children: [ + if (data.paymentStatus == "Un Paid") ...[ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 31, + horizontal: 20, + ), + child: Column( + children: [ + Container( + width: double.infinity, + decoration: BoxDecoration( + color: const Color(0xFFFFF6ED), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: const Color(0xFFD8CEC5), + width: 1, + ), + boxShadow: const [ + BoxShadow( + color: Color(0x66716E6E), + blurRadius: 15.2, + offset: Offset(0, 1), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Payment Advice", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.042, + height: 1.4, + letterSpacing: 0.03 * 16, + color: const Color(0xFF111827), + ), + ), + const SizedBox(height: 20), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + text: TextSpan( + children: [ + TextSpan( + text: 'Date: ', + style: TextStyle( + fontFamily: + 'Gilroy-SemiBold', + fontWeight: + FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + TextSpan( + text: + data.createdDate ?? + "-", + style: TextStyle( + fontFamily: + 'Gilroy-Medium', + fontWeight: + FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(width: 10), + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + text: TextSpan( + children: [ + TextSpan( + text: 'Payment : ', + style: TextStyle( + fontFamily: + 'Gilroy-SemiBold', + fontWeight: + FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + TextSpan( + text: + data.paymentStatus ?? + "-", + style: TextStyle( + fontFamily: + 'Gilroy-Medium', + fontWeight: + FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 20), + const Divider(), + const SizedBox(height: 20), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + "Total Amount", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + Text( + "₹ ${data.paymentAmount ?? '0'}", + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w600, + fontSize: width * 0.045, + color: const Color(0xFF111827), + ), + ), + ], + ), + ], + ), + ), + ), + const SizedBox(height: 20), + CommanButton(text: 'Pay Now', onPressed: () {}), + ], + ), + ), + ] else if (data.paymentStatus == "Paid") ...[ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 31, + horizontal: 20, + ), + child: Column( + children: [ + Container( + width: double.infinity, + decoration: BoxDecoration( + color: const Color(0xFFFFF6ED), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: const Color(0xFFD8CEC5), + width: 1, + ), + boxShadow: const [ + BoxShadow( + color: Color(0x66716E6E), + blurRadius: 15.2, + offset: Offset(0, 1), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Payment Advice", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.042, + height: 1.4, + letterSpacing: 0.03 * 16, + color: const Color(0xFF111827), + ), + ), + const SizedBox(height: 20), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + text: TextSpan( + children: [ + TextSpan( + text: 'Date: ', + style: TextStyle( + fontFamily: + 'Gilroy-SemiBold', + fontWeight: + FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + TextSpan( + text: + data.createdDate ?? + "-", + style: TextStyle( + fontFamily: + 'Gilroy-Medium', + fontWeight: + FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(width: 10), + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + text: TextSpan( + children: [ + TextSpan( + text: 'Payment: ', + style: TextStyle( + fontFamily: + 'Gilroy-SemiBold', + fontWeight: + FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + TextSpan( + text: + data.paymentStatus ?? + "-", + style: TextStyle( + fontFamily: + 'Gilroy-Medium', + fontWeight: + FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: + 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 20), + const Divider(), + const SizedBox(height: 20), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + "Total Amount", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + Text( + "₹ ${data.paymentAmount ?? '0'}", + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w600, + fontSize: width * 0.045, + color: const Color(0xFF111827), + ), + ), + ], + ), + ], + ), + ), + ), + const SizedBox(height: 20), + _buildInvoiceDownloadButton( + data.invoice, + width, + ), + ], + ), + ), + ] else if (data.paymentStatus == "Waiting") ...[ + const SizedBox.shrink(), + ] else ...[ + Text("Unknown Status: ${data.paymentStatus}"), + ], + + if (data.proforma != null && + data.proforma!.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 31, + horizontal: 20, + ), + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, // #FFFFFF + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: const Color(0xFFE1E1E1), + width: 1, + ), + boxShadow: const [ + BoxShadow( + color: Color(0x40757575), // #75757540 + offset: Offset(0, 1), + blurRadius: 15, + spreadRadius: 0, + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Payment Advice", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.042, + height: 1.4, + letterSpacing: 0.03 * 16, + color: const Color(0xFF111827), + ), + ), + const SizedBox(height: 20), + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: RichText( + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + text: TextSpan( + children: [ + TextSpan( + text: 'proforma Number : ', + style: TextStyle( + fontFamily: + 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + TextSpan( + text: + data.proformaNumber ?? + "-", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color( + 0xFF111827, + ), + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 10), + RichText( + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + text: TextSpan( + children: [ + TextSpan( + text: 'proforma Status : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: data.proformastatus ?? "-", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w400, + fontSize: width * 0.035, + height: 1.3, + letterSpacing: 0.04 * 13.97, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + const SizedBox(height: 20), + if (data.proformastatus != "Accepted") ...[ + Text( + "Note : Once you accept this proforma only you can pay the amount for the service", + textAlign: TextAlign.start, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 13, + height: 1.78, // 178% line-height + letterSpacing: 0.04 * 13, // 4% + color: Colors.red, + ), + ), + const SizedBox(height: 20), + ], + + Row( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + /// 📄 Proforma (More width) + Expanded( + flex: 3, + child: _buildProformaDownloadButton( + data.proforma, + ), + ), + + const SizedBox(width: 8), + + if (data.proformastatus != "Accepted") + /// ✅ Accept (Less width) + Expanded( + flex: 2, + child: SizedBox( + height: + 42, // match proforma height + child: CommanButton( + text: 'Accept', + onPressed: () async { + try { + await ApiRepository() + .proformaaccept( + proformaId: int.parse( + data.proformaId + .toString(), + ), + ); + + validationPopup + .showSuccessMessage( + context, + "Proforma accepted successfully", + ); + + ref.invalidate( + serviceDetailProvider, + ); + ref.invalidate( + serviceHistoryNotifierProvider, + ); + } catch (error) { + validationPopup.showErrorMessage( + context, + error is Map && + error['error'] != + null + ? error['error'] + : "Failed to accept proforma", + ); + } + }, + ), + ), + ), + ], + ), + + const SizedBox(height: 20), + ], + ), + ), + ), + ), + ], + ], + ), + + /// 🔹 Main Detail Box + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 12, + ), + child: Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildInfoRow("File ID", "${data.id}", width), + const SizedBox(height: 16), + _buildInfoRow( + "Request Type", + "${data.service}", + width, + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: _buildInfoRow( + "Date", + "${data.createdDate}", + width, + ), + ), + const SizedBox(width: 10), + Expanded( + child: _buildInfoRow( + "Time", + "${data.createdTime}", + width, + ), + ), + ], + ), + const SizedBox(height: 16), + _buildInfoRow( + "Created by", + "${data.createdBy}", + width, + ), + const SizedBox(height: 16), + _buildInfoRow("Message", "${data.message}", width), + const SizedBox(height: 16), + + /// 🔹 File List Section + Text( + "File Attachments:", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + const SizedBox(height: 10), + + if (data.userUploadedDocuments.isNotEmpty) + SizedBox( + height: 100, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: data.userUploadedDocuments.length, + itemBuilder: (context, index) { + final doc = + data.userUploadedDocuments[index]; + final filePath = doc.filePath ?? ''; + final isImage = + filePath.toLowerCase().endsWith( + '.jpg', + ) || + filePath.toLowerCase().endsWith( + '.jpeg', + ) || + filePath.toLowerCase().endsWith( + '.png', + ) || + filePath.toLowerCase().endsWith( + '.gif', + ) || + filePath.toLowerCase().endsWith( + '.webp', + ); + final isPdf = filePath + .toLowerCase() + .endsWith('.pdf'); + + final isDownloadingThis = + _downloadingFiles[filePath] == true; + + return Padding( + padding: const EdgeInsets.only(right: 10), + child: GestureDetector( + onTap: () => _handleDownload(filePath), + child: Container( + height: 90, + width: 90, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + 8, + ), + color: const Color(0xFFF5F5F5), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.05, + ), + blurRadius: 3, + offset: const Offset(0, 2), + ), + ], + ), + child: Stack( + children: [ + ClipRRect( + borderRadius: + BorderRadius.circular(8), + child: isImage + ? Image.network( + filePath, + width: 90, + height: 90, + fit: BoxFit.cover, + errorBuilder: + ( + context, + error, + stackTrace, + ) { + return const Center( + child: Icon( + Icons + .broken_image, + color: Colors + .grey, + ), + ); + }, + ) + : isPdf + ? const Center( + child: Icon( + Icons.picture_as_pdf, + color: Colors.red, + size: 50, + ), + ) + : const Center( + child: Icon( + Icons + .insert_drive_file, + color: Colors.grey, + size: 50, + ), + ), + ), + Center( + child: Container( + width: 56.12, + height: 56.12, + decoration: BoxDecoration( + color: Colors.white + .withOpacity(0.37), + borderRadius: + BorderRadius.circular( + 8, + ), + ), + child: Center( + child: Container( + width: 36.66, + height: 36.66, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.circular( + 6, + ), + boxShadow: const [ + BoxShadow( + color: + Colors.black12, + blurRadius: 4, + offset: Offset( + 0, + 2, + ), + ), + ], + ), + child: isDownloadingThis + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors + .deepPurple, + ), + ) + : FutureBuilder< + String? + >( + future: + DownloadHelper.checkFileExists( + filePath, + ), + builder: (context, snapshot) { + final fileExists = + snapshot + .data != + null; + return Icon( + fileExists + ? Icons + .visibility + : Icons + .download, + color: Colors + .black87, + size: 20, + ); + }, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ); + }, + ), + ) + else + const Text( + "No documents uploaded", + style: TextStyle( + fontFamily: 'Gilroy-Medium', + color: Color(0xFF6B7280), + ), + ), + ], + ), + ), + ), + if (data.chatId != null && data.chatId!.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 20, + ), + child: + countAsync?.when( + data: (count) => CommanButton( + text: "Chat", + backgroundImage: AppAssets.backgroundimages, + prefixIcon: messageIconWithBadge(count.count), + onPressed: () => + Get.to( + () => LiveChatScreen( + fileid: data.id.toString(), + chatid: int.parse( + data.chatId.toString(), + ), + ), + )?.then((_) { + ref + .read( + notificationTriggerProvider + .notifier, + ) + .state++; + ref.invalidate(chatMessagesProvider); + }), + ), + loading: () => CommanButton( + text: "Chat", + backgroundImage: AppAssets.backgroundimages, + prefixIcon: messageIconWithBadge(0), + onPressed: () => + Get.to( + () => LiveChatScreen( + fileid: data.id.toString(), + chatid: int.parse( + data.chatId.toString(), + ), + ), + )?.then((_) { + ref + .read( + notificationTriggerProvider + .notifier, + ) + .state++; + ref.invalidate(chatMessagesProvider); + }), + ), + error: (_, __) => CommanButton( + text: "Chat", + backgroundImage: AppAssets.backgroundimages, + prefixIcon: messageIconWithBadge(0), + onPressed: () => + Get.to( + () => LiveChatScreen( + fileid: data.id.toString(), + chatid: int.parse( + data.chatId.toString(), + ), + ), + )?.then((_) { + ref + .read( + notificationTriggerProvider + .notifier, + ) + .state++; + ref.invalidate(chatMessagesProvider); + }), + ), + ) ?? + CommanButton( + text: "Chat", + backgroundImage: AppAssets.backgroundimages, + prefixIcon: messageIconWithBadge(0), + onPressed: () => + Get.to( + () => LiveChatScreen( + fileid: data.id.toString(), + chatid: int.parse(data.chatId.toString()), + ), + )?.then((_) { + ref + .read( + notificationTriggerProvider.notifier, + ) + .state++; + ref.invalidate(chatMessagesProvider); + }), + ), + ), + + const SizedBox(height: 150), + ], + ), + ); + }, + ), + ), + ), + ); + } + + /// 🔹 Helper Widget for Each Info Row + Widget _buildInfoRow(String label, String value, double width) { + return RichText( + text: TextSpan( + children: [ + TextSpan( + text: '$label: ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: value.isEmpty ? '—' : value, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.04, + height: 1.5, + color: const Color(0xFF374151), + ), + ), + ], + ), + ); + } + + Widget messageIconWithBadge(int count) { + return Stack( + clipBehavior: Clip.none, + children: [ + const Icon(Icons.message_outlined, color: Colors.white, size: 26), + + if (count > 0) + Positioned( + right: -2, + top: -2, + child: Container( + padding: const EdgeInsets.all(3), + decoration: const BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + ), + child: Text( + count.toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/view/screens/history/flitter_popup.dart b/lib/view/screens/history/flitter_popup.dart new file mode 100644 index 0000000..7168bc1 --- /dev/null +++ b/lib/view/screens/history/flitter_popup.dart @@ -0,0 +1,243 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class FlitterPopup { + static void show(BuildContext context) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (context) { + return const _FilterBottomSheet(); + }, + ); + } +} + +class _FilterBottomSheet extends StatefulWidget { + const _FilterBottomSheet({Key? key}) : super(key: key); + + @override + State<_FilterBottomSheet> createState() => _FilterBottomSheetState(); +} + +class _FilterBottomSheetState extends State<_FilterBottomSheet> + with SingleTickerProviderStateMixin { + DateTime? fromDate; + DateTime? toDate; + + late AnimationController _controller; + late Animation _slideAnimation; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: const Duration(milliseconds: 400), + vsync: this, + ); + + _slideAnimation = Tween( + begin: const Offset(0, 1), + end: Offset.zero, + ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut)); + + _controller.forward(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future pickFromDate() async { + final picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2020), + lastDate: DateTime(2100), + ); + + if (picked != null) { + setState(() => fromDate = picked); + } + } + + Future pickToDate() async { + final picked = await showDatePicker( + context: context, + initialDate: fromDate ?? DateTime.now(), + firstDate: fromDate ?? DateTime(2020), + lastDate: DateTime(2100), + ); + + if (picked != null) { + setState(() => toDate = picked); + } + } + + @override + Widget build(BuildContext context) { + return SafeArea( + top: false, + child: SlideTransition( + position: _slideAnimation, + child: Container( + padding: const EdgeInsets.all(20), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + "Filter By Date", + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 20), + + /// FROM DATE + InkWell( + onTap: pickFromDate, + child: _dateBox(title: "From Date", value: fromDate), + ), + + const SizedBox(height: 12), + + /// TO DATE + InkWell( + onTap: pickToDate, + child: _dateBox(title: "To Date", value: toDate), + ), + + const SizedBox(height: 20), + + Row( + children: [ + Expanded( + child: SizedBox( + width: double.infinity, + height: 57, + child: ElevatedButton( + onPressed: () { + Navigator.pop(context); + }, + style: ElevatedButton.styleFrom( + backgroundColor: const Color( + 0xFFF7E9FF, + ), // ✅ background + elevation: 6, // ✅ shadow depth + shadowColor: const Color( + 0x40000000, + ), // ✅ shadow color + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6), // ✅ radius + side: const BorderSide( + color: Color(0xFFD39FEA), // ✅ border color + width: 1, // ✅ border width + ), + ), + ), + child: const Text( + "Cancel", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", // ✅ Font + fontWeight: FontWeight.w400, + fontSize: 16, + height: 1.3, // ✅ line-height 130% + letterSpacing: 0.64, // ✅ 4% + color: Color(0xFF61277A), // ✅ text color + ), + ), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Consumer( + builder: (context, ref, _) { + return CommanButton( + text: 'Submit', + onPressed: () { + final from = fromDate == null + ? null + : "${fromDate!.year}-${fromDate!.month.toString().padLeft(2, '0')}-${fromDate!.day.toString().padLeft(2, '0')}"; + + final to = toDate == null + ? null + : "${toDate!.year}-${toDate!.month.toString().padLeft(2, '0')}-${toDate!.day.toString().padLeft(2, '0')}"; + + // ✅ Apply filter to ALL TABS + ref + .read( + serviceHistoryNotifierProvider( + "pending", + ).notifier, + ) + .applyDateFilter(from: from, to: to); + + ref + .read( + serviceHistoryNotifierProvider( + "inprogress", + ).notifier, + ) + .applyDateFilter(from: from, to: to); + + ref + .read( + serviceHistoryNotifierProvider( + "completed", + ).notifier, + ) + .applyDateFilter(from: from, to: to); + + ref + .read( + serviceHistoryNotifierProvider( + "cancelled", + ).notifier, + ) + .applyDateFilter(from: from, to: to); + + Navigator.pop(context); // ✅ Close popup + }, + ); + }, + ), + ), + ], + ), + + const SizedBox(height: 10), + ], + ), + ), + ), + ); + } + + Widget _dateBox({required String title, DateTime? value}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), + decoration: BoxDecoration( + border: Border.all(color: Colors.grey), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + value == null ? title : "${value.day}-${value.month}-${value.year}", + style: const TextStyle(fontSize: 14), + ), + const Icon(Icons.calendar_month, size: 20), + ], + ), + ); + } +} diff --git a/lib/view/screens/history/pending_screen.dart b/lib/view/screens/history/pending_screen.dart new file mode 100644 index 0000000..005ee72 --- /dev/null +++ b/lib/view/screens/history/pending_screen.dart @@ -0,0 +1,551 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import 'package:taxglide/view/screens/history/detail_screen.dart'; + +class PendingScreen extends ConsumerWidget { + final String status; + + const PendingScreen({super.key, required this.status}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final pendingAsync = ref.watch(serviceHistoryNotifierProvider(status)); + final size = MediaQuery.of(context).size; + final width = size.width; + final height = size.height; + + return pendingAsync.when( + data: (data) { + final list = data.data ?? []; + if (list.isEmpty) { + // Using Get's capitalize extension explicitly + return Center(child: Text("No ${status.capitalizeFirst} Requests")); + } + + return ListView.separated( + physics: const BouncingScrollPhysics(), + padding: EdgeInsets.fromLTRB( + width * 0.04, + height * 0.01, + width * 0.04, + height * 0.2, + ), + itemCount: list.length, + separatorBuilder: (_, __) => SizedBox(height: height * 0.01), + itemBuilder: (context, index) { + final item = list[index]; + + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFE1E1E1), width: 1), + boxShadow: [ + BoxShadow( + color: const Color.fromARGB(117, 192, 192, 189), + blurRadius: 15, + offset: const Offset(0, 1), + ), + ], + ), + padding: EdgeInsets.all(width * 0.03), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 🔹 File ID Row + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'File ID : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: '${item.id}', + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.04, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + // 🔹 Status Badges + if (item.status == 'Waiting for Admin' || + item.status == 'Payment Pending' || + item.status == 'Cancelled By Admin') + Container( + width: width * 0.3, + height: height * 0.04, + decoration: BoxDecoration( + color: const Color(0xFFFFE8E8), + borderRadius: BorderRadius.circular(5.52), + border: Border.all( + color: const Color(0xFFFFD7D7), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: Center( + child: Text( + item.status.toString(), + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: 11.03, + color: Color(0xFFFF0F0F), + ), + ), + ), + ), + + // 🔹 In Progress Badge + if (item.status == 'In Progress') + Container( + width: 98, + height: 34.9, + decoration: BoxDecoration( + color: const Color(0xFFEAFAE6), + borderRadius: BorderRadius.circular(6.21), + border: Border.all( + color: const Color(0xFFDDFFDD), + width: 2.07, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 8.08, + offset: const Offset(0, 4.14), + ), + ], + ), + child: const Center( + child: Text( + 'In Progress', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: 12.43, + letterSpacing: 0.03, + color: Color(0xFF12800C), + ), + ), + ), + ), + + // 🔹 Completed Badge + if (item.status == 'Completed') + Container( + width: 87, + height: 31, + decoration: BoxDecoration( + color: const Color(0xFFFAF7E6), + borderRadius: BorderRadius.circular(5.52), + border: Border.all( + color: const Color(0xFFFFE9DD), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: const Center( + child: Text( + 'Completed', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: 11.03, + letterSpacing: 0.03, + color: Color(0xFFFF630F), + ), + ), + ), + ), + ], + ), + + SizedBox(height: height * 0.015), + + // 🔹 Request Type + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Request Type : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.service, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + SizedBox(height: height * 0.015), + + // 🔹 Date and Time Row + Row( + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Date : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.createdDate, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + SizedBox(width: width * 0.05), + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Time : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.createdTime, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + ], + ), + + SizedBox(height: height * 0.015), + + // 🔹 Message + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Message : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.message, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: width * 0.035, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + SizedBox(height: height * 0.015), + const Divider(), + SizedBox(height: height * 0.015), + + // 🔹 Conditional Buttons & Amount + if (item.paymentStatus == "Unpaid") ...[ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Total Amount", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: width * 0.038, + color: const Color(0xFF111827), + ), + ), + Text( + '₹ ${item.paymentAmount.toString()}', + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w600, + fontSize: width * 0.05, + color: const Color(0xFF111827), + ), + ), + ], + ), + SizedBox(height: height * 0.015), + Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () { + // Add payment functionality here + }, + child: Container( + height: height * 0.055, + decoration: BoxDecoration( + color: const Color(0xFFF7E9FF), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: const Color(0xFFD39FEA), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: const Center( + child: Text( + "Pay Now", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Color(0xFF61277A), + ), + ), + ), + ), + ), + ), + SizedBox(width: width * 0.03), + Expanded( + child: GestureDetector( + onTap: () { + ref.invalidate(serviceDetailProvider); + Get.offAll( + () => MainController( + initialIndex: 2, // ✅ History tab + child: DetailScreen( + id: int.parse(item.id.toString()), + sourceTabIndex: 2, // ✅ Remember source + ), + ), + ); + }, + child: Container( + height: height * 0.055, + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: const Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Colors.white, + ), + ), + ), + ), + ), + ), + ], + ), + ] else if (item.paymentStatus == "Paid") ...[ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 149, + height: 33, + decoration: BoxDecoration( + color: const Color(0xFF04690B), + borderRadius: BorderRadius.circular(4.53), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 5.89, + offset: const Offset(0, 3.02), + ), + ], + ), + alignment: Alignment.center, + child: const Text( + "Payment Status: Paid", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: 12.08, + letterSpacing: 0.04, + height: 1.3, + color: Colors.white, + ), + ), + ), + GestureDetector( + onTap: () { + ref.invalidate(serviceDetailProvider); + Get.offAll( + () => MainController( + initialIndex: 2, // ✅ History tab + child: DetailScreen( + id: int.parse(item.id.toString()), + sourceTabIndex: 2, // ✅ Remember source + ), + ), + ); + }, + child: Container( + height: height * 0.055, + width: width * 0.35, + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: const Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ), + ] else if (item.paymentStatus == "Waiting") ...[ + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: () { + ref.invalidate(serviceDetailProvider); + Get.offAll( + () => MainController( + initialIndex: 2, // ✅ History tab + child: DetailScreen( + id: int.parse(item.id.toString()), + sourceTabIndex: 2, // ✅ Remember source + ), + ), + ); + }, + child: Container( + height: height * 0.055, + width: width * 0.35, + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: const Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Colors.white, + ), + ), + ), + ), + ), + ), + ], + + SizedBox(height: height * 0.02), + ], + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Center( + child: Text("Error: $error", style: const TextStyle(color: Colors.red)), + ), + ); + } +} diff --git a/lib/view/screens/history/serivces_status_screen.dart b/lib/view/screens/history/serivces_status_screen.dart new file mode 100644 index 0000000..a22e4c5 --- /dev/null +++ b/lib/view/screens/history/serivces_status_screen.dart @@ -0,0 +1,180 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/view/screens/history/flitter_popup.dart'; +import 'package:taxglide/view/screens/history/pending_screen.dart'; + +class ServicesStatusScreen extends ConsumerStatefulWidget { + const ServicesStatusScreen({super.key}); + + @override + ConsumerState createState() => + _ServicesStatusScreenState(); +} + +class _ServicesStatusScreenState extends ConsumerState + with SingleTickerProviderStateMixin { + late TabController _tabController; + + final List _tabs = [ + "Pending", + "In Progress", + "Completed", + "Cancelled Request", + ]; + + @override + void initState() { + super.initState(); + _tabController = TabController( + length: _tabs.length, + vsync: this, + animationDuration: Duration.zero, + ); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ✅ Title + Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 21), + child: SizedBox( + height: 50, + width: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const SizedBox(width: 40), // ✅ Left side space balance + // ✅ CENTER TITLE + const Text( + "Service Status", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 24, + color: Color(0xFF111827), + ), + ), + + // ✅ RIGHT SIDE FILTER ICON + GestureDetector( + onTap: () { + FlitterPopup.show(context); + }, + child: Container( + width: 39, + height: 39, + decoration: BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + border: Border.all( + color: const Color(0xFF055976), + width: 0.8, + ), + ), + child: const Center( + child: Icon( + Icons.filter_list, + color: Color(0xFF055976), + size: 22, + ), + ), + ), + ), + ], + ), + ), + ), + + // ✅ Tabs + Container( + decoration: const BoxDecoration( + border: Border( + bottom: BorderSide(color: Color(0xFFDEDEDE), width: 1), + ), + ), + child: Align( + alignment: Alignment.centerLeft, + child: TabBar( + controller: _tabController, + isScrollable: true, + padding: EdgeInsets.zero, + labelPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + tabAlignment: TabAlignment.start, + splashFactory: NoSplash.splashFactory, + overlayColor: const MaterialStatePropertyAll( + Colors.transparent, + ), + indicatorColor: const Color(0xFF5F297B), + indicator: const UnderlineTabIndicator( + borderSide: BorderSide(width: 3, color: Color(0xFF5F297B)), + insets: EdgeInsets.fromLTRB(6, 0, 4, 10), + ), + labelColor: const Color(0xFF5F297B), + unselectedLabelColor: const Color(0xFF6C7278), + labelStyle: const TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + fontSize: 16, + height: 1.4, + letterSpacing: 0.03, + color: Color(0xFF5F297B), + ), + unselectedLabelStyle: const TextStyle( + fontFamily: "Gilroy-Regular", + fontWeight: FontWeight.w400, + fontSize: 16, + height: 1.4, + letterSpacing: 0.03, + color: Color(0xFF6C7278), + ), + tabs: _tabs.map((tab) => Tab(text: tab)).toList(), + ), + ), + ), + + // ✅ Tab Views + Expanded( + child: TabBarView( + controller: _tabController, + physics: const NeverScrollableScrollPhysics(), + children: const [ + ColoredBox( + color: Color.fromARGB(255, 230, 229, 229), + child: PendingScreen(status: "pending"), + ), + ColoredBox( + color: Color.fromARGB(255, 230, 229, 229), + child: PendingScreen(status: "inprogress"), + ), + ColoredBox( + color: Color.fromARGB(255, 230, 229, 229), + child: PendingScreen(status: "completed"), + ), + ColoredBox( + color: Color.fromARGB(255, 230, 229, 229), + child: PendingScreen(status: "cancelled"), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/screens/home_screen.dart b/lib/view/screens/home_screen.dart new file mode 100644 index 0000000..515969a --- /dev/null +++ b/lib/view/screens/home_screen.dart @@ -0,0 +1,1198 @@ +import 'package:carousel_slider/carousel_options.dart'; +import 'package:carousel_slider/carousel_slider.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_serivce.dart'; +import 'package:taxglide/consts/home_page_headers.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/consts/notification_webscoket.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/model/serivce_list_model.dart'; + +import 'package:taxglide/view/Main_controller/main_controller.dart'; +import 'package:taxglide/view/screens/history/detail_screen.dart'; + +class HomeScreen extends ConsumerStatefulWidget { + const HomeScreen({super.key}); + + @override + ConsumerState createState() => _HomeScreenState(); +} + +class _HomeScreenState extends ConsumerState { + final CarouselSliderController _carouselController = + CarouselSliderController(); + int _currentIndex = 0; + + @override + void initState() { + super.initState(); + _initializeWebSocket(); + } + + Future _initializeWebSocket() async { + final userId = await LocalStore().getUserId(); + if (userId == null) { + print("❌ No User ID found. Cannot connect WS"); + return; + } + NotificationWebSocket().connect( + userId: userId, + container: ProviderScope.containerOf(context), + ); + } + + @override + Widget build(BuildContext context) { + final dashboardAsync = ref.watch(dashboardProvider); + final serviceAsync = ref.watch(serviceListProvider); + final r = ResponsiveUtils(context); + + return Scaffold( + backgroundColor: const Color.fromARGB(255, 230, 229, 229), + body: SafeArea( + child: dashboardAsync.when( + data: (dashboard) => _buildHomeContent( + context, + dashboard, + dashboard.companyName.toString(), + serviceAsync, + r, + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center(child: Text('Error: $err')), + ), + ), + ); + } + + Widget _buildHomeContent( + BuildContext context, + dynamic dashboard, + String userName, + AsyncValue> serviceAsync, + ResponsiveUtils r, + ) { + final List list = dashboard.serviceRequestLists.data; + + // Responsive values + final hPadding = r.spacing(mobile: 16, tablet: 20, desktop: 28); + final sectionTitleSize = r.fontSize(mobile: 18, tablet: 18, desktop: 20); + final bookingTitleSize = r.fontSize(mobile: 20, tablet: 20, desktop: 22); + final seeAllSize = r.fontSize(mobile: 15, tablet: 15, desktop: 16); + final labelSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final valueSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final fileIdSize = r.fontSize(mobile: 14, tablet: 15, desktop: 16); + final amountSize = r.fontSize(mobile: 17, tablet: 18, desktop: 20); + final buttonTextSize = r.fontSize(mobile: 14, tablet: 16, desktop: 17); + final buttonHeight = r.getValue( + mobile: 44, + tablet: 50, + desktop: 54, + ); + final cardPadding = r.spacing(mobile: 12, tablet: 14, desktop: 16); + final cardSpacing = r.spacing(mobile: 10, tablet: 12, desktop: 14); + + final gridCrossAxisCount = r.getValue( + mobile: 3, + tablet: 4, + desktop: 5, + ); + final carouselHeight = r.getValue( + mobile: 160, + tablet: 180, + desktop: 200, + ); + final carouselSectionHeight = r.getValue( + mobile: 200, + tablet: 220, + desktop: 240, + ); + + final reviewCardWidth = r.getValue( + mobile: 160, + tablet: 180, + desktop: 200, + ); + final reviewCardHeight = r.getValue( + mobile: 180, + tablet: 192, + desktop: 210, + ); + final reviewTitleSize = r.fontSize(mobile: 20, tablet: 20, desktop: 22); + + final kycTitleSize = r.fontSize(mobile: 16, tablet: 18, desktop: 20); + final kycBodySize = r.fontSize(mobile: 10, tablet: 10, desktop: 11); + + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + HomePageHeader(userName: userName), + const SizedBox(height: 60), + + Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // KYC Banner + if (dashboard.isKycCompleted == false) + Container( + width: double.infinity, + padding: EdgeInsets.all(cardPadding), + decoration: const BoxDecoration( + color: AppColors.homepagekycdetails, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(10), + topRight: Radius.circular(100), + bottomRight: Radius.circular(100), + bottomLeft: Radius.circular(10), + ), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "KYC Details", + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: kycTitleSize, + color: Colors.white, + ), + ), + const SizedBox(height: 8), + Text( + "Your KYC verification couldn't be completed. Please complete your KYC details to continue exploring more features.", + style: TextStyle( + fontSize: kycBodySize, + color: const Color(0xFFFFFFCC), + ), + ), + ], + ), + ), + Stack( + alignment: Alignment.center, + children: [ + Container( + width: 79, + height: 79, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Color(0x9640ED8E), + ), + ), + SizedBox( + width: 90, + height: 90, + child: CircularProgressIndicator( + value: 0.6, + strokeWidth: 6, + backgroundColor: Colors.white, + valueColor: AlwaysStoppedAnimation( + AppColors.homepagekycdetailsorange, + ), + ), + ), + Icon( + Icons.person, + size: 35.25, + color: AppColors.homepagekycdetailsorange, + ), + ], + ), + ], + ), + ), + + SizedBox( + height: r.spacing(mobile: 26, tablet: 28, desktop: 32), + ), + + Text( + "List of Services Offered", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: sectionTitleSize, + height: 1.3, + letterSpacing: 0.72, + ), + ), + + SizedBox( + height: r.spacing(mobile: 26, tablet: 28, desktop: 32), + ), + + // Service Grid + serviceAsync.when( + data: (services) { + final searchText = ref.watch(serviceSearchProvider); + final filteredServices = services.where((service) { + return service.service.toLowerCase().contains( + searchText.toLowerCase(), + ); + }).toList(); + + if (filteredServices.isEmpty) { + return const Padding( + padding: EdgeInsets.only(top: 20), + child: Center(child: Text("No Services Found")), + ); + } + + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: services.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: gridCrossAxisCount, + mainAxisSpacing: 16, + crossAxisSpacing: 12, + childAspectRatio: 0.75, + ), + itemBuilder: (context, index) { + return CommonServiceItem( + service: services[index], + sourceTabIndex: 0, + ); + }, + ); + }, + loading: () => + const Center(child: CircularProgressIndicator()), + error: (err, _) => Center(child: Text('Error: $err')), + ), + ], + ), + ), + + SizedBox(height: r.spacing(mobile: 26, tablet: 28, desktop: 32)), + + // Booking List Section + if (list.isNotEmpty) + Container( + width: double.infinity, + color: const Color(0xFFFFFDF0), + child: Padding( + padding: EdgeInsets.symmetric( + vertical: r.spacing(mobile: 38, tablet: 40, desktop: 44), + horizontal: hPadding, + ), + child: Column( + children: [ + // Header Row + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Booking List", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: bookingTitleSize, + height: 1.4, + letterSpacing: 0.6, + ), + ), + GestureDetector( + onTap: () { + Get.offAll( + () => const MainController( + initialIndex: 2, + sourceTabIndex: 0, + ), + ); + }, + child: Text( + "See All", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: seeAllSize, + height: 1.4, + letterSpacing: 0.45, + color: const Color(0xFF000000), + ), + ), + ), + ], + ), + + // Booking Cards + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.symmetric(vertical: cardSpacing), + itemCount: list.length, + separatorBuilder: (_, __) => + SizedBox(height: cardSpacing), + itemBuilder: (context, index) { + final item = list[index]; + + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: const Color(0xFFE1E1E1), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: const Color.fromARGB(117, 192, 192, 189), + blurRadius: 15, + offset: const Offset(0, 1), + ), + ], + ), + padding: EdgeInsets.all(cardPadding), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // File ID Row + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'File ID : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: fileIdSize, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: '${item.id}', + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: fileIdSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + // Status Badge + if (item.status == 'Waiting for Admin' || + item.status == 'Payment Pending' || + item.status == 'Cancelled By Admin') + Container( + width: r.getValue( + mobile: 110, + tablet: 120, + desktop: 130, + ), + height: r.getValue( + mobile: 30, + tablet: 34, + desktop: 36, + ), + decoration: BoxDecoration( + color: const Color(0xFFFFE8E8), + borderRadius: BorderRadius.circular( + 5.52, + ), + border: Border.all( + color: const Color(0xFFFFD7D7), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: Center( + child: Text( + item.status.toString(), + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: r.fontSize( + mobile: 10, + tablet: 11, + desktop: 12, + ), + color: const Color(0xFFFF0F0F), + ), + ), + ), + ), + + if (item.status == 'In Progress') + Container( + width: r.getValue( + mobile: 88, + tablet: 98, + desktop: 108, + ), + height: r.getValue( + mobile: 30, + tablet: 34.9, + desktop: 38, + ), + decoration: BoxDecoration( + color: const Color(0xFFEAFAE6), + borderRadius: BorderRadius.circular( + 6.21, + ), + border: Border.all( + color: const Color(0xFFDDFFDD), + width: 2.07, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 8.08, + offset: const Offset(0, 4.14), + ), + ], + ), + child: Center( + child: Text( + 'In Progress', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: r.fontSize( + mobile: 11, + tablet: 12.43, + desktop: 13, + ), + letterSpacing: 0.03, + color: const Color(0xFF12800C), + ), + ), + ), + ), + + if (item.status == 'Completed') + Container( + width: r.getValue( + mobile: 78, + tablet: 87, + desktop: 96, + ), + height: r.getValue( + mobile: 28, + tablet: 31, + desktop: 34, + ), + decoration: BoxDecoration( + color: const Color(0xFFFAF7E6), + borderRadius: BorderRadius.circular( + 5.52, + ), + border: Border.all( + color: const Color(0xFFFFE9DD), + width: 1.84, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.17, + offset: const Offset(0, 3.68), + ), + ], + ), + child: Center( + child: Text( + 'Completed', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: r.fontSize( + mobile: 10, + tablet: 11.03, + desktop: 12, + ), + letterSpacing: 0.03, + color: const Color(0xFFFF630F), + ), + ), + ), + ), + ], + ), + + SizedBox(height: cardSpacing), + + // Request Type + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Request Type : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelSize, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.service, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: valueSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + SizedBox(height: cardSpacing), + + // Date and Time Row + Row( + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Date : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelSize, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.createdDate, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: valueSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + SizedBox( + width: r.spacing( + mobile: 16, + tablet: 20, + desktop: 24, + ), + ), + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Time : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelSize, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.createdTime, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: valueSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + ], + ), + + SizedBox(height: cardSpacing), + + // Message + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Message : ', + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelSize, + color: const Color(0xFF111827), + ), + ), + TextSpan( + text: item.message, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontWeight: FontWeight.w500, + fontSize: valueSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + ), + + SizedBox(height: cardSpacing), + const Divider(), + SizedBox(height: cardSpacing), + + // Payment Actions + if (item.paymentStatus == "Unpaid") ...[ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + "Total Amount", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelSize, + color: const Color(0xFF111827), + ), + ), + Text( + '₹ ${item.paymentAmount.toString()}', + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w600, + fontSize: amountSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + SizedBox(height: cardSpacing), + Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () {}, + child: Container( + height: buttonHeight, + decoration: BoxDecoration( + color: const Color(0xFFF7E9FF), + borderRadius: BorderRadius.circular( + 6, + ), + border: Border.all( + color: const Color(0xFFD39FEA), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: Center( + child: Text( + "Pay Now", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: buttonTextSize, + color: const Color(0xFF61277A), + ), + ), + ), + ), + ), + ), + SizedBox( + width: r.spacing( + mobile: 10, + tablet: 12, + desktop: 14, + ), + ), + Expanded( + child: GestureDetector( + onTap: () { + ref.invalidate(serviceDetailProvider); + Get.offAll( + () => MainController( + initialIndex: 0, + child: DetailScreen( + id: int.parse( + item.id.toString(), + ), + sourceTabIndex: 0, + ), + ), + ); + }, + child: Container( + height: buttonHeight, + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular( + 6, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: buttonTextSize, + color: Colors.white, + ), + ), + ), + ), + ), + ), + ], + ), + ] else if (item.paymentStatus == "Paid") ...[ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Container( + width: r.getValue( + mobile: 140, + tablet: 149, + desktop: 160, + ), + height: r.getValue( + mobile: 30, + tablet: 33, + desktop: 36, + ), + decoration: BoxDecoration( + color: const Color(0xFF04690B), + borderRadius: BorderRadius.circular( + 4.53, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 5.89, + offset: const Offset(0, 3.02), + ), + ], + ), + alignment: Alignment.center, + child: Text( + "Payment Status: Paid", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontSize: r.fontSize( + mobile: 11, + tablet: 12.08, + desktop: 13, + ), + letterSpacing: 0.04, + height: 1.3, + color: Colors.white, + ), + ), + ), + GestureDetector( + onTap: () { + Get.offAll( + () => MainController( + initialIndex: 0, + child: DetailScreen( + id: int.parse(item.id.toString()), + sourceTabIndex: 0, + ), + ), + ); + }, + child: Container( + height: buttonHeight, + width: r.getValue( + mobile: 130, + tablet: 140, + desktop: 150, + ), + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular( + 6, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: buttonTextSize, + color: Colors.white, + ), + ), + ), + ), + ), + ], + ), + ] else if (item.paymentStatus == "Waiting") ...[ + Align( + alignment: Alignment.centerRight, + child: GestureDetector( + onTap: () { + Get.offAll( + () => MainController( + initialIndex: 0, + child: DetailScreen( + id: int.parse(item.id.toString()), + sourceTabIndex: 0, + ), + ), + ); + }, + child: Container( + height: buttonHeight, + width: r.getValue( + mobile: 130, + tablet: 140, + desktop: 150, + ), + decoration: BoxDecoration( + color: const Color(0xFF5F297B), + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity( + 0.25, + ), + blurRadius: 7.8, + offset: const Offset(0, 4), + ), + ], + ), + child: Center( + child: Text( + "View Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: buttonTextSize, + color: Colors.white, + ), + ), + ), + ), + ), + ), + ], + + SizedBox(height: cardSpacing), + ], + ), + ); + }, + ), + ], + ), + ), + ), + + SizedBox(height: r.spacing(mobile: 16, tablet: 18, desktop: 20)), + + // Carousel Slider + dashboard.imageSlider.isEmpty + ? const SizedBox.shrink() + : SizedBox( + height: carouselSectionHeight, + child: Column( + children: [ + CarouselSlider.builder( + carouselController: _carouselController, + itemCount: dashboard.imageSlider.length, + itemBuilder: (context, index, realIndex) { + final slider = dashboard.imageSlider[index]; + return Container( + margin: const EdgeInsets.symmetric(horizontal: 8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + image: DecorationImage( + image: NetworkImage(slider.image), + fit: BoxFit.cover, + ), + ), + ); + }, + options: CarouselOptions( + height: carouselHeight, + autoPlay: true, + enlargeCenterPage: true, + viewportFraction: 0.9, + onPageChanged: (index, reason) { + setState(() => _currentIndex = index); + }, + ), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate( + dashboard.imageSlider.length, + (index) => GestureDetector( + onTap: () => + _carouselController.animateToPage(index), + child: AnimatedContainer( + duration: const Duration(milliseconds: 300), + width: _currentIndex == index ? 18 : 8, + height: 8, + margin: const EdgeInsets.symmetric(horizontal: 4), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + color: _currentIndex == index + ? AppColors.commanbutton + : Colors.grey.shade400, + ), + ), + ), + ), + ), + ], + ), + ), + + SizedBox(height: r.spacing(mobile: 16, tablet: 18, desktop: 20)), + + // Customer Review Section + Stack( + clipBehavior: Clip.none, + children: [ + Image.asset( + AppAssets.back, + width: double.infinity, + fit: BoxFit.cover, + ), + Container( + width: double.infinity, + height: r.getValue( + mobile: 240, + tablet: 260, + desktop: 280, + ), + color: Colors.black.withOpacity(0.45), + ), + Positioned.fill( + child: Padding( + padding: EdgeInsets.only( + top: r.spacing(mobile: 60, tablet: 70, desktop: 80), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Text( + "What Our Customers Say", + style: TextStyle( + fontFamily: "Gilroy-SemiBold", + fontSize: reviewTitleSize, + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ), + Transform.translate( + offset: Offset( + 0, + r.getValue(mobile: 140, tablet: 150, desktop: 160), + ), + child: SizedBox( + height: reviewCardHeight + 30, + child: ListView.builder( + scrollDirection: Axis.horizontal, + padding: EdgeInsets.symmetric(horizontal: hPadding), + itemCount: dashboard.reviews.length, + itemBuilder: (context, index) { + final review = dashboard.reviews[index]; + return Row( + children: [ + _testimonialCard( + name: review.name, + position: review.about, + content: review.content, + rating: review.rating, + iconColor: Colors.blueAccent, + cardWidth: reviewCardWidth, + cardHeight: reviewCardHeight, + r: r, + ), + const SizedBox(width: 16), + ], + ); + }, + ), + ), + ), + ], + ), + + const SizedBox(height: 200), + ], + ), + ); + } + + Widget _testimonialCard({ + required String name, + required String position, + required String content, + required int rating, + required Color iconColor, + required double cardWidth, + required double cardHeight, + required ResponsiveUtils r, + }) { + return Stack( + clipBehavior: Clip.none, + children: [ + Container( + width: cardWidth, + height: cardHeight, + padding: EdgeInsets.all( + r.spacing(mobile: 14, tablet: 16, desktop: 18), + ), + margin: EdgeInsets.only( + left: r.spacing(mobile: 26, tablet: 30, desktop: 34), + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(24), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + name, + style: TextStyle( + fontSize: r.fontSize(mobile: 13, tablet: 15, desktop: 16), + fontWeight: FontWeight.w700, + color: Colors.black87, + ), + ), + Text( + position, + style: TextStyle( + fontSize: r.fontSize(mobile: 10, tablet: 11, desktop: 12), + color: Colors.grey, + ), + ), + const SizedBox(height: 6), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate( + rating, + (index) => Icon( + Icons.star, + size: r.getValue( + mobile: 12, + tablet: 14, + desktop: 16, + ), + color: Colors.amber, + ), + ), + ), + const SizedBox(height: 8), + Text( + content, + maxLines: 4, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: r.fontSize(mobile: 11, tablet: 12, desktop: 13), + height: 1.3, + color: Colors.black87, + ), + ), + ], + ), + ), + Positioned( + left: 0, + top: cardHeight / 2 - 20, + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration(color: iconColor, shape: BoxShape.circle), + child: const Center( + child: Text( + "❝", + style: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/view/screens/list_service_screen.dart b/lib/view/screens/list_service_screen.dart new file mode 100644 index 0000000..8c770cf --- /dev/null +++ b/lib/view/screens/list_service_screen.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/comman_serivce.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/model/serivce_list_model.dart'; + +class ListServiceScreen extends ConsumerStatefulWidget { + const ListServiceScreen({super.key}); + + @override + ConsumerState createState() => _ListServiceScreenState(); +} + +class _ListServiceScreenState extends ConsumerState { + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + final serviceAsync = ref.watch(serviceListProvider); + final screenWidth = size.width; + + return Scaffold( + body: SafeArea( + child: Container( + height: size.height, + width: size.width, + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + "List of Services Offered", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontStyle: FontStyle.normal, + fontSize: 18, + height: 1.3, + letterSpacing: 0.72, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 26), + + /// 🔹 Service List from API + serviceAsync.when( + data: (services) { + if (services.isEmpty) { + return const Padding( + padding: EdgeInsets.only(top: 40), + child: Center( + child: Text( + "No Services Available", + style: TextStyle( + fontSize: 16, + fontFamily: 'Gilroy-SemiBold', + color: Colors.black54, + ), + ), + ), + ); + } + + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: services.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: screenWidth < 400 + ? 3 + : screenWidth < 700 + ? 3 + : 4, + mainAxisSpacing: 16, + crossAxisSpacing: 12, + childAspectRatio: 0.75, + ), + itemBuilder: (context, index) { + return CommonServiceItem( + service: ServiceListModel( + id: services[index].id, + service: services[index].service, + icon: services[index].icon, + ), + sourceTabIndex: 1, + ); + }, + ); + }, + loading: () => const Center( + child: Padding( + padding: EdgeInsets.all(20), + child: CircularProgressIndicator(), + ), + ), + error: (err, _) => Center( + child: Padding( + padding: const EdgeInsets.all(20), + child: Text('Error loading services: $err'), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/view/screens/notification_screen.dart b/lib/view/screens/notification_screen.dart new file mode 100644 index 0000000..a13181a --- /dev/null +++ b/lib/view/screens/notification_screen.dart @@ -0,0 +1,151 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/model/notification_model.dart'; +import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart'; +import 'package:taxglide/view/screens/history/detail_screen.dart'; +import 'package:taxglide/view/Main_controller/main_controller.dart'; + +class NotificationScreen extends ConsumerStatefulWidget { + const NotificationScreen({super.key}); + + @override + ConsumerState createState() => _NotificationScreenState(); +} + +class _NotificationScreenState extends ConsumerState { + @override + Widget build(BuildContext context) { + final state = ref.watch(notificationProvider(1)); // page = 1 + + return Scaffold( + body: SafeArea( + child: Column( + children: [ + _buildHeader(), + + Expanded( + child: state.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Center(child: Text("Error: $e")), + data: (list) => ListView.builder( + itemCount: list.length, + itemBuilder: (context, index) { + final item = list[index]; + return _buildNotificationTile(item); + }, + ), + ), + ), + ], + ), + ), + ); + } + + // HEADER UI + Widget _buildHeader() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 21), + child: SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + const Text( + "Notification", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 24, + color: Color(0xFF111827), + ), + ), + Positioned( + left: 0, + child: GestureDetector( + onTap: () { + // 🔥 Force refresh when user goes BACK + + ref.read(notificationTriggerProvider.notifier).state++; + + ref.invalidate(chatMessagesProvider); + Get.offAll(() => const MainController()); + }, + child: const Icon(Icons.arrow_back_ios_rounded), + ), + ), + ], + ), + ), + ); + } + + // NOTIFICATION TILE + Widget _buildNotificationTile(NotificationModel item) { + return GestureDetector( + onTap: () { + if (item.page.isEmpty || item.pageId == null) return; + + final String page = item.page.toLowerCase(); + final int id = item.pageId!; + + if (page == 'chat') { + // Navigate to chat + Get.to(() => LiveChatScreen(chatid: id, fileid: '0'))?.then((_) { + ref.read(notificationTriggerProvider.notifier).state++; + ref.invalidate(chatMessagesProvider); + ref.invalidate(notificationProvider); + }); + } else if (page == 'service') { + // Navigate to service detail + Get.to( + () => MainController( + initialIndex: 2, + child: DetailScreen(id: id, sourceTabIndex: 2), + ), + ); + } else if (page.contains('profile')) { + // Navigate to profile (Assuming MainController index 3 is Profile) + Get.to(() => const MainController(initialIndex: 3)); + } + }, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 4)], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.title, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w700, + fontSize: 16, + color: Colors.black, + ), + ), + const SizedBox(height: 4), + Text( + item.description, + style: const TextStyle(fontSize: 14, color: Colors.grey), + ), + const SizedBox(height: 8), + Text( + item.createdAt, + style: const TextStyle(fontSize: 12, color: Colors.grey), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/screens/profile/employee_profile/employee_profile_list.dart b/lib/view/screens/profile/employee_profile/employee_profile_list.dart new file mode 100644 index 0000000..b019906 --- /dev/null +++ b/lib/view/screens/profile/employee_profile/employee_profile_list.dart @@ -0,0 +1,260 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class EmployeeProfileList extends ConsumerStatefulWidget { + const EmployeeProfileList({super.key}); + + @override + ConsumerState createState() => + _EmployeeProfileListState(); +} + +class _EmployeeProfileListState extends ConsumerState { + String yesNo(dynamic value) { + return value == 1 ? "Yes" : "No"; + } + + String statusText(dynamic value) { + return value == 1 ? "Active" : "Inactive"; + } + + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + final profileAsync = ref.watch(employeeProfileProvider); + + return Scaffold( + body: Container( + height: size.height, + width: size.width, + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + child: SafeArea( + child: profileAsync.when( + data: (profile) { + final data = profile.data; + + if (data == null) { + return const Center( + child: Text( + "No profile data found", + style: TextStyle(color: Colors.white), + ), + ); + } + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 20, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ---------------- HEADER ---------------- + Padding( + padding: const EdgeInsets.symmetric(vertical: 21), + child: SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + const Text( + "KYC Details", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight + .w600, // equivalent to 400 (Normal) + fontStyle: FontStyle.normal, + fontSize: 24, + height: 1.3, // line-height: 130% + letterSpacing: + 0.04 * 24, // 4% of font size = 0.96px + color: Color(0xFF111827), // background: #111827 + ), + ), + + Positioned( + left: 0, + child: GestureDetector( + onTap: () => Get.back(), + child: const Icon(Icons.arrow_back_ios_rounded), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 20), + + /// ---------------- CARD ---------------- + Container( + width: double.infinity, + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 6, + offset: const Offset(0, 3), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + "Personal Details", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontSize: 20, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 25), + + _buildDetailRow("Name : ", data.name), + const SizedBox(height: 24), + + _buildDetailRow("Mobile : ", data.mobile), + const SizedBox(height: 24), + + _buildDetailRow("Email : ", data.email), + const SizedBox(height: 24), + + _buildDetailRow( + "Company Name : ", + data.company?.companyName ?? "N/A", + ), + const SizedBox(height: 24), + + _buildDetailRow( + "Service : ", + yesNo(data.createService), + ), + const SizedBox(height: 24), + + _buildDetailRow("Status : ", statusText(data.status)), + const SizedBox(height: 24), + + _buildDetailRow( + "General Chat : ", + yesNo(data.generalChat), + ), + ], + ), + ), + + const SizedBox(height: 30), + + /// ---------------- COMPANY LOGO ---------------- + if (data.company?.companyLogo != null) + GridView.count( + crossAxisCount: 2, + crossAxisSpacing: 15, + mainAxisSpacing: 15, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + children: [ + _buildImageBox( + "Company Logo", + data.company!.companyLogo!, + ), + ], + ), + + const SizedBox(height: 40), + ], + ), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(color: Colors.white), + ), + error: (e, _) => Center( + child: Text( + "Error loading profile: $e", + style: const TextStyle(color: Colors.redAccent), + ), + ), + ), + ), + ), + ); + } + + /// ---------------- TEXT ROW ---------------- + Widget _buildDetailRow(String title, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 14, + height: 1.3, + letterSpacing: 0.64, + color: Colors.black87, + ), + ), + Flexible( + child: Text( + value, + softWrap: true, + overflow: TextOverflow.visible, + style: const TextStyle( + fontFamily: 'Gilroy-Regular', + fontWeight: FontWeight.w400, + fontSize: 14, + height: 1.3, + letterSpacing: 0.64, + color: Color(0xFF111827), + ), + ), + ), + ], + ); + } + + /// ---------------- IMAGE BOX ---------------- + Widget _buildImageBox(String label, String imageUrl) { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey.shade300), + ), + child: Column( + children: [ + const SizedBox(height: 10), + Text( + label, + style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13), + ), + const SizedBox(height: 10), + Expanded( + child: Image.network( + imageUrl, + fit: BoxFit.contain, + errorBuilder: (_, __, ___) => const Icon(Icons.broken_image), + ), + ), + const SizedBox(height: 10), + ], + ), + ); + } +} diff --git a/lib/view/screens/profile/employee_profile/employee_profile_screen.dart b/lib/view/screens/profile/employee_profile/employee_profile_screen.dart new file mode 100644 index 0000000..1976092 --- /dev/null +++ b/lib/view/screens/profile/employee_profile/employee_profile_screen.dart @@ -0,0 +1,450 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; + +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/main.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class EmployeeProfileScreen extends ConsumerStatefulWidget { + const EmployeeProfileScreen({super.key}); + + @override + ConsumerState createState() => + _EmployeeProfileScreenState(); +} + +class _EmployeeProfileScreenState extends ConsumerState { + String? selectedItem; + bool _isLoggingOut = false; + + @override + Widget build(BuildContext context) { + final profileAsync = ref.watch(employeeProfileProvider); + + return Scaffold( + backgroundColor: Colors.white, + body: profileAsync.when( + data: (profile) { + final data = profile.data; + + return Column( + children: [ + Stack( + clipBehavior: Clip.none, + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(50), + bottomRight: Radius.circular(50), + ), + ), + child: ClipRRect( + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(140), + bottomRight: Radius.circular(0), + ), + child: Align( + alignment: Alignment.centerRight, + child: Image.asset( + AppAssets.profilebanner, + fit: BoxFit.cover, + height: 200, + width: MediaQuery.of(context).size.width * 1.3, + ), + ), + ), + ), + Positioned( + bottom: -50, + left: 0, + right: 0, + child: Center( + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 4), + ), + child: + (data?.company?.companyLogo != null && + data!.company!.companyLogo!.isNotEmpty) + ? CircleAvatar( + radius: 50, + backgroundImage: NetworkImage( + data.company!.companyLogo!, + ), + ) + : Container( + width: 100, + height: 100, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.black87, + ), + child: Center( + child: Text( + (data?.name != null && + data!.name.isNotEmpty) + ? data.name[0].toUpperCase() + : "M", + style: const TextStyle( + color: Colors.white, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ), + ), + ], + ), + const SizedBox(height: 60), + Text( + data?.name ?? 'No Company Name', + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 20, + color: Colors.black, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 30), + + Expanded( + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 20), + children: [ + _buildMenuItem( + id: 'profile', + icon: Icons.person_outline, + title: 'Profile', + onTap: () { + setState(() { + selectedItem = 'profile'; + }); + + ref.invalidate(employeeProfileProvider); + + Get.toNamed(ConstRouters.employeekycdetailslist); + }, + ), + const SizedBox(height: 16), + + _buildMenuItem( + id: 'terms', + icon: Icons.description_outlined, + title: 'Terms and Conditions', + onTap: () { + setState(() { + selectedItem = 'terms'; + }); + ref.invalidate(termsProvider); + Get.toNamed(ConstRouters.terms); + }, + ), + + const SizedBox(height: 16), + + _buildMenuItem( + id: 'policy', + icon: Icons.policy_outlined, + title: 'Policy', + onTap: () { + setState(() { + selectedItem = 'policy'; + }); + ref.invalidate(termsProvider); + Get.toNamed(ConstRouters.policy); + }, + ), + + const SizedBox(height: 16), + + _buildMenuItem( + id: 'logout', + icon: Icons.logout, + title: 'Log out', + onTap: () { + setState(() { + selectedItem = 'logout'; + }); + _showLogoutPopup(context); + }, + ), + ], + ), + ), + ], + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center(child: Text('Error: $err')), + ), + ); + } + + /// ----------------------- LOGOUT POPUP --------------------- + void _showLogoutPopup(BuildContext context) { + showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: 'Logout', + barrierColor: Colors.black.withOpacity(0.2), + transitionDuration: const Duration(milliseconds: 300), + pageBuilder: (context, animation, secondaryAnimation) { + return const SizedBox.shrink(); + }, + transitionBuilder: (context, animation, secondaryAnimation, child) { + final offsetAnimation = + Tween(begin: const Offset(0, -1), end: Offset.zero).animate( + CurvedAnimation(parent: animation, curve: Curves.easeOutBack), + ); + + return SlideTransition( + position: offsetAnimation, + child: Align( + alignment: Alignment.topCenter, + child: Padding( + padding: const EdgeInsets.only(top: 60.0), + child: Material( + color: Colors.transparent, + child: Container( + width: MediaQuery.of(context).size.width * 0.9, + height: 160, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(7.75), + border: Border.all(color: Colors.white, width: 3.87), + boxShadow: const [ + BoxShadow( + color: Color(0x7A5E5E5E), + offset: Offset(0, 2.32), + blurRadius: 9.14, + spreadRadius: 3.1, + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 16, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + "Note", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 20, + color: Colors.black, + ), + ), + const Text( + "Are you sure you want to log out?", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w500, + fontSize: 15, + color: Colors.black87, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text( + "Cancel", + style: TextStyle( + color: Color(0xFF535A5B), + fontSize: 16, + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(width: 8), + TextButton( + onPressed: _isLoggingOut + ? null + : () async { + Navigator.pop(context); + + setState(() { + _isLoggingOut = true; + }); + + try { + await ApiRepository().logout(); + _showSnackBar("Logout successful"); + + await Future.delayed( + const Duration(milliseconds: 800), + ); + Get.offAllNamed( + ConstRouters.employeelogin, + ); + } catch (e) { + _showSnackBar( + e.toString(), + isError: true, + ); + } finally { + setState(() { + _isLoggingOut = false; + }); + } + }, + child: _isLoggingOut + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Color(0xFF5F297B), + ), + ) + : const Text( + "Log Out", + style: TextStyle( + color: Color(0xFF5F297B), + fontSize: 16, + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ), + ); + }, + ); + } + + /// ----------------------- MENU ITEM --------------------- + Widget _buildMenuItem({ + required String id, + required IconData icon, + required String title, + required VoidCallback onTap, + }) { + final isSelected = selectedItem == id; + + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + child: Row( + children: [ + SizedBox( + width: 24, + height: 48, + child: isSelected + ? CustomPaint( + size: const Size(24, 48), + painter: BeveledTrianglePainter(), + ) + : const SizedBox.shrink(), + ), + Expanded( + child: Container( + height: 58, + decoration: BoxDecoration( + color: isSelected + ? const Color(0xFFEEFAFF) + : Colors.transparent, + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Icon(icon, size: 24, color: Colors.black87), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 16, + fontWeight: FontWeight.w500, + color: Colors.black87, + ), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } + + /// ----------------------- SNACK BAR --------------------- + void _showSnackBar(String msg, {bool isError = false}) { + rootScaffoldMessengerKey.currentState?.showSnackBar( + SnackBar( + duration: const Duration(seconds: 2), + backgroundColor: isError ? Colors.red : AppColors.commanbutton, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.symmetric(horizontal: 70, vertical: 25), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + content: Row( + children: [ + Image.asset(AppAssets.taxgildelogoauth, height: 18, width: 18), + const SizedBox(width: 8), + Expanded( + child: Text( + msg, + style: const TextStyle(color: Colors.white, fontSize: 12), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ); + } +} + +class BeveledTrianglePainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = const Color(0xFF5E2976) + ..style = PaintingStyle.fill; + + final path = Path() + ..moveTo(0, 4) + ..lineTo(size.width - 6, size.height / 2) + ..lineTo(0, size.height - 4) + ..close(); + + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) => false; +} diff --git a/lib/view/screens/profile/kyc_detail_screen.dart b/lib/view/screens/profile/kyc_detail_screen.dart new file mode 100644 index 0000000..4f7649c --- /dev/null +++ b/lib/view/screens/profile/kyc_detail_screen.dart @@ -0,0 +1,1085 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/comman_dropdown.dart'; +import 'package:taxglide/consts/image_permission.dart'; +import 'package:taxglide/consts/validation_popup.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/model/city_model.dart' as country; +import 'package:taxglide/model/country_model.dart' as country; + +class KycDetailScreen extends ConsumerStatefulWidget { + const KycDetailScreen({super.key}); + + @override + ConsumerState createState() => _KycDetailScreenState(); +} + +class _KycDetailScreenState extends ConsumerState { + final ScrollController _scrollController = ScrollController(); + + // Controllers + late final TextEditingController companyCtrl; + late final TextEditingController panCtrl; + late final TextEditingController gstCtrl; + late final TextEditingController tanCtrl; + late final TextEditingController cinCtrl; + late final TextEditingController yearCtrl; + late final TextEditingController emailCtrl; + late final TextEditingController phoneCtrl; + late final TextEditingController addressCtrl; + late final TextEditingController pincodeCtrl; + + // Focus Nodes + late final FocusNode companyNode; + late final FocusNode panNode; + late final FocusNode gstNode; + late final FocusNode tanNode; + late final FocusNode cinNode; + late final FocusNode yearNode; + late final FocusNode emailNode; + late final FocusNode phoneNode; + late final FocusNode addressNode; + late final FocusNode pincodeNode; + + // Keys + final companyKey = GlobalKey(); + final panKey = GlobalKey(); + final gstKey = GlobalKey(); + final tanKey = GlobalKey(); + final cinKey = GlobalKey(); + final yearKey = GlobalKey(); + final emailKey = GlobalKey(); + final phoneKey = GlobalKey(); + final addressKey = GlobalKey(); + final pincodeKey = GlobalKey(); + final countryKey = GlobalKey(); + final stateKey = GlobalKey(); + final cityKey = GlobalKey(); + final panImageKey = GlobalKey(); + final gstImageKey = GlobalKey(); + final incImageKey = GlobalKey(); + final logoImageKey = GlobalKey(); + + // Selection state + String? selectedCountryName; + int? selectedCountryId; + String? selectedStateName; + int? selectedStateId; + String? selectedCityName; + int? selectedCityId; + + String? countryError; + String? stateError; + String? cityError; + + // File state (now supports both image and PDF) + File? panImageFile; + String? panImageUrl; + File? gstImageFile; + String? gstImageUrl; + File? incorporationImageFile; + String? incorporationImageUrl; + File? logoImageFile; + String? logoImageUrl; + + String? panImageError; + String? gstImageError; + String? incImageError; + String? logoImageError; + + bool isChecked = false; + Map errors = {}; + bool _isInitialized = false; + bool _isSubmitting = false; + + @override + void initState() { + super.initState(); + companyCtrl = TextEditingController(); + panCtrl = TextEditingController(); + gstCtrl = TextEditingController(); + tanCtrl = TextEditingController(); + cinCtrl = TextEditingController(); + yearCtrl = TextEditingController(); + emailCtrl = TextEditingController(); + phoneCtrl = TextEditingController(); + addressCtrl = TextEditingController(); + pincodeCtrl = TextEditingController(); + + companyNode = FocusNode(); + panNode = FocusNode(); + gstNode = FocusNode(); + tanNode = FocusNode(); + cinNode = FocusNode(); + yearNode = FocusNode(); + emailNode = FocusNode(); + phoneNode = FocusNode(); + addressNode = FocusNode(); + pincodeNode = FocusNode(); + + _setupFocusListeners(); + } + + void _setupFocusListeners() { + companyNode.addListener(() => _scrollToFocused(companyKey, companyNode)); + panNode.addListener(() => _scrollToFocused(panKey, panNode)); + gstNode.addListener(() => _scrollToFocused(gstKey, gstNode)); + tanNode.addListener(() => _scrollToFocused(tanKey, tanNode)); + cinNode.addListener(() => _scrollToFocused(cinKey, cinNode)); + yearNode.addListener(() => _scrollToFocused(yearKey, yearNode)); + emailNode.addListener(() => _scrollToFocused(emailKey, emailNode)); + phoneNode.addListener(() => _scrollToFocused(phoneKey, phoneNode)); + addressNode.addListener(() => _scrollToFocused(addressKey, addressNode)); + pincodeNode.addListener(() => _scrollToFocused(pincodeKey, pincodeNode)); + } + + void _scrollToFocused(GlobalKey key, FocusNode node) { + if (node.hasFocus && mounted) { + Future.delayed(const Duration(milliseconds: 250), () { + if (!mounted) return; + final context = key.currentContext; + if (context != null) { + Scrollable.ensureVisible( + context, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + alignment: 0.2, + ); + } + }); + } + } + + void _scrollToWidget(GlobalKey key) { + if (!mounted) return; + Future.delayed(const Duration(milliseconds: 100), () { + if (!mounted) return; + final context = key.currentContext; + if (context != null) { + Scrollable.ensureVisible( + context, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + alignment: 0.2, + ); + } + }); + } + + bool _validate() { + final panRegex = RegExp(r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$'); + final gstRegex = RegExp( + r'^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$', + ); + final tanRegex = RegExp(r'^[A-Z]{4}[0-9]{5}[A-Z]{1}$'); + final cinRegex = RegExp( + r'^[A-Z]{1}[0-9]{5}[A-Z]{2}[0-9]{4}[A-Z]{3}[0-9]{6}$', + ); + final pincodeRegex = RegExp(r'^[0-9]{6}$'); + + setState(() { + errors.clear(); + + if (companyCtrl.text.isEmpty) { + errors['company'] = 'Company name required'; + } + + // PAN validation with exact digit check + if (panCtrl.text.isEmpty) { + errors['pan'] = 'PAN required'; + } else { + final panUpper = panCtrl.text.toUpperCase(); + if (!panRegex.hasMatch(panUpper)) { + errors['pan'] = 'Invalid PAN format (e.g. ABCDE1234F)'; + } else { + // Extract the 4 digits (positions 5-8) + final panDigits = panUpper.substring(5, 9); + final panYear = int.tryParse(panDigits); + + if (panYear == null) { + errors['pan'] = 'Invalid PAN number format'; + } + } + } + + if (gstCtrl.text.isEmpty) { + errors['gst'] = 'GST required'; + } else if (!gstRegex.hasMatch(gstCtrl.text.toUpperCase())) { + errors['gst'] = 'Invalid GST format (e.g. 22ABCDE1234F1Z5)'; + } + + // TAN validation with year check + if (tanCtrl.text.isEmpty) { + errors['tan'] = 'TAN required'; + } else { + final tanUpper = tanCtrl.text.toUpperCase(); + if (!tanRegex.hasMatch(tanUpper)) { + errors['tan'] = 'Invalid TAN format (e.g. ABCD12345E)'; + } else { + // Extract the 5 digits (positions 4-8) + final tanDigits = tanUpper.substring(4, 9); + final tanYear = int.tryParse(tanDigits); + + if (tanYear == null) { + errors['tan'] = 'Invalid TAN number format'; + } + } + } + + if (cinCtrl.text.isEmpty) { + errors['cin'] = 'CIN required'; + } else if (!cinRegex.hasMatch(cinCtrl.text.toUpperCase())) { + errors['cin'] = 'Invalid CIN format (e.g. L12345TN2000PLC123456)'; + } + + // Year of Incorporation validation + if (yearCtrl.text.isEmpty) { + errors['year'] = 'Year required'; + } else { + final year = int.tryParse(yearCtrl.text); + final currentYear = DateTime.now().year; + + if (year == null) { + errors['year'] = 'Invalid year format'; + } else if (year < 1800 || year > currentYear) { + errors['year'] = 'Year must be between 1800 and $currentYear'; + } + } + + if (emailCtrl.text.isEmpty) { + errors['email'] = 'Email required'; + } + + if (phoneCtrl.text.isEmpty) { + errors['phone'] = 'Phone required'; + } + + if (addressCtrl.text.isEmpty) { + errors['address'] = 'Address required'; + } + + // Pincode validation - must be exactly 6 digits + if (pincodeCtrl.text.isEmpty) { + errors['pincode'] = 'Pincode required'; + } else if (!pincodeRegex.hasMatch(pincodeCtrl.text)) { + errors['pincode'] = 'Pincode must be exactly 6 digits'; + } + + countryError = selectedCountryId == null ? 'Select country' : null; + stateError = selectedStateId == null ? 'Select state' : null; + cityError = selectedCityId == null ? 'Select city' : null; + + panImageError = (panImageFile == null && panImageUrl == null) + ? 'Upload PAN card image/PDF' + : null; + gstImageError = (gstImageFile == null && gstImageUrl == null) + ? 'Upload GST certificate image/PDF' + : null; + incImageError = + (incorporationImageFile == null && incorporationImageUrl == null) + ? 'Upload incorporation certificate image/PDF' + : null; + logoImageError = (logoImageFile == null && logoImageUrl == null) + ? 'Upload company logo' + : null; + }); + + if (errors.isNotEmpty) { + final firstError = errors.keys.first; + final keyMap = { + 'company': companyKey, + 'pan': panKey, + 'gst': gstKey, + 'tan': tanKey, + 'cin': cinKey, + 'year': yearKey, + 'email': emailKey, + 'phone': phoneKey, + 'address': addressKey, + 'pincode': pincodeKey, + }; + _scrollToWidget(keyMap[firstError]!); + return false; + } + + if (countryError != null) { + _scrollToWidget(countryKey); + return false; + } + if (stateError != null) { + _scrollToWidget(stateKey); + return false; + } + if (cityError != null) { + _scrollToWidget(cityKey); + return false; + } + if (panImageError != null) { + _scrollToWidget(panImageKey); + return false; + } + if (gstImageError != null) { + _scrollToWidget(gstImageKey); + return false; + } + if (incImageError != null) { + _scrollToWidget(incImageKey); + return false; + } + if (logoImageError != null) { + _scrollToWidget(logoImageKey); + return false; + } + + return true; + } + + Future _handleSubmit() async { + if (_isSubmitting) return; + + if (!_validate()) return; + + if (!isChecked) { + Get.snackbar( + "Error", + "Please accept declaration", + backgroundColor: Colors.red, + colorText: Colors.white, + duration: const Duration(seconds: 2), + ); + return; + } + + setState(() => _isSubmitting = true); + + try { + await ApiRepository().kycFormUpdate( + logo: logoImageFile, + panFile: panImageFile, + gstFile: gstImageFile, + incorporationFile: incorporationImageFile, + countryId: selectedCountryId!, + stateId: selectedStateId!, + cityId: selectedCityId!, + companyPincode: pincodeCtrl.text, + companyAddress: addressCtrl.text, + panNumber: panCtrl.text, + gstNumber: gstCtrl.text, + tanNumber: tanCtrl.text, + cinNumber: cinCtrl.text, + yearOfIncorporation: yearCtrl.text, + address: addressCtrl.text, + ); + + if (!mounted) return; + + ValidationPopup().showSuccessMessage( + context, + "Form Submitted Successfully", + ); + + ref.invalidate(profileProvider); + + await Future.delayed(const Duration(milliseconds: 500)); + + if (mounted) { + Navigator.pop(context); + } + } catch (e) { + if (!mounted) return; + + String errorMessage; + + if (e is Map) { + final buffer = StringBuffer(); + e.forEach((key, value) { + buffer.writeln(value); + }); + errorMessage = buffer.toString().trim(); + } else { + errorMessage = e.toString(); + } + + ValidationPopup().showErrorMessage(context, errorMessage); + } finally { + if (mounted) { + setState(() => _isSubmitting = false); + } + } + } + + @override + Widget build(BuildContext context) { + final profileAsync = ref.watch(profileProvider); + final countryAsync = ref.watch(countryAndStatesProvider); + + return Scaffold( + backgroundColor: AppColors.white, + body: SafeArea( + child: Stack( + children: [ + profileAsync.when( + data: (profileData) { + if (!_isInitialized && profileData.data != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + setState(() { + final p = profileData.data!; + companyCtrl.text = p.companyName ?? ''; + panCtrl.text = p.panNumber ?? ''; + gstCtrl.text = p.gstNumber ?? ''; + tanCtrl.text = p.tanNumber ?? ''; + cinCtrl.text = p.cin ?? ''; + yearCtrl.text = p.yearOfIncorporation?.toString() ?? ''; + emailCtrl.text = p.companyEmail ?? ''; + phoneCtrl.text = p.companyMobile ?? ''; + addressCtrl.text = p.companyAddress ?? ''; + pincodeCtrl.text = p.companyPincode ?? ''; + + selectedCountryName = p.countryName; + selectedStateName = p.stateName; + selectedCityName = p.districtName; + + panImageUrl = p.panFile; + gstImageUrl = p.gstFile; + incorporationImageUrl = p.incorporationFile; + logoImageUrl = p.logo; + + _isInitialized = true; + }); + }); + } + + return countryAsync.when( + data: (countryModel) { + final countryList = + countryModel.countriesData + ?.map((e) => e.countryName ?? '') + .toList() ?? + []; + + final selectedCountryData = countryModel.countriesData + ?.firstWhere( + (c) => c.countryName == selectedCountryName, + orElse: () => country.CountryData(), + ); + + if (selectedCountryData?.id != null) { + selectedCountryId = selectedCountryData!.id; + } + + final selectedStateList = + countryModel.statesData + ?.where((s) => s.countryId == selectedCountryId) + .map((s) => s.stateName ?? '') + .toList() ?? + []; + + final selectedStateData = countryModel.statesData + ?.firstWhere( + (s) => s.stateName == selectedStateName, + orElse: () => country.StateData(), + ); + + if (selectedStateData?.id != null) { + selectedStateId = selectedStateData!.id; + } + + final cityAsync = selectedStateId != null + ? ref.watch(fetchCityProvider(selectedStateId!)) + : const AsyncValue.data(null); + + return cityAsync.when( + data: (cityModel) { + final cityList = + cityModel?.districtsData + ?.map((c) => c.districtName ?? '') + .toList() ?? + []; + + if (cityModel?.districtsData != null) { + final selectedCityData = cityModel!.districtsData! + .firstWhere( + (c) => c.districtName == selectedCityName, + orElse: () => country.DistrictData(), + ); + + if (selectedCityData.id != null) { + selectedCityId = selectedCityData.id; + } + } + + return _buildForm( + countryList, + selectedStateList, + cityList, + countryModel, + cityModel, + ); + }, + loading: () => _buildForm( + countryList, + selectedStateList, + [], + countryModel, + null, + ), + error: (e, _) => _buildForm( + countryList, + selectedStateList, + [], + countryModel, + null, + ), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(color: Colors.blue), + ), + error: (e, _) => Center(child: Text('Error: $e')), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(color: Colors.blue), + ), + error: (e, _) => Center(child: Text('Error: $e')), + ), + + if (_isSubmitting) + Container( + color: Colors.black54, + child: const Center( + child: Card( + child: Padding( + padding: EdgeInsets.all(20), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text( + 'Submitting KYC Form...', + style: TextStyle(fontSize: 16), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildForm( + List countries, + List states, + List cities, + country.CountryModel countryModel, + country.CityModel? cityModel, + ) { + return SingleChildScrollView( + controller: _scrollController, + padding: const EdgeInsets.symmetric(horizontal: 23, vertical: 21), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + const Text( + "KYC Form", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w400, + fontStyle: FontStyle.normal, + fontSize: 24, + height: 1.3, + letterSpacing: 0.04 * 24, + color: Color(0xFF111827), + ), + ), + Positioned( + left: 0, + child: GestureDetector( + onTap: () => Get.back(), + child: const Icon(Icons.arrow_back_ios_rounded), + ), + ), + ], + ), + ), + + const SizedBox(height: 30), + + // Text fields + LabeledTextField( + fieldKey: companyKey, + label: 'Company Name', + keyName: 'company', + hint: 'Enter company name', + controller: companyCtrl, + focusNode: companyNode, + readOnly: true, + errors: errors, + onChanged: (val) { + if (errors['company'] != null && val.trim().isNotEmpty) { + setState(() => errors['company'] = null); + } + }, + ), + LabeledTextField( + fieldKey: panKey, + label: 'PAN Number', + keyName: 'pan', + hint: 'Enter PAN number', + controller: panCtrl, + focusNode: panNode, + textCapitalization: TextCapitalization.characters, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')), + LengthLimitingTextInputFormatter(10), + ], + errors: errors, + onChanged: (val) { + if (errors['pan'] != null) { + final upper = val.toUpperCase(); + if (RegExp(r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$').hasMatch(upper)) { + if (int.tryParse(upper.substring(5, 9)) != null) { + setState(() => errors['pan'] = null); + } + } + } + }, + ), + LabeledTextField( + fieldKey: gstKey, + label: 'GST Number', + keyName: 'gst', + hint: 'Enter GST number', + controller: gstCtrl, + focusNode: gstNode, + textCapitalization: TextCapitalization.characters, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')), + LengthLimitingTextInputFormatter(15), + ], + errors: errors, + onChanged: (val) { + if (errors['gst'] != null) { + if (RegExp( + r'^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$', + ).hasMatch(val.toUpperCase())) { + setState(() => errors['gst'] = null); + } + } + }, + ), + LabeledTextField( + fieldKey: tanKey, + label: 'TAN Number', + keyName: 'tan', + hint: 'Enter TAN number', + controller: tanCtrl, + focusNode: tanNode, + textCapitalization: TextCapitalization.characters, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')), + LengthLimitingTextInputFormatter(10), + ], + errors: errors, + onChanged: (val) { + if (errors['tan'] != null) { + final upper = val.toUpperCase(); + if (RegExp(r'^[A-Z]{4}[0-9]{5}[A-Z]{1}$').hasMatch(upper)) { + if (int.tryParse(upper.substring(4, 9)) != null) { + setState(() => errors['tan'] = null); + } + } + } + }, + ), + LabeledTextField( + fieldKey: cinKey, + label: 'CIN Number', + keyName: 'cin', + hint: 'Enter CIN number', + controller: cinCtrl, + focusNode: cinNode, + textCapitalization: TextCapitalization.characters, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')), + LengthLimitingTextInputFormatter(21), + ], + errors: errors, + onChanged: (val) { + if (errors['cin'] != null) { + if (RegExp( + r'^[A-Z]{1}[0-9]{5}[A-Z]{2}[0-9]{4}[A-Z]{3}[0-9]{6}$', + ).hasMatch(val.toUpperCase())) { + setState(() => errors['cin'] = null); + } + } + }, + ), + LabeledTextField( + fieldKey: yearKey, + label: 'Year of Incorporation', + keyName: 'year', + hint: 'Enter year (e.g. 2020)', + controller: yearCtrl, + focusNode: yearNode, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(4), + ], + errors: errors, + onChanged: (val) { + if (errors['year'] != null) { + final y = int.tryParse(val); + if (y != null && y >= 1800 && y <= DateTime.now().year) { + setState(() => errors['year'] = null); + } + } + }, + ), + LabeledTextField( + fieldKey: emailKey, + label: 'Official Email Address', + keyName: 'email', + hint: 'Enter email', + controller: emailCtrl, + focusNode: emailNode, + readOnly: true, + errors: errors, + onChanged: (val) { + if (errors['email'] != null && val.trim().isNotEmpty) { + setState(() => errors['email'] = null); + } + }, + ), + LabeledTextField( + fieldKey: phoneKey, + label: 'Phone Number', + keyName: 'phone', + hint: 'Enter phone number', + controller: phoneCtrl, + focusNode: phoneNode, + keyboardType: TextInputType.phone, + errors: errors, + readOnly: true, + onChanged: (val) { + if (errors['phone'] != null && val.trim().isNotEmpty) { + setState(() => errors['phone'] = null); + } + }, + ), + LabeledTextField( + fieldKey: addressKey, + label: 'Office Address', + keyName: 'address', + hint: 'Enter address', + controller: addressCtrl, + focusNode: addressNode, + errors: errors, + onChanged: (val) { + if (errors['address'] != null && val.trim().isNotEmpty) { + setState(() => errors['address'] = null); + } + }, + ), + + // Dropdowns + _buildDropdown( + key: countryKey, + label: "Country", + hint: "Select Country", + value: selectedCountryName, + items: countries, + onChanged: (val) { + if (!mounted) return; + final countryData = countryModel.countriesData?.firstWhere( + (c) => c.countryName == val, + orElse: () => country.CountryData(), + ); + + setState(() { + selectedCountryName = val; + selectedCountryId = countryData?.id; + selectedStateName = null; + selectedStateId = null; + selectedCityName = null; + selectedCityId = null; + stateError = null; + cityError = null; + countryError = null; + }); + }, + error: countryError, + ), + + _buildDropdown( + key: stateKey, + label: "State", + hint: "Select State", + value: selectedStateName, + items: states, + onChanged: (val) { + if (!mounted) return; + final stateData = countryModel.statesData?.firstWhere( + (s) => s.stateName == val, + orElse: () => country.StateData(), + ); + + setState(() { + selectedStateName = val; + selectedStateId = stateData?.id; + selectedCityName = null; + selectedCityId = null; + stateError = null; + cityError = null; + }); + }, + error: stateError, + ), + + _buildDropdown( + key: cityKey, + label: "City", + hint: "Select City", + value: selectedCityName, + items: cities, + onChanged: (val) { + if (!mounted) return; + final cityData = cityModel?.districtsData?.firstWhere( + (c) => c.districtName == val, + orElse: () => country.DistrictData(), + ); + + setState(() { + selectedCityName = val; + selectedCityId = cityData?.id; + cityError = null; + }); + }, + error: cityError, + ), + + LabeledTextField( + fieldKey: pincodeKey, + label: 'Pincode', + keyName: 'pincode', + hint: 'Enter 6 digit pincode', + controller: pincodeCtrl, + focusNode: pincodeNode, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(6), + ], + errors: errors, + onChanged: (val) { + if (errors['pincode'] != null) { + if (RegExp(r'^[0-9]{6}$').hasMatch(val)) { + setState(() => errors['pincode'] = null); + } + } + }, + ), + const SizedBox(height: 20), + + // 🔥 Updated File Upload Fields (Image/PDF support for PAN, GST, Incorporation) + FileUploadSectionField( + fileKey: panImageKey, + title: "Upload PAN Card (Image/PDF)", + fileData: panImageFile, + fileUrl: panImageUrl, + errorText: panImageError, + setError: (err) => setState(() => panImageError = err), + onFileSelected: (file) => setState(() { + panImageFile = file; + panImageUrl = null; + }), + onFileRemoved: () => setState(() { + panImageFile = null; + panImageUrl = null; + }), + ), + FileUploadSectionField( + fileKey: gstImageKey, + title: "Upload GST Certificate (Image/PDF)", + fileData: gstImageFile, + fileUrl: gstImageUrl, + errorText: gstImageError, + setError: (err) => setState(() => gstImageError = err), + onFileSelected: (file) => setState(() { + gstImageFile = file; + gstImageUrl = null; + }), + onFileRemoved: () => setState(() { + gstImageFile = null; + gstImageUrl = null; + }), + ), + FileUploadSectionField( + fileKey: incImageKey, + title: "Upload Incorporation Certificate (Image/PDF)", + fileData: incorporationImageFile, + fileUrl: incorporationImageUrl, + errorText: incImageError, + setError: (err) => setState(() => incImageError = err), + onFileSelected: (file) => setState(() { + incorporationImageFile = file; + incorporationImageUrl = null; + }), + onFileRemoved: () => setState(() { + incorporationImageFile = null; + incorporationImageUrl = null; + }), + ), + + // 🔥 Logo remains image-only + SingleImageSectionField( + imageKey: logoImageKey, + title: "Upload Company Logo", + imageFile: logoImageFile, + imageUrl: logoImageUrl, + errorText: logoImageError, + setError: (err) => setState(() => logoImageError = err), + onImageSelected: (file) => setState(() { + logoImageFile = file; + logoImageUrl = null; + }), + onImageRemoved: () => setState(() { + logoImageFile = null; + logoImageUrl = null; + }), + ), + + Row( + children: [ + Checkbox( + value: isChecked, + onChanged: (v) => setState(() => isChecked = v ?? false), + ), + const Expanded( + child: Text( + "I hereby declare that the above information is true.", + ), + ), + ], + ), + const SizedBox(height: 10), + + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: _isSubmitting ? null : _handleSubmit, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.commanbutton, + padding: const EdgeInsets.symmetric(vertical: 14), + disabledBackgroundColor: Colors.grey, + ), + child: _isSubmitting + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2, + ), + ) + : const Text( + "Submit", + style: TextStyle(color: Colors.white, fontSize: 16), + ), + ), + ), + + const SizedBox(height: 20), + ], + ), + ); + } + + Widget _buildDropdown({ + required GlobalKey key, + required String label, + required String hint, + required String? value, + required List items, + required void Function(String?) onChanged, + String? error, + }) { + return Padding( + key: key, + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16, + color: Colors.black, + ), + ), + const SizedBox(height: 8), + CommanDropdown( + items: items, + value: value, + hint: hint, + onChanged: onChanged, + ), + if (error != null) + Padding( + padding: const EdgeInsets.only(top: 4, left: 6), + child: Text( + error, + style: const TextStyle(color: Colors.red, fontSize: 12), + ), + ), + ], + ), + ); + } + + @override + void dispose() { + companyCtrl.dispose(); + panCtrl.dispose(); + gstCtrl.dispose(); + tanCtrl.dispose(); + cinCtrl.dispose(); + yearCtrl.dispose(); + emailCtrl.dispose(); + phoneCtrl.dispose(); + addressCtrl.dispose(); + pincodeCtrl.dispose(); + companyNode.dispose(); + panNode.dispose(); + gstNode.dispose(); + tanNode.dispose(); + cinNode.dispose(); + yearNode.dispose(); + emailNode.dispose(); + phoneNode.dispose(); + addressNode.dispose(); + pincodeNode.dispose(); + _scrollController.dispose(); + super.dispose(); + } +} diff --git a/lib/view/screens/profile/kyc_details_list.dart b/lib/view/screens/profile/kyc_details_list.dart new file mode 100644 index 0000000..b4ea404 --- /dev/null +++ b/lib/view/screens/profile/kyc_details_list.dart @@ -0,0 +1,449 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/download_helper.dart'; +import 'package:taxglide/controller/api_consts.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +class KycDetailsList extends ConsumerStatefulWidget { + const KycDetailsList({super.key}); + + @override + ConsumerState createState() => _KycDetailsListState(); +} + +class _KycDetailsListState extends ConsumerState { + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + final profileAsync = ref.watch(profileProvider); + + return Scaffold( + body: Container( + height: size.height, + width: size.width, + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage(AppAssets.backgroundimages), + fit: BoxFit.cover, + ), + ), + child: SafeArea( + child: profileAsync.when( + data: (profile) { + final data = profile.data; + + if (data == null) { + return const Center( + child: Text( + "No KYC data found", + style: TextStyle(color: Colors.white), + ), + ); + } + + return SingleChildScrollView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 20, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 21), + child: SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + const Text( + "KYC Details", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight + .w600, // equivalent to 400 (Normal) + fontStyle: FontStyle.normal, + fontSize: 24, + height: 1.3, // line-height: 130% + letterSpacing: + 0.04 * 24, // 4% of font size = 0.96px + color: Color(0xFF111827), // background: #111827 + ), + ), + + Positioned( + left: 0, + child: GestureDetector( + onTap: () => Get.back(), + child: const Icon(Icons.arrow_back_ios_rounded), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 20), + + // White Card + Container( + width: double.infinity, + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 6, + offset: const Offset(0, 3), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + "Personal Details", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight + .w400, // equivalent to 400 (Normal) + fontStyle: FontStyle.normal, + fontSize: 20, + height: 1.3, // line-height: 130% + letterSpacing: + 0.04 * 20, // 4% of font size = 0.8px + color: Color( + 0xFF111827, + ), // background: #111827 + ), + ), + + GestureDetector( + onTap: () { + Get.toNamed(ConstRouters.kycdetails); + }, + child: Container( + width: 109, + padding: const EdgeInsets.symmetric( + vertical: 8, + horizontal: 12, + ), + decoration: BoxDecoration( + color: const Color( + 0xFFFFFFFF, + ), // background: #FFFFFF + borderRadius: BorderRadius.circular( + 8, + ), // border-radius: 8px + border: Border.all( + color: const Color( + 0xFFE3E3E3, + ), // border: 1px solid #E3E3E3 + width: 1, + ), + boxShadow: [ + BoxShadow( + color: const Color(0xFF767373) + .withOpacity( + 0.25, + ), // #76737340 ≈ 25% opacity + blurRadius: 10, + offset: const Offset(0, 0), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment + .center, // center horizontally + crossAxisAlignment: CrossAxisAlignment + .center, // center vertically + children: const [ + Icon( + Icons.edit_outlined, + size: 18, + color: Color( + 0xFF111827, + ), // matches your text color + ), + SizedBox(width: 6), + Text( + 'Edit', + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontStyle: FontStyle.normal, + fontSize: 16, + height: 1.3, // 130% + letterSpacing: 0.04 * 16, // 4% + color: Color(0xFF111827), + ), + ), + ], + ), + ), + ), + ], + ), + SizedBox(height: 25), + _buildDetailRow('Company Name : ', data.companyName), + const SizedBox(height: 24), + _buildDetailRow('PAN Number : ', data.panNumber), + const SizedBox(height: 24), + _buildDetailRow('GST Number : ', data.gstNumber), + const SizedBox(height: 24), + _buildDetailRow( + 'Year of Incorporation : ', + data.yearOfIncorporation?.toString(), + ), + const SizedBox(height: 24), + _buildDetailRow('Email : ', data.companyEmail), + const SizedBox(height: 24), + _buildDetailRow( + 'Phone Number : ', + data.companyMobile, + ), + const SizedBox(height: 24), + _buildDetailRow('Address : ', data.companyAddress), + const SizedBox(height: 24), + _buildDetailRow('Country : ', data.countryName), + const SizedBox(height: 24), + _buildDetailRow('State : ', data.stateName), + const SizedBox(height: 24), + _buildDetailRow('City : ', data.districtName), + const SizedBox(height: 24), + _buildDetailRow('PinCode : ', data.companyPincode), + ], + ), + ), + + const SizedBox(height: 30), + + // 4 Image Containers + GridView.count( + crossAxisCount: 2, + crossAxisSpacing: 15, + mainAxisSpacing: 15, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + children: [ + _buildImageBox("GST Certificate ", data.gstFile), + _buildImageBox("PAN File", data.panFile), + + _buildImageBox( + "Incorporation File", + data.incorporationFile, + ), + _buildImageBox("Profile Image", data.logo), + ], + ), + + const SizedBox(height: 40), + ], + ), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(color: Colors.white), + ), + error: (e, st) => Center( + child: Text( + "Error loading KYC details: $e", + style: const TextStyle(color: Colors.redAccent), + ), + ), + ), + ), + ), + ); + } + + Widget _buildDetailRow(String title, String? value) { + if (value == null || value.isEmpty) return const SizedBox.shrink(); + + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 14, + height: 1.3, + letterSpacing: 0.64, + color: Colors.black87, + ), + ), + Flexible( + child: Text( + value, + softWrap: true, + overflow: TextOverflow.visible, + style: const TextStyle( + fontFamily: 'Gilroy-Regular', + fontWeight: FontWeight.w400, + fontSize: 14, + height: 1.3, + letterSpacing: 0.64, + color: Color(0xFF111827), + ), + ), + ), + ], + ); + } + + Widget _buildImageBox(String label, String? imageUrl) { + final fullUrl = imageUrl != null && imageUrl.isNotEmpty + ? imageUrl.startsWith('http') + ? imageUrl + : "${ConstsApi.baseUrl}/api/$imageUrl" + : null; + + final isDocument = + label.toLowerCase().contains('gst') || + label.toLowerCase().contains('pan') || + label.toLowerCase().contains('incorporation'); + + return Container( + width: 175, + height: 155, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey.shade300), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), + blurRadius: 8, + offset: const Offset(0, 3), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + /// ✅ LABEL + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: const TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w600, + fontSize: 13, + ), + ), + + const SizedBox(height: 8), + + /// ✅ IMAGE / DOCUMENT PREVIEW + Expanded( + child: InkWell( + onTap: fullUrl == null + ? null + : () async { + await DownloadHelper.downloadFileToReceived(fullUrl); + setState(() {}); + }, + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.grey.shade100, + borderRadius: BorderRadius.circular(10), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: fullUrl != null + ? isDocument + ? const Center( + child: Icon( + Icons.insert_drive_file_rounded, + size: 50, + color: Colors.blueGrey, + ), + ) + : Image.network( + fullUrl, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) => + const Center( + child: Icon(Icons.broken_image), + ), + ) + : const Center( + child: Icon(Icons.image_not_supported, size: 40), + ), + ), + ), + ), + ), + + const SizedBox(height: 8), + + /// ✅ DOWNLOAD / VIEW BUTTON + if (fullUrl != null) + FutureBuilder( + future: DownloadHelper.checkFileExistsInReceived(fullUrl), + builder: (context, snapshot) { + final existsPath = snapshot.data; + + return SizedBox( + height: 36, + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + elevation: 0, + backgroundColor: existsPath == null + ? Colors.blue + : Colors.green, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(30), + ), + ), + onPressed: () async { + if (existsPath == null) { + await DownloadHelper.downloadFileToReceived(fullUrl); + setState(() {}); + } else { + await DownloadHelper.openDownloadedFile(existsPath); + } + }, + icon: Icon( + existsPath == null + ? Icons.download_rounded + : Icons.remove_red_eye_rounded, + size: 18, + color: Colors.white, + ), + label: Text( + existsPath == null ? "Download" : "View", + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.white, + ), + ), + ), + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/screens/profile/policy_screen.dart b/lib/view/screens/profile/policy_screen.dart new file mode 100644 index 0000000..72862bf --- /dev/null +++ b/lib/view/screens/profile/policy_screen.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class PolicyScreen extends ConsumerStatefulWidget { + const PolicyScreen({super.key}); + + @override + ConsumerState createState() => _PolicyScreenState(); +} + +class _PolicyScreenState extends ConsumerState { + @override + Widget build(BuildContext context) { + final policyAsync = ref.watch(policyProvider); + + return Scaffold( + backgroundColor: const Color.fromARGB(255, 230, 229, 229), + body: SafeArea( + child: policyAsync.when( + data: (policy) => SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 🔹 Header Row with Back Arrow + Centered Title + Row( + children: [ + GestureDetector( + onTap: () => Navigator.pop(context), + child: const Icon( + Icons.arrow_back_ios_new, + color: Colors.black, + size: 22, + ), + ), + Expanded( + child: Center( + child: Text( + policy.data?.title ?? 'Privacy Policy', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + ), + ), + ), + // Invisible icon to balance the layout + const Opacity( + opacity: 0, + child: Icon(Icons.arrow_back_ios_new, size: 22), + ), + ], + ), + + const SizedBox(height: 24), + + // 🔹 Policy Content + Text( + policy.data?.content ?? '', + textAlign: TextAlign.start, + style: const TextStyle( + fontSize: 16, + height: 1.6, + color: Colors.black87, + ), + ), + ], + ), + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center( + child: Text( + 'Error: $err', + style: const TextStyle(color: Colors.red), + ), + ), + ), + ), + ); + } +} diff --git a/lib/view/screens/profile/profile_screen.dart b/lib/view/screens/profile/profile_screen.dart new file mode 100644 index 0000000..10dc23c --- /dev/null +++ b/lib/view/screens/profile/profile_screen.dart @@ -0,0 +1,539 @@ +import 'dart:math' as math show sqrt; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:taxglide/consts/app_asstes.dart'; +import 'package:taxglide/consts/app_colors.dart'; +import 'package:taxglide/consts/local_store.dart'; +import 'package:taxglide/controller/api_repository.dart'; +import 'package:taxglide/router/consts_routers.dart'; + +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/main.dart'; + +class ProfileScreen extends ConsumerStatefulWidget { + const ProfileScreen({super.key}); + + @override + ConsumerState createState() => _ProfileScreenState(); +} + +class _ProfileScreenState extends ConsumerState { + String? selectedItem; + bool _isLoggingOut = false; + + String? userRole; // <-- role variable + + @override + void initState() { + super.initState(); + _loadRole(); // <-- load role on start + } + + Future _loadRole() async { + userRole = await LocalStore().getRole(); + setState(() {}); + } + + @override + Widget build(BuildContext context) { + final profileAsync = ref.watch(profileProvider); + + return Scaffold( + backgroundColor: Colors.white, + body: profileAsync.when( + data: (profile) { + final data = profile.data; + + return SingleChildScrollView( + child: Column( + children: [ + Stack( + clipBehavior: Clip.none, + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(50), + bottomRight: Radius.circular(50), + ), + ), + child: ClipRRect( + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(140), + bottomRight: Radius.circular(0), + ), + child: Align( + alignment: Alignment.centerRight, + child: Image.asset( + AppAssets.profilebanner, + fit: BoxFit.cover, + height: 200, + width: MediaQuery.of(context).size.width * 1.3, + ), + ), + ), + ), + Positioned( + bottom: -50, + left: 0, + right: 0, + child: Center( + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 4), + ), + child: data?.logo != null && data!.logo!.isNotEmpty + ? CircleAvatar( + radius: 50, + backgroundImage: NetworkImage(data.logo!), + ) + : Container( + width: 100, + height: 100, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: Colors.black87, + ), + child: Center( + child: Text( + (data?.companyName != null && + data!.companyName!.isNotEmpty) + ? data.companyName![0].toUpperCase() + : "M", + style: const TextStyle( + color: Colors.white, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ), + ), + ], + ), + const SizedBox(height: 60), + Text( + data?.companyName ?? 'No Company Name', + style: const TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 20, + color: Colors.black, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 30), + + ListView( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: const EdgeInsets.symmetric(horizontal: 20), + children: [ + _buildMenuItem( + id: 'profile', + icon: Icons.person_outline, + title: 'Profile', + onTap: () { + setState(() { + selectedItem = 'profile'; + }); + final pan = profile.data?.panNumber ?? ''; + ref.invalidate(profileProvider); + if (pan.isNotEmpty) { + Get.toNamed(ConstRouters.kycdetailslist); + } else { + Get.toNamed(ConstRouters.kycdetails); + } + }, + ), + const SizedBox(height: 16), + if (userRole != "employee") + _buildMenuItem( + id: 'Staff', + icon: Icons.list_alt_outlined, + title: 'Sub - Staff List', + onTap: () { + setState(() { + selectedItem = 'staff'; + }); + ref.invalidate(staffListProvider); + Get.toNamed(ConstRouters.staff); + }, + ), + const SizedBox(height: 16), + + _buildMenuItem( + id: 'terms', + icon: Icons.description_outlined, + title: 'Terms and Conditions', + onTap: () { + setState(() { + selectedItem = 'terms'; + }); + ref.invalidate(termsProvider); + Get.toNamed(ConstRouters.terms); + }, + ), + + const SizedBox(height: 16), + + _buildMenuItem( + id: 'policy', + icon: Icons.policy_outlined, + title: 'Policy', + onTap: () { + setState(() { + selectedItem = 'policy'; + }); + ref.invalidate(termsProvider); + Get.toNamed(ConstRouters.policy); + }, + ), + + const SizedBox(height: 16), + + _buildMenuItem( + id: 'logout', + icon: Icons.logout, + title: 'Log out', + onTap: () { + setState(() { + selectedItem = 'logout'; + }); + _showLogoutPopup(context); + }, + ), + ], + ), + const SizedBox(height: 50), + ], + ), + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center(child: Text('Error: $err')), + ), + ); + } + + /// ----------------------- LOGOUT POPUP --------------------- + void _showLogoutPopup(BuildContext context) { + showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: 'Logout', + barrierColor: Colors.black.withOpacity(0.2), + transitionDuration: const Duration(milliseconds: 300), + pageBuilder: (context, animation, secondaryAnimation) { + return const SizedBox.shrink(); + }, + transitionBuilder: (context, animation, secondaryAnimation, child) { + final offsetAnimation = + Tween(begin: const Offset(0, -1), end: Offset.zero).animate( + CurvedAnimation(parent: animation, curve: Curves.easeOutBack), + ); + + return SlideTransition( + position: offsetAnimation, + child: Align( + alignment: Alignment.topCenter, + child: Padding( + padding: const EdgeInsets.only(top: 60.0), + child: Material( + color: Colors.transparent, + child: Container( + width: MediaQuery.of(context).size.width * 0.9, + height: 160, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(7.75), + border: Border.all(color: Colors.white, width: 3.87), + boxShadow: const [ + BoxShadow( + color: Color(0x7A5E5E5E), + offset: Offset(0, 2.32), + blurRadius: 9.14, + spreadRadius: 3.1, + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 16, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + "Note", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: 20, + color: Colors.black, + ), + ), + const Text( + "Are you sure you want to log out?", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w500, + fontSize: 15, + color: Colors.black87, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text( + "Cancel", + style: TextStyle( + color: Color(0xFF535A5B), + fontSize: 16, + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(width: 8), + TextButton( + onPressed: _isLoggingOut + ? null + : () async { + Navigator.pop(context); + + setState(() { + _isLoggingOut = true; + }); + + try { + await ApiRepository().logout(); + _showSnackBar("Logout successful"); + + await Future.delayed( + const Duration(milliseconds: 800), + ); + Get.offAllNamed(ConstRouters.login); + } catch (e) { + _showSnackBar( + e.toString(), + isError: true, + ); + } finally { + setState(() { + _isLoggingOut = false; + }); + } + }, + child: _isLoggingOut + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Color(0xFF5F297B), + ), + ) + : const Text( + "Log Out", + style: TextStyle( + color: Color(0xFF5F297B), + fontSize: 16, + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ), + ); + }, + ); + } + + /// ----------------------- MENU ITEM --------------------- + Widget _buildMenuItem({ + required String id, + required IconData icon, + required String title, + required VoidCallback onTap, + }) { + final isSelected = selectedItem == id; + + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + child: Row( + children: [ + SizedBox( + width: 24, + height: 48, + child: isSelected + ? CustomPaint( + size: const Size(24, 48), + painter: BeveledTrianglePainter(), + ) + : const SizedBox.shrink(), + ), + Expanded( + child: Container( + height: 58, + decoration: BoxDecoration( + color: isSelected + ? const Color(0xFFEEFAFF) + : Colors.transparent, + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Icon(icon, size: 24, color: Colors.black87), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + style: const TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: 16, + fontWeight: FontWeight.w500, + color: Colors.black87, + ), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } + + /// ----------------------- SNACK BAR --------------------- + void _showSnackBar(String msg, {bool isError = false}) { + rootScaffoldMessengerKey.currentState?.showSnackBar( + SnackBar( + duration: const Duration(seconds: 2), + backgroundColor: isError ? Colors.red : AppColors.commanbutton, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.symmetric(horizontal: 70, vertical: 25), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + content: Row( + children: [ + Image.asset(AppAssets.taxgildelogoauth, height: 18, width: 18), + const SizedBox(width: 8), + Expanded( + child: Text( + msg, + style: const TextStyle(color: Colors.white, fontSize: 12), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ); + } +} + +class BeveledTrianglePainter extends CustomPainter { + final double cornerRadius; + + BeveledTrianglePainter({ + this.cornerRadius = 4.0, // Adjust this value for more/less rounding + }); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = const Color(0xFF5E2976) + ..style = PaintingStyle.fill; + + // Triangle vertices + final vertices = [ + Offset(0, cornerRadius), // Top left (adjusted for bevel) + Offset(size.width - 6, size.height / 2), // Right point + Offset(0, size.height - cornerRadius), // Bottom left (adjusted for bevel) + ]; + + final path = Path(); + + for (int i = 0; i < vertices.length; i++) { + final current = vertices[i]; + final next = vertices[(i + 1) % vertices.length]; + final prev = vertices[(i - 1 + vertices.length) % vertices.length]; + + // Calculate direction vectors + final toCurrent = Offset(current.dx - prev.dx, current.dy - prev.dy); + final toNext = Offset(next.dx - current.dx, next.dy - current.dy); + + // Normalize + final lengthToCurrent = math.sqrt( + toCurrent.dx * toCurrent.dx + toCurrent.dy * toCurrent.dy, + ); + final lengthToNext = math.sqrt( + toNext.dx * toNext.dx + toNext.dy * toNext.dy, + ); + + final normalizedToCurrent = Offset( + toCurrent.dx / lengthToCurrent, + toCurrent.dy / lengthToCurrent, + ); + final normalizedToNext = Offset( + toNext.dx / lengthToNext, + toNext.dy / lengthToNext, + ); + + // Points before and after the corner + final beforeCorner = Offset( + current.dx - normalizedToCurrent.dx * cornerRadius, + current.dy - normalizedToCurrent.dy * cornerRadius, + ); + final afterCorner = Offset( + current.dx + normalizedToNext.dx * cornerRadius, + current.dy + normalizedToNext.dy * cornerRadius, + ); + + if (i == 0) { + path.moveTo(beforeCorner.dx, beforeCorner.dy); + } else { + path.lineTo(beforeCorner.dx, beforeCorner.dy); + } + + // Draw rounded corner + path.quadraticBezierTo( + current.dx, + current.dy, + afterCorner.dx, + afterCorner.dy, + ); + } + path.close(); + + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) => false; +} diff --git a/lib/view/screens/profile/staff_list_screen.dart b/lib/view/screens/profile/staff_list_screen.dart new file mode 100644 index 0000000..01a0401 --- /dev/null +++ b/lib/view/screens/profile/staff_list_screen.dart @@ -0,0 +1,242 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class StaffListScreen extends ConsumerStatefulWidget { + const StaffListScreen({super.key}); + + @override + ConsumerState createState() => _StaffListScreenState(); +} + +class _StaffListScreenState extends ConsumerState { + @override + Widget build(BuildContext context) { + final staffAsync = ref.watch(staffListProvider); + + const commonTextStyle = TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w600, + fontSize: 14.7, + height: 1.30, // 130% + letterSpacing: 0.04, + color: Color(0xFF111827), + ); + const commonTextStylevalue = TextStyle( + fontFamily: "Gilroy-SemiBold", + fontWeight: FontWeight.w400, + fontSize: 14.7, + height: 1.30, // 130% + letterSpacing: 0.04, + color: Color(0xFF111827), + ); + return Scaffold( + backgroundColor: const Color.fromARGB(255, 230, 229, 229), + body: SafeArea( + child: staffAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + + error: (err, _) => Center( + child: Text( + 'Error: $err', + style: const TextStyle(color: Colors.red), + ), + ), + + data: (staffList) { + if (staffList.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text( + "No Staff Found", + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: CommanButton( + text: 'Go Back', + onPressed: () { + Navigator.pop(context); + }, + ), + ), + ], + ), + ); + } + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + GestureDetector( + onTap: () => Navigator.pop(context), + child: const Icon( + Icons.arrow_back_ios_new, + color: Colors.black, + size: 22, + ), + ), + const Expanded( + child: Center( + child: Text( + 'Sub - Staff List', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + ), + ), + ), + const Opacity( + opacity: 0, + child: Icon(Icons.arrow_back_ios_new, size: 22), + ), + ], + ), + + const SizedBox(height: 50), + + ...staffList.map((staff) { + String statusText = staff.status == 1 + ? "Active" + : "Inactive"; + String generalChatText = staff.generalChat == 1 + ? "Yes" + : "No"; + String createServiceText = staff.createService == 1 + ? "Yes" + : "No"; + + Color statusColor = staff.status == 1 + ? Colors.green + : Colors.red; + + return Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 4, + offset: Offset(0, 2), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ✅ Name + Row( + children: [ + Text("Name : ", style: commonTextStyle), + Expanded( + child: Text( + staff.name, + style: commonTextStylevalue, + ), + ), + ], + ), + + const SizedBox(height: 6), + + /// ✅ Mobile + Row( + children: [ + Text("Mobile : ", style: commonTextStyle), + Expanded( + child: Text( + staff.mobile, + style: commonTextStylevalue, + ), + ), + ], + ), + + const SizedBox(height: 6), + + /// ✅ Email + Row( + children: [ + Text("Email : ", style: commonTextStyle), + Expanded( + child: Text( + staff.email, + style: commonTextStylevalue, + ), + ), + ], + ), + + const SizedBox(height: 10), + + /// ✅ Status + Row( + children: [ + Text("Status : ", style: commonTextStyle), + Text( + statusText, + style: commonTextStylevalue.copyWith( + color: statusColor, + ), + ), + ], + ), + + const SizedBox(height: 6), + + /// ✅ General Chat + Row( + children: [ + Text("General Chat : ", style: commonTextStyle), + Text( + generalChatText, + style: commonTextStylevalue, + ), + ], + ), + + const SizedBox(height: 6), + + /// ✅ Create Service + Row( + children: [ + Text( + "Create Service : ", + style: commonTextStyle, + ), + Text( + createServiceText, + style: commonTextStylevalue, + ), + ], + ), + ], + ), + ); + }).toList(), + ], + ), + ); + }, + ), + ), + ); + } +} diff --git a/lib/view/screens/profile/terms_and_condition_screen.dart b/lib/view/screens/profile/terms_and_condition_screen.dart new file mode 100644 index 0000000..8455871 --- /dev/null +++ b/lib/view/screens/profile/terms_and_condition_screen.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:taxglide/controller/api_contoller.dart'; + +class TermsAndConditionScreen extends ConsumerStatefulWidget { + const TermsAndConditionScreen({super.key}); + + @override + ConsumerState createState() => + _TermsAndConditionScreenState(); +} + +class _TermsAndConditionScreenState + extends ConsumerState { + @override + Widget build(BuildContext context) { + final termsAsync = ref.watch(termsProvider); + + return Scaffold( + backgroundColor: const Color.fromARGB(255, 230, 229, 229), + body: SafeArea( + child: termsAsync.when( + data: (terms) => SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 🔹 Header Row with Back Arrow + Centered Title + Row( + children: [ + GestureDetector( + onTap: () => Navigator.pop(context), + child: const Icon( + Icons.arrow_back_ios_new, + color: Colors.black, + size: 22, + ), + ), + Expanded( + child: Center( + child: Text( + terms.data?.title ?? 'Terms & Conditions', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + ), + ), + ), + // To balance layout so title stays centered + const Opacity( + opacity: 0, + child: Icon(Icons.arrow_back_ios_new, size: 22), + ), + ], + ), + + const SizedBox(height: 24), + + // 🔹 Terms Content + Text( + terms.data?.content ?? '', + textAlign: TextAlign.start, + style: const TextStyle( + fontSize: 16, + height: 1.6, + color: Colors.black87, + ), + ), + ], + ), + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (err, _) => Center( + child: Text( + 'Error: $err', + style: const TextStyle(color: Colors.red), + ), + ), + ), + ), + ); + } +} diff --git a/lib/view/screens/serivce_request_screen.dart b/lib/view/screens/serivce_request_screen.dart new file mode 100644 index 0000000..ec2379e --- /dev/null +++ b/lib/view/screens/serivce_request_screen.dart @@ -0,0 +1,910 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get/get.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:path/path.dart' as path; +import 'package:taxglide/consts/comman_button.dart'; +import 'package:taxglide/consts/responsive_helper.dart'; +import 'package:taxglide/controller/api_contoller.dart'; +import 'package:taxglide/controller/api_repository.dart'; + +import 'package:taxglide/view/Main_controller/main_controller.dart'; + +class ServiceRequestScreen extends ConsumerStatefulWidget { + final int id; + final String service; + final String icon; + final int? returnTabIndex; + + const ServiceRequestScreen({ + super.key, + required this.id, + required this.service, + required this.icon, + this.returnTabIndex, + }); + + @override + ConsumerState createState() => + _ServiceRequestScreenState(); +} + +class _ServiceRequestScreenState extends ConsumerState { + final List _selectedFiles = []; + final TextEditingController _messageController = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + bool _isFileError = false; + bool _isTermsAccepted = false; + bool _isCheckboxError = false; + + @override + void dispose() { + _messageController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + void _showSnackBar(String msg, {bool isError = false}) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + duration: const Duration(seconds: 2), + backgroundColor: isError ? Colors.red : Colors.green, + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + elevation: 6, + margin: const EdgeInsets.symmetric(horizontal: 50, vertical: 25), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + content: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + isError ? Icons.error_outline : Icons.check_circle_outline, + color: Colors.white, + size: 18, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + msg, + style: const TextStyle(color: Colors.white, fontSize: 12), + overflow: TextOverflow.ellipsis, + maxLines: 2, + ), + ), + ], + ), + ), + ); + } + + bool _validateForm() { + setState(() { + _isFileError = false; + _isCheckboxError = false; + }); + + bool isValid = true; + if (_selectedFiles.isEmpty) { + setState(() => _isFileError = true); + _showSnackBar("Please upload at least one file", isError: true); + isValid = false; + } + if (!_isTermsAccepted) { + setState(() => _isCheckboxError = true); + _showSnackBar("Please accept terms and conditions", isError: true); + isValid = false; + } + return isValid; + } + + Future _submitRequest() async { + if (_validateForm()) { + try { + _showSnackBar("Submitting request..."); + await ApiRepository().updateServiceRequest( + serviceId: widget.id, + message: _messageController.text.trim(), + documents: _selectedFiles, + ); + _showSnackBar("Request submitted successfully!"); + ref.invalidate(serviceHistoryNotifierProvider); + Get.offAll(() => const MainController()); + } catch (e) { + debugPrint("❌ Submit error: $e"); + _showSnackBar("Something went wrong. Please try again.", isError: true); + } + } + } + + Future _pickFile() async { + final choice = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: const Text('Select File Type'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.camera_alt, color: Colors.blue), + title: const Text('Camera'), + onTap: () => Navigator.pop(ctx, 'camera'), + ), + ListTile( + leading: const Icon(Icons.photo, color: Colors.blue), + title: const Text('Gallery'), + onTap: () => Navigator.pop(ctx, 'gallery'), + ), + ListTile( + leading: const Icon(Icons.picture_as_pdf, color: Colors.red), + title: const Text('Select PDF'), + onTap: () => Navigator.pop(ctx, 'pdf'), + ), + ListTile( + leading: const Icon(Icons.folder_zip, color: Colors.orange), + title: const Text('Select ZIP'), + onTap: () => Navigator.pop(ctx, 'zip'), + ), + ], + ), + ), + ); + + if (choice == null) return; + + try { + if (choice == 'camera') { + final hasPermission = await _requestPermission(ImageSource.camera); + if (!hasPermission) return; + final picked = await ImagePicker().pickImage( + source: ImageSource.camera, + ); + if (picked != null) { + setState(() { + _selectedFiles.add(File(picked.path)); + _isFileError = false; + }); + } + } else if (choice == 'gallery') { + final hasPermission = await _requestPermission(ImageSource.gallery); + if (!hasPermission) return; + final picked = await ImagePicker().pickMultiImage(); + if (picked.isNotEmpty) { + setState(() { + for (var image in picked) { + _selectedFiles.add(File(image.path)); + } + _isFileError = false; + }); + } + } else if (choice == 'pdf' || choice == 'zip') { + final result = await FilePicker.platform.pickFiles( + allowMultiple: true, + type: FileType.custom, + allowedExtensions: choice == 'pdf' ? ['pdf'] : ['zip', 'rar', '7z'], + ); + if (result != null && result.files.isNotEmpty) { + for (var file in result.files) { + if (file.path != null) { + setState(() { + _selectedFiles.add(File(file.path!)); + _isFileError = false; + }); + } + } + } + } + } catch (e) { + debugPrint("❌ File picking error: $e"); + _showSnackBar("Failed to pick file: $e", isError: true); + } + } + + Future _showSettingsDialog(String permission) async { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text('$permission Permission Required'), + content: Text( + 'Allow $permission access to capture and upload your documents easily. You can enable it in the app settings.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.pop(ctx); + openAppSettings(); + }, + child: const Text('Go to Settings'), + ), + ], + ), + ); + } + + Future _requestPermission(ImageSource source) async { + try { + Permission permission; + String name; + + if (source == ImageSource.camera) { + permission = Permission.camera; + name = 'Camera'; + } else { + if (Platform.isAndroid) { + final info = await DeviceInfoPlugin().androidInfo; + if (info.version.sdkInt >= 33) { + permission = Permission.photos; + name = 'Photos'; + } else { + permission = Permission.storage; + name = 'Storage'; + } + } else { + permission = Permission.photos; + name = 'Photos'; + } + } + + var status = await permission.status; + + print("status $status"); + status = await permission.request(); + if (status.isGranted || status.isLimited) return true; + if (status.isPermanentlyDenied || (Platform.isIOS && status.isDenied)) { + await _showSettingsDialog(name); + return false; + } + + await _showSettingsDialog(name); + return false; + } catch (e) { + debugPrint("Permission error: $e"); + return Platform.isIOS; + } + } + + bool _isImage(String pathStr) { + final ext = path.extension(pathStr).toLowerCase(); + return ['.jpg', '.jpeg', '.png', '.gif', '.webp'].contains(ext); + } + + bool _isPdf(String pathStr) => + path.extension(pathStr).toLowerCase() == '.pdf'; + + bool _isZip(String pathStr) => + ['.zip', '.rar', '.7z'].contains(path.extension(pathStr).toLowerCase()); + + @override + Widget build(BuildContext context) { + final r = ResponsiveUtils(context); + + // Responsive values + final hPadding = r.spacing(mobile: 10, tablet: 16, desktop: 24); + final hPaddingInner = r.spacing(mobile: 20, tablet: 24, desktop: 32); + final headerFontSize = r.fontSize(mobile: 20, tablet: 24, desktop: 28); + final labelFontSize = r.fontSize(mobile: 14, tablet: 16, desktop: 18); + final readOnlyFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final uploadFontSize = r.fontSize(mobile: 11.5, tablet: 12.78, desktop: 14); + final uploadSubFontSize = r.fontSize(mobile: 9, tablet: 10, desktop: 11); + final checkboxFontSize = r.fontSize( + mobile: 11.5, + tablet: 12.78, + desktop: 14, + ); + final messageFontSize = r.fontSize( + mobile: 10.5, + tablet: 11.31, + desktop: 12.5, + ); + final serviceNameFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15); + final uploadedCountFontSize = r.fontSize( + mobile: 13, + tablet: 14, + desktop: 15, + ); + + final serviceIconContainerW = r.getValue( + mobile: 90, + tablet: 110, + desktop: 130, + ); + final serviceIconContainerH = r.getValue( + mobile: 70, + tablet: 84, + desktop: 100, + ); + final serviceIconSize = r.getValue( + mobile: 36, + tablet: 42, + desktop: 50, + ); + + final messageBoxHeight = r.getValue( + mobile: 100, + tablet: 117, + desktop: 140, + ); + final fileCardWidth = r.getValue( + mobile: 90, + tablet: 110, + desktop: 130, + ); + final fileCardHeight = r.getValue( + mobile: 100, + tablet: 120, + desktop: 140, + ); + final fileIconSize = r.getValue( + mobile: 34, + tablet: 40, + desktop: 46, + ); + + final spacingSM = r.spacing(mobile: 10, tablet: 10, desktop: 12); + final spacingMD = r.spacing(mobile: 16, tablet: 20, desktop: 24); + final spacingLG = r.spacing(mobile: 20, tablet: 20, desktop: 24); + + return Scaffold( + backgroundColor: const Color.fromARGB(255, 230, 229, 229), + body: SafeArea( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + Padding( + padding: EdgeInsets.symmetric( + horizontal: hPadding, + vertical: 21, + ), + child: SizedBox( + height: 50, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + Text( + "New Service Request", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: headerFontSize, + color: const Color(0xFF111827), + ), + ), + Positioned( + left: 0, + child: GestureDetector( + onTap: () => Get.offAll(() => const MainController()), + child: const Icon(Icons.arrow_back_ios_rounded), + ), + ), + ], + ), + ), + ), + + SizedBox(height: spacingLG), + + // Service icon and name + Center( + child: Column( + children: [ + Container( + width: serviceIconContainerW, + height: serviceIconContainerH, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFE1E1E1)), + boxShadow: const [ + BoxShadow( + color: Color(0x66757575), + offset: Offset(0, 1), + blurRadius: 7.3, + ), + ], + ), + padding: const EdgeInsets.all(8), + child: Image.network( + widget.icon, + width: serviceIconSize, + height: serviceIconSize, + ), + ), + SizedBox(height: spacingMD), + Text( + widget.service, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: serviceNameFontSize, + color: const Color(0xFF3F3F3F), + ), + ), + ], + ), + ), + + SizedBox(height: spacingLG), + + // Request Type + _buildLabel("Request Type*", hPaddingInner, labelFontSize), + _buildReadOnlyBox( + widget.service, + hPaddingInner, + readOnlyFontSize, + ), + + SizedBox(height: spacingSM), + + // File Upload Header + Padding( + padding: EdgeInsets.symmetric(horizontal: hPaddingInner), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "File Upload *", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: labelFontSize, + color: const Color(0xFF111827), + ), + ), + GestureDetector( + onTap: _pickFile, + child: Container( + width: 20, + height: 20, + decoration: const BoxDecoration( + color: Colors.black, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.add, + size: 18, + color: Colors.white, + ), + ), + ), + ], + ), + ), + SizedBox(height: spacingLG), + + // Upload Box + _buildUploadBox(hPaddingInner, uploadFontSize, uploadSubFontSize), + + // Selected Files + if (_selectedFiles.isNotEmpty) + _buildEnhancedSelectedFiles( + hPaddingInner, + fileCardWidth, + fileCardHeight, + fileIconSize, + uploadedCountFontSize, + ), + SizedBox(height: spacingLG), + + // Message + _buildLabel("Message", hPaddingInner, labelFontSize), + _buildMessageBox( + hPaddingInner, + messageBoxHeight, + messageFontSize, + ), + + // Terms Checkbox + Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding), + child: Row( + children: [ + Checkbox( + value: _isTermsAccepted, + onChanged: (v) { + setState(() { + _isTermsAccepted = v ?? false; + if (v == true) _isCheckboxError = false; + }); + }, + activeColor: Colors.green, + side: BorderSide( + color: _isCheckboxError ? Colors.red : Colors.grey, + width: _isCheckboxError ? 2 : 1, + ), + ), + Expanded( + child: Text( + "I accept the terms and conditions *", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontStyle: FontStyle.normal, + fontSize: checkboxFontSize, + height: 25.56 / 12.78, + letterSpacing: 0.8, + color: _isCheckboxError + ? Colors.red + : const Color(0xFF4F4C4C), + ), + ), + ), + ], + ), + ), + + // Submit Button + Padding( + padding: EdgeInsets.symmetric( + horizontal: r.spacing(mobile: 30, tablet: 41, desktop: 60), + vertical: spacingLG, + ), + child: CommanButton( + text: 'Submit Request', + onPressed: _submitRequest, + ), + ), + + const SizedBox(height: 250), + ], + ), + ), + ), + ); + } + + Widget _buildLabel(String title, double hPadding, double fontSize) => Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding), + child: Text( + title, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: fontSize, + color: const Color(0xFF111827), + ), + ), + ); + + Widget _buildReadOnlyBox(String text, double hPadding, double fontSize) => + Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding, vertical: 15), + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFFDFDFDF)), + boxShadow: const [ + BoxShadow( + color: Color(0x66BDBDBD), + offset: Offset(0, 1), + blurRadius: 7, + ), + ], + ), + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 21), + child: Text( + text, + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: fontSize, + color: const Color(0xFF3F3F3F), + ), + ), + ), + ); + + Widget _buildUploadBox( + double hPadding, + double fontSize, + double subFontSize, + ) => Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding), + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: _isFileError ? Colors.red : const Color(0xFFDFDFDF), + width: _isFileError ? 2 : 1, + ), + ), + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 21), + child: Column( + children: [ + Text( + "Upload PDF, IMG, JPG, ZIP", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: fontSize, + height: 25.56 / 12.78, + letterSpacing: 0.8, + color: _isFileError ? Colors.red : const Color(0xFF4F4C4C), + ), + ), + Text( + "(40 MB only allowed File)", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: subFontSize, + height: 25.56 / 12.78, + letterSpacing: 0.8, + color: _isFileError ? Colors.red : const Color(0xFF4F4C4C), + ), + ), + if (_isFileError) + const Padding( + padding: EdgeInsets.only(top: 8), + child: Text( + "Please upload at least one file", + style: TextStyle(color: Colors.red, fontSize: 11), + ), + ), + ], + ), + ), + ); + + Widget _buildEnhancedSelectedFiles( + double hPadding, + double cardWidth, + double cardHeight, + double iconSize, + double countFontSize, + ) => Container( + margin: EdgeInsets.symmetric(horizontal: hPadding, vertical: 10), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE1E1E1)), + boxShadow: const [ + BoxShadow( + color: Color(0x1A000000), + offset: Offset(0, 2), + blurRadius: 8, + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: Colors.green.shade50, + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + Icons.check_circle, + color: Colors.green.shade600, + size: 18, + ), + ), + const SizedBox(width: 8), + Text( + "Uploaded Files (${_selectedFiles.length})", + style: TextStyle( + fontFamily: 'Gilroy-SemiBold', + fontWeight: FontWeight.w600, + fontSize: countFontSize, + color: const Color(0xFF111827), + ), + ), + ], + ), + if (_selectedFiles.length > 2) + Row( + children: [ + GestureDetector( + onTap: () { + _scrollController.animateTo( + _scrollController.offset - 120, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + }, + child: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: Colors.grey.shade200, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.arrow_back_ios_new, + size: 14, + color: Colors.black87, + ), + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () { + _scrollController.animateTo( + _scrollController.offset + 120, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + }, + child: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: Colors.grey.shade200, + shape: BoxShape.circle, + ), + child: const Icon( + Icons.arrow_forward_ios, + size: 14, + color: Colors.black87, + ), + ), + ), + ], + ), + ], + ), + const SizedBox(height: 12), + SizedBox( + height: cardHeight, + child: ListView.builder( + controller: _scrollController, + scrollDirection: Axis.horizontal, + itemCount: _selectedFiles.length, + itemBuilder: (context, index) { + final file = _selectedFiles[index]; + final pathStr = file.path; + + Widget preview; + Color bgColor; + + if (_isImage(pathStr)) { + preview = ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.file( + file, + fit: BoxFit.cover, + width: cardWidth, + height: cardHeight, + ), + ); + bgColor = Colors.transparent; + } else if (_isPdf(pathStr)) { + bgColor = Colors.red.shade50; + preview = Icon( + Icons.picture_as_pdf, + size: iconSize, + color: Colors.red.shade600, + ); + } else if (_isZip(pathStr)) { + bgColor = Colors.orange.shade50; + preview = Icon( + Icons.folder_zip, + size: iconSize, + color: Colors.orange.shade600, + ); + } else { + bgColor = Colors.blue.shade50; + preview = Icon( + Icons.insert_drive_file, + size: iconSize, + color: Colors.blue.shade600, + ); + } + + return Padding( + padding: const EdgeInsets.only(right: 12), + child: Stack( + children: [ + Container( + width: cardWidth, + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: Colors.grey.shade300, + width: 1.5, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + offset: const Offset(0, 2), + blurRadius: 4, + ), + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [Expanded(child: Center(child: preview))], + ), + ), + Positioned( + right: -2, + top: -2, + child: GestureDetector( + onTap: () { + setState(() { + _selectedFiles.removeAt(index); + if (_selectedFiles.isEmpty) _isFileError = true; + }); + }, + child: Container( + decoration: BoxDecoration( + color: Colors.red.shade600, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.2), + offset: const Offset(0, 2), + blurRadius: 4, + ), + ], + ), + padding: const EdgeInsets.all(4), + child: const Icon( + Icons.close, + size: 14, + color: Colors.white, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ), + ); + + Widget _buildMessageBox(double hPadding, double boxHeight, double fontSize) => + Padding( + padding: EdgeInsets.symmetric(horizontal: hPadding, vertical: 15), + child: Container( + width: double.infinity, + height: boxHeight, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFCFCFCF)), + ), + child: TextFormField( + controller: _messageController, + maxLines: null, + expands: true, + style: TextStyle( + fontFamily: 'Gilroy-Medium', + fontSize: fontSize, + color: const Color(0xFF6C7278), + ), + decoration: const InputDecoration( + hintText: "Enter your message", + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + ), + ), + ); +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..c7ea17f --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..2c37949 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "taxglide") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.amrithaa.taxglide") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..27860e8 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..3ccd551 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..9ce94c4 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + flutter_secure_storage_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..7ed6f3e --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..4340ffc --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..4da7983 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,144 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView *view) +{ + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "taxglide"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "taxglide"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..8f20fb5 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..d4e0569 --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..df4c964 --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..e79501e --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..603e83e --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,32 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import device_info_plus +import file_picker +import file_selector_macos +import firebase_core +import firebase_messaging +import flutter_local_notifications +import flutter_secure_storage_macos +import gal +import path_provider_foundation +import sqflite_darwin +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) + FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin")) + FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin")) + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) + GalPlugin.register(with: registry.registrar(forPlugin: "GalPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/macos/Podfile b/macos/Podfile new file mode 100644 index 0000000..a46f7f2 --- /dev/null +++ b/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..db0bb83 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* taxglide.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "taxglide.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* taxglide.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* taxglide.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/taxglide.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/taxglide"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/taxglide.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/taxglide"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/taxglide.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/taxglide"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..528b7da --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..59c6d39 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..c5c474d --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..8d4e7cb --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..4632c69 --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..3dae969 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = taxglide + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.amrithaa.taxglide + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..b398823 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..d93e5dc --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..fb4d7d3 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..51d0967 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..3733c1a --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..ab30cba --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..04336df --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..21fe1ab --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/process_icon.swift b/process_icon.swift new file mode 100644 index 0000000..ec7209d --- /dev/null +++ b/process_icon.swift @@ -0,0 +1,62 @@ +import AppKit + +let arguments = CommandLine.arguments +guard arguments.count > 3 else { + print("Usage: swift process_icon.swift ") + exit(1) +} + +let inputPath = arguments[1] +let outputPath = arguments[2] +let hexColor = arguments[3].replacingOccurrences(of: "#", with: "") +let scaleFactor = arguments.count > 4 ? Double(arguments[4]) ?? 0.8 : 0.8 + +func colorFromHex(_ hex: String) -> NSColor { + var rgbValue: UInt64 = 0 + Scanner(string: hex).scanHexInt64(&rgbValue) + let r = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 + let g = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0 + let b = CGFloat(rgbValue & 0x0000FF) / 255.0 + return NSColor(red: r, green: g, blue: b, alpha: 1.0) +} + +guard let inputImage = NSImage(contentsOfFile: inputPath) else { + print("Error: Could not load input image") + exit(1) +} + +// Fixed size for launcher icon (e.g. 1024x1024) +let size = NSSize(width: 1024, height: 1024) +let outputImage = NSImage(size: size) + +outputImage.lockFocus() + +// Fill background +let backgroundColor = colorFromHex(hexColor) +backgroundColor.set() +NSBezierPath(rect: NSRect(origin: .zero, size: size)).fill() + +// Draw input image centered +let inputSize = inputImage.size +let ratio = min(size.width / inputSize.width, size.height / inputSize.height) * CGFloat(scaleFactor) +let targetSize = NSSize(width: inputSize.width * ratio, height: inputSize.height * ratio) +let origin = NSPoint(x: (size.width - targetSize.width) / 2, y: (size.height - targetSize.height) / 2) + +inputImage.draw(in: NSRect(origin: origin, size: targetSize), from: .zero, operation: .sourceOver, fraction: 1.0) + +outputImage.unlockFocus() + +guard let tiffData = outputImage.tiffRepresentation, + let bitmapImage = NSBitmapImageRep(data: tiffData), + let pngData = bitmapImage.representation(using: .png, properties: [:]) else { + print("Error: Could not convert to PNG") + exit(1) +} + +do { + try pngData.write(to: URL(fileURLWithPath: outputPath)) + print("Success: \(outputPath) created") +} catch { + print("Error: Could not write file: \(error)") + exit(1) +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..fdde2f4 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1346 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + url: "https://pub.dev" + source: hosted + version: "93.0.0" + _flutterfire_internals: + dependency: transitive + description: + name: _flutterfire_internals + sha256: "8a1f5f3020ef2a74fb93f7ab3ef127a8feea33a7a2276279113660784ee7516a" + url: "https://pub.dev" + source: hosted + version: "1.3.64" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + url: "https://pub.dev" + source: hosted + version: "10.0.1" + animated_notch_bottom_bar: + dependency: "direct main" + description: + name: animated_notch_bottom_bar + sha256: adc389a39e7b015883bba22de57e691eb6445c98c055b2438d6593a7f68017fe + url: "https://pub.dev" + source: hosted + version: "1.0.3" + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + cached_network_image: + dependency: "direct main" + description: + name: cached_network_image + sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + cached_network_image_platform_interface: + dependency: transitive + description: + name: cached_network_image_platform_interface + sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829" + url: "https://pub.dev" + source: hosted + version: "4.1.1" + cached_network_image_web: + dependency: transitive + description: + name: cached_network_image_web + sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + carousel_slider: + dependency: "direct main" + description: + name: carousel_slider + sha256: bcc61735345c9ab5cb81073896579e735f81e35fd588907a393143ea986be8ff + url: "https://pub.dev" + source: hosted + version: "5.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "942a4791cd385a68ccb3b32c71c427aba508a1bb949b86dff2adbe4049f16239" + url: "https://pub.dev" + source: hosted + version: "0.3.5" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dbus: + dependency: transitive + description: + name: dbus + sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + device_info_plus: + dependency: "direct main" + description: + name: device_info_plus + sha256: dd0e8e02186b2196c7848c9d394a5fd6e5b57a43a546082c5820b1ec72317e33 + url: "https://pub.dev" + source: hosted + version: "12.2.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + url: "https://pub.dev" + source: hosted + version: "7.0.3" + dio: + dependency: "direct main" + description: + name: dio + sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9 + url: "https://pub.dev" + source: hosted + version: "5.9.0" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + dropdown_button2: + dependency: "direct main" + description: + name: dropdown_button2 + sha256: b0fe8d49a030315e9eef6c7ac84ca964250155a6224d491c1365061bc974a9e1 + url: "https://pub.dev" + source: hosted + version: "2.3.9" + dropdown_textfield: + dependency: "direct main" + description: + name: dropdown_textfield + sha256: ef8a35c52c92a563773d3efead94e5a1c162d6fe6c53974d0986aab6249928a1 + url: "https://pub.dev" + source: hosted + version: "1.2.0" + equatable: + dependency: transitive + description: + name: equatable + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.dev" + source: hosted + version: "2.0.7" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: f2d9f173c2c14635cc0e9b14c143c49ef30b4934e8d1d274d6206fcb0086a06f + url: "https://pub.dev" + source: hosted + version: "10.3.3" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33" + url: "https://pub.dev" + source: hosted + version: "0.9.3+2" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "19124ff4a3d8864fdc62072b6a2ef6c222d55a3404fe14893a3c02744907b60c" + url: "https://pub.dev" + source: hosted + version: "0.9.4+4" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b + url: "https://pub.dev" + source: hosted + version: "2.6.2" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "320fcfb6f33caa90f0b58380489fc5ac05d99ee94b61aa96ec2bff0ba81d3c2b" + url: "https://pub.dev" + source: hosted + version: "0.9.3+4" + firebase_core: + dependency: "direct main" + description: + name: firebase_core + sha256: "1f2dfd9f535d81f8b06d7a50ecda6eac1e6922191ed42e09ca2c84bd2288927c" + url: "https://pub.dev" + source: hosted + version: "4.2.1" + firebase_core_platform_interface: + dependency: transitive + description: + name: firebase_core_platform_interface + sha256: cccb4f572325dc14904c02fcc7db6323ad62ba02536833dddb5c02cac7341c64 + url: "https://pub.dev" + source: hosted + version: "6.0.2" + firebase_core_web: + dependency: transitive + description: + name: firebase_core_web + sha256: ff18fabb0ad0ed3595d2f2c85007ecc794aadecdff5b3bb1460b7ee47cded398 + url: "https://pub.dev" + source: hosted + version: "3.3.0" + firebase_messaging: + dependency: "direct main" + description: + name: firebase_messaging + sha256: "22086f857d2340f5d973776cfd542d3fb30cf98e1c643c3aa4a7520bb12745bb" + url: "https://pub.dev" + source: hosted + version: "16.0.4" + firebase_messaging_platform_interface: + dependency: transitive + description: + name: firebase_messaging_platform_interface + sha256: a59920cbf2eb7c83d34a5f354331210ffec116b216dc72d864d8b8eb983ca398 + url: "https://pub.dev" + source: hosted + version: "4.7.4" + firebase_messaging_web: + dependency: transitive + description: + name: firebase_messaging_web + sha256: "1183e40e6fd2a279a628951cc3b639fcf5ffe7589902632db645011eb70ebefb" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_cache_manager: + dependency: transitive + description: + name: flutter_cache_manager + sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: ef41ae901e7529e52934feba19ed82827b11baa67336829564aeab3129460610 + url: "https://pub.dev" + source: hosted + version: "18.0.1" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: "8f685642876742c941b29c32030f6f4f6dacd0e4eaecb3efbb187d6a3812ca01" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "6c5b83c86bf819cdb177a9247a3722067dd8cc6313827ce7c77a4b238a26fd52" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: c2fe1001710127dfa7da89977a08d591398370d099aacdaa6d44da7eb14b8476 + url: "https://pub.dev" + source: hosted + version: "2.0.31" + flutter_redux: + dependency: "direct main" + description: + name: flutter_redux + sha256: "3b20be9e08d0038e1452fbfa1fdb1ea0a7c3738c997734530b3c6d0bb5fcdbdc" + url: "https://pub.dev" + source: hosted + version: "0.10.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9e2d6907f12cc7d23a846847615941bddee8709bf2bfd274acdf5e80bcf22fde" + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: "055de8921be7b8e8b98a233c7a5ef84b3a6fcc32f46f1ebf5b9bb3576d108355" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + gal: + dependency: "direct main" + description: + name: gal + sha256: "969598f986789127fd407a750413249e1352116d4c2be66e81837ffeeaafdfee" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + get: + dependency: "direct main" + description: + name: get + sha256: c79eeb4339f1f3deffd9ec912f8a923834bec55f7b49c9e882b8fef2c139d425 + url: "https://pub.dev" + source: hosted + version: "4.7.2" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + http: + dependency: "direct main" + description: + name: http + sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007 + url: "https://pub.dev" + source: hosted + version: "1.5.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "736eb56a911cf24d1859315ad09ddec0b66104bc41a7f8c5b96b4e2620cf5041" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "28f3987ca0ec702d346eae1d90eda59603a2101b52f1e234ded62cff1d5cfa6e" + url: "https://pub.dev" + source: hosted + version: "0.8.13+1" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "40c2a6a0da15556dc0f8e38a3246064a971a9f512386c3339b89f76db87269b6" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: eb06fe30bab4c4497bad449b66448f50edcc695f1c59408e78aa3a8059eb8f0e + url: "https://pub.dev" + source: hosted + version: "0.8.13" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: d58cd9d67793d52beefd6585b12050af0a7663c0c2a6ece0fb110a35d6955e04 + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df" + url: "https://pub.dev" + source: hosted + version: "4.10.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" + url: "https://pub.dev" + source: hosted + version: "0.12.18" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + octo_image: + dependency: transitive + description: + name: octo_image + sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + open_filex: + dependency: "direct main" + description: + name: open_filex + sha256: "9976da61b6a72302cf3b1efbce259200cd40232643a467aac7370addf94d6900" + url: "https://pub.dev" + source: hosted + version: "4.7.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "3b4c1fc3aa55ddc9cd4aa6759984330d5c8e66aa7702a6223c61540dc6380c37" + url: "https://pub.dev" + source: hosted + version: "2.2.19" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: bc917da36261b00137bbc8896bf1482169cd76f866282368948f032c8c1caae1 + url: "https://pub.dev" + source: hosted + version: "12.0.1" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: "1e3bc410ca1bf84662104b100eb126e066cb55791b7451307f9708d4007350e6" + url: "https://pub.dev" + source: hosted + version: "13.0.1" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023 + url: "https://pub.dev" + source: hosted + version: "9.4.7" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24" + url: "https://pub.dev" + source: hosted + version: "0.1.3+5" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e" + url: "https://pub.dev" + source: hosted + version: "0.2.1" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + photo_view: + dependency: "direct main" + description: + name: photo_view + sha256: "1fc3d970a91295fbd1364296575f854c9863f225505c28c46e0a03e48960c75e" + url: "https://pub.dev" + source: hosted + version: "0.15.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" + posix: + dependency: transitive + description: + name: posix + sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + redux: + dependency: "direct main" + description: + name: redux + sha256: "1e86ed5b1a9a717922d0a0ca41f9bf49c1a587d50050e9426fc65b14e85ec4d7" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: c406de02bff19d920b832bddfb8283548bfa05ce41c59afba57ce643e116aa59 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + url: "https://pub.dev" + source: hosted + version: "0.10.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + sqflite: + dependency: transitive + description: + name: sqflite + sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "2b3070c5fa881839f8b402ee4a39c1b4d561704d4ebbbcfb808a119bc2a1701b" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: transitive + description: + name: test + sha256: "54c516bbb7cee2754d327ad4fca637f78abfc3cbcc5ace83b3eda117e42cd71a" + url: "https://pub.dev" + source: hosted + version: "1.29.0" + test_api: + dependency: transitive + description: + name: test_api + sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636" + url: "https://pub.dev" + source: hosted + version: "0.7.9" + test_core: + dependency: transitive + description: + name: test_core + sha256: "394f07d21f0f2255ec9e3989f21e54d3c7dc0e6e9dbce160e5a9c1a6be0e2943" + url: "https://pub.dev" + source: hosted + version: "0.6.15" + timezone: + dependency: transitive + description: + name: timezone + sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + url: "https://pub.dev" + source: hosted + version: "0.10.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "5387615091fb9bcacfe03e140437be22c3a3cd7ac53052ec9a16d2a6a370a994" + url: "https://pub.dev" + source: hosted + version: "6.3.27" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad + url: "https://pub.dev" + source: hosted + version: "6.3.6" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8 + url: "https://pub.dev" + source: hosted + version: "4.5.2" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6 + url: "https://pub.dev" + source: hosted + version: "1.1.19" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc + url: "https://pub.dev" + source: hosted + version: "1.1.19" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 + url: "https://pub.dev" + source: hosted + version: "15.0.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "592ab6e2892f67760543fb712ff0177f4ec76c031f02f5b4ff8d3fc5eb9fb61a" + url: "https://pub.dev" + source: hosted + version: "1.1.4" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: "direct main" + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.9.0 <4.0.0" + flutter: ">=3.35.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..c4b878a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,123 @@ +name: taxglide +description: "A new Flutter project." + +publish_to: 'none' # private project + +version: 1.0.0+1 + +environment: + sdk: ">=3.8.0 <4.0.0" + +dependencies: + flutter: + sdk: flutter + cupertino_icons: ^1.0.8 + flutter_svg: ^2.2.1 + get: ^4.7.2 + redux: ^5.0.0 + flutter_redux: ^0.10.0 + http: ^1.5.0 + flutter_riverpod: ^3.0.3 + + animated_notch_bottom_bar: ^1.0.3 + firebase_core: ^4.2.0 + flutter_secure_storage: ^9.2.4 + firebase_messaging: ^16.0.3 + dropdown_button2: ^2.3.9 + dropdown_textfield: ^1.2.0 + image_picker: ^1.2.0 + permission_handler: ^12.0.1 + device_info_plus: ^12.2.0 + path: ^1.9.1 + cached_network_image: ^3.4.1 + file_picker: ^10.3.3 + dio: ^5.9.0 + open_filex: ^4.7.0 + url_launcher: ^6.3.2 + photo_view: ^0.15.0 + carousel_slider: ^5.1.1 + gal: ^2.3.2 + web_socket_channel: ^3.0.2 + flutter_local_notifications: ^18.0.1 + + + + + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + flutter_launcher_icons: ^0.13.1 + +flutter_launcher_icons: + android: "launcher_icon" + ios: true + image_path: "assets/images/taxglidelogo.png" + image_path_ios: "assets/images/taxglidelogo_ios.png" + min_sdk_android: 21 + adaptive_icon_background: "#FFFFFF" + adaptive_icon_foreground: "assets/images/taxglidelogo_android.png" + remove_alpha_ios: true + +flutter: + uses-material-design: true + + assets: + - assets/images/ + - assets/svgs/ + + + fonts: + - family: Gilroy + fonts: + - asset: assets/fonts/Gilroy-Thin.ttf + weight: 100 + - asset: assets/fonts/Gilroy-ThinItalic.ttf + weight: 100 + style: italic + - asset: assets/fonts/Gilroy-UltraLight.ttf + weight: 200 + - asset: assets/fonts/Gilroy-UltraLightItalic.ttf + weight: 200 + style: italic + - asset: assets/fonts/Gilroy-Light.ttf + weight: 300 + - asset: assets/fonts/Gilroy-LightItalic.ttf + weight: 300 + style: italic + - asset: assets/fonts/Gilroy-Regular.ttf + weight: 400 + - asset: assets/fonts/Gilroy-RegularItalic.ttf + weight: 400 + style: italic + - asset: assets/fonts/Gilroy-Medium.ttf + weight: 500 + - asset: assets/fonts/Gilroy-MediumItalic.ttf + weight: 500 + style: italic + - asset: assets/fonts/Gilroy-SemiBold.ttf + weight: 600 + - asset: assets/fonts/Gilroy-SemiBoldItalic.ttf + weight: 600 + style: italic + - asset: assets/fonts/Gilroy-Bold.ttf + weight: 700 + - asset: assets/fonts/Gilroy-BoldItalic.ttf + weight: 700 + style: italic + - asset: assets/fonts/Gilroy-ExtraBold.ttf + weight: 800 + - asset: assets/fonts/Gilroy-ExtraBoldItalic.ttf + weight: 800 + style: italic + - asset: assets/fonts/Gilroy-Black.ttf + weight: 900 + - asset: assets/fonts/Gilroy-BlackItalic.ttf + weight: 900 + style: italic + - asset: assets/fonts/Gilroy-Heavy.ttf + weight: 900 + - asset: assets/fonts/Gilroy-HeavyItalic.ttf + weight: 900 + style: italic diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..7b794b2 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:taxglide/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const TaxglideApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..762f787 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + taxglide + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..bb2ce3c --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "taxglide", + "short_name": "taxglide", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..ec4098a --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..4f4c256 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(taxglide LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "taxglide") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..efb62eb --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..afce885 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,29 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + GalPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("GalPluginCApi")); + PermissionHandlerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..73fc759 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,29 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows + firebase_core + flutter_secure_storage_windows + gal + permission_handler_windows + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..2041a04 --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..6110b68 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "taxglide" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "taxglide" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "taxglide.exe" "\0" + VALUE "ProductName", "taxglide" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c819cb0 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..28c2383 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..145fc6d --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"taxglide", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..ddc7f3e --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..4b962bb --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..259d85b --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3f0e05c --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..b5ba2a0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..49b847f --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_