diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index db73bc05..3fc6cf0c 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -3,7 +3,7 @@ name: Eatvio App Android Test on: [ pull_request ] env: - flutter_version: "3.41.2" + flutter_version: "3.50.0" java_version: "21.x" flutter_channel: "stable" diff --git a/.gitea/workflows/docker-run-tests.yml b/.gitea/workflows/docker-run-tests.yml index 17902e45..4df0a96f 100644 --- a/.gitea/workflows/docker-run-tests.yml +++ b/.gitea/workflows/docker-run-tests.yml @@ -3,7 +3,7 @@ name: Eatvio App Android Test on custom docker on: [ pull_request ] env: - flutter_version: "3.41.2" + flutter_version: "3.50.0" java_version: "21.x" flutter_channel: "stable" my_local_cache_dir: "/opt/hostedtoolcache/" diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index 11c48f67..92687d36 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -6,7 +6,7 @@ on: - main env: - flutter_version: '3.41.2' + flutter_version: '3.50.0' java_version: '21.x' flutter_channel: 'stable' my_local_cache_dir: '/opt/hostedtoolcache/' @@ -14,7 +14,7 @@ env: jobs: build: - runs-on: [ubuntu-latest] + runs-on: [debian-12] steps: - uses: https://github.com/actions/checkout@v3 @@ -74,7 +74,7 @@ jobs: uses: 'https://github.com/actions/cache@v4' with: path: ${{ env.my_local_cache_dir }} - key: ${{ runner.os }}-cache-sdk + key: ${{ runner.os }}-cache-sdk-flutter-${{ env.flutter_version }} - name: Set up JDK uses: https://github.com/actions/setup-java@v3 @@ -117,15 +117,37 @@ jobs: - name: Set up Flutter run: | FLUTTER_DIR="${{ env.my_local_cache_dir }}flutter" - if [ ! -f "$FLUTTER_DIR/bin/flutter" ]; then - echo "Downloading Flutter ${{ env.flutter_version }}..." - curl -fsSL -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/${{ env.flutter_channel }}/linux/flutter_linux_${{ env.flutter_version }}-${{ env.flutter_channel }}.tar.xz" + EXPECTED_VERSION="${{ env.flutter_version }}" + echo "Checking Flutter at $FLUTTER_DIR (need ${EXPECTED_VERSION})" + CACHED_VERSION="" + if [ -d "$FLUTTER_DIR" ]; then + git config --global --add safe.directory "$FLUTTER_DIR" || true + # flutter --version writes several lines; with pipefail, head closes + # the pipe and the step exits before any log line. + set +e + set +o pipefail + CACHED_VERSION="$(git -C "$FLUTTER_DIR" describe --tags --exact-match 2>/dev/null)" + CACHED_VERSION="${CACHED_VERSION#v}" + if [ -z "$CACHED_VERSION" ] && [ -x "$FLUTTER_DIR/bin/flutter" ]; then + VERSION_LINE="$("$FLUTTER_DIR/bin/flutter" --version 2>&1 | head -n 1)" + echo "flutter --version: ${VERSION_LINE:-}" + CACHED_VERSION="$(printf '%s\n' "$VERSION_LINE" | awk '{print $2}')" + fi + set -e + set -o pipefail + fi + echo "Cached Flutter version: '${CACHED_VERSION:-none}'" + if [ "$CACHED_VERSION" != "$EXPECTED_VERSION" ]; then + echo "Downloading Flutter ${EXPECTED_VERSION}..." + rm -rf "$FLUTTER_DIR" + curl -fL --retry 3 --retry-delay 2 -o /tmp/flutter.tar.xz "https://storage.googleapis.com/flutter_infra_release/releases/${{ env.flutter_channel }}/linux/flutter_linux_${EXPECTED_VERSION}-${{ env.flutter_channel }}.tar.xz" echo "Extracting Flutter..." mkdir -p "${{ env.my_local_cache_dir }}" tar xf /tmp/flutter.tar.xz -C "${{ env.my_local_cache_dir }}" rm /tmp/flutter.tar.xz + git config --global --add safe.directory "$FLUTTER_DIR" || true else - echo "Flutter already cached at $FLUTTER_DIR" + echo "Flutter ${EXPECTED_VERSION} already cached at $FLUTTER_DIR" fi echo "$FLUTTER_DIR/bin" >> $GITHUB_PATH echo "$FLUTTER_DIR/bin/cache/dart-sdk/bin" >> $GITHUB_PATH @@ -155,10 +177,10 @@ jobs: - name: Get dependencies run: | - flutter clean - flutter pub cache repair - flutter pub get - dart run build_runner build --delete-conflicting-outputs + flutter clean + flutter pub cache repair + flutter pub get + dart run build_runner build --delete-conflicting-outputs # Контракт манифеста API: манифест обязан быть регенерирован из исходников freezed-моделей. # Diff после регенерации = PR менял модели, но не обновил api_contract/flutter_model_contract.json. diff --git a/.gitignore b/.gitignore index af0c7b6d..19c9caaa 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,8 @@ *.mocks.dart android/build/ ios/XCBuildData/ +docs/ +specs/ env/.env .env android/key.properties @@ -25,4 +27,4 @@ backend/ .fvm/ .fvmrc /eatvio -*.code-workspace \ No newline at end of file +*.code-workspace diff --git a/analysis_options.yaml b/analysis_options.yaml index 63d4f990..c4ab75c5 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -2,9 +2,9 @@ include: package:flutter_lints/flutter.yaml linter: rules: - prefer_const_constructors: true - prefer_const_declarations: true - prefer_const_literals_to_create_immutables: true + prefer_const_constructors: true + prefer_const_declarations: true + prefer_const_literals_to_create_immutables: true analyzer: exclude: @@ -13,36 +13,8 @@ analyzer: - '**/messages_all.dart' - '**/messages_en.dart' - '**/messages_ru.dart' + - build/** + - android/** + - ios/** errors: invalid_annotation_target: ignore - plugins: - - dart_code_metrics - -dart_code_metrics: - extends: - - package:dart_code_metrics_presets/flutter_all.yaml - - package:dart_code_metrics_presets/bloc.yaml - metrics: - cyclomatic-complexity: 20 - lines-of-executable-code: 50 - number-of-parameters: 4 - maximum-nesting-level: 5 - metrics-exclude: - - test/** -# extends: -# - recommended -# anti-patterns: -# - long-method -# - long-parameter-list -# metrics: -# cyclomatic-complexity: 20 -# lines-of-executable-code: 50 -# number-of-parameters: 4 -# maximum-nesting-level: 5 -# metrics-exclude: -# - test/** -# - newline-before-return -# - no-boolean-literal-compare -# - no-empty-block -# - prefer-conditional-expressions -# - no-equal-then-else diff --git a/android/app/build.gradle b/android/app/build.gradle index 569cd689..afec45b2 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -22,6 +22,13 @@ android { compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion + // Flutter 3.50 + AGP drops assets matching default ignoreAssetsPattern + // (files starting with '.' like .env, and '_*'-prefixed folders). + // See https://github.com/flutter/flutter/issues/196444 + androidResources { + ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~" + } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c2b6f6e2..aaeef03e 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -8,7 +8,13 @@ - + + @@ -16,7 +22,8 @@ android:label="Итвио" android:usesCleartextTraffic="true" android:name="${applicationName}" - android:icon="@mipmap/ic_launcher"> + android:icon="@mipmap/ic_launcher" + android:requestLegacyExternalStorage="true"> diff --git a/android/build.gradle b/android/build.gradle index af06c34c..9193d17f 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -2,11 +2,14 @@ buildscript { repositories { google() mavenCentral() - maven {url 'https://developer.huawei.com/repo/'} + maven { + url = 'https://repo.huaweicloud.com/repository/maven/' + content { includeGroupByRegex 'com\\.huawei.*' } + } gradlePluginPortal() } dependencies { - classpath 'com.android.tools.build:gradle:8.12.0' + classpath 'com.android.tools.build:gradle:9.3.1' classpath 'com.huawei.agconnect:agcp:1.9.1.301' } } @@ -15,7 +18,10 @@ allprojects { repositories { google() mavenCentral() - maven {url 'https://developer.huawei.com/repo/'} + maven { + url = 'https://repo.huaweicloud.com/repository/maven/' + content { includeGroupByRegex 'com\\.huawei.*' } + } } } @@ -53,6 +59,40 @@ subprojects { Project subproject -> } } +// AGP 9 lint crashes in CommentDetector with NoSuchMethodError List.removeLast() +// (image_picker_android:lintVitalAnalyzeRelease). That check is fatal for release. +subprojects { Project subproject -> + subproject.tasks.configureEach { task -> + if (task.name.startsWith("lintVital")) { + task.enabled = false + } + } +} + +// AGP 9 enforces AAR metadata: plugins that still declare compileSdk 31 fail the build. +subprojects { Project subproject -> + def bumpCompileSdk = { + if (!subproject.plugins.hasPlugin('com.android.library')) { + return + } + def androidExt = subproject.extensions.findByName('android') + if (androidExt == null) { + return + } + try { + androidExt.compileSdk = 36 + } catch (Throwable t) { + subproject.logger.warn("[compileSdk-fix] Failed for ${subproject.path}: ${t.message}") + } + } + // evaluationDependsOn(":app") can leave some projects already evaluated. + if (subproject.state.executed) { + bumpCompileSdk() + } else { + subproject.afterEvaluate { bumpCompileSdk() } + } +} + tasks.register("clean", Delete) { delete rootProject.buildDir } diff --git a/android/gradle.properties b/android/gradle.properties index f018a618..8dcb8ead 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,3 +1,11 @@ org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +systemProp.org.gradle.internal.http.connectionTimeout=60000 +systemProp.org.gradle.internal.http.socketTimeout=120000 +systemProp.org.gradle.internal.repository.max.retries=5 +systemProp.org.gradle.internal.repository.initial.backoff=2000 android.useAndroidX=true android.enableJetifier=true +# This builtInKotlin flag was added automatically by Flutter migrator +android.builtInKotlin=false +# This newDsl flag was added automatically by Flutter migrator +android.newDsl=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index e603bd33..76d4386d 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip diff --git a/android/settings.gradle b/android/settings.gradle index 76846d0d..96b9b6d6 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -12,18 +12,21 @@ pluginManagement { repositories { google() mavenCentral() - maven { url 'https://developer.huawei.com/repo/' } + maven { + url = 'https://repo.huaweicloud.com/repository/maven/' + content { includeGroupByRegex 'com\\.huawei.*' } + } gradlePluginPortal() } } plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.12.0" apply false + id "com.android.application" version "9.3.1" apply false // START: FlutterFire Configuration id "com.google.gms.google-services" version "4.4.3" apply false // END: FlutterFire Configuration - id "org.jetbrains.kotlin.android" version "2.2.10" apply false + id "org.jetbrains.kotlin.android" version "2.4.20" apply false } include ":app" diff --git a/integration_test/create_recipe/create_recipe_helpers.dart b/integration_test/create_recipe/create_recipe_helpers.dart index 3a7dbb3e..3dcc4115 100644 --- a/integration_test/create_recipe/create_recipe_helpers.dart +++ b/integration_test/create_recipe/create_recipe_helpers.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity.dart'; import 'package:eatvio_app/features/create_recipe/presentation/pages/recipe_create_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; /// Helper функции для интеграционных тестов создания рецепта diff --git a/ios/.gitignore b/ios/.gitignore index e96ef602..61fa3c45 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -22,6 +22,7 @@ Flutter/app.flx Flutter/app.zip Flutter/flutter_assets/ Flutter/flutter_export_environment.sh +Flutter/ephemeral/ ServiceDefinitions.json Runner/GeneratedPluginRegistrant.* diff --git a/ios/Podfile b/ios/Podfile index 217b4ecc..ffecb8c6 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -38,19 +38,34 @@ post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| - config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64" - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '16.0' - config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [ - '$(inherited)', + # iOS 26+ Apple Silicon simulators require arm64. Do not exclude it. + excluded = config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] + if excluded.is_a?(String) + cleaned = excluded.split(/\s+/).reject { |arch| arch == 'arm64' }.join(' ') + if cleaned.empty? + config.build_settings.delete('EXCLUDED_ARCHS[sdk=iphonesimulator*]') + else + config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = cleaned + end + end + + # Old plugins (e.g. flutter_keyboard_visibility) pin simulator to x86_64 only. + valid_archs = config.build_settings['VALID_ARCHS[sdk=iphonesimulator*]'] + if valid_archs == 'x86_64' + config.build_settings['VALID_ARCHS[sdk=iphonesimulator*]'] = '$(ARCHS_STANDARD)' + end + + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '16.0' + config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [ + '$(inherited)', ## dart: PermissionGroup.camera 'PERMISSION_CAMERA=1', ## dart: PermissionGroup.microphone 'PERMISSION_MICROPHONE=1', ## dart: PermissionGroup.photos - 'PERMISSION_PHOTOS=1', + 'PERMISSION_PHOTOS=1', 'PERMISSION_NOTIFICATIONS=1', ] - end end end diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 76a8087f..48f00256 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; ACF3142BB74D6F5F3C98AD82 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = EB9FE5381C3F532BD9A9456D /* GoogleService-Info.plist */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -54,6 +55,7 @@ DF0C4038A57E19D3ABA03C15 /* 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 = ""; }; EB9FE5381C3F532BD9A9456D /* GoogleService-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = "GoogleService-Info.plist"; path = "Runner/GoogleService-Info.plist"; sourceTree = ""; }; FEE92A0E2D772EA300E6E989 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -61,6 +63,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, 46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -81,6 +84,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -139,6 +143,9 @@ /* Begin PBXNativeTarget section */ 97C146ED1CF9000F007C117D /* Runner */ = { + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( @@ -165,6 +172,9 @@ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); isa = PBXProject; attributes = { BuildIndependentTargetsInParallel = YES; @@ -639,6 +649,18 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..ae0588ef --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,221 @@ +{ + "pins" : [ + { + "identity" : "abseil-cpp-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/abseil-cpp-binary.git", + "state" : { + "revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5", + "version" : "1.2024072200.0" + } + }, + { + "identity" : "app-check", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/app-check.git", + "state" : { + "revision" : "97f7d74dd0e8f3d0fe5fc75cc8957aa73bdc948a", + "version" : "11.3.2" + } + }, + { + "identity" : "appmetrica-sdk-ios", + "kind" : "remoteSourceControl", + "location" : "https://github.com/appmetrica/appmetrica-sdk-ios", + "state" : { + "revision" : "ed6c1a73eb2dae875a0d7801390eb6f0ee7bc12e", + "version" : "5.16.1" + } + }, + { + "identity" : "cryptoswift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/krzyzanowskim/CryptoSwift.git", + "state" : { + "revision" : "f2a627b84c1ff96f21ac2fcb623ab36142dd5512", + "version" : "1.10.0" + } + }, + { + "identity" : "dkcamera", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKCamera", + "state" : { + "branch" : "master", + "revision" : "5c691d11014b910aff69f960475d70e65d9dcc96" + } + }, + { + "identity" : "dkimagepickercontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKImagePickerController", + "state" : { + "branch" : "4.3.9", + "revision" : "0bdfeacefa308545adde07bef86e349186335915" + } + }, + { + "identity" : "dkphotogallery", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKPhotoGallery", + "state" : { + "branch" : "master", + "revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d" + } + }, + { + "identity" : "firebase-ios-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/firebase-ios-sdk", + "state" : { + "revision" : "42e81d245e30e49ea6a5830cf2842d44a1591270", + "version" : "12.15.0" + } + }, + { + "identity" : "google-ads-on-device-conversion-ios-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk", + "state" : { + "revision" : "dc39082d8881109d35b94b1c122164c0e8d08a55", + "version" : "3.6.1" + } + }, + { + "identity" : "googleappmeasurement", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleAppMeasurement.git", + "state" : { + "revision" : "144855f40d8668927f256a3045f7fdc4c3f4338b", + "version" : "12.15.0" + } + }, + { + "identity" : "googledatatransport", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleDataTransport.git", + "state" : { + "revision" : "ba3358d3c3dbae8ef230b58a46b97ad65e84e974", + "version" : "10.1.1" + } + }, + { + "identity" : "googleutilities", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleUtilities.git", + "state" : { + "revision" : "5459ee5603def3db0fe14ca522185f42c48d978e", + "version" : "8.1.5" + } + }, + { + "identity" : "grpc-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/grpc-binary.git", + "state" : { + "revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6", + "version" : "1.69.1" + } + }, + { + "identity" : "gtm-session-fetcher", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/gtm-session-fetcher.git", + "state" : { + "revision" : "724a52eea6329b7e12d3ad8300d76ca9f3895fcc", + "version" : "5.3.1" + } + }, + { + "identity" : "interop-ios-for-google-sdks", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/interop-ios-for-google-sdks.git", + "state" : { + "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe", + "version" : "101.0.0" + } + }, + { + "identity" : "kscrash", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kstenerud/KSCrash", + "state" : { + "revision" : "c0177658fc771ae833b6d3b8f5f3f5a14d59ec03", + "version" : "2.1.2" + } + }, + { + "identity" : "leveldb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/leveldb.git", + "state" : { + "revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1", + "version" : "1.22.5" + } + }, + { + "identity" : "nanopb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/nanopb.git", + "state" : { + "revision" : "3851d94a41890dea16dc3db34caf60e585cb4163", + "version" : "2.30910.1" + } + }, + { + "identity" : "promises", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/promises.git", + "state" : { + "revision" : "f4a19a3c313dc2616c70bb49d29a799fb16be837", + "version" : "2.4.1" + } + }, + { + "identity" : "sdwebimage", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SDWebImage/SDWebImage", + "state" : { + "revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0", + "version" : "5.21.7" + } + }, + { + "identity" : "sentry-cocoa", + "kind" : "remoteSourceControl", + "location" : "https://github.com/getsentry/sentry-cocoa", + "state" : { + "revision" : "9e193ac0b71760603aa666bad7e9e303dd7031a8", + "version" : "8.56.2" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "88754449ab766a739610b660e117762115fabc9c", + "version" : "1.7.6" + } + }, + { + "identity" : "swiftygif", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kirualex/SwiftyGif.git", + "state" : { + "revision" : "4430cbc148baa3907651d40562d96325426f409a", + "version" : "5.4.5" + } + }, + { + "identity" : "tocropviewcontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/TimOliver/TOCropViewController", + "state" : { + "revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e", + "version" : "2.8.0" + } + } + ], + "version" : 2 +} diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 1a6f2553..078f9dc2 100644 --- a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -5,6 +5,24 @@ + + + + + + + + + + pendingAcceptedCallTtl { + UserDefaults.standard.removeObject(forKey: pendingAcceptedVoipCallKey) return } - - recordVoipDiagnostic( - "accepted_call_open_app_requested", - data: [ - "callKitId": call.data.uuid, - "conversationUuid": conversationUuid, - "url": url.absoluteString, - "appState": UIApplication.shared.applicationState.rawValue, - ] - ) - - bringAppToForeground() - - UIApplication.shared.open(url, options: [:]) { [weak self] success in - self?.recordVoipDiagnostic( - success ? "accepted_call_open_app_succeeded" : "accepted_call_open_app_failed", - data: [ - "callKitId": call.data.uuid, - "conversationUuid": conversationUuid, - "url": url.absoluteString, - ] - ) - } + voipDiagnosticsChannel?.invokeMethod("acceptedVoipCall", arguments: payload) } private func sanitizedDiagnosticValue(_ value: Any?) -> Any { @@ -1177,6 +1125,8 @@ import flutter_foreground_task // activation and can start I/O before didActivate. prepareAvAudioSessionCategory() storePendingAcceptedCall(call) + let extra = call.data.extra as? [String: Any] ?? [:] + VideoCallDeclineClient.sendAccept(extra: extra, handle: call.data.handle) recordVoipDiagnostic( "callkit_accept_native", data: [ @@ -1185,11 +1135,7 @@ import flutter_foreground_task "data": call.data.toJSON(), ] ) - voipDiagnosticsChannel?.invokeMethod("acceptedVoipCall", arguments: call.data.toJSON()) - DispatchQueue.main.async { [weak self] in - self?.bringAppToForeground() - self?.openAppForAcceptedCall(call) - } + deliverStoredAcceptedCall() action.fulfill() } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 10a72b1c..edac8adf 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -24,6 +24,10 @@ $(FLUTTER_BUILD_NUMBER) ITSAppUsesNonExemptEncryption + LSSupportsOpeningDocumentsInPlace + + UIFileSharingEnabled + LSRequiresIPhoneOS NSAppTransportSecurity diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift index f27a5751..fd717aed 100644 --- a/ios/Runner/SceneDelegate.swift +++ b/ios/Runner/SceneDelegate.swift @@ -19,6 +19,10 @@ class SceneDelegate: FlutterSceneDelegate { override func sceneDidBecomeActive(_ scene: UIScene) { super.sceneDidBecomeActive(scene) registerCallChannels() + guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { + return + } + appDelegate.deliverStoredAcceptedCall() } override func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { diff --git a/ios/Runner/VideoCallDeclineClient.swift b/ios/Runner/VideoCallDeclineClient.swift index fb24ce50..2e3a20d7 100644 --- a/ios/Runner/VideoCallDeclineClient.swift +++ b/ios/Runner/VideoCallDeclineClient.swift @@ -8,25 +8,37 @@ enum VideoCallDeclineClient { /// `POST /video-call/decline` from the CallKit callback. The process is /// awake here even when the user never opens the app afterwards. static func send(extra: [String: Any], handle: String) { + post(action: "decline", extra: extra, handle: handle) + } + + /// `POST /video-call/accept` from the CallKit answer callback. Flutter may + /// still be frozen on the splash snapshot, so the other device must be + /// told from here. A later Dart retry with the same hw_id is idempotent. + static func sendAccept(extra: [String: Any], handle: String) { + post(action: "accept", extra: extra, handle: handle) + } + + private static func post(action: String, extra: [String: Any], handle: String) { let fields = declineFields(extra: extra, handle: handle) guard let request = makeRequest( baseUrl: prefsString("apiBaseUrl") ?? prefsString("customBaseUrl"), token: prefsString("token"), hwId: UIDevice.current.identifierForVendor?.uuidString, - fields: fields + fields: fields, + action: action ) else { NSLog( - "[EatvioVoIP] decline POST skipped conversation=\(fields.conversationUuid) ended=\(fields.endedPush)" + "[EatvioVoIP] \(action) POST skipped conversation=\(fields.conversationUuid) ended=\(fields.endedPush)" ) return } let task = EatvioBackgroundTask() - task.begin(name: "video-call-decline") + task.begin(name: "video-call-\(action)") let urlTask = URLSession.shared.dataTask(with: request) { _, response, error in let code = (response as? HTTPURLResponse)?.statusCode ?? -1 NSLog( - "[EatvioVoIP] decline POST status=\(code) conversation=\(fields.conversationUuid) error=\(error?.localizedDescription ?? "-")" + "[EatvioVoIP] \(action) POST status=\(code) conversation=\(fields.conversationUuid) error=\(error?.localizedDescription ?? "-")" ) task.end() } @@ -37,7 +49,8 @@ enum VideoCallDeclineClient { baseUrl: String?, token: String?, hwId: String?, - fields: VideoCallDeclineFields + fields: VideoCallDeclineFields, + action: String = "decline" ) -> URLRequest? { if fields.endedPush { return nil } let conversation = fields.conversationUuid.trimmingCharacters(in: .whitespacesAndNewlines) @@ -50,8 +63,9 @@ enum VideoCallDeclineClient { guard !conversation.isEmpty, !authToken.isEmpty else { return nil } guard deviceId.count >= 8, deviceId.count <= 64 else { return nil } guard root.hasPrefix("http://") || root.hasPrefix("https://") else { return nil } + guard action == "accept" || action == "decline" else { return nil } guard let encoded = conversation.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), - let url = URL(string: "\(root)/api/v2/chat/\(encoded)/video-call/decline") + let url = URL(string: "\(root)/api/v2/chat/\(encoded)/video-call/\(action)") else { return nil } var body: [String: String] = ["hw_id": deviceId] diff --git a/ios/fastlane/Fastfile b/ios/fastlane/Fastfile index 904991ee..924075b1 100644 --- a/ios/fastlane/Fastfile +++ b/ios/fastlane/Fastfile @@ -43,37 +43,95 @@ platform :ios do end UI.message "Using auth_key_path: #{auth_key_path}" - + + # Authenticate to App Store Connect early: + # needed here by latest_testflight_build_number, not only by upload_to_testflight. + app_store_connect_api_key( + key_id: "325JS9JCZH", + issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3", + key_filepath: auth_key_path, + duration: 1200, + in_house: false + ) + # Configure Flutter for release mode UI.message "Configuring Flutter for release mode..." sh("cd .. && flutter build ios --config-only --release") - # Read build number from Flutter Generated.xcconfig + # Read version and build number from Flutter Generated.xcconfig. + # They are only a floor: the actual build number is derived from TestFlight below, + # so repeated CI runs on the same commit can never hit + # ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE ("bundle version must be higher"). generated_xcconfig_path = File.join("..", "Flutter", "Generated.xcconfig") + flutter_build_name = nil flutter_build_number = nil - + if File.exist?(generated_xcconfig_path) File.foreach(generated_xcconfig_path) do |line| - matches = line.match(/FLUTTER_BUILD_NUMBER=(.*)/) - if matches - flutter_build_number = matches[1].strip - break + if (m = line.match(/FLUTTER_BUILD_NAME=(.*)/)) + flutter_build_name = m[1].strip + elsif (m = line.match(/FLUTTER_BUILD_NUMBER=(.*)/)) + flutter_build_number = m[1].strip end end end - - if flutter_build_number.nil? - UI.user_error!("Could not find FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}") + + if flutter_build_name.nil? || flutter_build_number.nil? + UI.user_error!("Could not find FLUTTER_BUILD_NAME/FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}") end - - UI.message "Flutter build number: #{flutter_build_number}" - + + UI.message "Flutter version from pubspec: #{flutter_build_name} (#{flutter_build_number})" + + # Apple closes a version train once that version is approved/released. + # Uploading into a closed train wastes a full ~8 min build and fails only + # at the upload step with altool 90186 ("closed for new build submissions") + # / 90062 ("must be higher than the previously approved version"). + # Fail fast here, before building. + closed_train_states = [ + Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_DISTRIBUTION, + Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PROCESSING_FOR_DISTRIBUTION, + Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_DEVELOPER_RELEASE, + Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_APPLE_RELEASE + ].join(",") + asc_app = Spaceship::ConnectAPI::App.find("com.eatvioapp.app") + closed_train = nil + if asc_app.nil? + UI.important("App com.eatvioapp.app not found in App Store Connect, skipping closed-train guard") + else + closed_train = asc_app.get_app_store_versions( + filter: { + appVersionState: closed_train_states, + platform: Spaceship::ConnectAPI::Platform::IOS + } + ).find do |v| + (Gem::Version.new(v.version_string) >= Gem::Version.new(flutter_build_name)) + rescue ArgumentError + false + end + end + if closed_train + UI.user_error!( + "Version train #{closed_train.version_string} is closed for new submissions " \ + "(#{closed_train.app_version_state}), pubspec version is #{flutter_build_name}. " \ + "Bump the version in pubspec.yaml above #{closed_train.version_string} and re-run." + ) + end + + asc_latest_build_number = latest_testflight_build_number( + app_identifier: "com.eatvioapp.app", + version: flutter_build_name, + initial_build_number: flutter_build_number.to_i + ) + + new_build_number = [flutter_build_number.to_i, asc_latest_build_number].max + 1 + UI.message "Latest TestFlight build number: #{asc_latest_build_number} -> uploading build #{new_build_number}" + match(type: "appstore", readonly: true) - + # Set build number explicitly instead of incrementing increment_build_number( xcodeproj: "Runner.xcodeproj", - build_number: flutter_build_number + build_number: new_build_number ) update_code_signing_settings( @@ -93,28 +151,33 @@ platform :ios do export_team_id: "VL68C36HYS" ) - app_store_connect_api_key( - key_id: "325JS9JCZH", - issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3", - key_filepath: auth_key_path, - duration: 1200, - in_house: false - ) - - begin upload_to_testflight( skip_waiting_for_build_processing: true, skip_submission: true, distribute_external: false, notify_external_testers: false, - changelog: "TestFlight build #{flutter_build_number}", + changelog: "TestFlight build #{new_build_number}", verbose: true ) rescue => ex - UI.error "Upload to TestFlight failed: #{ex.message}" - UI.error "Full error: #{ex.backtrace.join("\n")}" - raise ex + # Xcode 26 altool prints a harmless "ERROR: ... CDUploaderStateInfoResumeFilePath" + # line even when the package was delivered fine (UPLOAD SUCCEEDED appears in the + # same output). fastlane < 2.240.0 treats every ERROR line as a failure + # (fastlane#30130), so the lane would die after a successful upload. + # Real Apple rejections (90186 closed train, 90062 version too low, ...) always + # contain UPLOAD FAILED and/or iris-code - those must still fail the lane. + if ex.message.include?("CDUploaderStateInfoResumeFilePath") && + !ex.message.include?("UPLOAD FAILED") && + !ex.message.include?("iris-code") + UI.important("altool delivered the package but reported a bogus resume-file ERROR " \ + "(fastlane#30130). Treating upload as successful - " \ + "verify the build appears in TestFlight.") + else + UI.error "Upload to TestFlight failed: #{ex.message}" + UI.error "Full error: #{ex.backtrace.join("\n")}" + raise ex + end end end end diff --git a/lib/app_keys.dart b/lib/app_keys.dart index 912dab9b..2a69b798 100644 --- a/lib/app_keys.dart +++ b/lib/app_keys.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AppKeys { // Auth Screen diff --git a/lib/common/widgets/markdown_editor.dart b/lib/common/widgets/markdown_editor.dart index 551f1449..145a43db 100644 --- a/lib/common/widgets/markdown_editor.dart +++ b/lib/common/widgets/markdown_editor.dart @@ -1,5 +1,5 @@ import 'dart:async'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; diff --git a/lib/core/app_config.dart b/lib/core/app_config.dart index 921adaf5..f4197e07 100644 --- a/lib/core/app_config.dart +++ b/lib/core/app_config.dart @@ -15,9 +15,8 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cub import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; /// Конфигурация приложения class AppConfig { @@ -33,6 +32,20 @@ class AppConfig { late String _baseUrl; String get baseUrl => _baseUrl; + /// Продуктовые хосты API. Сравнение по хосту целиком: поддомены + /// (например `*-hasan.eatvio.ru`) — это стенды разработки, не прод. + static const List prodApiHosts = ['eatvio.ru', 'eatvio.com']; + + /// Текущий base URL указывает на продуктовый API? + bool get isProdApi { + final host = Uri.tryParse(baseUrl)?.host.toLowerCase() ?? ''; + if (host.isEmpty) return false; + return prodApiHosts.any((prodHost) => host == prodHost || host == 'www.$prodHost'); + } + + /// Работаем на стенде разработки/stage (не на продуктовом API)? + bool get isDevOrStageStand => !isProdApi; + void setBaseUrl(String baseUrls) { _baseUrl = baseUrls; _persistBaseUrl(baseUrls); @@ -83,12 +96,7 @@ class AppConfig { ]; /// Делегаты локализации - List get localizationDelegates => [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ]; + List get localizationDelegates => [S.delegate, ...GlobalMaterialLocalizations.delegates]; /// Поддерживаемые локали List get supportedLocales => [ diff --git a/lib/core/app_router.dart b/lib/core/app_router.dart index 9b6f9610..14701394 100644 --- a/lib/core/app_router.dart +++ b/lib/core/app_router.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/core/routing/route_constants.dart'; import 'package:eatvio_app/core/routing/settings_routes.dart'; import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/core/comments/presentation/comments_actions_bottom_sheet.dart b/lib/core/comments/presentation/comments_actions_bottom_sheet.dart index c4f3e540..4d8aaec7 100644 --- a/lib/core/comments/presentation/comments_actions_bottom_sheet.dart +++ b/lib/core/comments/presentation/comments_actions_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; void showCommentsActionsBottomSheet( diff --git a/lib/core/di/cubit_registrations.dart b/lib/core/di/cubit_registrations.dart index e58aa77c..92ba8925 100644 --- a/lib/core/di/cubit_registrations.dart +++ b/lib/core/di/cubit_registrations.dart @@ -42,7 +42,8 @@ import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_cubit.dart'; -import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' as profile_plans; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' + as profile_plans; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart'; @@ -54,6 +55,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart'; import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart'; import 'package:get_it/get_it.dart'; @@ -70,69 +72,174 @@ class CubitRegistrations { /// Регистрация Cubit'ов как синглтонов static void _registerSingletonCubits() { sl.registerLazySingleton(() => NewMessagesCubit()); - sl.registerLazySingleton(() => NotificationsCubit(wsManager: sl(), notificationsRepository: sl())); - sl.registerLazySingleton(() => ProfileAvatarCubit(profileRepository: sl())); - sl.registerLazySingleton(() => ChatsCubit(chatRepository: sl(), wsManager: sl(), profileRepository: sl())); - sl.registerLazySingleton(() => InternetConnectionCubit()); - sl.registerLazySingleton( - () => VideoCallManager( - videoCallRepository: sl(), + sl.registerLazySingleton( + () => NotificationsCubit(wsManager: sl(), notificationsRepository: sl()), + ); + sl.registerLazySingleton( + () => ProfileAvatarCubit(profileRepository: sl()), + ); + sl.registerLazySingleton( + () => ChatsCubit( + chatRepository: sl(), + wsManager: sl(), profileRepository: sl(), ), ); + sl.registerLazySingleton( + () => InternetConnectionCubit(), + ); + sl.registerLazySingleton( + () => + VideoCallManager(videoCallRepository: sl(), profileRepository: sl()), + ); sl.registerLazySingleton( () => VideoCallSessionCubit( videoCallManager: sl(), systemPipCoordinator: sl(), ), ); + sl.registerLazySingleton(() => FeedCubit(feedRepository: sl())); } /// Регистрация Cubit'ов как фабрик static void _registerFactoryCubits() { // Auth related cubits - sl.registerFactory(() => AuthCubit(authRepository: sl(), firebaseApi: sl(), prefs: sl(), profileRepository: sl())); - sl.registerFactory(() => RegistrationCubit(registrationRepository: sl(), prefs: sl())); - sl.registerFactory(() => ResetPasswordCubit(resetPasswordRepository: sl())); - sl.registerFactory(() => VerifyEmailCubit(profileRepository: sl(), prefs: sl())); - sl.registerFactory(() => OAuthCubit(authRepository: sl(), prefs: sl())); - sl.registerFactory(() => RegistrationCubitV2(registrationRepository: sl())); + sl.registerFactory( + () => AuthCubit( + authRepository: sl(), + firebaseApi: sl(), + prefs: sl(), + profileRepository: sl(), + sessionLifecycleService: sl(), + ), + ); + sl.registerFactory( + () => RegistrationCubit( + registrationRepository: sl(), + prefs: sl(), + sessionLifecycleService: sl(), + ), + ); + sl.registerFactory( + () => ResetPasswordCubit(resetPasswordRepository: sl()), + ); + sl.registerFactory( + () => VerifyEmailCubit(profileRepository: sl(), prefs: sl()), + ); + sl.registerFactory( + () => OAuthCubit( + authRepository: sl(), + firebaseApi: sl(), + prefs: sl(), + sessionLifecycleService: sl(), + ), + ); + sl.registerFactory( + () => RegistrationCubitV2( + registrationRepository: sl(), + firebaseApi: sl(), + sessionLifecycleService: sl(), + ), + ); // Feed related cubits - sl.registerFactory(() => FeedCubit(feedRepository: sl())); - sl.registerFactory(() => RecipesCubit(feedRepository: sl(), recipeRepository: sl(), aboutRecipeRepository: sl())); - sl.registerFactory(() => DietsCubit(feedRepository: sl(), dietsRepository: sl())); - sl.registerFactory(() => PlansCubit(feedRepository: sl(), planRepository: sl())); - sl.registerFactory(() => ConsultantsCubit(feedRepository: sl())); - sl.registerFactory(() => CommentsCubit(feedRepository: sl(), commentsRepository: sl())); - sl.registerFactory(() => FeedProfileCubit(profileRepository: sl())); + sl.registerFactory( + () => RecipesCubit( + feedRepository: sl(), + recipeRepository: sl(), + aboutRecipeRepository: sl(), + ), + ); + sl.registerFactory( + () => DietsCubit(feedRepository: sl(), dietsRepository: sl()), + ); + sl.registerFactory( + () => PlansCubit(feedRepository: sl(), planRepository: sl()), + ); + sl.registerFactory( + () => ConsultantsCubit(feedRepository: sl()), + ); + sl.registerFactory( + () => CommentsCubit(feedRepository: sl(), commentsRepository: sl()), + ); + sl.registerFactory( + () => FeedProfileCubit(profileRepository: sl()), + ); // Chat related cubits - sl.registerFactory(() => ChatRoomCubit(cardsRepository: sl(), chatRepository: sl(), wsManager: sl())); + sl.registerFactory( + () => ChatRoomCubit( + cardsRepository: sl(), + chatRepository: sl(), + wsManager: sl(), + ), + ); // Profile related cubits - sl.registerFactory(() => ProfileCubit(profileRepository: sl(), chatRepository: sl(), consultantRepository: sl())); - sl.registerFactory(() => profile_plans.PlansCubit(plansRepository: sl())); + sl.registerFactory( + () => ProfileCubit( + profileRepository: sl(), + chatRepository: sl(), + consultantRepository: sl(), + ), + ); + sl.registerFactory( + () => profile_plans.PlansCubit(plansRepository: sl()), + ); sl.registerFactory(() => SubCubit(profileRepository: sl())); // Content creation cubits - sl.registerFactory(() => CreateDietCubit(profileRepository: sl(), createDietRepository: sl(), glossaryRepository: sl())); - sl.registerFactory(() => CreatePlanCubit(createPlanRepository: sl())); - sl.registerFactory(() => CreateRecipeCubit(recipeRepository: sl(), glossaryRepository: sl())); - sl.registerFactory(() => BlogPostCreateCubit(blogPostRepository: sl())); + sl.registerFactory( + () => CreateDietCubit( + profileRepository: sl(), + createDietRepository: sl(), + glossaryRepository: sl(), + ), + ); + sl.registerFactory( + () => CreatePlanCubit(createPlanRepository: sl()), + ); + sl.registerFactory( + () => CreateRecipeCubit(recipeRepository: sl(), glossaryRepository: sl()), + ); + sl.registerFactory( + () => BlogPostCreateCubit(blogPostRepository: sl()), + ); // Content viewing cubits - sl.registerFactory(() => AboutDietCubit(dietsRepository: sl(), profileRepository: sl())); - sl.registerFactory(() => AboutPlanCubit(planRepository: sl(), profileRepository: sl(), dietRepository: sl())); - sl.registerFactory(() => AboutRecipeCubit(recipeRepository: sl(), profileRepository: sl())); + sl.registerFactory( + () => AboutDietCubit(dietsRepository: sl(), profileRepository: sl()), + ); + sl.registerFactory( + () => AboutPlanCubit( + planRepository: sl(), + profileRepository: sl(), + dietRepository: sl(), + ), + ); + sl.registerFactory( + () => AboutRecipeCubit(recipeRepository: sl(), profileRepository: sl()), + ); sl.registerFactory(() => BlogPostCubit(sl())); // User content cubits - sl.registerFactory(() => MyDietsCubit(myDietsRepository: sl(), createDietRepository: sl())); - sl.registerFactory(() => MyPlansCubit(myPlansRepository: sl())); - sl.registerFactory(() => MyRecipesCubit(myRecipesRepository: sl(), aboutRecipeRepository: sl(), recipeRepository: sl())); + sl.registerFactory( + () => MyDietsCubit(myDietsRepository: sl(), createDietRepository: sl()), + ); + sl.registerFactory( + () => MyPlansCubit(myPlansRepository: sl()), + ); + sl.registerFactory( + () => MyRecipesCubit( + myRecipesRepository: sl(), + aboutRecipeRepository: sl(), + recipeRepository: sl(), + ), + ); // Other feature cubits - sl.registerFactory(() => CalendarCubit(calendarRepository: sl())); + sl.registerFactory( + () => CalendarCubit(calendarRepository: sl()), + ); sl.registerFactory( () => DiaryCubit( chatRepository: sl(), @@ -144,28 +251,77 @@ class CubitRegistrations { ), ); sl.registerFactory( - () => SettingsCubit(profileRepository: sl(), settingsRepository: sl(), consultantRepository: sl(), consultationsRepository: sl()), + () => SettingsCubit( + profileRepository: sl(), + settingsRepository: sl(), + consultantRepository: sl(), + consultationsRepository: sl(), + sessionLifecycleService: sl(), + ), + ); + sl.registerFactory( + () => RegisterConsultantCubit(consultantRepository: sl()), + ); + sl.registerFactory( + () => ComplainingCubit(repository: sl()), + ); + sl.registerFactory( + () => UserCardsCubit(cardsRepository: sl()), + ); + sl.registerFactory( + () => OrderInfoCubit(chatRepository: sl(), profileRepository: sl()), ); - sl.registerFactory(() => RegisterConsultantCubit(consultantRepository: sl())); - sl.registerFactory(() => ComplainingCubit(repository: sl())); - sl.registerFactory(() => UserCardsCubit(cardsRepository: sl())); - sl.registerFactory(() => OrderInfoCubit(chatRepository: sl(), profileRepository: sl())); sl.registerFactory( - () => ConsultationPaymentCubit(paymentRepository: sl(), sbpRepository: sl()), + () => ConsultationPaymentCubit( + paymentRepository: sl(), + sbpRepository: sl(), + ), + ); + sl.registerFactory( + () => ConsultationsCubit(consultationsRepository: sl(), chatRepository: sl()), + ); + sl.registerFactory( + () => ConsultantCommentsCubit(diaryRepository: sl()), + ); + sl.registerFactory( + () => CancelPlanCubit(cancelPlanRepository: sl()), + ); + sl.registerFactory( + () => ConsultationsArchiveCubit(consultationsRepository: sl()), + ); + sl.registerFactory( + () => ConsultantFinancesCubit(consultationsRepository: sl()), + ); + sl.registerFactory( + () => UserPurchasesCubit(consultationsRepository: sl()), + ); + sl.registerFactory( + () => BlockedUsersCubit(blockedUsersRepository: sl()), + ); + sl.registerFactory( + () => NotificationSettingsCubit(notificationSettingsRepository: sl()), + ); + sl.registerFactory( + () => ConsultantRatingCubit( + feedRepository: sl(), + repository: sl(), + profileRepository: sl(), + ), ); - sl.registerFactory(() => ConsultationsCubit(consultationsRepository: sl())); - sl.registerFactory(() => ConsultantCommentsCubit(diaryRepository: sl())); - sl.registerFactory(() => CancelPlanCubit(cancelPlanRepository: sl())); - sl.registerFactory(() => ConsultationsArchiveCubit(consultationsRepository: sl())); - sl.registerFactory(() => ConsultantFinancesCubit(consultationsRepository: sl())); - sl.registerFactory(() => UserPurchasesCubit(consultationsRepository: sl())); - sl.registerFactory(() => BlockedUsersCubit(blockedUsersRepository: sl())); - sl.registerFactory(() => NotificationSettingsCubit(notificationSettingsRepository: sl())); - sl.registerFactory(() => ConsultantRatingCubit(feedRepository: sl(), repository: sl(), profileRepository: sl())); sl.registerFactory(() => ViewsCubit(viewsRepository: sl())); - sl.registerFactory(() => UserDetailsCubit(profileRepository: sl())); - sl.registerFactory(() => MenuCubit(sl())); + sl.registerFactory( + () => UserDetailsCubit(profileRepository: sl()), + ); + sl.registerFactory(() => MenuCubit(sl(), sl())); sl.registerFactory(() => MarketingCubit(sl())); - sl.registerFactory(() => PersonalDietSuggestionCubit(dietRepository: sl(), personalDietSuggestionService: sl())); + sl.registerFactory( + () => PersonalDietSuggestionCubit( + dietRepository: sl(), + personalDietSuggestionService: sl(), + ), + ); + sl.registerFactory( + () => VideoCallRecordingsCubit(repository: sl()), + ); } } diff --git a/lib/core/di/repository_registrations.dart b/lib/core/di/repository_registrations.dart index bb260432..545d009f 100644 --- a/lib/core/di/repository_registrations.dart +++ b/lib/core/di/repository_registrations.dart @@ -18,6 +18,7 @@ import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; import 'package:eatvio_app/features/barcode/repositories/barcode_repository.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; import 'package:eatvio_app/features/menu/presentation/repositories/blocked_users_repository.dart'; import 'package:eatvio_app/features/menu/repositories/notification_settings_repository.dart'; import 'package:eatvio_app/features/my_diets/repositories/my_diets_repository.dart'; @@ -35,6 +36,7 @@ import 'package:eatvio_app/features/recipe/repositories/my_recipes_repository.da import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart'; import 'package:get_it/get_it.dart'; @@ -53,8 +55,15 @@ class RepositoryRegistrations { // Core repositories sl.registerLazySingleton(() => ChatRepository(chatService: sl())); sl.registerLazySingleton(() => VideoCallRepository(videoCallService: sl())); + sl.registerLazySingleton( + () => VideoCallRecordingsRepository( + videoCallService: sl(), + fileService: sl(), + ), + ); sl.registerLazySingleton(() => FeedRepository(feedService: sl())); sl.registerLazySingleton(() => ProfileRepository(profileService: sl())); + sl.registerLazySingleton(() => InsightsRepository(profileRepository: sl(), insightsService: sl())); sl.registerLazySingleton(() => CalendarRepository(calendarService: sl())); sl.registerLazySingleton(() => SettingsRepository(settingsService: sl())); sl.registerLazySingleton(() => ConsultantRepository(consultantService: sl())); diff --git a/lib/core/di/service_registrations.dart b/lib/core/di/service_registrations.dart index 27152661..abddd8eb 100644 --- a/lib/core/di/service_registrations.dart +++ b/lib/core/di/service_registrations.dart @@ -19,6 +19,7 @@ import 'package:eatvio_app/features/diary/services/diary_service.dart'; import 'package:eatvio_app/features/diets/services/diet_service.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; import 'package:eatvio_app/features/glossary/services/glossary_service.dart'; +import 'package:eatvio_app/features/insights/services/insights_service.dart'; import 'package:eatvio_app/features/barcode/services/barcode_service.dart'; import 'package:eatvio_app/features/menu/services/blocked_users_service.dart'; import 'package:eatvio_app/features/menu/services/notification_settings_service.dart'; @@ -36,6 +37,8 @@ import 'package:eatvio_app/features/recipe/services/my_recipes_service.dart'; import 'package:eatvio_app/features/registration/services/registration_service.dart'; import 'package:eatvio_app/features/registration_v2/services/registration_service_v2.dart'; import 'package:eatvio_app/features/settings/services/settings_service.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/public_downloads_saver.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/video_call_recording_file_service.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_callkit_coordinator.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_service.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_system_pip_coordinator.dart'; @@ -55,8 +58,15 @@ class ServiceRegistrations { // Core services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => VideoCallService(sl())); + sl.registerLazySingleton( + () => const PublicDownloadsSaver(), + ); + sl.registerLazySingleton( + () => VideoCallRecordingFileService(dio: sl(), downloadsSaver: sl()), + ); sl.registerLazySingleton(() => FeedService(sl())); sl.registerLazySingleton(() => ProfileService(sl())); + sl.registerLazySingleton(() => InsightsService(sl())); sl.registerLazySingleton(() => CalendarService(sl())); sl.registerLazySingleton(() => SettingsService(sl())); sl.registerLazySingleton(() => ConsultantService(sl())); diff --git a/lib/core/di/session_registrations.dart b/lib/core/di/session_registrations.dart new file mode 100644 index 00000000..04e27f60 --- /dev/null +++ b/lib/core/di/session_registrations.dart @@ -0,0 +1,15 @@ +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; +import 'package:eatvio_app/core/websockets/ws_manager.dart'; + +class SessionRegistrations { + static void registerAll() { + sl.registerLazySingleton( + () => SessionLifecycleService( + wsManager: sl(), + errorReporter: sl(), + ), + ); + } +} diff --git a/lib/core/firebase_api.dart b/lib/core/firebase_api.dart index 19c7cbc7..78e31519 100644 --- a/lib/core/firebase_api.dart +++ b/lib/core/firebase_api.dart @@ -21,10 +21,9 @@ class FirebaseApi { final _firebaseMessaging = FirebaseMessaging.instance; FirebaseApi({ - required ErrorReporter errorReporter, + required this._errorReporter, NotificationPermissionRequester? notificationPermissionRequester, - }) : _errorReporter = errorReporter, - _notificationPermissionRequester = notificationPermissionRequester ?? NotificationPermissionRequester(); + }) : _notificationPermissionRequester = notificationPermissionRequester ?? NotificationPermissionRequester(); Future getToken() async { final credentials = await _resolvePushCredentials(); diff --git a/lib/core/interceptors/token_interceptor.dart b/lib/core/interceptors/token_interceptor.dart index 05f6be0c..2d65d04f 100644 --- a/lib/core/interceptors/token_interceptor.dart +++ b/lib/core/interceptors/token_interceptor.dart @@ -1,9 +1,7 @@ import 'package:dio/dio.dart'; -import 'package:eatvio_app/core/app_router.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; import 'package:eatvio_app/core/locator_service.dart'; -import 'package:go_router/go_router.dart'; class TokenInterceptor extends Interceptor { @override @@ -14,6 +12,7 @@ class TokenInterceptor extends Interceptor { final token = await TokenStorage.getTokenFromStorage(); if (token != null && token.isNotEmpty) { options.headers['Authorization'] = 'Bearer $token'; + options.extra['authToken'] = token; } super.onRequest(options, handler); @@ -25,9 +24,18 @@ class TokenInterceptor extends Interceptor { ErrorInterceptorHandler handler, ) async { if (err.response?.statusCode == 401) { - await sl().clear(); - await TokenStorage.removeTokenInStorage(); - AppRouter.navigatorKey.currentContext?.go('/auth-screen'); + final requestCarriedAuth = err.requestOptions.headers.containsKey( + 'Authorization', + ); + final requestToken = err.requestOptions.extra['authToken']; + final currentToken = await TokenStorage.getTokenFromStorage(); + if (requestCarriedAuth && + requestToken != null && + requestToken == currentToken) { + await sl().endSession( + reason: SessionEndReason.unauthorized, + ); + } } super.onError(err, handler); } diff --git a/lib/core/internet_connection_cubit/internet_connection_cubit.dart b/lib/core/internet_connection_cubit/internet_connection_cubit.dart index ef77c185..98da1724 100644 --- a/lib/core/internet_connection_cubit/internet_connection_cubit.dart +++ b/lib/core/internet_connection_cubit/internet_connection_cubit.dart @@ -5,7 +5,7 @@ import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:eatvio_app/core/env_config.dart'; import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_state.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/error_reporting/report_from.dart'; diff --git a/lib/core/locator_service.dart b/lib/core/locator_service.dart index cb2e63cc..46128cd3 100644 --- a/lib/core/locator_service.dart +++ b/lib/core/locator_service.dart @@ -5,6 +5,7 @@ import 'package:eatvio_app/core/di/cubit_registrations.dart'; import 'package:eatvio_app/core/di/external_registrations.dart'; import 'package:eatvio_app/core/di/repository_registrations.dart'; import 'package:eatvio_app/core/di/service_registrations.dart'; +import 'package:eatvio_app/core/di/session_registrations.dart'; import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/websockets/ws_manager.dart'; import 'package:get_it/get_it.dart'; @@ -38,4 +39,6 @@ Future init({required AppBuildType buildType}) async { sl.registerLazySingleton( () => WsManager(wsService: sl(), errorReporter: sl()), ); + + SessionRegistrations.registerAll(); } diff --git a/lib/core/permission_handler/permission_handler.dart b/lib/core/permission_handler/permission_handler.dart index f107c2c0..ece8c9c3 100644 --- a/lib/core/permission_handler/permission_handler.dart +++ b/lib/core/permission_handler/permission_handler.dart @@ -2,7 +2,7 @@ import 'dart:io'; import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:permission_handler/permission_handler.dart'; class PermissionHandler { diff --git a/lib/core/routing/main_navigation_routes.dart b/lib/core/routing/main_navigation_routes.dart index d0746c88..67e20fc1 100644 --- a/lib/core/routing/main_navigation_routes.dart +++ b/lib/core/routing/main_navigation_routes.dart @@ -1,6 +1,5 @@ import 'package:eatvio_app/core/routing/route_constants.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; -import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart'; @@ -12,7 +11,7 @@ import 'package:eatvio_app/features/notifications/presentation/notifications_scr import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/websockets/ws_manager.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'dart:developer'; @@ -24,14 +23,10 @@ class MainNavigationRoutes { return [ ShellRoute( builder: (context, state, child) { - // Инициализация ProfileAvatarCubit при первом использовании ShellRoute final profileAvatarCubit = context.read(); - if (profileAvatarCubit.state is ProfileAvatarStateLoading) { - // Вызываем getMyProfile() только если состояние loading (первый запуск) - WidgetsBinding.instance.addPostFrameCallback((_) { - profileAvatarCubit.getMyProfile(); - }); - } + WidgetsBinding.instance.addPostFrameCallback((_) { + profileAvatarCubit.ensureFreshForCurrentSession(); + }); return _MainShellWithNavScope(currentLocation: state.matchedLocation, child: child); }, diff --git a/lib/core/routing/other_routes.dart b/lib/core/routing/other_routes.dart index 96f5f2cb..f07247dd 100644 --- a/lib/core/routing/other_routes.dart +++ b/lib/core/routing/other_routes.dart @@ -16,6 +16,9 @@ import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart' import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart'; @@ -140,6 +143,18 @@ class OtherRoutes { GoRoute(path: ConsultationsArchiveScreen.path, name: ConsultationsArchiveScreen.name, builder: (context, state) => const ConsultationsArchiveScreen()), GoRoute(path: ConsultantFinancesScreen.path, name: ConsultantFinancesScreen.name, builder: (context, state) => const ConsultantFinancesScreen()), GoRoute(path: UserPurchasesScreen.path, name: UserPurchasesScreen.name, builder: (context, state) => const UserPurchasesScreen()), + GoRoute( + path: VideoCallRecordingsScreen.path, + name: VideoCallRecordingsScreen.name, + builder: (context, state) => const VideoCallRecordingsScreen(), + ), + GoRoute( + path: VideoCallRecordingPlayerScreen.path, + name: VideoCallRecordingPlayerScreen.name, + builder: (context, state) => VideoCallRecordingPlayerScreen( + recording: _videoCallRecordingFromRouteExtra(state.extra), + ), + ), // Finance routes GoRoute(path: RouteConstants.userFinanceScreen, name: 'userFinanceScreen', builder: (context, state) => const UserFinanceScreen()), @@ -192,7 +207,18 @@ class OtherRoutes { return CreatePlanScreen(plan: plan); }, ), - GoRoute(path: MyDietsScreen.path, name: MyDietsScreen.name, builder: (context, state) => const MyDietsScreen()), + GoRoute( + path: MyDietsScreen.path, + name: MyDietsScreen.name, + builder: (context, state) { + final initialTabIndex = int.tryParse( + state.uri.queryParameters['initialTabIndex'] ?? '', + ); + return MyDietsScreen( + initialTabIndex: initialTabIndex ?? 0, + ); + }, + ), GoRoute(path: MyPlansScreen.path, name: MyPlansScreen.name, builder: (context, state) => const MyPlansScreen()), GoRoute(path: MyRecipesScreen.path, name: MyRecipesScreen.name, builder: (context, state) => const MyRecipesScreen()), @@ -354,9 +380,10 @@ class OtherRoutes { path: UserDiaryScreen.path, name: UserDiaryScreen.name, builder: (context, state) { - final data = state.extra as Map; + final data = state.extra as Map; final diaryId = data['diaryId'] as int; - return UserDiaryScreen(diaryId: diaryId); + final ownerSlug = data['ownerSlug'] as String?; + return UserDiaryScreen(diaryId: diaryId, ownerSlug: ownerSlug); }, ), GoRoute( @@ -368,6 +395,17 @@ class OtherRoutes { } } +VideoCallRecordingModel? _videoCallRecordingFromRouteExtra(Object? extra) { + if (extra is! Map) { + return null; + } + try { + return VideoCallRecordingModel.fromJson(Map.from(extra)); + } on Object { + return null; + } +} + VideoCallEntryMode _videoCallEntryModeFromRouteExtra(Object? raw) { if (raw is VideoCallEntryMode) return raw; if (raw == VideoCallEntryMode.incomingAccepted.name) { diff --git a/lib/core/session/session_lifecycle_service.dart b/lib/core/session/session_lifecycle_service.dart new file mode 100644 index 00000000..1d3d83e9 --- /dev/null +++ b/lib/core/session/session_lifecycle_service.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:appmetrica_plugin/appmetrica_plugin.dart'; +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_router.dart'; +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:eatvio_app/core/firebase_api.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:eatvio_app/core/routing/route_constants.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/core/websockets/ws_manager.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; +import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; +import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; +import 'package:go_router/go_router.dart'; + +enum SessionEndReason { logout, unauthorized, accountDeleted } + +class SessionLifecycleService { + SessionLifecycleService({ + required this._wsManager, + required this._errorReporter, + }); + + final WsManager _wsManager; + final ErrorReporter _errorReporter; + + int? _authenticatedFingerprint; + bool _endingSession = false; + + Future endSession({required SessionEndReason reason}) async { + if (_endingSession) return; + _endingSession = true; + try { + await _run(() => _wsManager.clear()); + await _run(TokenStorage.removeTokenInStorage); + await _run(SocketIdStorage.removeSocketIdInStorage); + await _run(() => sl().reset()); + await _run(() => sl().reset()); + await _run(() => sl().reset()); + await _run(() => sl().reset()); + await _run(() => sl().reset()); + await _run(() async => ProfileCubit.clearMyProfileReference()); + await _run(() => sl().endCall()); + await _run(() async => AppMetrica.setUserProfileID(null)); + await _run( + () => sl().remove(PrefsKeys.isEmailVerificationSkipped), + ); + await _run(() => sl().remove(PrefsKeys.registrationDate)); + _authenticatedFingerprint = null; + await _run(() async { + final context = AppRouter.navigatorKey.currentContext; + if (context == null) return; + final path = + AppRouter.appRouter.routeInformationProvider.value.uri.path; + if (path != RouteConstants.authScreen) { + context.go(RouteConstants.authScreen); + } + }); + } finally { + _endingSession = false; + } + } + + Future onAuthenticated() async { + String? token; + try { + token = await TokenStorage.getTokenFromStorage(); + } catch (e, st) { + await _report(e, st); + return; + } + if (token == null || token.isEmpty) return; + final fingerprint = token.hashCode; + if (_authenticatedFingerprint == fingerprint) return; + _authenticatedFingerprint = fingerprint; + + await _run(() async { + await _wsManager.clear(); + await _wsManager.initialize(); + }); + await _run(() => sl().getMyProfile()); + await _run(() => sl().getChatRoomsWithLoading()); + await _run(() => sl().getNotifications()); + await _run(() => sl().registerPushToken()); + } + + Future logout() async { + try { + await _run(() => sl().unregisterPushTokens()); + await _run( + () => sl().post('${sl().baseUrl}/api/profile/logout'), + ); + } finally { + await endSession(reason: SessionEndReason.logout); + } + } + + Future _run(FutureOr Function() action) async { + try { + await action(); + } catch (e, st) { + await _report(e, st); + } + } + + Future _report(Object error, StackTrace stackTrace) { + return _errorReporter.report( + error, + stackTrace, + origin: 'SessionLifecycleService', + ); + } +} diff --git a/lib/core/theme/app_decoration.dart b/lib/core/theme/app_decoration.dart index 0eaf1bb5..3513c2e4 100644 --- a/lib/core/theme/app_decoration.dart +++ b/lib/core/theme/app_decoration.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AppDecoration { // Fill decorations diff --git a/lib/core/theme/custom_button_style.dart b/lib/core/theme/custom_button_style.dart index 50b9d186..ceac006e 100644 --- a/lib/core/theme/custom_button_style.dart +++ b/lib/core/theme/custom_button_style.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// A class that offers pre-defined button styles for customizing button appearance. class CustomButtonStyles { diff --git a/lib/core/theme/custom_text_style.dart b/lib/core/theme/custom_text_style.dart index 1e09ba93..b1eb29d8 100644 --- a/lib/core/theme/custom_text_style.dart +++ b/lib/core/theme/custom_text_style.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// A collection of pre-defined text styles for customizing text appearance, /// categorized by different font families and weights. diff --git a/lib/core/theme/theme_helper.dart b/lib/core/theme/theme_helper.dart index 957ae616..df525351 100644 --- a/lib/core/theme/theme_helper.dart +++ b/lib/core/theme/theme_helper.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; /// Helper class for managing themes and colors. diff --git a/lib/core/utils/pagination_utils.dart b/lib/core/utils/pagination_utils.dart index c6f6da95..4e255784 100644 --- a/lib/core/utils/pagination_utils.dart +++ b/lib/core/utils/pagination_utils.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/const.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; void loadNewContent(ScrollNotification notification, Future Function() load) { if (notification.metrics.pixels >= notification.metrics.maxScrollExtent - thresholdForPagination && !notification.metrics.outOfRange) { diff --git a/lib/core/utils/toasts.dart b/lib/core/utils/toasts.dart index 4683cb86..f0ec89f0 100644 --- a/lib/core/utils/toasts.dart +++ b/lib/core/utils/toasts.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:fluttertoast/fluttertoast.dart'; const int _toastDuration = 2; diff --git a/lib/core/websockets/ws_manager.dart b/lib/core/websockets/ws_manager.dart index 3ba31b8a..a78dcf94 100644 --- a/lib/core/websockets/ws_manager.dart +++ b/lib/core/websockets/ws_manager.dart @@ -17,8 +17,7 @@ class WsManager { final WsService wsService; final ErrorReporter _errorReporter; - WsManager({required this.wsService, required ErrorReporter errorReporter}) - : _errorReporter = errorReporter; + WsManager({required this.wsService, required this._errorReporter}); PusherChannelsClient? client; int? userId; @@ -48,6 +47,7 @@ class WsManager { Stream? _directChatStream; Stream? _clientTypingStream; + Stream? _chosenPlanStateChangedStream; Stream? get newMessagesStream => _privateMessagesChannel?.bind('App\\Events\\ChatMessageUpdated'); @@ -74,6 +74,9 @@ class WsManager { Stream? get clientTypingStream => _clientTypingStream; + Stream? get chosenPlanStateChangedStream => + _chosenPlanStateChangedStream; + /// Сигнал о реконнекте сокета: эмитится после повторной подписки на каналы. /// /// Подписчики используют его, чтобы догрузить пропущенные за время обрыва @@ -222,6 +225,9 @@ class WsManager { 'App\\Events\\ChatMessageUpdated', ); _clientTypingStream = _privateDirectChatChannel?.bind('client-typing'); + _chosenPlanStateChangedStream = _privateDirectChatChannel?.bind( + 'chosen-plan-state-changed', + ); } Future initPresenceDirectChatChannel(String chatId) async { @@ -367,6 +373,7 @@ class WsManager { _privateDirectChatChannel?.unsubscribe(); _directChatStream = null; _clientTypingStream = null; + _chosenPlanStateChangedStream = null; } void unsubscribePresenceDirectChatChannel() { @@ -401,6 +408,7 @@ class WsManager { _privateNotificationChannel = null; _directChatStream = null; _clientTypingStream = null; + _chosenPlanStateChangedStream = null; } } diff --git a/lib/core/widgets/add_item_button.dart b/lib/core/widgets/add_item_button.dart index 5aa1b010..b8867122 100644 --- a/lib/core/widgets/add_item_button.dart +++ b/lib/core/widgets/add_item_button.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class AddItemButton extends StatelessWidget { diff --git a/lib/core/widgets/animated_option_button.dart b/lib/core/widgets/animated_option_button.dart index 596c23ac..4c90cfc5 100644 --- a/lib/core/widgets/animated_option_button.dart +++ b/lib/core/widgets/animated_option_button.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AnimatedOptionButton extends StatelessWidget { const AnimatedOptionButton({super.key, required this.text, required this.isSelected, required this.onTap, this.textStyle}); diff --git a/lib/core/widgets/base_button.dart b/lib/core/widgets/base_button.dart index 18c5f030..8e48fc34 100644 --- a/lib/core/widgets/base_button.dart +++ b/lib/core/widgets/base_button.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class BaseButton extends StatelessWidget { const BaseButton({ diff --git a/lib/core/widgets/bookmark_button.dart b/lib/core/widgets/bookmark_button.dart index c9e939c4..42507019 100644 --- a/lib/core/widgets/bookmark_button.dart +++ b/lib/core/widgets/bookmark_button.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class BookmarkButton extends StatelessWidget { const BookmarkButton({ diff --git a/lib/core/widgets/bottom_sheet_action_widget.dart b/lib/core/widgets/bottom_sheet_action_widget.dart index 004b5567..0c85802d 100644 --- a/lib/core/widgets/bottom_sheet_action_widget.dart +++ b/lib/core/widgets/bottom_sheet_action_widget.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class BottomSheetActionWidget extends StatelessWidget { diff --git a/lib/core/widgets/bottom_sheet_handler_bar.dart b/lib/core/widgets/bottom_sheet_handler_bar.dart index ceaf2bca..a93422ec 100644 --- a/lib/core/widgets/bottom_sheet_handler_bar.dart +++ b/lib/core/widgets/bottom_sheet_handler_bar.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class BottomSheetHandlerBar extends StatelessWidget { const BottomSheetHandlerBar({super.key}); diff --git a/lib/core/widgets/bottom_sheet_with_blur.dart b/lib/core/widgets/bottom_sheet_with_blur.dart index 57dc9026..c27ea0a9 100644 --- a/lib/core/widgets/bottom_sheet_with_blur.dart +++ b/lib/core/widgets/bottom_sheet_with_blur.dart @@ -1,9 +1,13 @@ import 'dart:ui'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; -Future showBottomSheetWithBlur({ +/// Показывает modal bottom sheet с blur-фоном. +/// +/// Дженерик [T] пробрасывает значение, переданное в `Navigator.pop(T)` +/// внутри шита (по умолчанию `null`). +Future showBottomSheetWithBlur({ required BuildContext context, required Widget child, double? height = 200, @@ -11,7 +15,7 @@ Future showBottomSheetWithBlur({ bool enableDrag = true, bool userRootNavigator = false, }) { - return showModalBottomSheet( + return showModalBottomSheet( context: context, isScrollControlled: true, barrierColor: appTheme.transparentBlack, diff --git a/lib/core/widgets/cpfc_container.dart b/lib/core/widgets/cpfc_container.dart index f5026c9a..4406bb58 100644 --- a/lib/core/widgets/cpfc_container.dart +++ b/lib/core/widgets/cpfc_container.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CpfcContainer extends StatelessWidget { const CpfcContainer({super.key, required this.calories, required this.proteins, required this.fats, required this.carbohydrates}); diff --git a/lib/core/widgets/custom_divider.dart b/lib/core/widgets/custom_divider.dart index 7bf88514..1fe1e1ae 100644 --- a/lib/core/widgets/custom_divider.dart +++ b/lib/core/widgets/custom_divider.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CustomDivider extends StatelessWidget { const CustomDivider({super.key}); diff --git a/lib/core/widgets/custom_drop_down.dart b/lib/core/widgets/custom_drop_down.dart index 9580afe7..f9b63910 100644 --- a/lib/core/widgets/custom_drop_down.dart +++ b/lib/core/widgets/custom_drop_down.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CustomDropDown extends StatelessWidget { const CustomDropDown({ diff --git a/lib/core/widgets/custom_drop_down_button.dart b/lib/core/widgets/custom_drop_down_button.dart index d4c0e571..d7927a40 100644 --- a/lib/core/widgets/custom_drop_down_button.dart +++ b/lib/core/widgets/custom_drop_down_button.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class CustomDropDownButton extends StatelessWidget { diff --git a/lib/core/widgets/custom_outlined_button.dart b/lib/core/widgets/custom_outlined_button.dart index cb396f56..864d8979 100644 --- a/lib/core/widgets/custom_outlined_button.dart +++ b/lib/core/widgets/custom_outlined_button.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/widgets/base_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CustomOutlinedButton extends BaseButton { const CustomOutlinedButton({super.key, diff --git a/lib/core/widgets/custom_popup.dart b/lib/core/widgets/custom_popup.dart index e0abdefe..26033b3d 100644 --- a/lib/core/widgets/custom_popup.dart +++ b/lib/core/widgets/custom_popup.dart @@ -24,7 +24,7 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/core/widgets/custom_search_bar.dart b/lib/core/widgets/custom_search_bar.dart index 4ce02f5b..71d3d6aa 100644 --- a/lib/core/widgets/custom_search_bar.dart +++ b/lib/core/widgets/custom_search_bar.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CustomSearchBar extends StatelessWidget { const CustomSearchBar({super.key, required this.searchController, required this.onChanged, this.backgroundColor, this.borderRadius, this.enableIcon = true, this.width}); diff --git a/lib/core/widgets/custom_text_form_field.dart b/lib/core/widgets/custom_text_form_field.dart index 041bee70..60de4ad8 100644 --- a/lib/core/widgets/custom_text_form_field.dart +++ b/lib/core/widgets/custom_text_form_field.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; class CustomTextFormField extends StatelessWidget { diff --git a/lib/core/widgets/data_error_widget.dart b/lib/core/widgets/data_error_widget.dart index 7d8562ba..57428032 100644 --- a/lib/core/widgets/data_error_widget.dart +++ b/lib/core/widgets/data_error_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class DataErrorWidget extends StatefulWidget { diff --git a/lib/core/widgets/feed_icon_button.dart b/lib/core/widgets/feed_icon_button.dart index ee96cd0b..421bd770 100644 --- a/lib/core/widgets/feed_icon_button.dart +++ b/lib/core/widgets/feed_icon_button.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class FeedIconButton extends StatelessWidget { diff --git a/lib/core/widgets/info_row.dart b/lib/core/widgets/info_row.dart index fbf0b8bf..265d897f 100644 --- a/lib/core/widgets/info_row.dart +++ b/lib/core/widgets/info_row.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class InfoRow extends StatelessWidget { diff --git a/lib/core/widgets/item_widget.dart b/lib/core/widgets/item_widget.dart index ac43f779..0fe167fb 100644 --- a/lib/core/widgets/item_widget.dart +++ b/lib/core/widgets/item_widget.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; class ItemWidget extends StatelessWidget { diff --git a/lib/core/widgets/loader.dart b/lib/core/widgets/loader.dart index ae69e10f..31fcb57b 100644 --- a/lib/core/widgets/loader.dart +++ b/lib/core/widgets/loader.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:lottie/lottie.dart'; class Loader extends StatelessWidget { diff --git a/lib/core/widgets/main_background_bouble.dart b/lib/core/widgets/main_background_bouble.dart index cec9c57b..ed64ea56 100644 --- a/lib/core/widgets/main_background_bouble.dart +++ b/lib/core/widgets/main_background_bouble.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class MainBackgroundBouble extends StatelessWidget { const MainBackgroundBouble({ diff --git a/lib/core/widgets/markdown_html_widget.dart b/lib/core/widgets/markdown_html_widget.dart index 5361e840..e4f0c8b2 100644 --- a/lib/core/widgets/markdown_html_widget.dart +++ b/lib/core/widgets/markdown_html_widget.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:markdown/markdown.dart' as md; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/core/widgets/marketing_bottom_sheet.dart b/lib/core/widgets/marketing_bottom_sheet.dart index 53b833ae..446b5d7e 100644 --- a/lib/core/widgets/marketing_bottom_sheet.dart +++ b/lib/core/widgets/marketing_bottom_sheet.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; import 'package:share_plus/share_plus.dart'; diff --git a/lib/core/widgets/network_svg_picture.dart b/lib/core/widgets/network_svg_picture.dart index fecd2748..52b35ac5 100644 --- a/lib/core/widgets/network_svg_picture.dart +++ b/lib/core/widgets/network_svg_picture.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/utils/inline_svg_css.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:http/http.dart' as http; diff --git a/lib/core/widgets/option_widget.dart b/lib/core/widgets/option_widget.dart index bed09c27..9e8b5694 100644 --- a/lib/core/widgets/option_widget.dart +++ b/lib/core/widgets/option_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/core/widgets/item_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class OptionWidget extends StatelessWidget { const OptionWidget({super.key, required this.option, this.disableDuration = false, required this.duration}); diff --git a/lib/core/widgets/show_error_dialog.dart b/lib/core/widgets/show_error_dialog.dart index c6acef34..cd58bf8f 100644 --- a/lib/core/widgets/show_error_dialog.dart +++ b/lib/core/widgets/show_error_dialog.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:permission_handler/permission_handler.dart'; Future showErrorDialog(BuildContext context, {String? title, String? description, String? buttonTitle, bool? needToOpenSettings}) async { diff --git a/lib/core/widgets/success_published_diet_bottom_sheet.dart b/lib/core/widgets/success_published_diet_bottom_sheet.dart index 3794e5c0..138f07d8 100644 --- a/lib/core/widgets/success_published_diet_bottom_sheet.dart +++ b/lib/core/widgets/success_published_diet_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class SuccessPublishedDietOrPlanBottomSheet extends StatelessWidget { diff --git a/lib/core/widgets/success_published_recipe_bottom_sheet.dart b/lib/core/widgets/success_published_recipe_bottom_sheet.dart index 796e7d91..0a028f3b 100644 --- a/lib/core/widgets/success_published_recipe_bottom_sheet.dart +++ b/lib/core/widgets/success_published_recipe_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class SuccessPublishedRecipeBottomSheet extends StatelessWidget { diff --git a/lib/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart b/lib/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart index f36f43cf..98865cf2 100644 --- a/lib/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart +++ b/lib/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart @@ -3,6 +3,7 @@ import 'dart:developer'; import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart'; @@ -17,15 +18,26 @@ class AuthCubit extends Cubit { final ProfileRepository profileRepository; final FirebaseApi firebaseApi; final Prefs prefs; + final SessionLifecycleService sessionLifecycleService; - AuthCubit({required this.authRepository, required this.prefs, required this.profileRepository, required this.firebaseApi}) : super(const AuthState()); + AuthCubit({ + required this.authRepository, + required this.prefs, + required this.profileRepository, + required this.firebaseApi, + required this.sessionLifecycleService, + }) : super(const AuthState()); Future getTokenByCredentials(String email, String password) async { emit(const AuthState.loading()); try { - final token = (await authRepository.getTokenByCredentials(email, password)).token; + final token = (await authRepository.getTokenByCredentials( + email, + password, + )).token; emit(AuthState.loaded(token: token)); await TokenStorage.saveTokenInStorage(token); + await sessionLifecycleService.onAuthenticated(); return true; } catch (e, st) { await reportFrom(e, st, this); @@ -48,7 +60,8 @@ class AuthCubit extends Cubit { Future registerAnonymousPushToken() async { try { - final hasAnonymousTokenBeenSent = prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false; + final hasAnonymousTokenBeenSent = + prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false; if (!hasAnonymousTokenBeenSent) { await firebaseApi.registerAnonymousPushToken(); prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true); diff --git a/lib/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart b/lib/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart index 45d00f13..22193998 100644 --- a/lib/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart +++ b/lib/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart @@ -1,7 +1,9 @@ import 'dart:developer'; import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart'; import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/auth/models/oauth_verification_request_response.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart'; @@ -11,12 +13,24 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart'; class OAuthCubit extends Cubit with RegistrationDateCacheMixin { final AuthRepository authRepository; + final FirebaseApi firebaseApi; + final SessionLifecycleService sessionLifecycleService; - OAuthCubit({required this.authRepository, required Prefs prefs}) : super(const OAuthState()) { + OAuthCubit({ + required this.authRepository, + required this.firebaseApi, + required this.sessionLifecycleService, + required Prefs prefs, + }) : super(const OAuthState()) { this.prefs = prefs; } - Future signInViaSocialMedia({required String provider, required String accessToken, required String refreshToken, required String clientId}) async { + Future signInViaSocialMedia({ + required String provider, + required String accessToken, + required String refreshToken, + required String clientId, + }) async { try { emit(const OAuthState.loading()); @@ -28,7 +42,8 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { ); log('OAuthCubit: Got token model: ${tokenModel.token}'); - TokenStorage.saveTokenInStorage(tokenModel.token); + await TokenStorage.saveTokenInStorage(tokenModel.token); + await sessionLifecycleService.onAuthenticated(); emit(OAuthState.loaded(token: tokenModel.token)); } on DioException catch (e, st) { await reportFrom(e, st, this); @@ -45,7 +60,8 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { if (errorStr.contains('Некорректный формат email')) { errorsList.add(RegistrationValidationErrors.incorrectEmailFormat); } - if (errorStr.contains('почта уже существует') || errorStr.contains('Эл. почта уже существует')) { + if (errorStr.contains('почта уже существует') || + errorStr.contains('Эл. почта уже существует')) { errorsList.add(RegistrationValidationErrors.emailExist); } } @@ -53,14 +69,20 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { if (phoneErrors != null && phoneErrors.isNotEmpty) { for (final error in phoneErrors) { final errorStr = error.toString(); - if (errorStr.contains('phone уже существует') || errorStr.contains('телефон уже существует')) { + if (errorStr.contains('phone уже существует') || + errorStr.contains('телефон уже существует')) { errorsList.add(RegistrationValidationErrors.phoneExist); } } } if (errorsList.isNotEmpty) { - emit(OAuthState.error(errorMessage: 'validation_error', registrationValidationErrors: errorsList)); + emit( + OAuthState.error( + errorMessage: 'validation_error', + registrationValidationErrors: errorsList, + ), + ); } else { emit(OAuthState.error(errorMessage: e.toString())); } @@ -103,7 +125,8 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { height: height, clientId: clientId, ); - TokenStorage.saveTokenInStorage(token); + await TokenStorage.saveTokenInStorage(token); + await sessionLifecycleService.onAuthenticated(); cacheRegistrationDate(DateTime.now()); emit(OAuthState.loaded(token: token)); } on DioException catch (e, st) { @@ -120,7 +143,8 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { if (errorStr.contains('Некорректный формат email')) { errorsList.add(RegistrationValidationErrors.incorrectEmailFormat); } - if (errorStr.contains('почта уже существует') || errorStr.contains('Эл. почта уже существует')) { + if (errorStr.contains('почта уже существует') || + errorStr.contains('Эл. почта уже существует')) { errorsList.add(RegistrationValidationErrors.emailExist); } } @@ -128,14 +152,17 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { if (phoneErrors != null && phoneErrors.isNotEmpty) { for (final error in phoneErrors) { final errorStr = error.toString(); - if (errorStr.contains('phone уже существует') || errorStr.contains('телефон уже существует')) { + if (errorStr.contains('phone уже существует') || + errorStr.contains('телефон уже существует')) { errorsList.add(RegistrationValidationErrors.phoneExist); } } } if (dateOfBirth != null && dateOfBirth.isNotEmpty) { if (dateOfBirth.contains('Некорректный формат даты рождения')) { - errorsList.add(RegistrationValidationErrors.incorrectDateOfBirthFormat); + errorsList.add( + RegistrationValidationErrors.incorrectDateOfBirthFormat, + ); } } if (errorsList.isNotEmpty) { @@ -146,13 +173,23 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { return null; } - Future requestOAuthVerification({String? email, String? phone}) async { + Future requestOAuthVerification({ + String? email, + String? phone, + }) async { try { emit(const OAuthState.loading()); - log('OAuthCubit: Requesting verification code for email: $email, phone: $phone'); - final response = await authRepository.requestOAuthVerification(email: email, phone: phone); + log( + 'OAuthCubit: Requesting verification code for email: $email, phone: $phone', + ); + final response = await authRepository.requestOAuthVerification( + email: email, + phone: phone, + ); if (response != null) { - log('OAuthCubit: Verification code requested successfully, masked email: ${response.email}'); + log( + 'OAuthCubit: Verification code requested successfully, masked email: ${response.email}', + ); } // Сбрасываем состояние после успешного запроса кода emit(const OAuthState()); @@ -184,7 +221,9 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { }) async { try { emit(const OAuthState.loading()); - log('OAuthCubit: Confirming OAuth verification - provider: $provider, verificationType: $verificationType, code: $code'); + log( + 'OAuthCubit: Confirming OAuth verification - provider: $provider, verificationType: $verificationType, code: $code', + ); final response = await authRepository.confirmOAuthVerification( provider: provider, accessToken: accessToken, @@ -202,8 +241,11 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { weight: weight, height: height, ); - log('OAuthCubit: OAuth verification confirmed successfully, token received'); - TokenStorage.saveTokenInStorage(response.token); + log( + 'OAuthCubit: OAuth verification confirmed successfully, token received', + ); + await TokenStorage.saveTokenInStorage(response.token); + await sessionLifecycleService.onAuthenticated(); emit(OAuthState.loaded(token: response.token)); } catch (e, st) { await reportFrom(e, st, this); @@ -212,4 +254,3 @@ class OAuthCubit extends Cubit with RegistrationDateCacheMixin { } } } - diff --git a/lib/features/auth/presentation/pages/auth_screen.dart b/lib/features/auth/presentation/pages/auth_screen.dart index d1c1ccfd..acd938bc 100644 --- a/lib/features/auth/presentation/pages/auth_screen.dart +++ b/lib/features/auth/presentation/pages/auth_screen.dart @@ -4,12 +4,10 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/const.dart'; -import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/utils/image_constant.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart'; @@ -18,13 +16,11 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cub import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart'; import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; import 'package:eatvio_app/core/di/cubit_registrations.dart'; -import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; -import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_svg/flutter_svg.dart'; @@ -68,23 +64,8 @@ class _AuthScreenState extends State { super.dispose(); } - Future _reconnectWebSocket(BuildContext context) async { - try { - await sl().clear(); - await sl().initialize(); - } catch (e) { - rethrow; - } - if (context.mounted) { - try { - await sl().getMyProfile(); - await sl().getChatRoomsWithLoading(); - await sl().registerPushToken(); - showSuccessToast('Успешный вход'); - } catch (e) { - rethrow; - } - } + Future _reconnectWebSocket() async { + showSuccessToast('Успешный вход'); AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false}); } @@ -202,18 +183,7 @@ class _AuthScreenState extends State { } Future _reconnectAfterAuth() async { - final context = AppRouter.navigatorKey.currentContext; - if (context == null) return; - try { - await sl().clear(); - await sl().initialize(); - await sl().getMyProfile(); - await sl().getChatRoomsWithLoading(); - await sl().registerPushToken(); - showSuccessToast('Успешный вход'); - } catch (e) { - log(e.toString()); - } + showSuccessToast('Успешный вход'); AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false}); } @@ -395,7 +365,7 @@ class _AuthScreenState extends State { final isAuthenticated = await authCubit.getTokenByCredentials(emailController.text, passwordController.text); if (isAuthenticated) { if (context.mounted) { - await _reconnectWebSocket(context); + await _reconnectWebSocket(); } } setState(() { diff --git a/lib/features/auth/presentation/pages/forget_password_screen.dart b/lib/features/auth/presentation/pages/forget_password_screen.dart index 911805c8..b805d7e3 100644 --- a/lib/features/auth/presentation/pages/forget_password_screen.dart +++ b/lib/features/auth/presentation/pages/forget_password_screen.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/auth/presentation/pages/register_via_social_screen.dart b/lib/features/auth/presentation/pages/register_via_social_screen.dart index 1ea307f0..57a50d47 100644 --- a/lib/features/auth/presentation/pages/register_via_social_screen.dart +++ b/lib/features/auth/presentation/pages/register_via_social_screen.dart @@ -9,15 +9,11 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_sta import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/locator_service.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; -import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; -import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; -import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/utils/validation_utils.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -62,23 +58,8 @@ class _RegisterViaSocialScreenState extends State { _initializeFieldsFromAuthResult(); } - Future _reconnectWebSocket(BuildContext context) async { - try { - await sl().clear(); - await sl().initialize(); - } catch (e) { - rethrow; - } - if (context.mounted) { - try { - await sl().getMyProfile(); - await sl().getChatRoomsWithLoading(); - await sl().registerPushToken(); - showSuccessToast('Успешная регистрация'); - } catch (e) { - rethrow; - } - } + Future _reconnectWebSocket() async { + showSuccessToast('Успешная регистрация'); AppRouter.appRouter.go('/feed-screen', extra: {'needToInitializeWebSocket': false}); } @@ -451,7 +432,7 @@ class _RegisterViaSocialScreenState extends State { Builder( builder: (context) { WidgetsBinding.instance.addPostFrameCallback((_) { - _reconnectWebSocket(context); + _reconnectWebSocket(); }); return const SizedBox.shrink(); }, @@ -795,7 +776,7 @@ class _RegisterViaSocialScreenState extends State { // Перезагружаем веб-сокет и переходим на главный экран if (widgetContext.mounted) { - _reconnectWebSocket(widgetContext); + _reconnectWebSocket(); } } catch (e, stackTrace) { log('OAuth Verification Confirm Error: $e', error: e, stackTrace: stackTrace); diff --git a/lib/features/auth/presentation/pages/scan_qr_code_screen.dart b/lib/features/auth/presentation/pages/scan_qr_code_screen.dart index 4b90fe70..3b9aeb2a 100644 --- a/lib/features/auth/presentation/pages/scan_qr_code_screen.dart +++ b/lib/features/auth/presentation/pages/scan_qr_code_screen.dart @@ -3,14 +3,11 @@ import 'dart:io'; import 'package:dio/dio.dart'; import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_router.dart'; -import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; -import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; -import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart'; @@ -39,7 +36,10 @@ class _ScanQRCodeScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: const Text('Сканирование QR-кода'), centerTitle: true), + appBar: AppBar( + title: const Text('Сканирование QR-кода'), + centerTitle: true, + ), body: Column( children: [ Expanded( @@ -60,30 +60,33 @@ class _ScanQRCodeScreenState extends State { try { final scannedUrl = scanData.code; final uri = Uri.parse(scannedUrl ?? ''); - final scannedBaseUrl = (uri.hasAuthority) ? '${uri.scheme}://${uri.host}' : ''; + final scannedBaseUrl = (uri.hasAuthority) + ? '${uri.scheme}://${uri.host}' + : ''; sl().setBaseUrl(scannedBaseUrl); sl().options.baseUrl = scannedBaseUrl; - final response = await Dio().getUri(uri, options: Options(headers: {'accept': 'application/json', 'content-type': 'application/json'})); + final response = await Dio().getUri( + uri, + options: Options( + headers: { + 'accept': 'application/json', + 'content-type': 'application/json', + }, + ), + ); final token = response.data['token']; await TokenStorage.saveTokenInStorage(token); - try { - await sl().clear(); - await sl().initialize(); - } catch (e) { - rethrow; - } - try { - await sl().getMyProfile(); - await sl().getChatRoomsWithLoading(); - await sl().registerPushToken(); - } catch (e) { - rethrow; - } - AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false}); + await sl().onAuthenticated(); + AppRouter.navigatorKey.currentContext?.go( + '/feed-screen', + extra: {'needToInitializeWebSocket': false}, + ); showSuccessToast('Добро пожаловать!'); } catch (e) { await controller.resumeCamera(); - showErrorToast('Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.'); + showErrorToast( + 'Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.', + ); } }); } diff --git a/lib/features/auth/sdk/social_auth_facade.dart b/lib/features/auth/sdk/social_auth_facade.dart index 341e98a2..49cf2d1d 100644 --- a/lib/features/auth/sdk/social_auth_facade.dart +++ b/lib/features/auth/sdk/social_auth_facade.dart @@ -5,7 +5,7 @@ import 'dart:io'; import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; import 'package:eatvio_app/features/auth/models/yandex_profile_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/env_config.dart'; import 'package:eatvio_app/core/locator_service.dart'; diff --git a/lib/features/blog_post/presentation/pages/blog_post_screen.dart b/lib/features/blog_post/presentation/pages/blog_post_screen.dart index f79d9ef2..022259c3 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -18,7 +18,7 @@ import 'package:eatvio_app/features/feed/presentation/widgets/comments_widget.da import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; diff --git a/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart index b0099417..f9b612c7 100644 --- a/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart +++ b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart @@ -21,8 +21,8 @@ import 'package:eatvio_app/features/feed/models/post_feed_pagination_model.dart' import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:go_router/go_router.dart'; @@ -614,10 +614,6 @@ class _BlogPostCreateScreenState extends State { void _onReorderGallery(int oldIndex, int newIndex) { setState(() { - if (newIndex > oldIndex) { - newIndex -= 1; - } - if (oldIndex < savedImages.length && newIndex < savedImages.length) { final item = savedImages.removeAt(oldIndex); savedImages.insert(newIndex, item); @@ -988,7 +984,7 @@ class _BlogPostCreateScreenState extends State { child: ReorderableListView.builder( scrollDirection: Axis.horizontal, buildDefaultDragHandles: false, - onReorder: _onReorderGallery, + onReorderItem: _onReorderGallery, itemCount: _galleryCount + (_remainingSlots > 0 ? 1 : 0), itemBuilder: (context, index) { if (index == _galleryCount) { diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart index 8aef9871..8293bdc7 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart @@ -6,6 +6,13 @@ class NewMessagesCubit extends Cubit { NewMessagesCubit() : super(const NewMessagesState.empty()); + void reset() { + _messagesCount = 0; + if (!isClosed) { + emit(const NewMessagesState.empty()); + } + } + void incrementCounter() { _messagesCount++; emit(NewMessagesState.loaded(messagesCount: _messagesCount)); diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart b/lib/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart index 2a51eca4..ffde009e 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart @@ -1,18 +1,22 @@ import 'dart:async'; import 'package:appmetrica_plugin/appmetrica_plugin.dart'; -import 'package:eatvio_app/core/app_router.dart'; +import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/error_reporting/report_from.dart'; -import 'package:go_router/go_router.dart'; import 'package:permission_handler/permission_handler.dart'; class ProfileAvatarCubit extends Cubit { final ProfileRepository profileRepository; - ProfileAvatarCubit({required this.profileRepository}) : super(const ProfileAvatarState.loading()); + ProfileAvatarCubit({required this.profileRepository}) + : super(const ProfileAvatarState.loading()); + + int _requestId = 0; + int? _sessionFingerprint; + bool _ensuring = false; int _calculateAge(String birthdate) { try { @@ -25,7 +29,8 @@ class ProfileAvatarCubit extends Cubit { final now = DateTime.now(); int age = now.year - birthYear; - if (now.month < birthMonth || (now.month == birthMonth && now.day < birthDay)) { + if (now.month < birthMonth || + (now.month == birthMonth && now.day < birthDay)) { age--; } @@ -38,30 +43,82 @@ class ProfileAvatarCubit extends Cubit { return 0; } + void reset() { + _requestId++; + _sessionFingerprint = null; + unawaited(AppMetrica.setUserProfileID(null).catchError((Object _) {})); + if (!isClosed) emit(const ProfileAvatarState.loading()); + } + + Future ensureFreshForCurrentSession() async { + final token = await TokenStorage.getTokenFromStorage(); + if (token == null || token.isEmpty) { + reset(); + return; + } + + final fingerprint = token.hashCode; + if (_sessionFingerprint == fingerprint && + state is ProfileAvatarStateLoaded) { + return; + } + + if (_ensuring) { + return; + } + + _ensuring = true; + try { + await getMyProfile(); + } finally { + _ensuring = false; + } + } + Future getMyProfile() async { + final requestId = ++_requestId; + final token = await TokenStorage.getTokenFromStorage(); + final fingerprint = token?.hashCode; + if (isClosed || requestId != _requestId) return; + emit(const ProfileAvatarState.loading()); try { final profile = await profileRepository.getMyProfile(); + if (isClosed || requestId != _requestId) return; + final profileDetails = await profileRepository.getMyProfileDetails(); + if (isClosed || requestId != _requestId) return; + + _sessionFingerprint = fingerprint; emit(ProfileAvatarState.loaded(profile: profile)); + try { final notificationStatus = await Permission.notification.status; + if (isClosed || requestId != _requestId) return; final isNotificationEnabled = notificationStatus.isGranted; AppMetricaUserProfile userProfile = AppMetricaUserProfile([ AppMetricaNameAttribute.withValue(profile.name), - AppMetricaGenderAttribute.withValue(profileDetails.gender == 'male' ? AppMetricaGender.male : AppMetricaGender.female), - AppMetricaBirthDateAttribute.withAge(_calculateAge(profileDetails.birthdate)), - AppMetricaNotificationEnabledAttribute.withValue(isNotificationEnabled), + AppMetricaGenderAttribute.withValue( + profileDetails.gender == 'male' + ? AppMetricaGender.male + : AppMetricaGender.female, + ), + AppMetricaBirthDateAttribute.withAge( + _calculateAge(profileDetails.birthdate), + ), + AppMetricaNotificationEnabledAttribute.withValue( + isNotificationEnabled, + ), ]); AppMetrica.setUserProfileID(profile.slug); AppMetrica.reportUserProfile(userProfile); } catch (e, st) { await reportFrom(e, st, this); - // Игнорируем ошибки плагинов, профиль уже загружен } } catch (e, st) { + if (isClosed || requestId != _requestId) return; await reportFrom(e, st, this); - AppRouter.navigatorKey.currentContext?.go('/auth-screen'); + if (isClosed || requestId != _requestId) return; emit(ProfileAvatarState.error(errorMessage: e.toString())); } } diff --git a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart index 53ea8741..8404efd4 100644 --- a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart +++ b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class BottomNavController { BottomNavController(); diff --git a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart index c3317d8c..a651ab9f 100644 --- a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart +++ b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart @@ -14,7 +14,7 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cub import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; @@ -39,6 +39,8 @@ class BottomNavigationBarWidget extends StatefulWidget { class _BottomNavigationBarWidgetState extends State { int currentBottomNavBarIndex = 1; List? pages; + int? _pagesProfileId; + bool? _pagesIsConsultant; int tapsCount = 0; List _getPages(bool isConsultant) { @@ -179,7 +181,16 @@ class _BottomNavigationBarWidgetState extends State { final isConsultant = profileModel.roles.contains('consultant'); // Инициализируем pages на основе profileModel - pages ??= _getPages(isConsultant); + if (pages == null || + _pagesProfileId != profileModel.id || + _pagesIsConsultant != isConsultant) { + _pagesProfileId = profileModel.id; + _pagesIsConsultant = isConsultant; + pages = _getPages(isConsultant); + if (currentBottomNavBarIndex >= pages!.length) { + currentBottomNavBarIndex = 0; + } + } // Expose tab switching to descendants (e.g. notification widget) final controller = BottomNavScope.maybeOf(context); diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 2ba9a0b7..d3bcca8b 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.da import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet.dart b/lib/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet.dart index ceec1294..5bfaad28 100644 --- a/lib/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet.dart +++ b/lib/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cubit/cancel_plan_cubit.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 27ffb620..e0cb7d6a 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -31,7 +31,9 @@ class ChatRoomCubit extends Cubit { StreamSubscription? typingSubscription; StreamSubscription? messagesSubscription; + StreamSubscription? _chosenPlanStateSubscription; StreamSubscription? _reconnectSubscription; + bool _isUpdatingChosenPlan = false; int currentPage = 1; late int lastPage; bool isLoading = false; @@ -171,6 +173,7 @@ class ChatRoomCubit extends Cubit { log(e.toString()); typingSubscription?.cancel(); messagesSubscription?.cancel(); + _chosenPlanStateSubscription?.cancel(); _reconnectSubscription?.cancel(); _reconnectSubscription = null; wsManager.unsubscribeDirectChatChannel(); @@ -260,19 +263,30 @@ class ChatRoomCubit extends Cubit { } Future updateChosenPlanState() async { + if (_isUpdatingChosenPlan) return; try { + _isUpdatingChosenPlan = true; final currentState = state; if (currentState is! ChatRoomStateLoaded) { return; } - final chosenPlanId = currentState.chatRoom.chosenPlanId; + final chosenPlanId = + currentState.chatRoom.chosenPlanId ?? + currentState.chatRoom.chosenPlan?.id; if (chosenPlanId == null) { return; } final chosenPlan = await chatRepository.getChosenPlan(id: chosenPlanId); - _emitLoaded((latest) => latest.copyWith.chatRoom(chosenPlan: chosenPlan)); + if (isClosed) return; + _emitLoaded( + (latest) => latest.copyWith( + chatRoom: latest.chatRoom.copyWith(chosenPlan: chosenPlan), + ), + ); } catch (e, st) { await reportFrom(e, st, this); + } finally { + _isUpdatingChosenPlan = false; } } @@ -338,8 +352,10 @@ class ChatRoomCubit extends Cubit { if (client == null) return; await messagesSubscription?.cancel(); await typingSubscription?.cancel(); + await _chosenPlanStateSubscription?.cancel(); messagesSubscription = null; typingSubscription = null; + _chosenPlanStateSubscription = null; await wsManager.initPrivateDirectChatChannel(chatId); wsManager.subscribeDirectChatChannel(); messagesSubscription = wsManager.directChatStream?.listen( @@ -361,6 +377,20 @@ class ChatRoomCubit extends Cubit { ), ); }); + _chosenPlanStateSubscription = wsManager + .chosenPlanStateChangedStream + ?.listen( + (_) { + EasyDebounce.debounce( + 'chosen-plan-state-changed', + const Duration(milliseconds: 250), + () => unawaited(updateChosenPlanState()), + ); + }, + onError: (Object e, StackTrace st) { + unawaited(reportFrom(e, st, this)); + }, + ); } void _onDirectChatEvent(ChannelReadEvent event) { @@ -731,6 +761,7 @@ class ChatRoomCubit extends Cubit { Future close() async { EasyDebounce.cancel('client-typing'); EasyDebounce.cancel('searchChatRoom'); + EasyDebounce.cancel('chosen-plan-state-changed'); if (_presenceOnlineListener != null) { wsManager.removePresenceDirectChatListener(_presenceOnlineListener!); _presenceOnlineListener = null; @@ -739,6 +770,7 @@ class ChatRoomCubit extends Cubit { _timer?.cancel(); await messagesSubscription?.cancel(); await typingSubscription?.cancel(); + await _chosenPlanStateSubscription?.cancel(); await _reconnectSubscription?.cancel(); super.close(); } diff --git a/lib/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart b/lib/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart index 499766f6..363d02fd 100644 --- a/lib/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart +++ b/lib/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart @@ -57,6 +57,17 @@ class ChatsCubit extends Cubit { int page = 1; late int lastPage; + /// Clears all user-scoped state. WS subscriptions stay intact so that + /// `getChatRoomsWithLoading` can re-load the new user's chats. + void reset() { + _query = null; + page = 1; + lastPage = 1; + if (!isClosed) { + emit(ChatsState()); + } + } + Future connectToWebSocket() async { try { await newIncomingMessagesSubscription?.cancel(); diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 99822267..6714a27a 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -11,7 +11,6 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; -import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart'; import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/models/chat_user_model.dart'; @@ -24,9 +23,11 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart'; +import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart'; +import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart'; import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart'; -import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; @@ -34,8 +35,8 @@ import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:file_picker/file_picker.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:image_picker/image_picker.dart'; @@ -63,8 +64,6 @@ class _ChatScreenState extends State { final TextEditingController textEditingController = TextEditingController(); final ChatRoomCubit chatRoomCubit = sl(); final List unreadMessageIds = []; - final showableChatBadgeStates = - ChosenPlanStateEnum.getShowableChatBadgeStates(); late AppLifecycleListener _listener; List pickedFiles = []; @@ -188,49 +187,24 @@ class _ChatScreenState extends State { ChosenPlanStateEnum.statePendingPayment, ChosenPlanStateEnum.stateInCoordination, ].contains(chosenPlan?.chosenPlanState); - PacketOptions? chosenOption; - if (chosenPlan?.optionType == 'options1') { - chosenOption = chosenPlan?.plan.packet1Options; - } else if (chosenPlan?.optionType == 'options2') { - chosenOption = chosenPlan?.plan.packet2Options; - } else if (chosenPlan?.optionType == 'options3') { - chosenOption = chosenPlan?.plan.packet3Options; - } - - final showAboutOrderButton = - state.chatRoom.chosenPlan != null && - state.chatRoom.chosenPlan!.chosenPlanState != + final chosenOption = chosenPlan?.chosenOption; + final progress = chosenPlan == null + ? null + : mapConsultationProgress( + state: chosenPlan.chosenPlanState, + hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false, + personalDietName: chosenPlan.personalDietName, + ); + final bannerType = resolveChatBanner( + progress: progress, + amIConsultant: amIConsultant, + hasCard: state.hasCard, + state: chosenPlan?.chosenPlanState, + ); + final showInfoButton = + chosenPlan != null && + chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateCanceledByTheInitiator; - BannerType? bannerType; - if (chosenPlan == null || - chosenPlan.chosenPlanState == - ChosenPlanStateEnum.stateCanceledByTheInitiator) { - bannerType = null; - } else if (amIConsultant && - !state.hasCard && - chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) { - bannerType = BannerType.card; - } else if (amIConsultant && - chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) { - bannerType = BannerType.date; - } else if (!amIConsultant && - (chosenPlan.chosenPlanState == - ChosenPlanStateEnum.stateStartDateHasBeenSet || - chosenPlan.chosenPlanState == - ChosenPlanStateEnum.statePendingPayment)) { - bannerType = BannerType.payment; - } else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateDone && - amIConsultant) { - bannerType = BannerType.collectCharge; - } else if (chosenPlan.chosenPlanState == - ChosenPlanStateEnum.stateLastDayFinished && - !amIConsultant) { - bannerType = BannerType.finishPlan; - } else if (chosenOption?.hasPersonalDiet == true && - amIConsultant && - chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateDone) { - bannerType = BannerType.setPersonalDiet; - } return Scaffold( resizeToAvoidBottomInset: true, @@ -340,6 +314,28 @@ class _ChatScreenState extends State { Column( mainAxisSize: MainAxisSize.min, children: [ + if (progress != null) + ChatConsultationHeader( + progress: progress, + showInfoButton: showInfoButton, + onInfoTap: () { + if (amIConsultant) { + GoRouter.of(context).push( + InfoByOrderScreen.path, + extra: { + 'planId': chosenPlan?.id, + 'customerSlug': + state.chatRoom.users.receiver.slug, + }, + ); + return; + } + GoRouter.of(context).push( + InfoByOrderScreen.path, + extra: {'planId': chosenPlan?.id}, + ); + }, + ), Expanded( child: Container( color: appTheme.whiteA700, @@ -384,22 +380,9 @@ class _ChatScreenState extends State { final isPlanOrderMessage = message.type == ChatMessageType.planOrder; - PacketOptions? messageOption; - if (isPlanOrderMessage && - chosenPlan != null) { - if (chosenPlan.optionType == 'options1') { - messageOption = - chosenPlan.plan.packet1Options; - } else if (chosenPlan.optionType == - 'options2') { - messageOption = - chosenPlan.plan.packet2Options; - } else if (chosenPlan.optionType == - 'options3') { - messageOption = - chosenPlan.plan.packet3Options; - } - } + final messageOption = isPlanOrderMessage + ? chosenPlan?.chosenOption + : null; return Column( children: [ @@ -450,21 +433,9 @@ class _ChatScreenState extends State { final isPlanOrderMessage = message.type == ChatMessageType.planOrder; - PacketOptions? messageOption; - if (isPlanOrderMessage && chosenPlan != null) { - if (chosenPlan.optionType == 'options1') { - messageOption = - chosenPlan.plan.packet1Options; - } else if (chosenPlan.optionType == - 'options2') { - messageOption = - chosenPlan.plan.packet2Options; - } else if (chosenPlan.optionType == - 'options3') { - messageOption = - chosenPlan.plan.packet3Options; - } - } + final messageOption = isPlanOrderMessage + ? chosenPlan?.chosenOption + : null; return Column( children: [ @@ -804,30 +775,6 @@ class _ChatScreenState extends State { ), ], ), - if (showAboutOrderButton) - Positioned( - top: 8, - right: 15, - left: 16, - child: AboutOrderButton( - onTap: () async { - if (amIConsultant) { - GoRouter.of(context).push( - InfoByOrderScreen.path, - extra: { - 'planId': state.chatRoom.chosenPlan?.id, - 'customerSlug': state.chatRoom.users.receiver.slug, - }, - ); - return; - } - GoRouter.of(context).push( - InfoByOrderScreen.path, - extra: {'planId': state.chatRoom.chosenPlan?.id}, - ); - }, - ), - ), ], ), ), diff --git a/lib/features/chat/presentation/pages/chats_screen.dart b/lib/features/chat/presentation/pages/chats_screen.dart index 993bcfd3..1828c544 100644 --- a/lib/features/chat/presentation/pages/chats_screen.dart +++ b/lib/features/chat/presentation/pages/chats_screen.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cub import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_entry_widget.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_search_bar_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ChatsScreen extends StatefulWidget { diff --git a/lib/features/chat/presentation/pages/empty_chat_screen.dart b/lib/features/chat/presentation/pages/empty_chat_screen.dart index a0ddf60a..75de1ffe 100644 --- a/lib/features/chat/presentation/pages/empty_chat_screen.dart +++ b/lib/features/chat/presentation/pages/empty_chat_screen.dart @@ -8,8 +8,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:file_picker/file_picker.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:go_router/go_router.dart'; import 'package:image_picker/image_picker.dart'; import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart'; @@ -135,9 +135,9 @@ class _EmptyChatScreenState extends State { textEditingController.clear(); }); } - final chatIdOrError = await sl().getChatByUserSlug(widget.user.slug); - if (context.mounted) { - AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError}); + final chatId = await sl().getChatByUserSlug(widget.user.slug); + if (chatId != null && chatId.isNotEmpty && context.mounted) { + AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId}); } } }, @@ -189,9 +189,9 @@ class _EmptyChatScreenState extends State { if (images.isNotEmpty) { List files = images.map((image) => File(image.path)).toList(); await sl().sendMessage(files: files, slug: widget.user.slug); - final chatIdOrError = await sl().getChatByUserSlug(widget.user.slug); - if (mounted) { - AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError}); + final chatId = await sl().getChatByUserSlug(widget.user.slug); + if (chatId != null && chatId.isNotEmpty && mounted) { + AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId}); } } }, @@ -205,9 +205,9 @@ class _EmptyChatScreenState extends State { if (images.isNotEmpty) { List files = images.map((image) => File(image.path)).toList(); await sl().sendMessage(files: files, slug: widget.user.slug); - final chatIdOrError = await sl().getChatByUserSlug(widget.user.slug); - if (mounted) { - AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError}); + final chatId = await sl().getChatByUserSlug(widget.user.slug); + if (chatId != null && chatId.isNotEmpty && mounted) { + AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId}); } } }, @@ -243,9 +243,9 @@ class _EmptyChatScreenState extends State { if (result != null) { List files = result.paths.map((path) => File(path!)).toList(); await sl().sendMessage(files: files, slug: widget.user.slug); - final chatIdOrError = await sl().getChatByUserSlug(widget.user.slug); - if (mounted) { - AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError}); + final chatId = await sl().getChatByUserSlug(widget.user.slug); + if (chatId != null && chatId.isNotEmpty && mounted) { + AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId}); } } }, diff --git a/lib/features/chat/presentation/pages/payment_screen.dart b/lib/features/chat/presentation/pages/payment_screen.dart index 236827ad..012aea4b 100644 --- a/lib/features/chat/presentation/pages/payment_screen.dart +++ b/lib/features/chat/presentation/pages/payment_screen.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; import 'package:webview_flutter/webview_flutter.dart'; diff --git a/lib/features/chat/presentation/pages/photo_view_screen.dart b/lib/features/chat/presentation/pages/photo_view_screen.dart index b9910feb..445fc055 100644 --- a/lib/features/chat/presentation/pages/photo_view_screen.dart +++ b/lib/features/chat/presentation/pages/photo_view_screen.dart @@ -3,7 +3,7 @@ import 'package:dismissible_page/dismissible_page.dart'; import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/app_decoration.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; diff --git a/lib/features/chat/presentation/utils/chat_banner_resolver.dart b/lib/features/chat/presentation/utils/chat_banner_resolver.dart new file mode 100644 index 00000000..f2ab62c1 --- /dev/null +++ b/lib/features/chat/presentation/utils/chat_banner_resolver.dart @@ -0,0 +1,52 @@ +import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; + +BannerType? resolveChatBanner({ + required ConsultationProgress? progress, + required bool amIConsultant, + required bool hasCard, + required ChosenPlanStateEnum? state, +}) { + if (progress == null || + state == null || + progress.phase != ConsultationPhase.active) { + return null; + } + + if (amIConsultant && + !hasCard && + state == ChosenPlanStateEnum.stateInCoordination) { + return BannerType.card; + } + if (amIConsultant && state == ChosenPlanStateEnum.stateInCoordination) { + return BannerType.date; + } + if (!amIConsultant && + (state == ChosenPlanStateEnum.stateStartDateHasBeenSet || + state == ChosenPlanStateEnum.statePendingPayment)) { + return BannerType.payment; + } + if (state == ChosenPlanStateEnum.stateDone && amIConsultant) { + return BannerType.collectCharge; + } + if (state == ChosenPlanStateEnum.stateLastDayFinished && !amIConsultant) { + return BannerType.finishPlan; + } + if (!amIConsultant) { + return null; + } + + if (state == ChosenPlanStateEnum.statePaid && + progress.dietStatus == PersonalDietStatus.notProposed) { + return BannerType.setPersonalDiet; + } + if ((state == ChosenPlanStateEnum.personalDietSet || + state == ChosenPlanStateEnum.stateStarted || + state == ChosenPlanStateEnum.stateInProgress) && + progress.dietStatus == PersonalDietStatus.proposed) { + return BannerType.changePersonalDiet; + } + + return null; +} diff --git a/lib/features/chat/presentation/widgets/about_order_button.dart b/lib/features/chat/presentation/widgets/about_order_button.dart index 26fe8b86..a4303562 100644 --- a/lib/features/chat/presentation/widgets/about_order_button.dart +++ b/lib/features/chat/presentation/widgets/about_order_button.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class AboutOrderButton extends StatelessWidget { diff --git a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart index 8d83e961..38213ad7 100644 --- a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/message_action_bottom_sheet.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/chat/presentation/widgets/chat_consultation_header.dart b/lib/features/chat/presentation/widgets/chat_consultation_header.dart new file mode 100644 index 00000000..382a60d2 --- /dev/null +++ b/lib/features/chat/presentation/widgets/chat_consultation_header.dart @@ -0,0 +1,112 @@ +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +class ChatConsultationHeader extends StatelessWidget { + const ChatConsultationHeader({ + super.key, + required this.progress, + required this.showInfoButton, + required this.onInfoTap, + }); + + final ConsultationProgress progress; + final bool showInfoButton; + final VoidCallback onInfoTap; + + @override + Widget build(BuildContext context) { + final showPlank = progress.showProgressPlank; + final showChip = progress.hasChip; + if (!showPlank && !showChip && !showInfoButton) { + return const SizedBox.shrink(); + } + + final s = S.of(context); + + return Container( + margin: const EdgeInsets.fromLTRB(16, 8, 16, 0), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: appTheme.commentBg, + borderRadius: BorderRadius.circular(20), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (progress.phase == ConsultationPhase.active || showPlank) + Row( + children: [ + Expanded( + child: Text( + _title(s), + style: TextStyles.textMMedium.copyWith( + color: appTheme.black, + ), + ), + ), + if (showInfoButton) + _InfoButton( + onTap: onInfoTap, + ), + ], + ) + else if (showInfoButton) + Align( + alignment: Alignment.centerRight, + child: _InfoButton( + onTap: onInfoTap, + ), + ), + if (showPlank) ...[ + const SizedBox(height: 8), + ConsultationProgressPlank(progress: progress), + ], + if (showChip) ...[ + const SizedBox(height: 8), + PersonalDietStatusChip(progress: progress), + ], + ], + ), + ); + } + + String _title(S s) { + if (progress.isCanceled) return s.orderCanceled; + if (progress.isPaymentFailed) return s.payment_failed; + if (progress.isStepCompleted(ConsultationStep.finished)) return s.done; + if (progress.showProgressPlank) return s.order_in_progress; + return s.more_about_order; + } +} + +class _InfoButton extends StatelessWidget { + const _InfoButton({required this.onTap}); + + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + customBorder: const CircleBorder(), + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: appTheme.whiteA700, + shape: BoxShape.circle, + ), + child: Icon( + Icons.info_outline_rounded, + size: 18, + color: appTheme.blueA400, + ), + ), + ); + } +} diff --git a/lib/features/chat/presentation/widgets/chat_entry_widget.dart b/lib/features/chat/presentation/widgets/chat_entry_widget.dart index dacff9cb..66094e87 100644 --- a/lib/features/chat/presentation/widgets/chat_entry_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_entry_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:eatvio_app/features/chat/models/chat_room_pagination_model.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class ChatEntryWidget extends StatefulWidget { diff --git a/lib/features/chat/presentation/widgets/chat_search_bar_widget.dart b/lib/features/chat/presentation/widgets/chat_search_bar_widget.dart index 8691beb3..e1bae3e3 100644 --- a/lib/features/chat/presentation/widgets/chat_search_bar_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_search_bar_widget.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ChatSearchBarWidget extends StatelessWidget { const ChatSearchBarWidget({ diff --git a/lib/features/chat/presentation/widgets/chat_user_online_status_line.dart b/lib/features/chat/presentation/widgets/chat_user_online_status_line.dart index 8f851ab2..a486b5cc 100644 --- a/lib/features/chat/presentation/widgets/chat_user_online_status_line.dart +++ b/lib/features/chat/presentation/widgets/chat_user_online_status_line.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ChatUserOnlineStatusLine extends StatelessWidget { const ChatUserOnlineStatusLine({ diff --git a/lib/features/chat/presentation/widgets/chose_plan_date_widget.dart b/lib/features/chat/presentation/widgets/chose_plan_date_widget.dart index 5b385a5c..344caccd 100644 --- a/lib/features/chat/presentation/widgets/chose_plan_date_widget.dart +++ b/lib/features/chat/presentation/widgets/chose_plan_date_widget.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart b/lib/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart index ef950bc9..84ddd193 100644 --- a/lib/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart +++ b/lib/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class CompletePlanBottomSheet extends StatefulWidget { diff --git a/lib/features/chat/presentation/widgets/message_action_bottom_sheet.dart b/lib/features/chat/presentation/widgets/message_action_bottom_sheet.dart index 1f455764..4243f4c2 100644 --- a/lib/features/chat/presentation/widgets/message_action_bottom_sheet.dart +++ b/lib/features/chat/presentation/widgets/message_action_bottom_sheet.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_action_widget.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; void showMessageActionsBottomSheet(BuildContext context, {required void Function() resend, required void Function() delete}) { showModalBottomSheet( diff --git a/lib/features/chat/presentation/widgets/notification_banner.dart b/lib/features/chat/presentation/widgets/notification_banner.dart index 11db4288..47e1c55c 100644 --- a/lib/features/chat/presentation/widgets/notification_banner.dart +++ b/lib/features/chat/presentation/widgets/notification_banner.dart @@ -11,7 +11,7 @@ import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; import 'package:eatvio_app/features/payment/presentation/payment_flow.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; @@ -106,7 +106,11 @@ class _NotificationBannerState extends State { onTap: () { final planId = (context.read().state as ChatRoomStateLoaded).chatRoom.chosenPlan?.id; if (planId != null) { - showConsultationPaymentFlow(context, planId: planId); + showConsultationPaymentFlow( + context, + planId: planId, + amount: widget.planPrice, + ); } }, child: Text(s.pay, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)), @@ -142,12 +146,37 @@ class _NotificationBannerState extends State { BannerType.setPersonalDiet => [ SizedBox( width: size.width * 0.6, - child: Text(s.createPersonalDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)), + child: Text(s.suggestDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)), ), const SizedBox(height: 12), GestureDetector( onTap: () { - GoRouter.of(context).pushNamed(MyDietsScreen.name); + GoRouter.of(context).pushNamed( + MyDietsScreen.name, + queryParameters: {'initialTabIndex': '2'}, + ); + }, + child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)), + ), + const SizedBox(height: 16), + ], + BannerType.changePersonalDiet => [ + SizedBox( + width: size.width * 0.6, + child: Text(s.change_personal_diet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)), + ), + const SizedBox(height: 8), + SizedBox( + width: size.width * 0.6, + child: Text(s.personal_diet_replaces_tomorrow, style: TextStyles.textSMedium.copyWith(color: appTheme.black)), + ), + const SizedBox(height: 12), + GestureDetector( + onTap: () { + GoRouter.of(context).pushNamed( + MyDietsScreen.name, + queryParameters: {'initialTabIndex': '2'}, + ); }, child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)), ), @@ -240,4 +269,4 @@ class _StarIcon extends StatelessWidget { } } -enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet } +enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet, changePersonalDiet } diff --git a/lib/features/chat/presentation/widgets/order_card.dart b/lib/features/chat/presentation/widgets/order_card.dart index 2b7b50b2..5ff752da 100644 --- a/lib/features/chat/presentation/widgets/order_card.dart +++ b/lib/features/chat/presentation/widgets/order_card.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/core/widgets/item_widget.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class OrderCard extends StatefulWidget { final PlanModel plan; diff --git a/lib/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart b/lib/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart index 34f500f7..31637725 100644 --- a/lib/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart +++ b/lib/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class PlanComplainBottomSheet extends StatefulWidget { diff --git a/lib/features/chat/presentation/widgets/plan_order_message_widget.dart b/lib/features/chat/presentation/widgets/plan_order_message_widget.dart index 73581f82..26ba903c 100644 --- a/lib/features/chat/presentation/widgets/plan_order_message_widget.dart +++ b/lib/features/chat/presentation/widgets/plan_order_message_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class PlanOrderMessageWidget extends StatelessWidget { diff --git a/lib/features/chat/presentation/widgets/video_call_chat_message_widget.dart b/lib/features/chat/presentation/widgets/video_call_chat_message_widget.dart index 90930e1d..4598bcec 100644 --- a/lib/features/chat/presentation/widgets/video_call_chat_message_widget.dart +++ b/lib/features/chat/presentation/widgets/video_call_chat_message_widget.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; class VideoCallChatMessageWidget extends StatelessWidget { diff --git a/lib/features/chat/repositories/chat_repository.dart b/lib/features/chat/repositories/chat_repository.dart index ade2ed26..9230e4d8 100644 --- a/lib/features/chat/repositories/chat_repository.dart +++ b/lib/features/chat/repositories/chat_repository.dart @@ -137,11 +137,12 @@ class ChatRepository { } - Future getChatByUserSlug(String slug) async { + Future getChatByUserSlug(String slug) async { final response = await chatService.getChatByUserSlug(slug: slug); - if (response.response.statusCode == 404) { - return '404'; + final data = response.data; + if (data is Map && data['id'] is String && (data['id'] as String).isNotEmpty) { + return data['id'] as String; } - return response.data['id']; + return null; } } diff --git a/lib/features/complaining/presentation/complaining_bottom_sheet.dart b/lib/features/complaining/presentation/complaining_bottom_sheet.dart index 185738c2..d65c34f4 100644 --- a/lib/features/complaining/presentation/complaining_bottom_sheet.dart +++ b/lib/features/complaining/presentation/complaining_bottom_sheet.dart @@ -11,7 +11,7 @@ import 'package:eatvio_app/features/complaining/presentation/cubit/complaining_c import 'package:eatvio_app/features/complaining/presentation/cubit/complaining_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/consultant/become_consultant/entities/diploma_entity.dart b/lib/features/consultant/become_consultant/entities/diploma_entity.dart index 0194a811..6a147bf8 100644 --- a/lib/features/consultant/become_consultant/entities/diploma_entity.dart +++ b/lib/features/consultant/become_consultant/entities/diploma_entity.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class DiplomaEntity { TextEditingController textEditingController; diff --git a/lib/features/consultant/become_consultant/presentation/pages/additional_settings_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/additional_settings_screen.dart index 90b673a5..70fcdc13 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/additional_settings_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/additional_settings_screen.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AdditionalSettingsScreen extends StatefulWidget { diff --git a/lib/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart index 2955ee09..25d8554a 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class BecomeConsultantScreen extends StatefulWidget { @@ -14,6 +14,8 @@ class BecomeConsultantScreen extends StatefulWidget { class _BecomeConsultantScreenState extends State { @override Widget build(BuildContext context) { + final bottomInset = MediaQuery.paddingOf(context).bottom; + return Scaffold( appBar: AppBar( title: const Text('Стать консультантом'), @@ -24,14 +26,18 @@ class _BecomeConsultantScreenState extends State { icon: const Icon(Icons.close), ), ), - body: const Padding( - padding: EdgeInsets.all(16), - child: Text( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + 52 + 8 + bottomInset), + child: const Text( 'Чтобы стать консультантом необходимо пройти короткую регистрацию. Подготовьте свои дипломы и/или сертификаты в формате jpg, они Вам пригодятся для проверки и подтверждения. Также необходимо будет указать ссылки на Ваши соц. сети и указать тип лица (физ. лицо или юр. лицо). На данный момент доступна регистрация в качестве физ. лица.\n\nВнутри Итвио разница между обычным пользователем и консультантом заключается в дополнительных возможностях последнего создавать публичные диеты, рецепты и планы питания; участвовать в ежемесячных рейтингах.', style: TextStyle(fontSize: 16), ), ), - bottomSheet: _startRegistrationButton(), + bottomSheet: Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 8 + bottomInset), + child: _startRegistrationButton(), + ), ); } @@ -44,7 +50,7 @@ class _BecomeConsultantScreenState extends State { borderRadius: BorderRadius.circular(20), child: Ink( height: 52, - width: MediaQuery.of(context).size.width - 32, + width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: appTheme.blueA400, diff --git a/lib/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen.dart index 33772eb5..e65361f6 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen.dart @@ -2,8 +2,8 @@ import 'package:eatvio_app/features/consultant/become_consultant/entities/diplom import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/pages/last_step_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/last_step_screen.dart index 5e87ba50..f1b8c067 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/last_step_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/last_step_screen.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/enums/alfa_scor import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/widgets/scoring_status_widget.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/pages/passport_data_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/passport_data_screen.dart index 4cde5a95..ff897e3f 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/passport_data_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/passport_data_screen.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/widgets/passport_field_with_error.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/widgets/passport_section_title.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart index 87269eb5..776981f9 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.da import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:image_picker/image_picker.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/pages/registration_as_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/registration_as_screen.dart index e10fc74a..84ec5f08 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/registration_as_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/registration_as_screen.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class RegistrationAsScreen extends StatefulWidget { diff --git a/lib/features/consultant/become_consultant/presentation/pages/social_networks_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/social_networks_screen.dart index 1847ec60..2fcd8113 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/social_networks_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/social_networks_screen.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart index 49e30959..f177d554 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart @@ -14,7 +14,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/pa import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/consultant/become_consultant/presentation/widgets/passport_field_with_error.dart b/lib/features/consultant/become_consultant/presentation/widgets/passport_field_with_error.dart index 5e34fa79..be36105d 100644 --- a/lib/features/consultant/become_consultant/presentation/widgets/passport_field_with_error.dart +++ b/lib/features/consultant/become_consultant/presentation/widgets/passport_field_with_error.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Wraps a form field with [ValidationErrorWidget] when [error] is present. /// Pass [hasError] into [CustomTextFormField] from the parent. diff --git a/lib/features/consultant/become_consultant/presentation/widgets/passport_section_title.dart b/lib/features/consultant/become_consultant/presentation/widgets/passport_section_title.dart index 29abf8af..b3b5d376 100644 --- a/lib/features/consultant/become_consultant/presentation/widgets/passport_section_title.dart +++ b/lib/features/consultant/become_consultant/presentation/widgets/passport_section_title.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class PassportSectionTitle extends StatelessWidget { const PassportSectionTitle({required this.title, super.key}); diff --git a/lib/features/consultant/become_consultant/presentation/widgets/scoring_status_widget.dart b/lib/features/consultant/become_consultant/presentation/widgets/scoring_status_widget.dart index 764c803d..ed397976 100644 --- a/lib/features/consultant/become_consultant/presentation/widgets/scoring_status_widget.dart +++ b/lib/features/consultant/become_consultant/presentation/widgets/scoring_status_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/enums/alfa_scor import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ScoringStatusWidget extends StatelessWidget { diff --git a/lib/features/consultant_rating/presentation/consultant_rating_screen.dart b/lib/features/consultant_rating/presentation/consultant_rating_screen.dart index 000367e0..ce43cbab 100644 --- a/lib/features/consultant_rating/presentation/consultant_rating_screen.dart +++ b/lib/features/consultant_rating/presentation/consultant_rating_screen.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/consultant_rating/presentation/widgets/ratin import 'package:eatvio_app/features/consultant_rating/presentation/widgets/rating_widget.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/statistic_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/consultant_rating/presentation/widgets/period_filter_widget.dart b/lib/features/consultant_rating/presentation/widgets/period_filter_widget.dart index 3f15be8e..565ce940 100644 --- a/lib/features/consultant_rating/presentation/widgets/period_filter_widget.dart +++ b/lib/features/consultant_rating/presentation/widgets/period_filter_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/cubit/consultant_rating_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:collection/collection.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/consultant_rating/presentation/widgets/rating_history_item.dart b/lib/features/consultant_rating/presentation/widgets/rating_history_item.dart index 4bafd1b3..a723a92d 100644 --- a/lib/features/consultant_rating/presentation/widgets/rating_history_item.dart +++ b/lib/features/consultant_rating/presentation/widgets/rating_history_item.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class RatingHistoryItem extends StatelessWidget { const RatingHistoryItem({super.key, required this.title, required this.amount, required this.date}); diff --git a/lib/features/consultant_rating/presentation/widgets/rating_history_widget.dart b/lib/features/consultant_rating/presentation/widgets/rating_history_widget.dart index d6f8969b..cb227594 100644 --- a/lib/features/consultant_rating/presentation/widgets/rating_history_widget.dart +++ b/lib/features/consultant_rating/presentation/widgets/rating_history_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/consultant_rating/models/rating_model.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/period_filter_widget.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/rating_history_item.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class RatingHistoryWidget extends StatelessWidget { diff --git a/lib/features/consultant_rating/presentation/widgets/rating_widget.dart b/lib/features/consultant_rating/presentation/widgets/rating_widget.dart index 4f7c8206..66d90950 100644 --- a/lib/features/consultant_rating/presentation/widgets/rating_widget.dart +++ b/lib/features/consultant_rating/presentation/widgets/rating_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class RatingWidget extends StatelessWidget { diff --git a/lib/features/consultant_rating/presentation/widgets/statistic_bouble.dart b/lib/features/consultant_rating/presentation/widgets/statistic_bouble.dart index 2f28ee23..8ec819fe 100644 --- a/lib/features/consultant_rating/presentation/widgets/statistic_bouble.dart +++ b/lib/features/consultant_rating/presentation/widgets/statistic_bouble.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class StatisticBouble extends StatelessWidget { const StatisticBouble({super.key, required this.number, required this.title}); diff --git a/lib/features/consultant_rating/presentation/widgets/statistic_widget.dart b/lib/features/consultant_rating/presentation/widgets/statistic_widget.dart index ef148adf..82f6d50e 100644 --- a/lib/features/consultant_rating/presentation/widgets/statistic_widget.dart +++ b/lib/features/consultant_rating/presentation/widgets/statistic_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/consultant_rating/models/statistics_model.da import 'package:eatvio_app/features/consultant_rating/presentation/widgets/period_filter_widget.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/statistic_bouble.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class StatisticWidget extends StatelessWidget { diff --git a/lib/features/consultations/models/consultation_model.dart b/lib/features/consultations/models/consultation_model.dart index c73a8d37..0e321e2c 100644 --- a/lib/features/consultations/models/consultation_model.dart +++ b/lib/features/consultations/models/consultation_model.dart @@ -9,6 +9,7 @@ part 'consultation_model.g.dart'; abstract class ConsultationModel with _$ConsultationModel { factory ConsultationModel({ required int id, + @JsonKey(name: 'chat_id') String? chatId, @JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState, @JsonKey(name: 'plan_title') required String planTitle, @JsonKey(name: 'user_name') required String userName, @@ -19,10 +20,11 @@ abstract class ConsultationModel with _$ConsultationModel { @JsonKey(name: 'user_profile_photo_url') required String userProfilePhotoUrl, @JsonKey(name: 'consultation_option_price') required int consultationOptionPrice, @JsonKey(name: 'start_date', fromJson: parseDate) required DateTime startDate, - @JsonKey(name: 'end_date', fromJson: parseDate) required DateTime endDate, + @JsonKey(name: 'end_date', fromJson: parseDateOrNull) DateTime? endDate, @JsonKey(name: 'consultant_id') required int consultantId, required List diaries, @JsonKey(name: 'personal_diet_id') required int? personalDietId, + @JsonKey(name: 'personal_diet_name') String? personalDietName, }) = _ConsultationModel; factory ConsultationModel.fromJson(Map json) => _$ConsultationModelFromJson(json); @@ -39,6 +41,11 @@ abstract class DiaryModel with _$DiaryModel { factory DiaryModel.fromJson(Map json) => _$DiaryModelFromJson(json); } +DateTime? parseDateOrNull(dynamic date) { + if (date == null) return null; + return parseDate(date as String); +} + DateTime parseUnformattedDate(String date) { final dateChunks = date.split('-').map(int.parse).toList(); diff --git a/lib/features/consultations/models/consultation_progress.dart b/lib/features/consultations/models/consultation_progress.dart new file mode 100644 index 00000000..35f56f50 --- /dev/null +++ b/lib/features/consultations/models/consultation_progress.dart @@ -0,0 +1,33 @@ +enum ConsultationStep { startDate, paid, inProgress, finished } + +enum PersonalDietStatus { notRequired, notProposed, proposed } + +enum ConsultationPhase { active, canceled, paymentFailed } + +class ConsultationProgress { + const ConsultationProgress({ + required this.completedSteps, + required this.showProgressPlank, + required this.dietStatus, + required this.phase, + this.personalDietName, + }); + + final Set completedSteps; + final bool showProgressPlank; + final PersonalDietStatus dietStatus; + final ConsultationPhase phase; + final String? personalDietName; + + bool isStepCompleted(ConsultationStep step) => completedSteps.contains(step); + + bool get hasDietChip => dietStatus != PersonalDietStatus.notRequired; + + bool get hasStatusChip => phase != ConsultationPhase.active; + + bool get hasChip => hasDietChip || hasStatusChip; + + bool get isCanceled => phase == ConsultationPhase.canceled; + + bool get isPaymentFailed => phase == ConsultationPhase.paymentFailed; +} diff --git a/lib/features/consultations/presentation/cubit/consultations_cubit.dart b/lib/features/consultations/presentation/cubit/consultations_cubit.dart index 80f8b206..3b94fa8c 100644 --- a/lib/features/consultations/presentation/cubit/consultations_cubit.dart +++ b/lib/features/consultations/presentation/cubit/consultations_cubit.dart @@ -1,6 +1,7 @@ import 'dart:developer'; import 'package:eatvio_app/core/enums/base_state.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart'; import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -8,7 +9,8 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart'; class ConsultationsCubit extends Cubit { final ConsultationsRepository consultationsRepository; - ConsultationsCubit({required this.consultationsRepository}) : super(ConsultationsState()); + final ChatRepository chatRepository; + ConsultationsCubit({required this.consultationsRepository, required this.chatRepository}) : super(ConsultationsState()); Future loadConsultations() async { try { @@ -20,4 +22,14 @@ class ConsultationsCubit extends Cubit { emit(state.copyWith(state: BaseState.error)); } } + + Future getChatIdByUserSlug(String slug) async { + try { + return await chatRepository.getChatByUserSlug(slug); + } catch (e, st) { + await reportFrom(e, st, this); + log(e.toString(), stackTrace: st); + return null; + } + } } diff --git a/lib/features/consultations/presentation/pages/consultations_screen.dart b/lib/features/consultations/presentation/pages/consultations_screen.dart index 6f0021d9..ab9609b5 100644 --- a/lib/features/consultations/presentation/pages/consultations_screen.dart +++ b/lib/features/consultations/presentation/pages/consultations_screen.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/consultations/presentation/cubit/consultatio import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart'; import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_card_widget.dart'; import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/consultations/presentation/widgets/consultation_card_widget.dart b/lib/features/consultations/presentation/widgets/consultation_card_widget.dart index 7efa25f7..94c74932 100644 --- a/lib/features/consultations/presentation/widgets/consultation_card_widget.dart +++ b/lib/features/consultations/presentation/widgets/consultation_card_widget.dart @@ -3,14 +3,17 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; +import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/pages/diary_screen.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class ConsultationCardWidget extends StatefulWidget { @@ -34,6 +37,7 @@ class _ConsultationCardWidgetState extends State { final List legendColors = const [Colors.white, Color(0xFFF0C497), Color(0xFFFF9500), Color(0xFF2F80ED), Color(0xFF4CD964)]; late final List<(int, DiaryModel)> givenDaysWithDayNumber; + bool _isOpeningChat = false; final List> legendStates = [ [DiaryStateEnum.init], [DiaryStateEnum.started, DiaryStateEnum.lastDayStarted], @@ -81,6 +85,30 @@ class _ConsultationCardWidgetState extends State { widget.consultationsModel.planTitle, style: const TextStyle(height: 1, color: Color(0xFF88949F), fontSize: 14, fontWeight: FontWeight.w500), ), + if (widget.consultationsModel.personalDietId != null) ...[ + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: appTheme.transparentGreen, + borderRadius: BorderRadius.circular(100), + ), + child: Text( + widget.consultationsModel.personalDietName == null || + widget.consultationsModel.personalDietName!.isEmpty + ? s.personal_diet_proposed + : s.personal_diet_proposed_named( + widget.consultationsModel.personalDietName!, + ), + style: TextStyles.textXSSemibold.copyWith( + color: appTheme.greenA700, + ), + ), + ), + ], ], ), ], @@ -172,7 +200,7 @@ class _ConsultationCardWidgetState extends State { ); return; } - GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': day.$2.id,}); + GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': day.$2.id, 'ownerSlug': widget.consultationsModel.userSlug}); }, borderRadius: BorderRadius.circular(100), child: Ink( @@ -255,7 +283,7 @@ class _ConsultationCardWidgetState extends State { .where((e) => e.$2.state == DiaryStateEnum.finished || e.$2.state == DiaryStateEnum.lastDayFinished) .lastOrNull; if (lastActiveDay != null) { - GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': lastActiveDay.$2.id,}); + GoRouter.of(context).push(UserDiaryScreen.path, extra: {'diaryId': lastActiveDay.$2.id, 'ownerSlug': widget.consultationsModel.userSlug}); return; } showErrorDialog( @@ -279,7 +307,7 @@ class _ConsultationCardWidgetState extends State { const SizedBox(width: 8), InkWell( borderRadius: BorderRadius.circular(20), - onTap: () {}, + onTap: _isOpeningChat ? null : _openChat, child: Ink( height: 52, width: 52, @@ -308,6 +336,22 @@ class _ConsultationCardWidgetState extends State { ); } + Future _openChat() async { + if (_isOpeningChat) return; + setState(() => _isOpeningChat = true); + var chatId = widget.consultationsModel.chatId; + if (chatId == null || chatId.isEmpty) { + chatId = await context.read().getChatIdByUserSlug(widget.consultationsModel.userSlug); + } + if (!mounted) return; + setState(() => _isOpeningChat = false); + if (chatId == null || chatId.isEmpty) { + showErrorToast(S.of(context).msg_something_went_wrong); + return; + } + GoRouter.of(context).pushNamed('chatScreen', extra: {'uuid': chatId}); + } + Row _legendTitle(String text, Color color) { return Row( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/features/consultations/presentation/widgets/consultation_progress_plank.dart b/lib/features/consultations/presentation/widgets/consultation_progress_plank.dart new file mode 100644 index 00000000..64199f86 --- /dev/null +++ b/lib/features/consultations/presentation/widgets/consultation_progress_plank.dart @@ -0,0 +1,123 @@ +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +class ConsultationProgressPlank extends StatelessWidget { + const ConsultationProgressPlank({super.key, required this.progress}); + + final ConsultationProgress progress; + + static const _steps = [ + ConsultationStep.startDate, + ConsultationStep.paid, + ConsultationStep.inProgress, + ConsultationStep.finished, + ]; + + @override + Widget build(BuildContext context) { + if (!progress.showProgressPlank) { + return const SizedBox.shrink(); + } + + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (var index = 0; index < _steps.length; index++) + Expanded( + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Container( + height: 2, + color: index == 0 + ? Colors.transparent + : progress.isStepCompleted(_steps[index - 1]) + ? appTheme.greenA700 + : appTheme.lightGray00, + ), + ), + _ProgressStepCircle( + key: ValueKey('consultation_step_circle_$index'), + index: index, + isCompleted: progress.isStepCompleted(_steps[index]), + ), + Expanded( + child: Container( + height: 2, + color: index == _steps.length - 1 + ? Colors.transparent + : progress.isStepCompleted(_steps[index]) + ? appTheme.greenA700 + : appTheme.lightGray00, + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + _stepLabel(S.of(context), _steps[index]), + key: ValueKey('consultation_step_label_$index'), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyles.textFS10FW500.copyWith( + color: progress.isStepCompleted(_steps[index]) + ? appTheme.black + : appTheme.gray, + ), + ), + ], + ), + ), + ], + ); + } + + String _stepLabel(S s, ConsultationStep step) { + switch (step) { + case ConsultationStep.startDate: + return s.startDateHasBeenSet; + case ConsultationStep.paid: + return s.order_paid; + case ConsultationStep.inProgress: + return s.order_in_progress; + case ConsultationStep.finished: + return s.done; + } + } +} + +class _ProgressStepCircle extends StatelessWidget { + const _ProgressStepCircle({ + super.key, + required this.index, + required this.isCompleted, + }); + + final int index; + final bool isCompleted; + + @override + Widget build(BuildContext context) { + return Container( + width: 24, + height: 24, + alignment: Alignment.center, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isCompleted ? appTheme.greenA700 : appTheme.lightGray00, + ), + child: isCompleted + ? Icon(Icons.check, size: 14, color: appTheme.whiteA700) + : Text( + '${index + 1}', + style: TextStyles.textFS10FW500.copyWith(color: appTheme.gray), + ), + ); + } +} diff --git a/lib/features/consultations/presentation/widgets/personal_diet_status_chip.dart b/lib/features/consultations/presentation/widgets/personal_diet_status_chip.dart new file mode 100644 index 00000000..91464f41 --- /dev/null +++ b/lib/features/consultations/presentation/widgets/personal_diet_status_chip.dart @@ -0,0 +1,61 @@ +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +class PersonalDietStatusChip extends StatelessWidget { + const PersonalDietStatusChip({super.key, required this.progress}); + + final ConsultationProgress progress; + + @override + Widget build(BuildContext context) { + if (!progress.hasChip) { + return const SizedBox.shrink(); + } + + final s = S.of(context); + final (label, background, foreground) = _chipStyle(s); + + return Align( + alignment: Alignment.centerLeft, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(100), + ), + child: Text( + label, + style: TextStyles.textXSSemibold.copyWith(color: foreground), + ), + ), + ); + } + + (String, Color, Color) _chipStyle(S s) { + if (progress.isCanceled) { + return (s.orderCanceled, appTheme.lightRed, appTheme.red); + } + if (progress.isPaymentFailed) { + return (s.payment_failed, appTheme.lightRed, appTheme.red); + } + if (progress.dietStatus == PersonalDietStatus.proposed) { + final dietName = progress.personalDietName; + final label = dietName == null || dietName.isEmpty + ? s.personal_diet_proposed + : s.personal_diet_proposed_named(dietName); + return ( + label, + appTheme.transparentGreen, + appTheme.greenA700, + ); + } + return ( + s.personal_diet_not_proposed, + appTheme.gray100, + appTheme.gray, + ); + } +} diff --git a/lib/features/consultations/utils/consultation_progress_mapper.dart b/lib/features/consultations/utils/consultation_progress_mapper.dart new file mode 100644 index 00000000..c815c7a1 --- /dev/null +++ b/lib/features/consultations/utils/consultation_progress_mapper.dart @@ -0,0 +1,116 @@ +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; + +ConsultationProgress mapConsultationProgress({ + required ChosenPlanStateEnum state, + required bool hasPersonalDiet, + String? personalDietName, +}) { + return ConsultationProgress( + completedSteps: _completedSteps(state), + showProgressPlank: _showProgressPlank(state), + dietStatus: _dietStatus(state, hasPersonalDiet), + phase: _phase(state), + personalDietName: personalDietName, + ); +} + +Set _completedSteps(ChosenPlanStateEnum state) { + switch (state) { + case ChosenPlanStateEnum.stateInited: + case ChosenPlanStateEnum.stateConfirmedByConsultant: + case ChosenPlanStateEnum.stateInCoordination: + case ChosenPlanStateEnum.stateCanceledByTheInitiator: + return const {}; + case ChosenPlanStateEnum.stateStartDateHasBeenSet: + case ChosenPlanStateEnum.statePendingPayment: + case ChosenPlanStateEnum.statePaymentFailed: + return const {ConsultationStep.startDate}; + case ChosenPlanStateEnum.statePaid: + case ChosenPlanStateEnum.personalDietSet: + return const {ConsultationStep.startDate, ConsultationStep.paid}; + case ChosenPlanStateEnum.stateStarted: + case ChosenPlanStateEnum.stateInProgress: + case ChosenPlanStateEnum.stateLastDayStarted: + case ChosenPlanStateEnum.stateLastDayFinished: + case ChosenPlanStateEnum.stateComplained: + return const { + ConsultationStep.startDate, + ConsultationStep.paid, + ConsultationStep.inProgress, + }; + case ChosenPlanStateEnum.stateDone: + case ChosenPlanStateEnum.stateChargeWasCollected: + return const { + ConsultationStep.startDate, + ConsultationStep.paid, + ConsultationStep.inProgress, + ConsultationStep.finished, + }; + } +} + +bool _showProgressPlank(ChosenPlanStateEnum state) { + switch (state) { + case ChosenPlanStateEnum.stateInited: + case ChosenPlanStateEnum.stateConfirmedByConsultant: + case ChosenPlanStateEnum.stateChargeWasCollected: + case ChosenPlanStateEnum.stateCanceledByTheInitiator: + case ChosenPlanStateEnum.statePaymentFailed: + return false; + case ChosenPlanStateEnum.stateInCoordination: + case ChosenPlanStateEnum.stateStartDateHasBeenSet: + case ChosenPlanStateEnum.statePendingPayment: + case ChosenPlanStateEnum.statePaid: + case ChosenPlanStateEnum.personalDietSet: + case ChosenPlanStateEnum.stateStarted: + case ChosenPlanStateEnum.stateInProgress: + case ChosenPlanStateEnum.stateLastDayStarted: + case ChosenPlanStateEnum.stateLastDayFinished: + case ChosenPlanStateEnum.stateComplained: + case ChosenPlanStateEnum.stateDone: + return true; + } +} + +PersonalDietStatus _dietStatus( + ChosenPlanStateEnum state, + bool hasPersonalDiet, +) { + if (!hasPersonalDiet) { + return PersonalDietStatus.notRequired; + } + + switch (state) { + case ChosenPlanStateEnum.personalDietSet: + case ChosenPlanStateEnum.stateStarted: + case ChosenPlanStateEnum.stateInProgress: + case ChosenPlanStateEnum.stateLastDayStarted: + case ChosenPlanStateEnum.stateLastDayFinished: + case ChosenPlanStateEnum.stateComplained: + case ChosenPlanStateEnum.stateDone: + case ChosenPlanStateEnum.stateChargeWasCollected: + return PersonalDietStatus.proposed; + case ChosenPlanStateEnum.stateInited: + case ChosenPlanStateEnum.stateInCoordination: + case ChosenPlanStateEnum.stateConfirmedByConsultant: + case ChosenPlanStateEnum.stateStartDateHasBeenSet: + case ChosenPlanStateEnum.statePendingPayment: + case ChosenPlanStateEnum.statePaid: + return PersonalDietStatus.notProposed; + case ChosenPlanStateEnum.stateCanceledByTheInitiator: + case ChosenPlanStateEnum.statePaymentFailed: + return PersonalDietStatus.notRequired; + } +} + +ConsultationPhase _phase(ChosenPlanStateEnum state) { + switch (state) { + case ChosenPlanStateEnum.stateCanceledByTheInitiator: + return ConsultationPhase.canceled; + case ChosenPlanStateEnum.statePaymentFailed: + return ConsultationPhase.paymentFailed; + default: + return ConsultationPhase.active; + } +} diff --git a/lib/features/create_diet/presentation/create_diet_screen.dart b/lib/features/create_diet/presentation/create_diet_screen.dart index c04f1e1c..504c57e5 100644 --- a/lib/features/create_diet/presentation/create_diet_screen.dart +++ b/lib/features/create_diet/presentation/create_diet_screen.dart @@ -21,7 +21,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/status_drop import 'package:eatvio_app/features/create_diet/presentation/widgets/diet_type_choice_widget.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_diet/presentation/cubit/create_diet_cubit.dart b/lib/features/create_diet/presentation/cubit/create_diet_cubit.dart index 9788c7ce..f175af6c 100644 --- a/lib/features/create_diet/presentation/cubit/create_diet_cubit.dart +++ b/lib/features/create_diet/presentation/cubit/create_diet_cubit.dart @@ -324,7 +324,8 @@ class CreateDietCubit extends Cubit { final tempDir = await getTemporaryDirectory(); final filePath = '${tempDir.path}/${imageUrl.split('/').last}'; final file = File(filePath); - return file.writeAsBytes(response.bodyBytes); + await file.writeAsBytes(response.bodyBytes); + return file; } catch (e, st) { await reportFrom(e, st, this); return null; diff --git a/lib/features/create_diet/presentation/diet_preview_screen.dart b/lib/features/create_diet/presentation/diet_preview_screen.dart index fd5a2f3b..2106e900 100644 --- a/lib/features/create_diet/presentation/diet_preview_screen.dart +++ b/lib/features/create_diet/presentation/diet_preview_screen.dart @@ -16,7 +16,7 @@ import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class DietPreviewScreen extends StatefulWidget { diff --git a/lib/features/create_diet/presentation/widgets/add_meal_widget.dart b/lib/features/create_diet/presentation/widgets/add_meal_widget.dart index bfe5d823..ce3bb267 100644 --- a/lib/features/create_diet/presentation/widgets/add_meal_widget.dart +++ b/lib/features/create_diet/presentation/widgets/add_meal_widget.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AddMealWidget extends StatefulWidget { const AddMealWidget({ diff --git a/lib/features/create_diet/presentation/widgets/day_widget.dart b/lib/features/create_diet/presentation/widgets/day_widget.dart index 9e5fe5fb..bedbe056 100644 --- a/lib/features/create_diet/presentation/widgets/day_widget.dart +++ b/lib/features/create_diet/presentation/widgets/day_widget.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/add_meal_wi import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/choice_chip_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/create_diet/presentation/widgets/diet_duration_drop_down_widget.dart b/lib/features/create_diet/presentation/widgets/diet_duration_drop_down_widget.dart index 0c05c61f..e7dc76f2 100644 --- a/lib/features/create_diet/presentation/widgets/diet_duration_drop_down_widget.dart +++ b/lib/features/create_diet/presentation/widgets/diet_duration_drop_down_widget.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_s import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:collection/collection.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/create_diet/presentation/widgets/diet_image_picker_widget.dart b/lib/features/create_diet/presentation/widgets/diet_image_picker_widget.dart index 192df5d3..0b62df41 100644 --- a/lib/features/create_diet/presentation/widgets/diet_image_picker_widget.dart +++ b/lib/features/create_diet/presentation/widgets/diet_image_picker_widget.dart @@ -9,8 +9,8 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_c import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_diet/presentation/widgets/diet_type_choice_widget.dart b/lib/features/create_diet/presentation/widgets/diet_type_choice_widget.dart index b8db4b7a..3c0789f5 100644 --- a/lib/features/create_diet/presentation/widgets/diet_type_choice_widget.dart +++ b/lib/features/create_diet/presentation/widgets/diet_type_choice_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_cubit.dart'; import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/create_diet/presentation/widgets/error_widget.dart b/lib/features/create_diet/presentation/widgets/error_widget.dart index cab9324e..1c15057f 100644 --- a/lib/features/create_diet/presentation/widgets/error_widget.dart +++ b/lib/features/create_diet/presentation/widgets/error_widget.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class ValidationErrorWidget extends StatelessWidget { diff --git a/lib/features/create_diet/presentation/widgets/status_drop_down_widget.dart b/lib/features/create_diet/presentation/widgets/status_drop_down_widget.dart index 249e897a..665e423e 100644 --- a/lib/features/create_diet/presentation/widgets/status_drop_down_widget.dart +++ b/lib/features/create_diet/presentation/widgets/status_drop_down_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:collection/collection.dart'; diff --git a/lib/features/create_plan/presentation/create_plan_screen.dart b/lib/features/create_plan/presentation/create_plan_screen.dart index c3076ed0..0914efee 100644 --- a/lib/features/create_plan/presentation/create_plan_screen.dart +++ b/lib/features/create_plan/presentation/create_plan_screen.dart @@ -19,7 +19,7 @@ import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_image_ import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_type_choice_widget.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/select_exact_option_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_plan/presentation/widgets/option_widget.dart b/lib/features/create_plan/presentation/widgets/option_widget.dart index 29805d82..961ed21e 100644 --- a/lib/features/create_plan/presentation/widgets/option_widget.dart +++ b/lib/features/create_plan/presentation/widgets/option_widget.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_s import 'package:eatvio_app/features/create_plan/presentation/widgets/add_item_widget.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/create_plan/presentation/widgets/options_count_button.dart b/lib/features/create_plan/presentation/widgets/options_count_button.dart index 09833c70..a4efe545 100644 --- a/lib/features/create_plan/presentation/widgets/options_count_button.dart +++ b/lib/features/create_plan/presentation/widgets/options_count_button.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/animated_option_button.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class OptionsCountButton extends StatelessWidget { diff --git a/lib/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart b/lib/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart index ad4100c0..280e6428 100644 --- a/lib/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart +++ b/lib/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:collection/collection.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/create_plan/presentation/widgets/plan_image_picker_widget.dart b/lib/features/create_plan/presentation/widgets/plan_image_picker_widget.dart index 3083c8b6..2c945fd4 100644 --- a/lib/features/create_plan/presentation/widgets/plan_image_picker_widget.dart +++ b/lib/features/create_plan/presentation/widgets/plan_image_picker_widget.dart @@ -11,8 +11,8 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_plan/presentation/widgets/plan_type_choice_widget.dart b/lib/features/create_plan/presentation/widgets/plan_type_choice_widget.dart index a50d461d..26b26fd4 100644 --- a/lib/features/create_plan/presentation/widgets/plan_type_choice_widget.dart +++ b/lib/features/create_plan/presentation/widgets/plan_type_choice_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PlanTypeChoiceWidget extends StatefulWidget { diff --git a/lib/features/create_plan/presentation/widgets/select_exact_option_widget.dart b/lib/features/create_plan/presentation/widgets/select_exact_option_widget.dart index ba428c3e..6479350b 100644 --- a/lib/features/create_plan/presentation/widgets/select_exact_option_widget.dart +++ b/lib/features/create_plan/presentation/widgets/select_exact_option_widget.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SelectExactOptionWidget extends StatefulWidget { diff --git a/lib/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart b/lib/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart index e65fe5ef..aadcbf18 100644 --- a/lib/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart +++ b/lib/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart @@ -213,7 +213,8 @@ class CreateRecipeCubit extends Cubit { final tempDir = await getTemporaryDirectory(); final filePath = '${tempDir.path}/${imageUrl.split('/').last}'; final file = File(filePath); - return file.writeAsBytes(response.bodyBytes); + await file.writeAsBytes(response.bodyBytes); + return file; } catch (e, st) { await reportFrom(e, st, this); return null; diff --git a/lib/features/create_recipe/presentation/pages/recipe_create_screen.dart b/lib/features/create_recipe/presentation/pages/recipe_create_screen.dart index d4b622aa..1131c8df 100644 --- a/lib/features/create_recipe/presentation/pages/recipe_create_screen.dart +++ b/lib/features/create_recipe/presentation/pages/recipe_create_screen.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/features/create_recipe/presentation/widgets/ingredien import 'package:eatvio_app/features/create_recipe/presentation/widgets/steps_widget.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_recipe/presentation/widgets/add_portion_widget.dart b/lib/features/create_recipe/presentation/widgets/add_portion_widget.dart index 9fd0a25d..43928d4b 100644 --- a/lib/features/create_recipe/presentation/widgets/add_portion_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/add_portion_widget.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AddPortionWidget extends StatefulWidget { const AddPortionWidget({super.key, required this.createRecipeCubit, this.portionIndex, this.productNameControllerText, this.quantityControllerText}); diff --git a/lib/features/create_recipe/presentation/widgets/image_widget.dart b/lib/features/create_recipe/presentation/widgets/image_widget.dart index bbb93c35..8dffd6eb 100644 --- a/lib/features/create_recipe/presentation/widgets/image_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/image_widget.dart @@ -4,8 +4,8 @@ import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/permission_handler/permission_handler.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/create_recipe/presentation/widgets/info_about_recipe_widget.dart b/lib/features/create_recipe/presentation/widgets/info_about_recipe_widget.dart index 0eb609e4..3ce039c7 100644 --- a/lib/features/create_recipe/presentation/widgets/info_about_recipe_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/info_about_recipe_widget.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/create_recipe/presentation/widgets/image_wid import 'package:eatvio_app/features/create_recipe/presentation/widgets/portion_widget.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/tags_widget.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/time_of_cook_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class InfoAboutRecipeWidget extends StatefulWidget { diff --git a/lib/features/create_recipe/presentation/widgets/ingredients_widget.dart b/lib/features/create_recipe/presentation/widgets/ingredients_widget.dart index 6894c162..aa625597 100644 --- a/lib/features/create_recipe/presentation/widgets/ingredients_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/ingredients_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/add_portion_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class IngredientsWidget extends StatefulWidget { @@ -47,12 +47,7 @@ class _IngredientsWidgetState extends State { ReorderableListView( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), - onReorder: (int oldIndex, int newIndex) { - setState(() { - if (oldIndex < newIndex) { - newIndex -= 1; - } - }); + onReorderItem: (int oldIndex, int newIndex) { createRecipeCubit.replaceIngredientPosition(oldIndex, newIndex); }, children: [ diff --git a/lib/features/create_recipe/presentation/widgets/portion_widget.dart b/lib/features/create_recipe/presentation/widgets/portion_widget.dart index 608218b1..c122ccea 100644 --- a/lib/features/create_recipe/presentation/widgets/portion_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/portion_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PortionWidget extends StatefulWidget { diff --git a/lib/features/create_recipe/presentation/widgets/step_image_widget.dart b/lib/features/create_recipe/presentation/widgets/step_image_widget.dart index 8c18b185..7520a2ba 100644 --- a/lib/features/create_recipe/presentation/widgets/step_image_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/step_image_widget.dart @@ -4,8 +4,8 @@ import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/permission_handler/permission_handler.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:image_picker/image_picker.dart'; diff --git a/lib/features/create_recipe/presentation/widgets/steps_widget.dart b/lib/features/create_recipe/presentation/widgets/steps_widget.dart index 9beaa707..a4d9aebb 100644 --- a/lib/features/create_recipe/presentation/widgets/steps_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/steps_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/step_image_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class StepsWidget extends StatefulWidget { diff --git a/lib/features/create_recipe/presentation/widgets/tags_widget.dart b/lib/features/create_recipe/presentation/widgets/tags_widget.dart index 5356132e..d15f3fa3 100644 --- a/lib/features/create_recipe/presentation/widgets/tags_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/tags_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class TagsWidget extends StatefulWidget { diff --git a/lib/features/create_recipe/presentation/widgets/time_of_cook_widget.dart b/lib/features/create_recipe/presentation/widgets/time_of_cook_widget.dart index 78403de1..d0253dff 100644 --- a/lib/features/create_recipe/presentation/widgets/time_of_cook_widget.dart +++ b/lib/features/create_recipe/presentation/widgets/time_of_cook_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class TimeOfCookWidget extends StatefulWidget { diff --git a/lib/features/dev_tools/presentation/dev_tools_screen.dart b/lib/features/dev_tools/presentation/dev_tools_screen.dart index a21f9282..c6c2ace9 100644 --- a/lib/features/dev_tools/presentation/dev_tools_screen.dart +++ b/lib/features/dev_tools/presentation/dev_tools_screen.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/core/env_config.dart'; import 'package:eatvio_app/features/diary/presentation/pages/barcode_scanner_screen.dart'; import 'package:eatvio_app/features/barcode/repositories/barcode_repository.dart'; import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'dart:async'; diff --git a/lib/features/diary/entities/diary_day_entity.dart b/lib/features/diary/entities/diary_day_entity.dart index e533dda7..99dd1dad 100644 --- a/lib/features/diary/entities/diary_day_entity.dart +++ b/lib/features/diary/entities/diary_day_entity.dart @@ -17,6 +17,9 @@ abstract class DiaryDayEntity with _$DiaryDayEntity { @JsonKey(name: "chosen_plan_id") required int? chosenPlanId, @JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet, @JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet, + + /// Slug владельца дневника; `null`, если сервер его не вернул. + String? ownerSlug, }) = _DiaryDayEntity; const DiaryDayEntity._(); diff --git a/lib/features/diary/models/diary_day_model.dart b/lib/features/diary/models/diary_day_model.dart index 76a353d9..62212f1e 100644 --- a/lib/features/diary/models/diary_day_model.dart +++ b/lib/features/diary/models/diary_day_model.dart @@ -48,6 +48,10 @@ abstract class DiaryDayModel with _$DiaryDayModel { @JsonKey(name: "chosen_plan_id") required int? chosenPlanId, @JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet, @JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet, + + /// Владелец дневника (`user` в `DiaryResource`): по `slug` консультант + /// запрашивает `/api/profile/insights/{slug}`. + @JsonKey(name: "user") DiaryOwnerModel? owner, }) = _DiaryDayModel; const DiaryDayModel._(); factory DiaryDayModel.fromJson(Map json) => _$DiaryDayModelFromJson(json); @@ -68,6 +72,7 @@ abstract class DiaryDayModel with _$DiaryDayModel { wakeup: wakeup, retire: retire, diet: diet, + ownerSlug: owner?.slug, ); } @@ -81,6 +86,13 @@ DiaryDietModel? parseDiet(dynamic json) { return DiaryDietModel.fromJson(json['diet']); } +@freezed +abstract class DiaryOwnerModel with _$DiaryOwnerModel { + const factory DiaryOwnerModel({int? id, String? slug}) = _DiaryOwnerModel; + + factory DiaryOwnerModel.fromJson(Map json) => _$DiaryOwnerModelFromJson(json); +} + @freezed abstract class DiaryDietModel with _$DiaryDietModel { const factory DiaryDietModel({required int id, required int duration, required String name}) = _DiaryDietModel; diff --git a/lib/features/diary/presentation/pages/barcode_scanner_screen.dart b/lib/features/diary/presentation/pages/barcode_scanner_screen.dart index dde46894..561680b5 100644 --- a/lib/features/diary/presentation/pages/barcode_scanner_screen.dart +++ b/lib/features/diary/presentation/pages/barcode_scanner_screen.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; class BarcodeScannerScreen extends StatefulWidget { diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index b91bcba7..00c73b02 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -20,8 +20,10 @@ import 'package:eatvio_app/features/diary/presentation/widgets/day_comment_widge import 'package:eatvio_app/features/diary/presentation/widgets/finish_day_button_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/wakeup_and_retire_widget.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class DiaryScreen extends StatelessWidget { @@ -36,18 +38,27 @@ class DiaryScreen extends StatelessWidget { class UserDiaryScreen extends StatelessWidget { static const path = '/user-diary-screen'; static const name = 'userDiaryScreen'; - const UserDiaryScreen({super.key, required this.diaryId}); + const UserDiaryScreen({super.key, required this.diaryId, this.ownerSlug}); final int diaryId; + + /// Slug владельца дневника (клиента) — нужен консультанту для блока «Аналитика». + final String? ownerSlug; @override Widget build(BuildContext context) { - return DiaryScreenContent(diaryId: diaryId); + return DiaryScreenContent(diaryId: diaryId, ownerSlug: ownerSlug); } } class DiaryScreenContent extends StatefulWidget { - const DiaryScreenContent({super.key, this.diaryId, this.date}); + const DiaryScreenContent({ + super.key, + this.diaryId, + this.date, + this.ownerSlug, + }); final int? diaryId; final DateTime? date; + final String? ownerSlug; @override State createState() => _DiaryScreenContentState(); } @@ -55,6 +66,16 @@ class DiaryScreenContent extends StatefulWidget { class _DiaryScreenContentState extends State { bool _isDiaryFinishing = false; + /// Slug владельца: из `user.slug` дневника, иначе из параметра экрана. + String? _ownerSlug(DiaryStateLoaded state) { + return state.diary.ownerSlug ?? widget.ownerSlug; + } + + /// Консультант видит аналитику клиента только при известном slug владельца. + bool _canShowInsights(DiaryStateLoaded state) { + return !state.isConsultantView || _ownerSlug(state) != null; + } + @override Widget build(BuildContext context) { final s = S.of(context); @@ -110,6 +131,15 @@ class _DiaryScreenContentState extends State { const SizedBox(height: 60), const Loader(), ], + if (state is DiaryStateLoaded && _canShowInsights(state)) + Padding( + padding: const EdgeInsets.fromLTRB(4, 12, 4, 12), + child: _DiaryInsights( + slug: state.isConsultantView ? _ownerSlug(state) : null, + canAdd: !state.isConsultantView, + diaryDate: state.diary.date, + ), + ), if (state is DiaryStateLoaded) WakeupAndRetireWidget( isEnabled: @@ -249,3 +279,53 @@ class _DiaryScreenContentState extends State { ); } } + +/// Блок «Аналитика» в дневнике. Для своего дневника перезапрашивает данные, +/// когда в том же дне меняются приёмы пищи или время подъёма/отбоя: от них +/// зависят КБЖУ-графики. Чужой дневник консультант не редактирует. +class _DiaryInsights extends StatefulWidget { + const _DiaryInsights({ + required this.slug, + required this.canAdd, + required this.diaryDate, + }); + + final String? slug; + final bool canAdd; + + /// Дата открытого дня дневника (`YYYY-MM-DD`) — стартовый день «В течение дня». + final String diaryDate; + + @override + State<_DiaryInsights> createState() => _DiaryInsightsState(); +} + +class _DiaryInsightsState extends State<_DiaryInsights> { + int _refreshToken = 0; + + bool _isOwnDiaryMutation(DiaryState previous, DiaryState current) { + if (!widget.canAdd || + previous is! DiaryStateLoaded || + current is! DiaryStateLoaded || + previous.diary.id != current.diary.id) { + return false; + } + return !listEquals(previous.diary.meals, current.diary.meals) || + previous.diary.wakeup != current.diary.wakeup || + previous.diary.retire != current.diary.retire; + } + + @override + Widget build(BuildContext context) { + return BlocListener( + listenWhen: _isOwnDiaryMutation, + listener: (context, state) => setState(() => _refreshToken++), + child: InsightsCard( + slug: widget.slug, + canAdd: widget.canAdd, + refreshToken: _refreshToken, + initialIntraDate: widget.diaryDate, + ), + ); + } +} diff --git a/lib/features/diary/presentation/widgets/add_product_button_widget.dart b/lib/features/diary/presentation/widgets/add_product_button_widget.dart index b804989a..59427b9d 100644 --- a/lib/features/diary/presentation/widgets/add_product_button_widget.dart +++ b/lib/features/diary/presentation/widgets/add_product_button_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/add_product_modal.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AddProductButtonWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/add_product_modal.dart b/lib/features/diary/presentation/widgets/add_product_modal.dart index 611652cf..1247b0ff 100644 --- a/lib/features/diary/presentation/widgets/add_product_modal.dart +++ b/lib/features/diary/presentation/widgets/add_product_modal.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class AddProductModal extends StatefulWidget { final PortionModel? portion; diff --git a/lib/features/diary/presentation/widgets/calendar_widget.dart b/lib/features/diary/presentation/widgets/calendar_widget.dart index 56361371..0ad135f4 100644 --- a/lib/features/diary/presentation/widgets/calendar_widget.dart +++ b/lib/features/diary/presentation/widgets/calendar_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:table_calendar/table_calendar.dart'; diff --git a/lib/features/diary/presentation/widgets/calories_chart_widget.dart b/lib/features/diary/presentation/widgets/calories_chart_widget.dart index 4aca0334..884f208b 100644 --- a/lib/features/diary/presentation/widgets/calories_chart_widget.dart +++ b/lib/features/diary/presentation/widgets/calories_chart_widget.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncfusion_flutter_gauges/gauges.dart'; diff --git a/lib/features/diary/presentation/widgets/chosen_diet_widget.dart b/lib/features/diary/presentation/widgets/chosen_diet_widget.dart index 622e0e5e..97af2ba4 100644 --- a/lib/features/diary/presentation/widgets/chosen_diet_widget.dart +++ b/lib/features/diary/presentation/widgets/chosen_diet_widget.dart @@ -4,8 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -19,9 +18,7 @@ class ChosenDietWidget extends StatelessWidget { if (state is DiaryStateLoaded) { if (state.diary.typeOfDiary.hasChosenDiet) { return ChosenDietWidgetContent( - currentDietDay: state.diary.dayOfChosenDiet ?? 0, dietName: state.diary.diet?.name ?? '', - dietDuration: state.diary.diet?.duration ?? 0, dietId: state.diary.diet?.id ?? 0, ); } @@ -33,9 +30,7 @@ class ChosenDietWidget extends StatelessWidget { const CustomDivider(), const SizedBox(height: 16), ChosenDietWidgetContent( - currentDietDay: state.diary.dayOfChosenDiet ?? 0, dietName: state.diary.diet?.name ?? '', - dietDuration: state.diary.diet?.duration ?? 0, dietId: state.diary.diet?.id ?? 0, ), ], @@ -50,15 +45,11 @@ class ChosenDietWidget extends StatelessWidget { } class ChosenDietWidgetContent extends StatelessWidget { - const ChosenDietWidgetContent({super.key, required this.currentDietDay, required this.dietName, required this.dietDuration, required this.dietId}); - final int currentDietDay; + const ChosenDietWidgetContent({super.key, required this.dietName, required this.dietId}); final String dietName; - final int dietDuration; final int dietId; @override Widget build(BuildContext context) { - final size = MediaQuery.sizeOf(context); - final s = S.of(context); return GestureDetector( onTap: () { GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false}); @@ -67,19 +58,12 @@ class ChosenDietWidgetContent extends StatelessWidget { children: [ Row( children: [ - SizedBox( - width: size.width * 0.4, + Expanded( child: Text( dietName, style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline), ), ), - const Spacer(), - Container( - decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)), - padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12), - child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)), - ), ], ), const SizedBox(height: 16), diff --git a/lib/features/diary/presentation/widgets/chosen_plan_widget.dart b/lib/features/diary/presentation/widgets/chosen_plan_widget.dart index d8c51ba9..a9018a6e 100644 --- a/lib/features/diary/presentation/widgets/chosen_plan_widget.dart +++ b/lib/features/diary/presentation/widgets/chosen_plan_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ChosenPlanWidget extends StatelessWidget { diff --git a/lib/features/diary/presentation/widgets/comment_container.dart b/lib/features/diary/presentation/widgets/comment_container.dart index 24f7ff38..7faade3d 100644 --- a/lib/features/diary/presentation/widgets/comment_container.dart +++ b/lib/features/diary/presentation/widgets/comment_container.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CommentContainer extends StatelessWidget { const CommentContainer({super.key, required this.comment}); diff --git a/lib/features/diary/presentation/widgets/comment_for_consultant_widget.dart b/lib/features/diary/presentation/widgets/comment_for_consultant_widget.dart index bf73970a..7b437ce9 100644 --- a/lib/features/diary/presentation/widgets/comment_for_consultant_widget.dart +++ b/lib/features/diary/presentation/widgets/comment_for_consultant_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class CommentForConsultantWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/day_comment_widget.dart b/lib/features/diary/presentation/widgets/day_comment_widget.dart index fa6d3ffa..087d0aaf 100644 --- a/lib/features/diary/presentation/widgets/day_comment_widget.dart +++ b/lib/features/diary/presentation/widgets/day_comment_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class DayCommentWidget extends StatelessWidget { diff --git a/lib/features/diary/presentation/widgets/finish_day_button_widget.dart b/lib/features/diary/presentation/widgets/finish_day_button_widget.dart index d38e32e3..684ffb20 100644 --- a/lib/features/diary/presentation/widgets/finish_day_button_widget.dart +++ b/lib/features/diary/presentation/widgets/finish_day_button_widget.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FinishDayButtonWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart b/lib/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart index 1c93bb8f..eabec23b 100644 --- a/lib/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart +++ b/lib/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:lottie/lottie.dart'; class GlossaryModerationRequestModalWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/meal_button_widget.dart b/lib/features/diary/presentation/widgets/meal_button_widget.dart index 9e17c217..c12dd567 100644 --- a/lib/features/diary/presentation/widgets/meal_button_widget.dart +++ b/lib/features/diary/presentation/widgets/meal_button_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_summary_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MealButtonWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/meal_comment_widget.dart b/lib/features/diary/presentation/widgets/meal_comment_widget.dart index da5f3b11..e5f971aa 100644 --- a/lib/features/diary/presentation/widgets/meal_comment_widget.dart +++ b/lib/features/diary/presentation/widgets/meal_comment_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MealCommentWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/meal_summary_widget.dart b/lib/features/diary/presentation/widgets/meal_summary_widget.dart index 934786bf..23a5e69b 100644 --- a/lib/features/diary/presentation/widgets/meal_summary_widget.dart +++ b/lib/features/diary/presentation/widgets/meal_summary_widget.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class MealSummaryWidget extends StatelessWidget { final List portions; diff --git a/lib/features/diary/presentation/widgets/meal_widget.dart b/lib/features/diary/presentation/widgets/meal_widget.dart index 21b7fe20..3f0807b9 100644 --- a/lib/features/diary/presentation/widgets/meal_widget.dart +++ b/lib/features/diary/presentation/widgets/meal_widget.dart @@ -15,7 +15,7 @@ import 'package:eatvio_app/features/diary/presentation/widgets/products_list_wid import 'package:eatvio_app/features/diary/presentation/widgets/satiety_rating_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/time_of_meal_picker_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MealWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/mood_rating_widget.dart b/lib/features/diary/presentation/widgets/mood_rating_widget.dart index c6057764..cf30163b 100644 --- a/lib/features/diary/presentation/widgets/mood_rating_widget.dart +++ b/lib/features/diary/presentation/widgets/mood_rating_widget.dart @@ -1,7 +1,7 @@ import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/cupertino.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/diary/presentation/widgets/photo_gallery_widget.dart b/lib/features/diary/presentation/widgets/photo_gallery_widget.dart index cbd65add..3fb612a5 100644 --- a/lib/features/diary/presentation/widgets/photo_gallery_widget.dart +++ b/lib/features/diary/presentation/widgets/photo_gallery_widget.dart @@ -10,8 +10,8 @@ import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/diary/presentation/widgets/portion_comment_widget.dart b/lib/features/diary/presentation/widgets/portion_comment_widget.dart index 8c4c1b13..09b7fc5d 100644 --- a/lib/features/diary/presentation/widgets/portion_comment_widget.dart +++ b/lib/features/diary/presentation/widgets/portion_comment_widget.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/comment_container.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PortionCommentWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/product_loader_widget.dart b/lib/features/diary/presentation/widgets/product_loader_widget.dart index 7b679354..dbfeda02 100644 --- a/lib/features/diary/presentation/widgets/product_loader_widget.dart +++ b/lib/features/diary/presentation/widgets/product_loader_widget.dart @@ -1,5 +1,5 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; class ProductLoaderWidget extends StatefulWidget { const ProductLoaderWidget({ diff --git a/lib/features/diary/presentation/widgets/product_widget.dart b/lib/features/diary/presentation/widgets/product_widget.dart index ccf0d0dd..0f28b580 100644 --- a/lib/features/diary/presentation/widgets/product_widget.dart +++ b/lib/features/diary/presentation/widgets/product_widget.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/add_product_modal.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/portion_comment_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/diary/presentation/widgets/products_list_widget.dart b/lib/features/diary/presentation/widgets/products_list_widget.dart index d3d7ac10..6aa53c9a 100644 --- a/lib/features/diary/presentation/widgets/products_list_widget.dart +++ b/lib/features/diary/presentation/widgets/products_list_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_summary_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/product_loader_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/product_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ProductsListWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/satiety_rating_widget.dart b/lib/features/diary/presentation/widgets/satiety_rating_widget.dart index a463196d..2231674d 100644 --- a/lib/features/diary/presentation/widgets/satiety_rating_widget.dart +++ b/lib/features/diary/presentation/widgets/satiety_rating_widget.dart @@ -1,7 +1,7 @@ import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/cupertino.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/diary/presentation/widgets/time_of_meal_picker_widget.dart b/lib/features/diary/presentation/widgets/time_of_meal_picker_widget.dart index eb85f711..4919ccc6 100644 --- a/lib/features/diary/presentation/widgets/time_of_meal_picker_widget.dart +++ b/lib/features/diary/presentation/widgets/time_of_meal_picker_widget.dart @@ -2,8 +2,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class TimeOfMealPickerWidget extends StatefulWidget { diff --git a/lib/features/diary/presentation/widgets/wakeup_and_retire_widget.dart b/lib/features/diary/presentation/widgets/wakeup_and_retire_widget.dart index 6e74f5ec..7421cf2f 100644 --- a/lib/features/diary/presentation/widgets/wakeup_and_retire_widget.dart +++ b/lib/features/diary/presentation/widgets/wakeup_and_retire_widget.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/diets/presentation/pages/about_diet_screen.dart b/lib/features/diets/presentation/pages/about_diet_screen.dart index 1eb81593..6e3bcd2c 100644 --- a/lib/features/diets/presentation/pages/about_diet_screen.dart +++ b/lib/features/diets/presentation/pages/about_diet_screen.dart @@ -27,7 +27,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/diets/presentation/widgets/author_card.dart b/lib/features/diets/presentation/widgets/author_card.dart index 69a92966..705c717f 100644 --- a/lib/features/diets/presentation/widgets/author_card.dart +++ b/lib/features/diets/presentation/widgets/author_card.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/diets/presentation/widgets/calendar_widget.dart b/lib/features/diets/presentation/widgets/calendar_widget.dart index 1daace4b..b88a78d8 100644 --- a/lib/features/diets/presentation/widgets/calendar_widget.dart +++ b/lib/features/diets/presentation/widgets/calendar_widget.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/utils/string_extentions.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:intl/intl.dart'; import 'package:table_calendar/table_calendar.dart'; diff --git a/lib/features/diets/presentation/widgets/cancel_diet_bottom_sheet.dart b/lib/features/diets/presentation/widgets/cancel_diet_bottom_sheet.dart index 3a324c19..4c455812 100644 --- a/lib/features/diets/presentation/widgets/cancel_diet_bottom_sheet.dart +++ b/lib/features/diets/presentation/widgets/cancel_diet_bottom_sheet.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diets/presentation/widgets/start_diet_bottom import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class CancelDietBottomSheet extends StatelessWidget { const CancelDietBottomSheet({super.key, required this.aboutDietCubit, this.title, this.dietName}); diff --git a/lib/features/diets/presentation/widgets/expandable_text.dart b/lib/features/diets/presentation/widgets/expandable_text.dart index bb2bb9e7..4f4eee93 100644 --- a/lib/features/diets/presentation/widgets/expandable_text.dart +++ b/lib/features/diets/presentation/widgets/expandable_text.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; class ExpandableText extends StatefulWidget { diff --git a/lib/features/diets/presentation/widgets/info_bouble.dart b/lib/features/diets/presentation/widgets/info_bouble.dart index 1cb12f9d..3ca8027d 100644 --- a/lib/features/diets/presentation/widgets/info_bouble.dart +++ b/lib/features/diets/presentation/widgets/info_bouble.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class InfoBouble extends StatelessWidget { const InfoBouble({ diff --git a/lib/features/diets/presentation/widgets/more_options.dart b/lib/features/diets/presentation/widgets/more_options.dart index cb3e33b2..fa8b089a 100644 --- a/lib/features/diets/presentation/widgets/more_options.dart +++ b/lib/features/diets/presentation/widgets/more_options.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:share_plus/share_plus.dart'; diff --git a/lib/features/diets/presentation/widgets/start_diet_bottom_sheet.dart b/lib/features/diets/presentation/widgets/start_diet_bottom_sheet.dart index d05dc121..c53ee80f 100644 --- a/lib/features/diets/presentation/widgets/start_diet_bottom_sheet.dart +++ b/lib/features/diets/presentation/widgets/start_diet_bottom_sheet.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class StartDietBottomSheet extends StatefulWidget { const StartDietBottomSheet({super.key, required this.aboutDietCubit}); diff --git a/lib/features/diets/presentation/widgets/type_badges.dart b/lib/features/diets/presentation/widgets/type_badges.dart index e852b084..d5e0673e 100644 --- a/lib/features/diets/presentation/widgets/type_badges.dart +++ b/lib/features/diets/presentation/widgets/type_badges.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart index a88d4623..0aa05206 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart @@ -12,9 +12,19 @@ class FeedCubit extends Cubit { bool _hasMore = true; bool isLoading = false; String? _query; + int _requestId = 0; FeedCubit({required this.feedRepository}) : super(const FeedState.loading()); + void reset() { + _requestId++; + _nextCursor = null; + _hasMore = true; + isLoading = false; + _query = null; + if (!isClosed) emit(const FeedState.loading()); + } + void updateFeedBlogPostList(FeedBlogPostModel? feedBlogPostModel, bool wasLikedByMe) { if (feedBlogPostModel == null || isClosed || state is! FeedStateLoaded) return; final List feedBlogPostList = [...(state as FeedStateLoaded).feedBlogPostList]; @@ -39,17 +49,18 @@ class FeedCubit extends Cubit { } Future loadFeedBlogPostList({String? query, int? currentUserId}) async { + final requestId = ++_requestId; try { _query = query; _nextCursor = null; _hasMore = true; final feed = await feedRepository.getFeed(search: query, currentUserId: currentUserId); + if (isClosed || requestId != _requestId) return; _nextCursor = feed.nextCursor; _hasMore = _nextCursor != null; - if (!isClosed) { - emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false)); - } + emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false)); } catch (e, st) { + if (isClosed || requestId != _requestId) return; await reportFrom(e, st, this); if (!isClosed) { emit(FeedState.error(errorMessage: e.toString())); @@ -62,14 +73,16 @@ class FeedCubit extends Cubit { return; } + final requestId = _requestId; isLoading = true; emit((state as FeedStateLoaded).copyWith(isLoading: true)); try { final feed = await feedRepository.getFeed(search: _query, cursor: _nextCursor, currentUserId: currentUserId); + if (isClosed || requestId != _requestId) return; _nextCursor = feed.nextCursor; _hasMore = _nextCursor != null; - if (!isClosed && state is FeedStateLoaded) { + if (state is FeedStateLoaded) { emit( FeedState.loaded( feedBlogPostList: [...(state as FeedStateLoaded).feedBlogPostList, ...feed.posts], @@ -78,14 +91,15 @@ class FeedCubit extends Cubit { ); } } catch (e, st) { + if (isClosed || requestId != _requestId) return; await reportFrom(e, st, this); - if (!isClosed && state is FeedStateLoaded) { + if (state is FeedStateLoaded) { emit((state as FeedStateLoaded).copyWith(isLoading: false)); - } else if (!isClosed) { + } else { emit(FeedState.error(errorMessage: e.toString())); } } finally { - isLoading = false; + if (requestId == _requestId) isLoading = false; } } diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index 0dfb28e8..74c21b49 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -25,7 +25,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cub import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_recipe/presentation/pages/recipe_create_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/feed/presentation/widgets/blog_post_media_content.dart b/lib/features/feed/presentation/widgets/blog_post_media_content.dart index 03dd10a4..476dd4a1 100644 --- a/lib/features/feed/presentation/widgets/blog_post_media_content.dart +++ b/lib/features/feed/presentation/widgets/blog_post_media_content.dart @@ -5,7 +5,7 @@ import 'package:carousel_slider_plus/carousel_slider_plus.dart'; import 'package:eatvio_app/features/feed/models/post_feed_mapper.dart'; import 'package:eatvio_app/features/feed/models/post_feed_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Gallery + optional embed video for feed card and blog post detail. class BlogPostMediaContent extends StatefulWidget { diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index 98de8abc..3a62316b 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/features/feed/models/post_feed_mapper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_media_content.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/subscribe_button_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/feed/presentation/widgets/blog_posts.dart b/lib/features/feed/presentation/widgets/blog_posts.dart index afae31c7..70ff0e4a 100644 --- a/lib/features/feed/presentation/widgets/blog_posts.dart +++ b/lib/features/feed/presentation/widgets/blog_posts.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state import 'package:eatvio_app/features/feed/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:visibility_detector/visibility_detector.dart'; diff --git a/lib/features/feed/presentation/widgets/choice_chip_widget.dart b/lib/features/feed/presentation/widgets/choice_chip_widget.dart index a2e7fc30..4e127074 100644 --- a/lib/features/feed/presentation/widgets/choice_chip_widget.dart +++ b/lib/features/feed/presentation/widgets/choice_chip_widget.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ChoiceChipWidget extends StatelessWidget { const ChoiceChipWidget({ diff --git a/lib/features/feed/presentation/widgets/comments_widget.dart b/lib/features/feed/presentation/widgets/comments_widget.dart index e1383e9a..5e19991d 100644 --- a/lib/features/feed/presentation/widgets/comments_widget.dart +++ b/lib/features/feed/presentation/widgets/comments_widget.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/feed/models/comment_model.dart'; import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/feed/presentation/widgets/consultant_widget.dart b/lib/features/feed/presentation/widgets/consultant_widget.dart index 686b1244..fcb31dc5 100644 --- a/lib/features/feed/presentation/widgets/consultant_widget.dart +++ b/lib/features/feed/presentation/widgets/consultant_widget.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/core/widgets/network_svg_picture.dart'; import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart'; import 'package:eatvio_app/features/profile/models/badge_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/feed/presentation/widgets/consultants.dart b/lib/features/feed/presentation/widgets/consultants.dart index 4aed497c..f1c5abd7 100644 --- a/lib/features/feed/presentation/widgets/consultants.dart +++ b/lib/features/feed/presentation/widgets/consultants.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/consultant_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class Consultants extends StatelessWidget { diff --git a/lib/features/feed/presentation/widgets/diet_filter_bottom_sheet.dart b/lib/features/feed/presentation/widgets/diet_filter_bottom_sheet.dart index 2a7c17a8..289cf21d 100644 --- a/lib/features/feed/presentation/widgets/diet_filter_bottom_sheet.dart +++ b/lib/features/feed/presentation/widgets/diet_filter_bottom_sheet.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.d import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class DietFilterBottomSheet extends StatelessWidget { const DietFilterBottomSheet({super.key, this.dietsCubit, this.myDietsCubit}); diff --git a/lib/features/feed/presentation/widgets/diets.dart b/lib/features/feed/presentation/widgets/diets.dart index 080b1a14..c528bc9d 100644 --- a/lib/features/feed/presentation/widgets/diets.dart +++ b/lib/features/feed/presentation/widgets/diets.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/diet_filter_bottom_sheet.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/diets_widget.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/filter_badge.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:visibility_detector/visibility_detector.dart'; diff --git a/lib/features/feed/presentation/widgets/diets_widget.dart b/lib/features/feed/presentation/widgets/diets_widget.dart index 93268f27..6281e779 100644 --- a/lib/features/feed/presentation/widgets/diets_widget.dart +++ b/lib/features/feed/presentation/widgets/diets_widget.dart @@ -11,7 +11,7 @@ import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_cubit.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart b/lib/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart index 2f850923..dfe3696c 100644 --- a/lib/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart +++ b/lib/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/feed/presentation/widgets/feed_video_player/ import 'package:eatvio_app/features/feed/presentation/widgets/feed_video_player/feed_video_embed_scripts.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/feed_video_player/feed_video_preview_placeholder.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; diff --git a/lib/features/feed/presentation/widgets/feed_video_player/feed_video_preview_placeholder.dart b/lib/features/feed/presentation/widgets/feed_video_player/feed_video_preview_placeholder.dart index 1721e45b..c3541f74 100644 --- a/lib/features/feed/presentation/widgets/feed_video_player/feed_video_preview_placeholder.dart +++ b/lib/features/feed/presentation/widgets/feed_video_player/feed_video_preview_placeholder.dart @@ -1,5 +1,5 @@ import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class FeedVideoPreviewPlaceholder extends StatelessWidget { const FeedVideoPreviewPlaceholder({ diff --git a/lib/features/feed/presentation/widgets/filter_badge.dart b/lib/features/feed/presentation/widgets/filter_badge.dart index 5778dfe6..78d3c41a 100644 --- a/lib/features/feed/presentation/widgets/filter_badge.dart +++ b/lib/features/feed/presentation/widgets/filter_badge.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; class FilterBadge extends StatelessWidget { diff --git a/lib/features/feed/presentation/widgets/plan_widget.dart b/lib/features/feed/presentation/widgets/plan_widget.dart index 13f57367..a8a05179 100644 --- a/lib/features/feed/presentation/widgets/plan_widget.dart +++ b/lib/features/feed/presentation/widgets/plan_widget.dart @@ -15,7 +15,7 @@ import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/feed/presentation/widgets/plans.dart b/lib/features/feed/presentation/widgets/plans.dart index 42e107e5..78bd3f65 100644 --- a/lib/features/feed/presentation/widgets/plans.dart +++ b/lib/features/feed/presentation/widgets/plans.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/filter_badge.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/plans_filter_bottom_sheet.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:visibility_detector/visibility_detector.dart'; diff --git a/lib/features/feed/presentation/widgets/plans_filter_bottom_sheet.dart b/lib/features/feed/presentation/widgets/plans_filter_bottom_sheet.dart index c5ab32ba..118995ce 100644 --- a/lib/features/feed/presentation/widgets/plans_filter_bottom_sheet.dart +++ b/lib/features/feed/presentation/widgets/plans_filter_bottom_sheet.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.d import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class PlansFilterBottomSheet extends StatelessWidget { const PlansFilterBottomSheet({super.key, this.plansCubit, this.myPlansCubit}); diff --git a/lib/features/feed/presentation/widgets/price_choice_filter_widget.dart b/lib/features/feed/presentation/widgets/price_choice_filter_widget.dart index ce7e43cf..68ec0237 100644 --- a/lib/features/feed/presentation/widgets/price_choice_filter_widget.dart +++ b/lib/features/feed/presentation/widgets/price_choice_filter_widget.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cub import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.dart'; import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PriceChoiceFilterWidget extends StatefulWidget { diff --git a/lib/features/feed/presentation/widgets/recipes.dart b/lib/features/feed/presentation/widgets/recipes.dart index 1271a493..af981a14 100644 --- a/lib/features/feed/presentation/widgets/recipes.dart +++ b/lib/features/feed/presentation/widgets/recipes.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/recipes_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:visibility_detector/visibility_detector.dart'; diff --git a/lib/features/feed/presentation/widgets/recipes_widget.dart b/lib/features/feed/presentation/widgets/recipes_widget.dart index 01438f7d..8e4ddd7b 100644 --- a/lib/features/feed/presentation/widgets/recipes_widget.dart +++ b/lib/features/feed/presentation/widgets/recipes_widget.dart @@ -14,7 +14,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/feed/presentation/widgets/sorting_drop_down_filter.dart b/lib/features/feed/presentation/widgets/sorting_drop_down_filter.dart index f77a14c8..b106624b 100644 --- a/lib/features/feed/presentation/widgets/sorting_drop_down_filter.dart +++ b/lib/features/feed/presentation/widgets/sorting_drop_down_filter.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.d import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:collection/collection.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/feed/presentation/widgets/subscribe_button_widget.dart b/lib/features/feed/presentation/widgets/subscribe_button_widget.dart index c927d810..de5103fb 100644 --- a/lib/features/feed/presentation/widgets/subscribe_button_widget.dart +++ b/lib/features/feed/presentation/widgets/subscribe_button_widget.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class SubscribeButtonWidget extends StatefulWidget { final String slug; diff --git a/lib/features/feed/presentation/widgets/tags_modal_widget.dart b/lib/features/feed/presentation/widgets/tags_modal_widget.dart index 640f5ac0..794d1116 100644 --- a/lib/features/feed/presentation/widgets/tags_modal_widget.dart +++ b/lib/features/feed/presentation/widgets/tags_modal_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/create_recipe/models/recipe_tag_model.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class TagsModalWidget extends StatefulWidget { diff --git a/lib/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart b/lib/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart index 085e9fa6..1cf4c1fa 100644 --- a/lib/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart +++ b/lib/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/period_en import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart b/lib/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart index c356e9fb..f00b858e 100644 --- a/lib/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart +++ b/lib/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart @@ -11,7 +11,7 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/period_en import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ConsultationsArchiveScreen extends StatefulWidget { diff --git a/lib/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart b/lib/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart index 67d4652f..8466d83e 100644 --- a/lib/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart +++ b/lib/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart @@ -11,7 +11,7 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/period_en import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class UserPurchasesScreen extends StatefulWidget { diff --git a/lib/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart b/lib/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart index fab1fc21..dc701f23 100644 --- a/lib/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart +++ b/lib/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class StatusWidget extends StatelessWidget { const StatusWidget({super.key, required this.status}); diff --git a/lib/features/glossary/presentation/pages/glossary_screen.dart b/lib/features/glossary/presentation/pages/glossary_screen.dart index 3df941cb..3ec38953 100644 --- a/lib/features/glossary/presentation/pages/glossary_screen.dart +++ b/lib/features/glossary/presentation/pages/glossary_screen.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:webview_flutter/webview_flutter.dart'; const _passKeyLoginPath = 'login_with_pass_key'; diff --git a/lib/features/insights/domain/insights_text_builder.dart b/lib/features/insights/domain/insights_text_builder.dart new file mode 100644 index 00000000..f6673022 --- /dev/null +++ b/lib/features/insights/domain/insights_text_builder.dart @@ -0,0 +1,222 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/profile/models/weight_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; + +/// Собирает [InsightsPayloadModel] из сырых точек мобильного API. +/// +/// Зеркало веб-`UserInsightsService`: порог изменения [deltaEpsilon], минимум две +/// точки для дельты, те же категории ИМТ и формат подписей. +class InsightsTextBuilder { + InsightsTextBuilder(this.s); + + final S s; + + static const double deltaEpsilon = 0.05; + static const String _emptyHeadline = '—'; + + InsightsPayloadModel build({ + required List weights, + required List circumferences, + required BodyPeriod period, + int? heightCm, + }) { + final sortedWeights = [...weights] + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + final sortedCircumferences = [...circumferences] + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + + return InsightsPayloadModel( + weight: buildWeight(sortedWeights, period), + bmi: buildBmi(sortedWeights, period, heightCm), + measure: buildMeasure(sortedCircumferences, period), + ); + } + + WeightChartModel buildWeight(List weights, BodyPeriod period) { + final values = weights.map((e) => e.weight).toList(); + final last = values.isEmpty ? null : values.last; + final delta = values.length < 2 ? null : _round(values.last - values.first); + + return WeightChartModel( + labels: weights.map((e) => formatLabel(e.createdAt)).toList(), + values: values, + last: last, + delta: delta, + headline: last == null ? _emptyHeadline : last.toStringAsFixed(1), + unit: s.insights_unit_kg, + deltaText: _weightDeltaText(values, period), + ); + } + + BmiChartModel buildBmi( + List weights, + BodyPeriod period, + int? heightCm, + ) { + final hasHeight = heightCm != null && heightCm > 0; + if (!hasHeight) { + return BmiChartModel( + headline: _emptyHeadline, + deltaText: s.insights_need_height, + hint: s.insights_need_height, + ); + } + + final points = weights.where((e) => e.bmi != null).toList(); + final values = points.map((e) => e.bmi!).toList(); + final last = values.isEmpty ? null : values.last; + final delta = values.length < 2 ? null : _round(values.last - values.first); + final category = last == null ? null : bmiCategory(last); + + return BmiChartModel( + labels: points.map((e) => formatLabel(e.createdAt)).toList(), + values: values, + last: last, + delta: delta, + headline: last == null ? _emptyHeadline : last.toStringAsFixed(1), + category: category, + deltaText: _bmiDeltaText(values, period, category), + hint: s.insights_bmi_hint(heightCm.toString()), + ); + } + + MeasureChartModel buildMeasure( + List circumferences, + BodyPeriod period, + ) { + final waist = circumferences.map((e) => e.waistCircumference).toList(); + final chest = circumferences.map((e) => e.chestCircumference).toList(); + final hips = circumferences.map((e) => e.hipCircumference).toList(); + + return MeasureChartModel( + labels: circumferences.map((e) => formatLabel(e.createdAt)).toList(), + waist: waist, + chest: chest, + hips: hips, + headline: waist.isEmpty ? _emptyHeadline : waist.last.round().toString(), + deltaText: _measureDeltaText( + waist: waist, + chest: chest, + hips: hips, + period: period, + ), + ); + } + + /// Категория по таблице ВОЗ из постановки #2120. + String bmiCategory(double bmi) { + if (bmi < 16) { + return s.insights_bmi_severe_underweight; + } + if (bmi < 18.5) { + return s.insights_bmi_underweight; + } + if (bmi < 25) { + return s.insights_bmi_normal; + } + if (bmi < 30) { + return s.insights_bmi_overweight; + } + if (bmi < 35) { + return s.insights_bmi_obesity_1; + } + if (bmi < 40) { + return s.insights_bmi_obesity_2; + } + return s.insights_bmi_obesity_3; + } + + String periodLabel(BodyPeriod period) { + switch (period) { + case BodyPeriod.month: + return s.insights_period_label_1; + case BodyPeriod.threeMonths: + return s.insights_period_label_3; + case BodyPeriod.sixMonths: + return s.insights_period_label_6; + case BodyPeriod.year: + return s.insights_period_label_12; + case BodyPeriod.all: + return s.insights_period_label_all; + } + } + + String formatLabel(DateTime date) { + final local = date.toLocal(); + final day = local.day.toString().padLeft(2, '0'); + final month = local.month.toString().padLeft(2, '0'); + return '$day.$month'; + } + + /// Одна цифра после запятой без хвостового нуля: `3`, `3.5`. + String formatNumber(double value) { + final text = value.toStringAsFixed(1); + return text.endsWith('.0') ? text.substring(0, text.length - 2) : text; + } + + String _weightDeltaText(List values, BodyPeriod period) { + if (values.length < 2) { + return s.insights_not_enough; + } + final diff = values.last - values.first; + final periodText = periodLabel(period); + if (diff.abs() < deltaEpsilon) { + return s.insights_weight_same(periodText); + } + final value = formatNumber(diff.abs()); + return diff < 0 + ? s.insights_weight_lost(value, periodText) + : s.insights_weight_gained(value, periodText); + } + + String _bmiDeltaText( + List values, + BodyPeriod period, + String? category, + ) { + if (values.length < 2 || category == null) { + return s.insights_not_enough; + } + final diff = values.last - values.first; + final periodText = periodLabel(period); + if (diff.abs() < deltaEpsilon) { + return s.insights_bmi_same(periodText, category); + } + final value = formatNumber(diff.abs()); + return diff < 0 + ? s.insights_bmi_lower(value, periodText, category) + : s.insights_bmi_higher(value, periodText, category); + } + + String _measureDeltaText({ + required List waist, + required List chest, + required List hips, + required BodyPeriod period, + }) { + if (waist.length < 2) { + return s.insights_not_enough; + } + final parts = [ + _measurePart(s.insights_series_waist, waist), + _measurePart(s.insights_series_chest, chest), + _measurePart(s.insights_series_hips, hips), + ]; + return s.insights_measures_summary(parts.join(', '), periodLabel(period)); + } + + String _measurePart(String name, List values) { + final diff = values.last - values.first; + if (diff.abs() < deltaEpsilon) { + return s.insights_measure_same(name); + } + final value = formatNumber(diff.abs()); + return diff < 0 + ? s.insights_measure_less(name, value) + : s.insights_measure_more(name, value); + } + + double _round(double value) => (value * 10).round() / 10; +} diff --git a/lib/features/insights/insights_feature_flags.dart b/lib/features/insights/insights_feature_flags.dart new file mode 100644 index 00000000..d33af602 --- /dev/null +++ b/lib/features/insights/insights_feature_flags.dart @@ -0,0 +1,8 @@ +/// Флаги поэтапного включения аналитики. +abstract final class InsightsFeatureFlags { + /// Вкладки «КБЖУ по дням» и «В течение дня». При `true` весь блок берёт + /// данные и тексты с сервера (`GET /api/profile/insights*`, eatvio/eatvio#3017), + /// при `false` — вкладки скрыты, а вес/ИМТ/замеры собираются на клиенте из + /// `/api/profile/measure/*`. + static const bool kbjuEnabled = true; +} diff --git a/lib/features/insights/models/insights_payload_model.dart b/lib/features/insights/models/insights_payload_model.dart new file mode 100644 index 00000000..17b3e50c --- /dev/null +++ b/lib/features/insights/models/insights_payload_model.dart @@ -0,0 +1,132 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'insights_payload_model.freezed.dart'; +part 'insights_payload_model.g.dart'; + +/// Структура повторяет веб-`UserInsightsService::chartPayload()`, чтобы во второй +/// итерации заменить только источник данных. +@freezed +abstract class InsightsPayloadModel with _$InsightsPayloadModel { + const factory InsightsPayloadModel({ + required WeightChartModel weight, + required BmiChartModel bmi, + required MeasureChartModel measure, + DailyChartModel? daily, + IntraChartModel? intra, + }) = _InsightsPayloadModel; + + factory InsightsPayloadModel.fromJson(Map json) => + _$InsightsPayloadModelFromJson(json); +} + +@freezed +abstract class WeightChartModel with _$WeightChartModel { + const factory WeightChartModel({ + @Default([]) List labels, + @Default([]) List values, + double? last, + double? delta, + @Default('') String headline, + @Default('') String unit, + @Default('') String deltaText, + }) = _WeightChartModel; + + factory WeightChartModel.fromJson(Map json) => + _$WeightChartModelFromJson(json); +} + +@freezed +abstract class BmiChartModel with _$BmiChartModel { + const factory BmiChartModel({ + @Default([]) List labels, + @Default([]) List values, + double? last, + double? delta, + @Default('') String headline, + String? category, + @Default('') String deltaText, + @Default('') String hint, + }) = _BmiChartModel; + + factory BmiChartModel.fromJson(Map json) => + _$BmiChartModelFromJson(json); +} + +@freezed +abstract class MeasureChartModel with _$MeasureChartModel { + const factory MeasureChartModel({ + @Default([]) List labels, + @Default([]) List waist, + @Default([]) List chest, + @Default([]) List hips, + @Default('') String headline, + @Default('') String deltaText, + }) = _MeasureChartModel; + + factory MeasureChartModel.fromJson(Map json) => + _$MeasureChartModelFromJson(json); +} + +@freezed +abstract class DailyChartModel with _$DailyChartModel { + const factory DailyChartModel({ + @Default([]) List labels, + @Default([]) List kcal, + @Default([]) List proteins, + @Default([]) List fats, + @Default([]) List carbs, + double? average, + double? percent, + @Default('') String headline, + @Default('') String deltaText, + }) = _DailyChartModel; + + factory DailyChartModel.fromJson(Map json) => + _$DailyChartModelFromJson(json); +} + +@freezed +abstract class IntraChartModel with _$IntraChartModel { + const factory IntraChartModel({ + @Default([]) List bars, + @Default([]) List satiety, + @Default([]) List mood, + double? wake, + double? sleep, + String? wakeLabel, + String? sleepLabel, + String? wakeText, + String? sleepText, + @Default('') String date, + @Default('') String maxDate, + @Default('') String dateLabel, + @Default(false) bool isToday, + }) = _IntraChartModel; + + factory IntraChartModel.fromJson(Map json) => + _$IntraChartModelFromJson(json); +} + +/// Приём пищи: время `x` (часы 0–24) и калории из белков/жиров/углеводов. +@freezed +abstract class IntraBarModel with _$IntraBarModel { + const factory IntraBarModel({ + required double x, + @Default(0) double p, + @Default(0) double f, + @Default(0) double c, + }) = _IntraBarModel; + + factory IntraBarModel.fromJson(Map json) => + _$IntraBarModelFromJson(json); +} + +/// Точка шкалы 0–5 (сытость/настроение) в момент времени `x`. +@freezed +abstract class ScalePointModel with _$ScalePointModel { + const factory ScalePointModel({required double x, required double y}) = + _ScalePointModel; + + factory ScalePointModel.fromJson(Map json) => + _$ScalePointModelFromJson(json); +} diff --git a/lib/features/insights/models/insights_period.dart b/lib/features/insights/models/insights_period.dart new file mode 100644 index 00000000..cd3d01a2 --- /dev/null +++ b/lib/features/insights/models/insights_period.dart @@ -0,0 +1,46 @@ +import 'package:eatvio_app/generated/l10n.dart'; + +/// Период для вкладок «Вес», «ИМТ» и «Замеры». Значение совпадает с `{period}` в +/// `/api/profile/measure/weight/{period}`. +enum BodyPeriod { + month('1'), + threeMonths('3'), + sixMonths('6'), + year('12'), + all('all'); + + const BodyPeriod(this.apiValue); + + final String apiValue; + + /// Подпись пилюли периода. + String pillLabel(S s) => switch (this) { + month => s.insights_period_1m, + threeMonths => s.insights_period_3m, + sixMonths => s.insights_period_6m, + year => s.insights_period_1y, + all => s.insights_period_all, + }; +} + +/// Период для вкладки «КБЖУ по дням». Значение совпадает с `daily_period` в `/api/profile/insights`. +enum DailyPeriod { + week('7'), + twoWeeks('14'), + month('30'), + threeMonths('90'), + all('all'); + + const DailyPeriod(this.apiValue); + + final String apiValue; + + /// Подпись пилюли периода. + String pillLabel(S s) => switch (this) { + week => s.insights_period_1w, + twoWeeks => s.insights_period_2w, + month => s.insights_period_1m, + threeMonths => s.insights_period_3m, + all => s.insights_period_all, + }; +} diff --git a/lib/features/insights/models/insights_response_model.dart b/lib/features/insights/models/insights_response_model.dart new file mode 100644 index 00000000..0d78f7b3 --- /dev/null +++ b/lib/features/insights/models/insights_response_model.dart @@ -0,0 +1,36 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'insights_response_model.freezed.dart'; +part 'insights_response_model.g.dart'; + +/// Ответ `GET /api/profile/insights[/{slug}]`: `{ "data": { weight, bmi, measure, daily, intra } }`. +@freezed +abstract class InsightsResponseModel with _$InsightsResponseModel { + const factory InsightsResponseModel({required InsightsPayloadModel data}) = + _InsightsResponseModel; + + factory InsightsResponseModel.fromJson(Map json) => + _$InsightsResponseModelFromJson(json); +} + +/// Ответ `GET /api/profile/insights/intra` и `/insights/{slug}/intra`: +/// `{ "data": { "intra": { ... } } }`. +@freezed +abstract class InsightsIntraResponseModel with _$InsightsIntraResponseModel { + const factory InsightsIntraResponseModel({ + required InsightsIntraDataModel data, + }) = _InsightsIntraResponseModel; + + factory InsightsIntraResponseModel.fromJson(Map json) => + _$InsightsIntraResponseModelFromJson(json); +} + +@freezed +abstract class InsightsIntraDataModel with _$InsightsIntraDataModel { + const factory InsightsIntraDataModel({required IntraChartModel intra}) = + _InsightsIntraDataModel; + + factory InsightsIntraDataModel.fromJson(Map json) => + _$InsightsIntraDataModelFromJson(json); +} diff --git a/lib/features/insights/presentation/charts/bmi_chart.dart b/lib/features/insights/presentation/charts/bmi_chart.dart new file mode 100644 index 00000000..2c6776b9 --- /dev/null +++ b/lib/features/insights/presentation/charts/bmi_chart.dart @@ -0,0 +1,91 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +/// График ИМТ с цветными зонами: норма 18.5–25, избыточная масса 25–30, ожирение 30–40. +class BmiChart extends StatelessWidget { + const BmiChart({super.key, required this.model}); + + final BmiChartModel model; + + @override + Widget build(BuildContext context) { + final points = buildPoints(model.labels, model.values); + if (points.isEmpty) { + return InsightsChartPlaceholder(text: model.deltaText); + } + final s = S.of(context); + final dataRange = paddedRange(points.map((e) => e.value), minPadding: 2); + // Ось всегда покрывает зоны нормы/избытка/ожирения, иначе при ИМТ ≈30 + // зелёная полоса 18.5–25 уезжает за нижний край графика. + const zoneMin = 18.5; + const zoneMax = 40.0; + final min = dataRange.min < zoneMin ? dataRange.min : zoneMin; + final max = dataRange.max > zoneMax ? dataRange.max : zoneMax; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: insightsChartHeight, + child: SfCartesianChart( + key: const Key('insights_bmi_chart'), + margin: insightsChartMargin, + plotAreaBorderWidth: 0, + primaryXAxis: buildInsightsIndexAxis(model.labels), + primaryYAxis: buildInsightsValueAxis( + unit: s.insights_unit_bmi, + min: min, + max: max, + plotBands: const [ + PlotBand( + start: 18.5, + end: 25, + color: InsightsColors.bmiNormalZone, + ), + PlotBand( + start: 25, + end: 30, + color: InsightsColors.bmiOverweightZone, + ), + PlotBand( + start: 30, + end: 40, + color: InsightsColors.bmiObesityZone, + ), + ], + ), + trackballBehavior: buildInsightsTrackball(), + series: >[ + SplineAreaSeries( + name: s.insights_tab_bmi, + dataSource: points, + xValueMapper: (point, _) => point.index, + yValueMapper: (point, _) => point.value, + splineType: insightsSplineType, + borderColor: InsightsColors.blue, + borderWidth: 3, + gradient: buildInsightsAreaGradient(InsightsColors.blue), + markerSettings: buildInsightsMarker(InsightsColors.blue), + ), + ], + ), + ), + if (model.hint.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + model.hint, + key: const Key('insights_bmi_hint'), + style: const TextStyle( + fontSize: 13, + color: InsightsColors.subtitle, + ), + ), + ], + ], + ); + } +} diff --git a/lib/features/insights/presentation/charts/daily_kbju_chart.dart b/lib/features/insights/presentation/charts/daily_kbju_chart.dart new file mode 100644 index 00000000..f1013ea7 --- /dev/null +++ b/lib/features/insights/presentation/charts/daily_kbju_chart.dart @@ -0,0 +1,135 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +/// КБЖУ по дням: калории — площадь на левой оси («ккал»), Б/Ж/У — линии на +/// правой оси («граммы»). [visibility] — Калории, Белки, Жиры, Углеводы. +class DailyKbjuChart extends StatelessWidget { + const DailyKbjuChart({ + super.key, + required this.model, + required this.visibility, + }); + + final DailyChartModel model; + final List visibility; + + static const String _gramsAxisName = 'grams'; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final calories = buildPoints(model.labels, model.kcal); + if (calories.isEmpty) { + return InsightsChartPlaceholder(text: s.insights_not_enough); + } + final proteins = buildPoints(model.labels, model.proteins); + final fats = buildPoints(model.labels, model.fats); + final carbs = buildPoints(model.labels, model.carbs); + + // Локальный диапазон по данным (как на вебе), не ось от нуля. + // Кривую ниже точек держит insightsSplineType (monotonic). + final kcalRange = paddedRange( + calories.map((e) => e.value), + minPadding: 50, + clampZero: true, + ); + final gramValues = [ + ...proteins.map((e) => e.value), + ...fats.map((e) => e.value), + ...carbs.map((e) => e.value), + ]; + final gramsRange = paddedRange( + gramValues, + minPadding: 5, + clampZero: true, + ); + + final grams = [ + ( + name: s.insights_series_proteins, + color: InsightsColors.proteins, + points: proteins, + ), + (name: s.insights_series_fats, color: InsightsColors.fats, points: fats), + ( + name: s.insights_series_carbs, + color: InsightsColors.carbs, + points: carbs, + ), + ]; + + return SizedBox( + height: insightsChartHeight, + child: SfCartesianChart( + key: const Key('insights_daily_chart'), + margin: insightsChartMargin, + plotAreaBorderWidth: 0, + primaryXAxis: buildInsightsIndexAxis(model.labels), + primaryYAxis: NumericAxis( + title: AxisTitle( + text: s.insights_unit_kcal, + textStyle: insightsAxisLabelStyle, + ), + labelStyle: insightsAxisLabelStyle, + minimum: kcalRange.min, + maximum: kcalRange.max, + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(width: 0), + majorGridLines: MajorGridLines( + color: InsightsColors.border.withValues(alpha: 0.8), + dashArray: const [4, 4], + ), + ), + axes: [ + NumericAxis( + name: _gramsAxisName, + opposedPosition: true, + minimum: gramsRange.min, + maximum: gramsRange.max, + title: AxisTitle( + text: s.insights_unit_grams, + textStyle: insightsAxisLabelStyle, + ), + labelStyle: insightsAxisLabelStyle, + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(width: 0), + majorGridLines: const MajorGridLines(width: 0), + ), + ], + trackballBehavior: buildInsightsTrackball(), + series: >[ + if (_isVisible(0)) + SplineAreaSeries( + name: s.insights_series_calories, + dataSource: calories, + xValueMapper: (point, _) => point.index, + yValueMapper: (point, _) => point.value, + splineType: insightsSplineType, + borderColor: InsightsColors.calories, + borderWidth: 3, + gradient: buildInsightsAreaGradient(InsightsColors.calories), + ), + for (var i = 0; i < grams.length; i++) + if (_isVisible(i + 1)) + SplineSeries( + name: grams[i].name, + yAxisName: _gramsAxisName, + dataSource: grams[i].points, + xValueMapper: (point, _) => point.index, + yValueMapper: (point, _) => point.value, + splineType: insightsSplineType, + color: grams[i].color, + width: 2.5, + ), + ], + ), + ); + } + + bool _isVisible(int index) => + index < visibility.length ? visibility[index] : true; +} diff --git a/lib/features/insights/presentation/charts/insights_chart_common.dart b/lib/features/insights/presentation/charts/insights_chart_common.dart new file mode 100644 index 00000000..600677f6 --- /dev/null +++ b/lib/features/insights/presentation/charts/insights_chart_common.dart @@ -0,0 +1,180 @@ +import 'dart:math' as math; + +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +/// Точка графика: индекс по оси X (как у Chart.js), подпись `dd.MM` и значение. +/// +/// Индекс обязателен: Syncfusion `CategoryAxis` склеивает одинаковые строки +/// (`05.07` несколько раз → одна категория). На вебе labels идут по индексу, +/// поэтому здесь X = index, а дата рисуется через [axisLabelFormatter]. +class InsightsPoint { + const InsightsPoint({ + required this.index, + required this.label, + required this.value, + }); + + final int index; + final String label; + final double value; +} + +/// Склеивает `labels[]` и `values[]` (по минимальной длине). +List buildPoints(List labels, List values) { + final count = math.min(labels.length, values.length); + return [ + for (var i = 0; i < count; i++) + InsightsPoint(index: i, label: labels[i], value: values[i]), + ]; +} + +/// Локальный диапазон оси Y вокруг данных (не от нуля), с запасом под сплайн. +/// +/// [clampZero] — не уводить минимум в минус на осях КБЖУ (ккал/граммы ≥ 0). +({double min, double max}) paddedRange( + Iterable values, { + double minPadding = 1, + bool clampZero = false, +}) { + if (values.isEmpty) { + return (min: 0, max: 1); + } + final lowest = values.reduce(math.min); + final highest = values.reduce(math.max); + final padding = math.max((highest - lowest) * 0.2, minPadding); + var min = lowest - padding; + var max = highest + padding; + if (clampZero) { + min = math.max(0, min); + } + if (max <= min) { + max = min + minPadding; + } + return (min: min, max: max); +} + + +const SplineType insightsSplineType = SplineType.monotonic; + +const TextStyle insightsAxisLabelStyle = TextStyle( + fontSize: 11, + color: InsightsColors.subtitle, +); + +/// Ось X по индексу точки; подпись — дата из [labels]. +/// +/// Так даты `05.07`, `06.07`, … не схлопываются и не размножаются, когда на +/// графике несколько серий с одним и тем же набором labels (КБЖУ, замеры). +NumericAxis buildInsightsIndexAxis(List labels) { + final lastIndex = math.max(labels.length - 1, 0).toDouble(); + // На узком экране не подписываем каждую точку: ~6 подписей, как авто-тики Chart.js. + final interval = labels.length <= 7 + ? 1.0 + : (labels.length / 6).ceilToDouble(); + + return NumericAxis( + minimum: 0, + maximum: lastIndex, + interval: interval, + labelStyle: insightsAxisLabelStyle, + majorGridLines: const MajorGridLines(width: 0), + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(color: InsightsColors.border, width: 1), + edgeLabelPlacement: EdgeLabelPlacement.shift, + axisLabelFormatter: (details) { + final index = details.value.round(); + if (index < 0 || index >= labels.length) { + return ChartAxisLabel('', details.textStyle); + } + // Промежуточные дробные тики (если Syncfusion их поставит) не подписываем. + if ((details.value - index).abs() > 0.01) { + return ChartAxisLabel('', details.textStyle); + } + return ChartAxisLabel(labels[index], insightsAxisLabelStyle); + }, + ); +} + +NumericAxis buildInsightsValueAxis({ + required String unit, + required double min, + required double max, + List plotBands = const [], +}) { + return NumericAxis( + minimum: min, + maximum: max, + // Доп. воздух, чтобы сплайн не врезался в край plot area. + rangePadding: ChartRangePadding.additional, + labelFormat: '{value} $unit', + labelStyle: insightsAxisLabelStyle, + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(width: 0), + majorGridLines: MajorGridLines( + color: InsightsColors.border.withValues(alpha: 0.8), + dashArray: const [4, 4], + ), + plotBands: plotBands, + ); +} + +/// Небольшой внутренний отступ, чтобы кривая и подписи не резались контейнером. +const EdgeInsets insightsChartMargin = EdgeInsets.fromLTRB(0, 8, 0, 4); + +TrackballBehavior buildInsightsTrackball() { + return TrackballBehavior( + enable: true, + activationMode: ActivationMode.singleTap, + tooltipDisplayMode: TrackballDisplayMode.groupAllPoints, + lineType: TrackballLineType.vertical, + tooltipSettings: const InteractiveTooltip(), + ); +} + +MarkerSettings buildInsightsMarker(Color color) { + return MarkerSettings( + isVisible: true, + width: 4, + height: 4, + color: Colors.white, + borderColor: color, + borderWidth: 2, + ); +} + +LinearGradient buildInsightsAreaGradient(Color color) { + return LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [color.withValues(alpha: 0.18), color.withValues(alpha: 0)], + ); +} + +/// Пустое состояние графика (нет данных). +class InsightsChartPlaceholder extends StatelessWidget { + const InsightsChartPlaceholder({super.key, required this.text}); + + final String text; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: insightsChartHeight, + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Text( + text, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 14, + color: InsightsColors.subtitle, + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/insights/presentation/charts/intra_day_chart.dart b/lib/features/insights/presentation/charts/intra_day_chart.dart new file mode 100644 index 00000000..4274ca8c --- /dev/null +++ b/lib/features/insights/presentation/charts/intra_day_chart.dart @@ -0,0 +1,214 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +/// График «В течение дня»: столбики Б/Ж/У (ккал) по приёмам пищи на оси 0–24 ч, +/// линии сытости и настроения (шкала 0–5) и затемнение времени сна. +/// +/// [visibility] — Белки, Жиры, Углеводы, Сытость, Настроение. +class IntraDayChart extends StatelessWidget { + const IntraDayChart({ + super.key, + required this.model, + required this.visibility, + required this.showSleep, + }); + + final IntraChartModel model; + final List visibility; + final bool showSleep; + + static const String _scaleAxisName = 'scale'; + static const double _barWidthPx = 26; + static const double _axesReservedWidthPx = 80; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + if (model.bars.isEmpty && + model.satiety.isEmpty && + model.mood.isEmpty && + model.wake == null && + model.sleep == null) { + return InsightsChartPlaceholder(text: s.insights_not_enough); + } + + return SizedBox( + height: insightsChartHeight, + child: LayoutBuilder( + builder: (context, constraints) { + final plotWidth = (constraints.maxWidth - _axesReservedWidthPx).clamp( + 120.0, + double.infinity, + ); + final barFraction = (_barWidthPx / (plotWidth / 24)).clamp(0.1, 1.0); + return SfCartesianChart( + key: const Key('insights_intra_chart'), + margin: insightsChartMargin, + plotAreaBorderWidth: 0, + primaryXAxis: NumericAxis( + minimum: 0, + maximum: 24, + interval: 2, + labelStyle: insightsAxisLabelStyle, + majorGridLines: const MajorGridLines(width: 0), + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(color: InsightsColors.border, width: 1), + axisLabelFormatter: (details) => ChartAxisLabel( + '${details.value.toInt().toString().padLeft(2, '0')}:00', + details.textStyle, + ), + plotBands: _sleepBands(), + ), + primaryYAxis: NumericAxis( + minimum: 0, + title: AxisTitle( + text: s.insights_unit_kcal_per_meal, + textStyle: insightsAxisLabelStyle, + ), + labelStyle: insightsAxisLabelStyle, + majorTickLines: const MajorTickLines(size: 0), + axisLine: const AxisLine(width: 0), + majorGridLines: MajorGridLines( + color: InsightsColors.border.withValues(alpha: 0.8), + dashArray: const [4, 4], + ), + ), + axes: const [ + NumericAxis( + name: _scaleAxisName, + opposedPosition: true, + minimum: 0, + maximum: 5, + interval: 1, + labelStyle: insightsAxisLabelStyle, + majorTickLines: MajorTickLines(size: 0), + axisLine: AxisLine(width: 0), + majorGridLines: MajorGridLines(width: 0), + ), + ], + trackballBehavior: buildInsightsTrackball(), + series: >[ + if (_isVisible(0)) + _barSeries( + s.insights_series_proteins, + InsightsColors.proteins, + (bar) => bar.p, + barFraction, + ), + if (_isVisible(1)) + _barSeries( + s.insights_series_fats, + InsightsColors.fats, + (bar) => bar.f, + barFraction, + ), + if (_isVisible(2)) + _barSeries( + s.insights_series_carbs, + InsightsColors.carbs, + (bar) => bar.c, + barFraction, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(6), + ), + ), + if (_isVisible(3) && model.satiety.isNotEmpty) + _scaleSeries( + s.insights_series_satiety, + InsightsColors.satiety, + model.satiety, + ), + if (_isVisible(4) && model.mood.isNotEmpty) + _scaleSeries( + s.insights_series_mood, + InsightsColors.mood, + model.mood, + ), + ], + ); + }, + ), + ); + } + + bool _isVisible(int index) => + index < visibility.length ? visibility[index] : true; + + CartesianSeries _barSeries( + String name, + Color color, + double Function(IntraBarModel bar) valueOf, + double widthFraction, { + BorderRadius borderRadius = BorderRadius.zero, + }) { + return StackedColumnSeries( + name: name, + dataSource: model.bars, + xValueMapper: (bar, _) => bar.x, + yValueMapper: (bar, _) => valueOf(bar), + color: color, + width: widthFraction, + spacing: 0, + borderRadius: borderRadius, + ); + } + + CartesianSeries _scaleSeries( + String name, + Color color, + List points, + ) { + return SplineSeries( + name: name, + yAxisName: _scaleAxisName, + dataSource: points, + xValueMapper: (point, _) => point.x, + yValueMapper: (point, _) => point.y, + splineType: insightsSplineType, + color: color, + width: 2.5, + markerSettings: MarkerSettings( + isVisible: true, + width: 3, + height: 3, + color: color, + borderColor: color, + ), + ); + } + + /// Затемнение `[0, wake]` и `[sleep, 24]` плюс пунктиры подъёма и отхода ко сну. + List _sleepBands() { + if (!showSleep) { + return const []; + } + final wake = model.wake; + final sleep = model.sleep; + return [ + if (wake != null && wake > 0) + PlotBand(start: 0, end: wake, color: InsightsColors.sleepShade), + if (sleep != null && sleep < 24 && (wake == null || sleep > wake)) + PlotBand(start: sleep, end: 24, color: InsightsColors.sleepShade), + if (wake != null) + PlotBand( + start: wake, + end: wake, + borderColor: InsightsColors.wake, + borderWidth: 1.5, + dashArray: const [5, 4], + ), + if (sleep != null) + PlotBand( + start: sleep, + end: sleep, + borderColor: InsightsColors.sleepLine, + borderWidth: 1.5, + dashArray: const [5, 4], + ), + ]; + } +} diff --git a/lib/features/insights/presentation/charts/measure_chart.dart b/lib/features/insights/presentation/charts/measure_chart.dart new file mode 100644 index 00000000..8503c6e8 --- /dev/null +++ b/lib/features/insights/presentation/charts/measure_chart.dart @@ -0,0 +1,87 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +/// Три линии: талия, грудь, бёдра. [visibility] — видимость серий в этом порядке. +class MeasureChart extends StatelessWidget { + const MeasureChart({ + super.key, + required this.model, + required this.visibility, + required this.emptyText, + }); + + final MeasureChartModel model; + final List visibility; + final String emptyText; + + @override + Widget build(BuildContext context) { + final waist = buildPoints(model.labels, model.waist); + final chest = buildPoints(model.labels, model.chest); + final hips = buildPoints(model.labels, model.hips); + if (waist.isEmpty && chest.isEmpty && hips.isEmpty) { + return InsightsChartPlaceholder(text: emptyText); + } + final s = S.of(context); + final series = [ + ( + name: s.insights_series_waist, + color: InsightsColors.waist, + points: waist, + ), + ( + name: s.insights_series_chest, + color: InsightsColors.chest, + points: chest, + ), + (name: s.insights_series_hips, color: InsightsColors.hips, points: hips), + ]; + final visibleValues = [ + for (var i = 0; i < series.length; i++) + if (_isVisible(i)) ...series[i].points.map((e) => e.value), + ]; + final range = paddedRange( + visibleValues.isEmpty + ? series.expand((e) => e.points).map((e) => e.value) + : visibleValues, + minPadding: 2, + ); + + return SizedBox( + height: insightsChartHeight, + child: SfCartesianChart( + key: const Key('insights_measure_chart'), + margin: insightsChartMargin, + plotAreaBorderWidth: 0, + primaryXAxis: buildInsightsIndexAxis(model.labels), + primaryYAxis: buildInsightsValueAxis( + unit: s.insights_unit_cm, + min: range.min, + max: range.max, + ), + trackballBehavior: buildInsightsTrackball(), + series: >[ + for (var i = 0; i < series.length; i++) + if (_isVisible(i)) + SplineSeries( + name: series[i].name, + dataSource: series[i].points, + xValueMapper: (point, _) => point.index, + yValueMapper: (point, _) => point.value, + splineType: insightsSplineType, + color: series[i].color, + width: 3, + markerSettings: buildInsightsMarker(series[i].color), + ), + ], + ), + ); + } + + bool _isVisible(int index) => + index < visibility.length ? visibility[index] : true; +} diff --git a/lib/features/insights/presentation/charts/weight_chart.dart b/lib/features/insights/presentation/charts/weight_chart.dart new file mode 100644 index 00000000..34881c62 --- /dev/null +++ b/lib/features/insights/presentation/charts/weight_chart.dart @@ -0,0 +1,54 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +class WeightChart extends StatelessWidget { + const WeightChart({super.key, required this.model, required this.emptyText}); + + final WeightChartModel model; + + /// Текст при отсутствии точек («Добавьте Ваш вес»). + final String emptyText; + + @override + Widget build(BuildContext context) { + final points = buildPoints(model.labels, model.values); + if (points.isEmpty) { + return InsightsChartPlaceholder(text: emptyText); + } + final s = S.of(context); + final range = paddedRange(points.map((e) => e.value)); + + return SizedBox( + height: insightsChartHeight, + child: SfCartesianChart( + key: const Key('insights_weight_chart'), + margin: insightsChartMargin, + plotAreaBorderWidth: 0, + primaryXAxis: buildInsightsIndexAxis(model.labels), + primaryYAxis: buildInsightsValueAxis( + unit: s.insights_unit_kg, + min: range.min, + max: range.max, + ), + trackballBehavior: buildInsightsTrackball(), + series: >[ + SplineAreaSeries( + name: s.insights_tab_weight, + dataSource: points, + xValueMapper: (point, _) => point.index, + yValueMapper: (point, _) => point.value, + splineType: insightsSplineType, + borderColor: InsightsColors.blue, + borderWidth: 3, + gradient: buildInsightsAreaGradient(InsightsColors.blue), + markerSettings: buildInsightsMarker(InsightsColors.blue), + ), + ], + ), + ); + } +} diff --git a/lib/features/insights/presentation/cubit/insights_cubit.dart b/lib/features/insights/presentation/cubit/insights_cubit.dart new file mode 100644 index 00000000..4c1a4cd1 --- /dev/null +++ b/lib/features/insights/presentation/cubit/insights_cubit.dart @@ -0,0 +1,400 @@ +import 'dart:developer'; + +import 'package:eatvio_app/core/error_reporting/report_from.dart'; +import 'package:eatvio_app/features/insights/insights_feature_flags.dart'; +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class InsightsCubit extends Cubit { + InsightsCubit({ + required this.repository, + this.slug, + this.canAdd = false, + this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled, + }) : super(const InsightsState.initial()); + + final InsightsRepository repository; + + /// `null` — собственные данные, иначе slug владельца (консультант → клиент). + final String? slug; + + /// Показывать ли кнопку «+» (только владелец). + final bool canAdd; + + final bool kbjuEnabled; + + bool _isHeightLoaded = false; + int? _heightCm; + + /// Полный payload и вкладка «В течение дня» координируются отдельно: смена + /// дня не должна отменять загрузку периода, и наоборот. + int _fullRequestId = 0; + int _intraRequestId = 0; + int _inflightFull = 0; + int _inflightIntra = 0; + + List get panels => + InsightsPanel.available(kbjuEnabled: kbjuEnabled); + + bool get _isBusy => _inflightFull > 0 || _inflightIntra > 0; + + Future load({String? intraDate}) async { + emit(const InsightsState.loading()); + await _fetch( + bodyPeriod: BodyPeriod.threeMonths, + dailyPeriod: DailyPeriod.twoWeeks, + intraDate: intraDate, + isInitial: true, + ); + } + + /// Перезапрашивает данные, сохраняя вкладку, период, серии и раскрытие. + Future refresh() async { + final current = state; + if (current is InsightsStateLoading || current is InsightsStateHidden) { + return; + } + if (current is! InsightsStateLoaded) { + return load(); + } + await _fetch( + bodyPeriod: current.bodyPeriod, + dailyPeriod: current.dailyPeriod, + intraDate: current.intraDate, + isInitial: false, + ); + } + + Future setBodyPeriod(BodyPeriod period) async { + final current = state; + if (current is! InsightsStateLoaded || current.bodyPeriod == period) { + return; + } + emit(current.copyWith(bodyPeriod: period, isRefreshing: true)); + await _fetch( + bodyPeriod: period, + dailyPeriod: current.dailyPeriod, + intraDate: current.intraDate, + isInitial: false, + ); + } + + /// Период вкладки «КБЖУ по дням». Работает только с серверными данными. + Future setDailyPeriod(DailyPeriod period) async { + final current = state; + if (!kbjuEnabled || + current is! InsightsStateLoaded || + current.dailyPeriod == period) { + return; + } + emit(current.copyWith(dailyPeriod: period, isRefreshing: true)); + await _fetch( + bodyPeriod: current.bodyPeriod, + dailyPeriod: period, + intraDate: current.intraDate, + isInitial: false, + ); + } + + /// Показывает вкладку «В течение дня» за [day] (запрашивается только она). + Future setIntraDate(DateTime day) { + return _loadIntra(_formatDate(day)); + } + + Future showPreviousDay() async { + final base = _currentIntraDay(); + if (base != null) { + await setIntraDate(DateTime(base.year, base.month, base.day - 1)); + } + } + + Future showNextDay() async { + final current = state; + final base = _currentIntraDay(); + if (base == null || + current is! InsightsStateLoaded || + !_canGoToNextDay(current, base)) { + return; + } + await setIntraDate(DateTime(base.year, base.month, base.day + 1)); + } + + /// База для листания: сначала оптимистично запрошенная дата, иначе ответ сервера. + DateTime? _currentIntraDay() { + final current = state; + if (!kbjuEnabled || current is! InsightsStateLoaded) { + return null; + } + final optimistic = current.intraDate; + if (optimistic != null && optimistic.isNotEmpty) { + return DateTime.tryParse(optimistic); + } + return DateTime.tryParse(current.payload.intra?.date ?? ''); + } + + bool _canGoToNextDay(InsightsStateLoaded current, DateTime base) { + final maxRaw = + current.payload.intra?.maxDate ?? current.payload.intra?.date ?? ''; + final maxDate = DateTime.tryParse(maxRaw); + if (maxDate == null) { + return !(current.payload.intra?.isToday ?? true); + } + final baseDay = DateTime(base.year, base.month, base.day); + final maxDay = DateTime(maxDate.year, maxDate.month, maxDate.day); + return baseDay.isBefore(maxDay); + } + + Future _loadIntra(String date) async { + final current = state; + if (!kbjuEnabled || current is! InsightsStateLoaded) { + return; + } + final requestId = ++_intraRequestId; + _inflightIntra++; + final previousIntraDate = current.intraDate; + // Оптимистично фиксируем запрошенный день до ответа, чтобы быстрые + // нажатия «‹ ›» считали базу от него, а не от устаревшего payload. + emit(current.copyWith(intraDate: date, isRefreshing: true)); + try { + final intra = await repository.fetchIntra(slug: slug, intraDate: date); + if (requestId != _intraRequestId || isClosed) { + return; + } + final latest = state; + if (latest is! InsightsStateLoaded) { + return; + } + emit( + latest.copyWith( + payload: latest.payload.copyWith(intra: intra), + intraDate: intra.isToday + ? null + : (intra.date.isEmpty ? date : intra.date), + isRefreshing: _inflightFull > 0 || _inflightIntra > 1, + ), + ); + } on InsightsForbidden { + if (requestId == _intraRequestId && !isClosed) { + emit(const InsightsState.hidden()); + } + } catch (e, st) { + await reportFrom(e, st, this); + log(e.toString(), stackTrace: st); + if (requestId == _intraRequestId && !isClosed) { + final latest = state; + if (latest is InsightsStateLoaded) { + emit( + latest.copyWith( + intraDate: previousIntraDate, + isRefreshing: _inflightFull > 0 || _inflightIntra > 1, + ), + ); + } + } + } finally { + _inflightIntra--; + _syncRefreshingFlag(); + } + } + + static String _formatDate(DateTime day) { + final month = day.month.toString().padLeft(2, '0'); + final dayOfMonth = day.day.toString().padLeft(2, '0'); + return '${day.year.toString().padLeft(4, '0')}-$month-$dayOfMonth'; + } + + void toggleExpanded() { + final current = state; + if (current is InsightsStateLoaded) { + emit(current.copyWith(isExpanded: !current.isExpanded)); + } + } + + void setPanel(InsightsPanel panel) { + final current = state; + if (current is! InsightsStateLoaded || !panels.contains(panel)) { + return; + } + emit(current.copyWith(panel: panel)); + } + + /// Включает/выключает серию [index] на вкладке [panel]. + void toggleSeries(InsightsPanel panel, int index) { + final current = state; + if (current is! InsightsStateLoaded) { + return; + } + final visibility = current.seriesVisibility; + final source = switch (panel) { + InsightsPanel.measures => visibility.measure, + InsightsPanel.daily => visibility.daily, + InsightsPanel.intra => visibility.intra, + _ => null, + }; + if (source == null || index < 0 || index >= source.length) { + return; + } + final updated = [...source]..[index] = !source[index]; + final nextVisibility = switch (panel) { + InsightsPanel.measures => visibility.copyWith(measure: updated), + InsightsPanel.daily => visibility.copyWith(daily: updated), + _ => visibility.copyWith(intra: updated), + }; + emit(current.copyWith(seriesVisibility: nextVisibility)); + } + + void toggleSleep() { + final current = state; + if (current is InsightsStateLoaded) { + emit(current.copyWith(showSleep: !current.showSleep)); + } + } + + /// Сохраняет вес и обновляет данные. Возвращает `false`, если сохранить не удалось. + Future addWeight({required double weight}) { + return _add(() => repository.addWeight(weight: weight)); + } + + /// Сохраняет замеры и обновляет данные. Возвращает `false`, если сохранить не удалось. + Future addCircumference({ + required int chestCircumference, + required int waistCircumference, + required int hipCircumference, + }) { + return _add( + () => repository.addCircumference( + chestCircumference: chestCircumference, + waistCircumference: waistCircumference, + hipCircumference: hipCircumference, + ), + ); + } + + Future _add(Future Function() action) async { + try { + await action(); + } catch (e, st) { + await reportFrom(e, st, this); + log(e.toString(), stackTrace: st); + return false; + } + await refresh(); + return true; + } + + Future _requestPayload({ + required BodyPeriod bodyPeriod, + required DailyPeriod dailyPeriod, + required String? intraDate, + }) async { + if (kbjuEnabled) { + return repository.fetchInsights( + slug: slug, + bodyPeriod: bodyPeriod, + dailyPeriod: dailyPeriod, + intraDate: intraDate, + ); + } + if (!_isHeightLoaded) { + _heightCm = await repository.getHeightCm(slug: slug); + _isHeightLoaded = true; + } + return repository.getInsights( + slug: slug, + bodyPeriod: bodyPeriod, + heightCm: _heightCm, + ); + } + + Future _fetch({ + required BodyPeriod bodyPeriod, + required DailyPeriod dailyPeriod, + required String? intraDate, + required bool isInitial, + }) async { + final requestId = ++_fullRequestId; + final intraGenerationAtStart = _intraRequestId; + _inflightFull++; + final before = state; + if (before is InsightsStateLoaded && !before.isRefreshing) { + emit(before.copyWith(isRefreshing: true)); + } + try { + final payload = await _requestPayload( + bodyPeriod: bodyPeriod, + dailyPeriod: dailyPeriod, + intraDate: intraDate, + ); + if (requestId != _fullRequestId || isClosed) { + return; + } + final latest = state; + if (latest is InsightsStateLoaded) { + // Более свежий intra-запрос не перезаписываем полным ответом. + final keepIntra = _intraRequestId > intraGenerationAtStart; + emit( + latest.copyWith( + payload: keepIntra + ? payload.copyWith(intra: latest.payload.intra) + : payload, + bodyPeriod: bodyPeriod, + dailyPeriod: dailyPeriod, + intraDate: keepIntra ? latest.intraDate : intraDate, + isRefreshing: _inflightIntra > 0 || _inflightFull > 1, + ), + ); + } else if (isInitial || latest is! InsightsStateError) { + emit( + InsightsState.loaded( + payload: payload, + bodyPeriod: bodyPeriod, + dailyPeriod: dailyPeriod, + intraDate: intraDate, + ), + ); + } + } on InsightsForbidden { + if (requestId == _fullRequestId && !isClosed) { + emit(const InsightsState.hidden()); + } + } catch (e, st) { + await reportFrom(e, st, this); + log(e.toString(), stackTrace: st); + if (requestId != _fullRequestId || isClosed) { + return; + } + final latest = state; + // Ошибка перезапроса не должна стирать уже показанные данные и UI-выбор. + if (latest is InsightsStateLoaded) { + emit( + latest.copyWith( + isRefreshing: _inflightIntra > 0 || _inflightFull > 1, + ), + ); + } else if (isInitial) { + emit(InsightsState.error(message: e.toString())); + } + } finally { + _inflightFull--; + _syncRefreshingFlag(); + } + } + + void _syncRefreshingFlag() { + if (isClosed) { + return; + } + final current = state; + if (current is! InsightsStateLoaded) { + return; + } + final busy = _isBusy; + if (current.isRefreshing != busy) { + emit(current.copyWith(isRefreshing: busy)); + } + } +} diff --git a/lib/features/insights/presentation/cubit/insights_panel.dart b/lib/features/insights/presentation/cubit/insights_panel.dart new file mode 100644 index 00000000..39aff3a9 --- /dev/null +++ b/lib/features/insights/presentation/cubit/insights_panel.dart @@ -0,0 +1,29 @@ +import 'package:eatvio_app/generated/l10n.dart'; + +/// Вкладки блока «Аналитика». +enum InsightsPanel { + weight, + bmi, + measures, + daily, + intra; + + /// Вкладки КБЖУ доступны только при включённом флаге. + bool get isKbju => this == daily || this == intra; + + /// Кнопка «+» есть только у вкладок с ручным вводом. + bool get supportsAdd => this == weight || this == measures; + + /// Подпись вкладки. + String label(S s) => switch (this) { + weight => s.insights_tab_weight, + bmi => s.insights_tab_bmi, + measures => s.insights_tab_measures, + daily => s.insights_tab_daily, + intra => s.insights_tab_intra, + }; + + static List available({required bool kbjuEnabled}) { + return values.where((panel) => kbjuEnabled || !panel.isKbju).toList(); + } +} diff --git a/lib/features/insights/presentation/cubit/insights_state.dart b/lib/features/insights/presentation/cubit/insights_state.dart new file mode 100644 index 00000000..d14d5fab --- /dev/null +++ b/lib/features/insights/presentation/cubit/insights_state.dart @@ -0,0 +1,51 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'insights_state.freezed.dart'; + +/// Видимость серий (чипы под графиком): `true` — серия показана. +@freezed +abstract class InsightsSeriesVisibility with _$InsightsSeriesVisibility { + const factory InsightsSeriesVisibility({ + /// Талия, Грудь, Бёдра. + @Default([true, true, true]) List measure, + + /// Калории, Белки, Жиры, Углеводы. + @Default([true, true, true, true]) List daily, + + /// Белки, Жиры, Углеводы, Сытость, Настроение. + @Default([true, true, true, true, true]) List intra, + }) = _InsightsSeriesVisibility; +} + +@freezed +abstract class InsightsState with _$InsightsState { + const factory InsightsState.initial() = InsightsStateInitial; + + const factory InsightsState.loading() = InsightsStateLoading; + + /// 403: данные недоступны, блок не показывается. + const factory InsightsState.hidden() = InsightsStateHidden; + + const factory InsightsState.error({required String message}) = + InsightsStateError; + + const factory InsightsState.loaded({ + required InsightsPayloadModel payload, + @Default(BodyPeriod.threeMonths) BodyPeriod bodyPeriod, + @Default(DailyPeriod.twoWeeks) DailyPeriod dailyPeriod, + + /// День вкладки «В течение дня» (`YYYY-MM-DD`); `null` — сегодня. + String? intraDate, + @Default(InsightsPanel.weight) InsightsPanel panel, + @Default(InsightsSeriesVisibility()) + InsightsSeriesVisibility seriesVisibility, + @Default(true) bool showSleep, + @Default(false) bool isExpanded, + + /// Идёт перезапрос (смена периода / обновление) — старые данные остаются на экране. + @Default(false) bool isRefreshing, + }) = InsightsStateLoaded; +} diff --git a/lib/features/insights/presentation/widgets/add_circumference_bottom_sheet.dart b/lib/features/insights/presentation/widgets/add_circumference_bottom_sheet.dart new file mode 100644 index 00000000..24477e15 --- /dev/null +++ b/lib/features/insights/presentation/widgets/add_circumference_bottom_sheet.dart @@ -0,0 +1,175 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +const int _minValue = 20; +const int _maxValue = 199; + +/// Значения замеров в сантиметрах. +typedef CircumferenceValues = ({int chest, int waist, int hip}); + +/// Выбор замеров груди, талии и бёдер. [onSave] вызывается после закрытия шторки. +Future showAddCircumferenceBottomSheet( + BuildContext context, { + CircumferenceValues? initial, + required Future Function(CircumferenceValues values) onSave, +}) { + return showModalBottomSheet( + useRootNavigator: true, + context: context, + builder: (_) => + AddCircumferenceBottomSheet(initial: initial, onSave: onSave), + ); +} + +class AddCircumferenceBottomSheet extends StatefulWidget { + const AddCircumferenceBottomSheet({ + super.key, + this.initial, + required this.onSave, + }); + + final CircumferenceValues? initial; + final Future Function(CircumferenceValues values) onSave; + + @override + State createState() => + _AddCircumferenceBottomSheetState(); +} + +class _AddCircumferenceBottomSheetState + extends State { + late final FixedExtentScrollController _chestController; + late final FixedExtentScrollController _waistController; + late final FixedExtentScrollController _hipController; + late int _chest; + late int _waist; + late int _hip; + + @override + void initState() { + super.initState(); + _chest = _clamp(widget.initial?.chest); + _waist = _clamp(widget.initial?.waist); + _hip = _clamp(widget.initial?.hip); + _chestController = FixedExtentScrollController( + initialItem: _chest - _minValue, + ); + _waistController = FixedExtentScrollController( + initialItem: _waist - _minValue, + ); + _hipController = FixedExtentScrollController(initialItem: _hip - _minValue); + } + + @override + void dispose() { + _chestController.dispose(); + _waistController.dispose(); + _hipController.dispose(); + super.dispose(); + } + + int _clamp(int? value) => (value ?? _minValue).clamp(_minValue, _maxValue); + + void _save() { + final values = (chest: _chest, waist: _waist, hip: _hip); + Navigator.of(context).pop(); + widget.onSave(values); + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), + child: Row( + children: [ + for (final title in [ + s.insights_series_chest, + s.insights_series_waist, + s.insights_series_hips, + ]) + Expanded( + child: Center( + child: Text( + title, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + ), + ], + ), + ), + SizedBox( + height: 200, + child: Row( + children: [ + _picker( + const Key('add_circumference_chest_picker'), + _chestController, + (value) => _chest = value, + ), + _picker( + const Key('add_circumference_waist_picker'), + _waistController, + (value) => _waist = value, + ), + _picker( + const Key('add_circumference_hip_picker'), + _hipController, + (value) => _hip = value, + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: InkWell( + key: const Key('add_sheet_save'), + onTap: _save, + borderRadius: BorderRadius.circular(16), + child: Ink( + width: MediaQuery.of(context).size.width - 32, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: appTheme.blueA400, + borderRadius: BorderRadius.circular(16), + ), + child: Center( + child: Text( + s.save, + style: const TextStyle(color: Colors.white), + ), + ), + ), + ), + ), + ], + ), + ); + } + + Widget _picker( + Key key, + FixedExtentScrollController controller, + ValueChanged onChanged, + ) { + return Expanded( + child: CupertinoPicker( + key: key, + magnification: 1.22, + squeeze: 1.2, + useMagnifier: true, + scrollController: controller, + itemExtent: 24, + onSelectedItemChanged: (index) => onChanged(index + _minValue), + children: [for (int i = _minValue; i <= _maxValue; i++) Text('$i')], + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/add_weight_bottom_sheet.dart b/lib/features/insights/presentation/widgets/add_weight_bottom_sheet.dart new file mode 100644 index 00000000..c2c0f0d0 --- /dev/null +++ b/lib/features/insights/presentation/widgets/add_weight_bottom_sheet.dart @@ -0,0 +1,147 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +const int _minKilo = 20; +const int _maxKilo = 299; + +/// Выбор веса (кг + десятые). [onSave] вызывается после закрытия шторки. +Future showAddWeightBottomSheet( + BuildContext context, { + double? initialWeight, + required Future Function(double weight) onSave, +}) { + return showModalBottomSheet( + useRootNavigator: true, + context: context, + builder: (_) => + AddWeightBottomSheet(initialWeight: initialWeight, onSave: onSave), + ); +} + +class AddWeightBottomSheet extends StatefulWidget { + const AddWeightBottomSheet({ + super.key, + this.initialWeight, + required this.onSave, + }); + + final double? initialWeight; + final Future Function(double weight) onSave; + + @override + State createState() => _AddWeightBottomSheetState(); +} + +class _AddWeightBottomSheetState extends State { + late final FixedExtentScrollController _kiloController; + late final FixedExtentScrollController _gramsController; + late int _kilo; + late int _grams; + + @override + void initState() { + super.initState(); + final initial = widget.initialWeight; + final tenths = initial == null + ? 0 + : (initial * 10).round().clamp(_minKilo * 10, _maxKilo * 10 + 9); + _kilo = initial == null ? _minKilo : tenths ~/ 10; + _grams = initial == null ? 0 : tenths % 10; + _kiloController = FixedExtentScrollController( + initialItem: _kilo - _minKilo, + ); + _gramsController = FixedExtentScrollController(initialItem: _grams); + } + + @override + void dispose() { + _kiloController.dispose(); + _gramsController.dispose(); + super.dispose(); + } + + void _save() { + final weight = double.parse('$_kilo.$_grams'); + Navigator.of(context).pop(); + widget.onSave(weight); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + height: 200, + child: Row( + children: [ + Expanded( + child: CupertinoPicker( + key: const Key('add_weight_kilo_picker'), + magnification: 1.22, + squeeze: 1.2, + useMagnifier: true, + scrollController: _kiloController, + itemExtent: 24, + onSelectedItemChanged: (value) => _kilo = value + _minKilo, + children: [ + for (int i = _minKilo; i <= _maxKilo; i++) Text('$i'), + ], + ), + ), + Expanded( + child: CupertinoPicker( + key: const Key('add_weight_grams_picker'), + magnification: 1.22, + squeeze: 1.2, + useMagnifier: true, + scrollController: _gramsController, + itemExtent: 24, + onSelectedItemChanged: (value) => _grams = value, + children: [for (int i = 0; i < 10; i++) Text('$i')], + ), + ), + ], + ), + ), + _SaveButton(onTap: _save), + ], + ), + ); + } +} + +class _SaveButton extends StatelessWidget { + const _SaveButton({required this.onTap}); + + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: InkWell( + key: const Key('add_sheet_save'), + onTap: onTap, + borderRadius: BorderRadius.circular(16), + child: Ink( + width: MediaQuery.of(context).size.width - 32, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: appTheme.blueA400, + borderRadius: BorderRadius.circular(16), + ), + child: Center( + child: Text( + S.of(context).save, + style: const TextStyle(color: Colors.white), + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/insights_card.dart b/lib/features/insights/presentation/widgets/insights_card.dart new file mode 100644 index 00000000..9432221f --- /dev/null +++ b/lib/features/insights/presentation/widgets/insights_card.dart @@ -0,0 +1,640 @@ +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:eatvio_app/features/insights/insights_feature_flags.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/bmi_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/daily_kbju_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/intra_day_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/measure_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/weight_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_cubit.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/add_circumference_bottom_sheet.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/add_weight_bottom_sheet.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_fab.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_head.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_tabs.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/intra_date_nav.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/intra_legend.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/period_pills.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/series_chips.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// Сворачиваемый блок «Аналитика» (вес, ИМТ, замеры). +/// +/// [slug] — владелец данных (`null` — текущий пользователь). При 403 блок +/// скрывается целиком. [canAdd] включает кнопку «+» на вкладках «Вес» и «Замеры». +class InsightsCard extends StatelessWidget { + const InsightsCard({ + super.key, + this.slug, + this.canAdd = false, + this.repository, + this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled, + this.refreshToken = 0, + this.initialIntraDate, + }); + + final String? slug; + final bool canAdd; + final InsightsRepository? repository; + final bool kbjuEnabled; + + /// При смене значения блок перезапрашивает данные (например, после правок + /// в дневнике), сохраняя вкладку, период и выбранный день. + final int refreshToken; + + /// День вкладки «В течение дня» при первой загрузке (`YYYY-MM-DD`). + /// В дневнике совпадает с открытой датой; `null` — сегодня. + final String? initialIntraDate; + + @override + Widget build(BuildContext context) { + return KeyedSubtree( + key: ValueKey('insights_card_$slug'), + child: BlocProvider( + create: (_) => InsightsCubit( + repository: repository ?? sl(), + slug: slug, + canAdd: canAdd, + kbjuEnabled: kbjuEnabled, + )..load(intraDate: initialIntraDate), + child: _InsightsView( + refreshToken: refreshToken, + initialIntraDate: initialIntraDate, + ), + ), + ); + } +} + +class _InsightsView extends StatefulWidget { + const _InsightsView({ + required this.refreshToken, + required this.initialIntraDate, + }); + + final int refreshToken; + final String? initialIntraDate; + + @override + State<_InsightsView> createState() => _InsightsViewState(); +} + +class _InsightsViewState extends State<_InsightsView> { + @override + void didUpdateWidget(covariant _InsightsView oldWidget) { + super.didUpdateWidget(oldWidget); + final cubit = context.read(); + if (oldWidget.refreshToken != widget.refreshToken) { + cubit.refresh(); + } + final nextDate = widget.initialIntraDate; + if (nextDate != null && + nextDate.isNotEmpty && + oldWidget.initialIntraDate != nextDate) { + final parsed = DateTime.tryParse(nextDate); + if (parsed != null) { + cubit.setIntraDate(parsed); + } + } + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + return switch (state) { + InsightsStateLoaded() => _CardShell( + child: _LoadedContent(state: state), + ), + InsightsStateError() => const _CardShell(child: _ErrorContent()), + _ => const SizedBox.shrink(), + }; + }, + ); + } +} + +class _CardShell extends StatelessWidget { + const _CardShell({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return Container( + key: const Key('insights_card'), + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: const [ + BoxShadow( + color: InsightsColors.cardShadow, + blurRadius: 4, + offset: Offset(0, 2), + ), + ], + ), + child: child, + ); + } +} + +class _ErrorContent extends StatelessWidget { + const _ErrorContent(); + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Expanded( + child: Text( + s.insights_load_error, + style: const TextStyle( + fontSize: 14, + color: InsightsColors.subtitle, + ), + ), + ), + TextButton( + key: const Key('insights_retry'), + onPressed: () => context.read().load(), + child: Text(s.insights_retry), + ), + ], + ), + ); + } +} + +class _LoadedContent extends StatelessWidget { + const _LoadedContent({required this.state}); + + final InsightsStateLoaded state; + + @override + Widget build(BuildContext context) { + final cubit = context.read(); + final showFab = cubit.canAdd && state.panel.supportsAdd; + + return Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _Toggle(isExpanded: state.isExpanded, onTap: cubit.toggleExpanded), + AnimatedSize( + duration: const Duration(milliseconds: 200), + alignment: Alignment.topCenter, + child: state.isExpanded + ? Padding( + padding: EdgeInsets.fromLTRB( + 16, + 0, + 16, + showFab ? 24 + 44 : 24, + ), + child: _Body(state: state), + ) + : const SizedBox(width: double.infinity), + ), + ], + ), + if (showFab && state.isExpanded) + Positioned( + right: 16, + bottom: 16, + child: InsightsFab( + tooltip: S.of(context).insights_add_record, + onPressed: () => _onAddPressed(context, cubit, state), + ), + ), + ], + ); + } + + void _onAddPressed( + BuildContext context, + InsightsCubit cubit, + InsightsStateLoaded state, + ) { + final s = S.of(context); + if (state.panel == InsightsPanel.weight) { + showAddWeightBottomSheet( + context, + initialWeight: state.payload.weight.last, + onSave: (weight) async { + if (!await cubit.addWeight(weight: weight)) { + showErrorToast(s.insights_save_error); + } + }, + ); + } else if (state.panel == InsightsPanel.measures) { + final measure = state.payload.measure; + showAddCircumferenceBottomSheet( + context, + initial: + measure.waist.isEmpty || + measure.chest.isEmpty || + measure.hips.isEmpty + ? null + : ( + chest: measure.chest.last.round(), + waist: measure.waist.last.round(), + hip: measure.hips.last.round(), + ), + onSave: (values) async { + final isSaved = await cubit.addCircumference( + chestCircumference: values.chest, + waistCircumference: values.waist, + hipCircumference: values.hip, + ); + if (!isSaved) { + showErrorToast(s.insights_save_error); + } + }, + ); + } + } +} + +class _Toggle extends StatelessWidget { + const _Toggle({required this.isExpanded, required this.onTap}); + + final bool isExpanded; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return InkWell( + key: const Key('insights_toggle'), + borderRadius: BorderRadius.circular(8), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: InsightsColors.accentBackground, + borderRadius: BorderRadius.circular(10), + ), + child: const Icon( + Icons.show_chart_rounded, + size: 20, + color: InsightsColors.blue, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + s.insights_title, + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w700, + color: InsightsColors.title, + ), + ), + const SizedBox(height: 2), + Text( + key: const Key('insights_subtitle'), + isExpanded + ? s.insights_subtitle_open + : s.insights_subtitle_closed, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: InsightsColors.subtitle, + ), + ), + ], + ), + ), + AnimatedRotation( + turns: isExpanded ? 0 : 0.5, + duration: const Duration(milliseconds: 200), + child: const Icon( + Icons.keyboard_arrow_up_rounded, + size: 26, + color: InsightsColors.blue, + ), + ), + ], + ), + ), + ); + } +} + +class _Body extends StatelessWidget { + const _Body({required this.state}); + + final InsightsStateLoaded state; + + @override + Widget build(BuildContext context) { + final cubit = context.read(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InsightsTabs( + panels: cubit.panels, + selected: state.panel, + onSelected: cubit.setPanel, + ), + const SizedBox(height: 12), + AnimatedOpacity( + duration: const Duration(milliseconds: 150), + opacity: state.isRefreshing ? 0.5 : 1, + child: _PanelContent(state: state, canAdd: cubit.canAdd), + ), + ], + ); + } +} + +class _PanelContent extends StatelessWidget { + const _PanelContent({required this.state, required this.canAdd}); + + final InsightsStateLoaded state; + final bool canAdd; + + @override + Widget build(BuildContext context) { + final cubit = context.read(); + final s = S.of(context); + final payload = state.payload; + + final Widget content; + switch (state.panel) { + case InsightsPanel.weight: + content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InsightsHead( + headline: payload.weight.headline, + unit: payload.weight.unit, + deltaText: payload.weight.deltaText, + isDeltaHighlighted: payload.weight.delta != null, + ), + const SizedBox(height: 12), + WeightChart( + model: payload.weight, + emptyText: canAdd + ? s.insights_add_weight_empty + : s.insights_not_enough, + ), + ], + ); + case InsightsPanel.bmi: + content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (payload.bmi.values.isNotEmpty) ...[ + InsightsHead( + headline: payload.bmi.headline, + unit: s.insights_unit_bmi, + deltaText: payload.bmi.deltaText, + isDeltaHighlighted: payload.bmi.delta != null, + ), + const SizedBox(height: 12), + ], + BmiChart(model: payload.bmi), + ], + ); + case InsightsPanel.measures: + final visibility = state.seriesVisibility.measure; + content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InsightsHead( + headline: payload.measure.headline, + unit: s.insights_unit_cm_waist, + deltaText: payload.measure.deltaText, + isDeltaHighlighted: payload.measure.waist.length > 1, + ), + const SizedBox(height: 12), + SeriesChips( + chips: [ + SeriesChipData( + label: s.insights_series_waist, + color: InsightsColors.waist, + isVisible: visibility[0], + ), + SeriesChipData( + label: s.insights_series_chest, + color: InsightsColors.chest, + isVisible: visibility[1], + ), + SeriesChipData( + label: s.insights_series_hips, + color: InsightsColors.hips, + isVisible: visibility[2], + ), + ], + onToggle: (index) => + cubit.toggleSeries(InsightsPanel.measures, index), + ), + const SizedBox(height: 12), + MeasureChart( + model: payload.measure, + visibility: visibility, + emptyText: canAdd + ? s.insights_add_measures_empty + : s.insights_not_enough, + ), + ], + ); + case InsightsPanel.daily: + return _DailyPanel(state: state); + case InsightsPanel.intra: + return _IntraPanel(state: state); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PeriodPills( + periods: BodyPeriod.values, + selected: state.bodyPeriod, + labelOf: (period) => period.pillLabel(s), + keyOf: (period) => period.apiValue, + onSelected: cubit.setBodyPeriod, + ), + const SizedBox(height: 16), + content, + ], + ); + } +} + +/// «КБЖУ по дням». Смена периода перезапрашивает `GET /api/profile/insights`. +class _DailyPanel extends StatelessWidget { + const _DailyPanel({required this.state}); + + final InsightsStateLoaded state; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final cubit = context.read(); + final daily = state.payload.daily; + final visibility = state.seriesVisibility.daily; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PeriodPills( + periods: DailyPeriod.values, + selected: state.dailyPeriod, + labelOf: (period) => period.pillLabel(s), + keyOf: (period) => period.apiValue, + onSelected: cubit.setDailyPeriod, + ), + const SizedBox(height: 16), + if (daily == null) + InsightsChartPlaceholder(text: s.insights_not_enough) + else ...[ + InsightsHead( + headline: daily.headline, + unit: s.insights_unit_kcal_avg, + deltaText: daily.deltaText, + isDeltaHighlighted: (daily.percent ?? 0) != 0, + ), + const SizedBox(height: 12), + SeriesChips( + chips: [ + SeriesChipData( + label: s.insights_series_calories, + color: InsightsColors.calories, + isVisible: visibility[0], + ), + SeriesChipData( + label: s.insights_series_proteins, + color: InsightsColors.proteins, + isVisible: visibility[1], + ), + SeriesChipData( + label: s.insights_series_fats, + color: InsightsColors.fats, + isVisible: visibility[2], + ), + SeriesChipData( + label: s.insights_series_carbs, + color: InsightsColors.carbs, + isVisible: visibility[3], + ), + ], + onToggle: (index) => cubit.toggleSeries(InsightsPanel.daily, index), + ), + const SizedBox(height: 12), + DailyKbjuChart(model: daily, visibility: visibility), + ], + ], + ); + } +} + +/// «В течение дня». Листание дней запрашивает только `/insights/intra`. +class _IntraPanel extends StatelessWidget { + const _IntraPanel({required this.state}); + + final InsightsStateLoaded state; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final cubit = context.read(); + final intra = state.payload.intra; + final visibility = state.seriesVisibility.intra; + + if (intra == null) { + return InsightsChartPlaceholder(text: s.insights_not_enough); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + IntraDateNav( + model: intra, + onPreviousDay: cubit.showPreviousDay, + onNextDay: cubit.showNextDay, + onDatePicked: cubit.setIntraDate, + ), + const SizedBox(height: 16), + SeriesChips( + chips: [ + SeriesChipData( + label: s.insights_series_proteins, + color: InsightsColors.proteins, + isVisible: visibility[0], + ), + SeriesChipData( + label: s.insights_series_fats, + color: InsightsColors.fats, + isVisible: visibility[1], + ), + SeriesChipData( + label: s.insights_series_carbs, + color: InsightsColors.carbs, + isVisible: visibility[2], + ), + SeriesChipData( + label: s.insights_series_satiety, + color: InsightsColors.satiety, + isVisible: visibility[3], + ), + SeriesChipData( + label: s.insights_series_mood, + color: InsightsColors.mood, + isVisible: visibility[4], + ), + SeriesChipData( + label: s.insights_series_sleep, + color: InsightsColors.sleepLine, + isVisible: state.showSleep, + ), + ], + onToggle: (index) { + if (index == 5) { + cubit.toggleSleep(); + } else { + cubit.toggleSeries(InsightsPanel.intra, index); + } + }, + ), + const SizedBox(height: 12), + IntraDayChart( + model: intra, + visibility: visibility, + showSleep: state.showSleep, + ), + const SizedBox(height: 8), + IntraLegend(model: intra), + const SizedBox(height: 8), + Text( + s.insights_intra_hint, + key: const Key('insights_intra_hint'), + style: const TextStyle(fontSize: 13, color: InsightsColors.subtitle), + ), + ], + ); + } +} diff --git a/lib/features/insights/presentation/widgets/insights_colors.dart b/lib/features/insights/presentation/widgets/insights_colors.dart new file mode 100644 index 00000000..38bd90f8 --- /dev/null +++ b/lib/features/insights/presentation/widgets/insights_colors.dart @@ -0,0 +1,36 @@ +import 'package:flutter/painting.dart'; + +/// Токены из `latest-tmpls/src/scss/pages/diary.scss` (`&__analytics*`). +abstract final class InsightsColors { + static const Color blue = Color(0xFF2F80ED); + static const Color accentBackground = Color(0xFFF6FAFF); + static const Color title = Color(0xFF323F4B); + static const Color subtitle = Color(0xFF7B8794); + static const Color border = Color(0xFFE6E6E6); + static const Color positive = Color(0xFF019A3E); + + static const Color calories = Color(0xFF323F4B); + static const Color proteins = Color(0xFF2F80ED); + static const Color fats = Color(0xFFF2994A); + static const Color carbs = Color(0xFF0D6EFD); + static const Color satiety = Color(0xFF019A3E); + static const Color mood = Color(0xFFEB555C); + + static const Color waist = Color(0xFF2F80ED); + static const Color chest = Color(0xFF9B51E0); + static const Color hips = Color(0xFFF2994A); + + static const Color wake = Color(0xFFF2994A); + static const Color sleepLine = Color(0xFF7B8794); + static const Color sleepShade = Color(0x1A7B8794); + + static const Color bmiNormalZone = Color(0x14019A3E); + static const Color bmiOverweightZone = Color(0x1AF2994A); + static const Color bmiObesityZone = Color(0x14EB555C); + + static const Color cardShadow = Color(0x26000000); + static const Color fabShadow = Color(0x592F80ED); +} + +/// Высота области графика. +const double insightsChartHeight = 270; diff --git a/lib/features/insights/presentation/widgets/insights_fab.dart b/lib/features/insights/presentation/widgets/insights_fab.dart new file mode 100644 index 00000000..02ec76ed --- /dev/null +++ b/lib/features/insights/presentation/widgets/insights_fab.dart @@ -0,0 +1,42 @@ +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Круглая кнопка «+» (52px) справа-снизу карточки. +class InsightsFab extends StatelessWidget { + const InsightsFab({super.key, required this.onPressed, this.tooltip}); + + final VoidCallback onPressed; + final String? tooltip; + + @override + Widget build(BuildContext context) { + return Tooltip( + message: tooltip ?? '', + child: Container( + width: 52, + height: 52, + decoration: const BoxDecoration( + color: InsightsColors.blue, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: InsightsColors.fabShadow, + blurRadius: 20, + offset: Offset(0, 8), + ), + ], + ), + child: Material( + color: Colors.transparent, + shape: const CircleBorder(), + child: InkWell( + key: const Key('insights_fab'), + customBorder: const CircleBorder(), + onTap: onPressed, + child: const Icon(Icons.add, color: Colors.white, size: 28), + ), + ), + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/insights_head.dart b/lib/features/insights/presentation/widgets/insights_head.dart new file mode 100644 index 00000000..7cad6850 --- /dev/null +++ b/lib/features/insights/presentation/widgets/insights_head.dart @@ -0,0 +1,70 @@ +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Крупное число + единица + строка с дельтой. +class InsightsHead extends StatelessWidget { + const InsightsHead({ + super.key, + required this.headline, + required this.unit, + required this.deltaText, + this.isDeltaHighlighted = true, + }); + + final String headline; + final String unit; + final String deltaText; + + /// Зелёная дельта при наличии изменения, иначе нейтральный серый. + final bool isDeltaHighlighted; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + headline, + key: const Key('insights_headline'), + style: const TextStyle( + fontSize: 34, + fontWeight: FontWeight.w800, + color: InsightsColors.title, + height: 1.1, + ), + ), + if (unit.isNotEmpty) ...[ + const SizedBox(width: 6), + Text( + unit, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: InsightsColors.subtitle, + ), + ), + ], + ], + ), + if (deltaText.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + deltaText, + key: const Key('insights_delta'), + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: isDeltaHighlighted + ? InsightsColors.positive + : InsightsColors.subtitle, + ), + ), + ], + ], + ); + } +} diff --git a/lib/features/insights/presentation/widgets/insights_tabs.dart b/lib/features/insights/presentation/widgets/insights_tabs.dart new file mode 100644 index 00000000..41340114 --- /dev/null +++ b/lib/features/insights/presentation/widgets/insights_tabs.dart @@ -0,0 +1,63 @@ +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Горизонтально прокручиваемые вкладки (`l-tab`). +class InsightsTabs extends StatelessWidget { + const InsightsTabs({ + super.key, + required this.panels, + required this.selected, + required this.onSelected, + }); + + final List panels; + final InsightsPanel selected; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final panel in panels) + InkWell( + key: Key('insights_tab_${panel.name}'), + onTap: () => onSelected(panel), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: panel == selected + ? InsightsColors.blue + : Colors.transparent, + width: 2, + ), + ), + ), + child: Text( + panel.label(s), + style: TextStyle( + fontSize: 13, + fontWeight: panel == selected + ? FontWeight.w700 + : FontWeight.w600, + color: panel == selected + ? InsightsColors.blue + : InsightsColors.subtitle, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/intra_date_nav.dart b/lib/features/insights/presentation/widgets/intra_date_nav.dart new file mode 100644 index 00000000..8771f608 --- /dev/null +++ b/lib/features/insights/presentation/widgets/intra_date_nav.dart @@ -0,0 +1,130 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Навигация по дням для вкладки «В течение дня»: `‹ дата ›` и выбор даты. +/// +/// Колбэки `null` — навигация неактивна (данные других дней ещё не подключены). +class IntraDateNav extends StatelessWidget { + const IntraDateNav({ + super.key, + required this.model, + this.onPreviousDay, + this.onNextDay, + this.onDatePicked, + }); + + final IntraChartModel model; + final VoidCallback? onPreviousDay; + final VoidCallback? onNextDay; + final ValueChanged? onDatePicked; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final canGoNext = !model.isToday && onNextDay != null; + + return Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: InsightsColors.accentBackground, + borderRadius: BorderRadius.circular(999), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _NavButton( + key: const Key('insights_intra_prev'), + icon: Icons.chevron_left_rounded, + tooltip: s.insights_prev_day, + onPressed: onPreviousDay, + ), + InkWell( + key: const Key('insights_intra_pick'), + borderRadius: BorderRadius.circular(999), + onTap: onDatePicked == null ? null : () => _pickDate(context), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 72), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.calendar_today_rounded, + size: 14, + color: InsightsColors.blue, + ), + const SizedBox(width: 6), + Text( + model.dateLabel, + key: const Key('insights_intra_date_label'), + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: InsightsColors.title, + ), + ), + ], + ), + ), + ), + ), + _NavButton( + key: const Key('insights_intra_next'), + icon: Icons.chevron_right_rounded, + tooltip: s.insights_next_day, + onPressed: canGoNext ? onNextDay : null, + ), + ], + ), + ); + } + + Future _pickDate(BuildContext context) async { + final lastDate = DateTime.tryParse(model.maxDate) ?? DateTime.now(); + final current = DateTime.tryParse(model.date) ?? lastDate; + final picked = await showDatePicker( + context: context, + initialDate: current.isAfter(lastDate) ? lastDate : current, + firstDate: DateTime(2000), + lastDate: lastDate, + helpText: S.of(context).insights_pick_date, + ); + if (picked != null) { + onDatePicked?.call(picked); + } + } +} + +class _NavButton extends StatelessWidget { + const _NavButton({ + super.key, + required this.icon, + required this.tooltip, + required this.onPressed, + }); + + final IconData icon; + final String tooltip; + final VoidCallback? onPressed; + + @override + Widget build(BuildContext context) { + return Opacity( + opacity: onPressed == null ? 0.35 : 1, + child: SizedBox( + width: 36, + height: 36, + child: IconButton( + padding: EdgeInsets.zero, + tooltip: tooltip, + onPressed: onPressed, + icon: Icon(icon, color: InsightsColors.blue), + ), + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/intra_legend.dart b/lib/features/insights/presentation/widgets/intra_legend.dart new file mode 100644 index 00000000..738f375d --- /dev/null +++ b/lib/features/insights/presentation/widgets/intra_legend.dart @@ -0,0 +1,96 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Легенда под графиком «В течение дня»: подъём, отход ко сну, затемнение сна. +class IntraLegend extends StatelessWidget { + const IntraLegend({super.key, required this.model}); + + final IntraChartModel model; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final wakeText = + model.wakeText ?? + (model.wakeLabel == null ? null : s.insights_wake_at(model.wakeLabel!)); + final sleepText = + model.sleepText ?? + (model.sleepLabel == null + ? null + : s.insights_sleep_at(model.sleepLabel!)); + + return Wrap( + spacing: 16, + runSpacing: 6, + children: [ + if (wakeText != null) + _LegendItem( + key: const Key('insights_legend_wake'), + color: InsightsColors.wake, + text: wakeText, + isDashed: true, + ), + if (sleepText != null) + _LegendItem( + key: const Key('insights_legend_sleep'), + color: InsightsColors.sleepLine, + text: sleepText, + isDashed: true, + ), + _LegendItem( + key: const Key('insights_legend_shade'), + color: InsightsColors.sleepShade, + text: s.insights_sleep_shade, + ), + ], + ); + } +} + +class _LegendItem extends StatelessWidget { + const _LegendItem({ + super.key, + required this.color, + required this.text, + this.isDashed = false, + }); + + final Color color; + final String text; + final bool isDashed; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + isDashed + ? Container( + width: 18, + height: 0, + decoration: BoxDecoration( + border: Border(top: BorderSide(color: color, width: 2)), + ), + ) + : Container( + width: 18, + height: 10, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(2), + ), + ), + const SizedBox(width: 6), + Text( + text, + style: const TextStyle( + fontSize: 12.5, + color: InsightsColors.subtitle, + ), + ), + ], + ); + } +} diff --git a/lib/features/insights/presentation/widgets/period_pills.dart b/lib/features/insights/presentation/widgets/period_pills.dart new file mode 100644 index 00000000..d8c6c76d --- /dev/null +++ b/lib/features/insights/presentation/widgets/period_pills.dart @@ -0,0 +1,79 @@ +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Пилюли выбора периода (`1М 3М 6М 1Г Всё время`). +class PeriodPills extends StatelessWidget { + const PeriodPills({ + super.key, + required this.periods, + required this.selected, + required this.labelOf, + required this.keyOf, + this.onSelected, + }); + + final List periods; + final T selected; + final String Function(T period) labelOf; + final String Function(T period) keyOf; + + /// `null` — пилюли неинтерактивны (данные для периода ещё не подключены). + final ValueChanged? onSelected; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final period in periods) + Padding( + padding: const EdgeInsets.only(right: 6), + child: _Pill( + key: Key('insights_period_${keyOf(period)}'), + label: labelOf(period), + isActive: period == selected, + onTap: onSelected == null ? null : () => onSelected!(period), + ), + ), + ], + ), + ); + } +} + +class _Pill extends StatelessWidget { + const _Pill({ + super.key, + required this.label, + required this.isActive, + required this.onTap, + }); + + final String label; + final bool isActive; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: isActive ? InsightsColors.blue : InsightsColors.accentBackground, + borderRadius: BorderRadius.circular(999), + child: InkWell( + borderRadius: BorderRadius.circular(999), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 7), + child: Text( + label, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: isActive ? Colors.white : InsightsColors.subtitle, + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/insights/presentation/widgets/series_chips.dart b/lib/features/insights/presentation/widgets/series_chips.dart new file mode 100644 index 00000000..2c300a93 --- /dev/null +++ b/lib/features/insights/presentation/widgets/series_chips.dart @@ -0,0 +1,76 @@ +import 'package:eatvio_app/features/insights/presentation/widgets/insights_colors.dart'; +import 'package:material_ui/material_ui.dart'; + +class SeriesChipData { + const SeriesChipData({ + required this.label, + required this.color, + required this.isVisible, + }); + + final String label; + final Color color; + final bool isVisible; +} + +/// Чипы-переключатели серий под графиком. +class SeriesChips extends StatelessWidget { + const SeriesChips({super.key, required this.chips, required this.onToggle}); + + final List chips; + final ValueChanged onToggle; + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (var i = 0; i < chips.length; i++) + Opacity( + opacity: chips[i].isVisible ? 1 : 0.45, + child: InkWell( + key: Key('insights_series_$i'), + borderRadius: BorderRadius.circular(999), + onTap: () => onToggle(i), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 7, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(999), + border: Border.all(color: InsightsColors.border, width: 1.5), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + color: chips[i].color, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: 8), + Text( + chips[i].label, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: InsightsColors.title, + decoration: chips[i].isVisible + ? TextDecoration.none + : TextDecoration.lineThrough, + ), + ), + ], + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/features/insights/repositories/insights_repository.dart b/lib/features/insights/repositories/insights_repository.dart new file mode 100644 index 00000000..4da18a0d --- /dev/null +++ b/lib/features/insights/repositories/insights_repository.dart @@ -0,0 +1,103 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/insights/domain/insights_text_builder.dart'; +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/services/insights_service.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; + +/// Данные аналитики недоступны текущему пользователю (HTTP 403): консультация +/// не активна либо это чужой профиль без доступа. +class InsightsForbidden implements Exception { + const InsightsForbidden(); + + @override + String toString() => 'InsightsForbidden'; +} + +typedef InsightsTextBuilderFactory = InsightsTextBuilder Function(); + +/// Источники данных блока «Аналитика»: +/// - [fetchInsights] / [fetchIntra] — серверные `GET /api/profile/insights*` +/// (графики и тексты считает `UserInsightsService`, включая КБЖУ); +/// - [getInsights] — собирает payload на клиенте из эндпоинтов веса и замеров +/// (используется, пока выключен `InsightsFeatureFlags.kbjuEnabled`). +class InsightsRepository { + InsightsRepository({required this.profileRepository, required this.insightsService, InsightsTextBuilderFactory? textBuilderFactory}) + : _textBuilderFactory = textBuilderFactory ?? (() => InsightsTextBuilder(S.current)); + + final ProfileRepository profileRepository; + final InsightsService insightsService; + final InsightsTextBuilderFactory _textBuilderFactory; + + /// Рост в сантиметрах для расчёта подсказки ИМТ; `null`, если не указан или + /// профиль не удалось загрузить (кроме 403 — он пробрасывается как [InsightsForbidden]). + Future getHeightCm({String? slug}) async { + try { + final details = slug == null ? await profileRepository.getMyProfileDetails() : await profileRepository.getProfileDetailsBySlug(slug); + return details.height > 0 ? details.height : null; + } on DioException catch (e) { + _throwIfForbidden(e); + return null; + } catch (_) { + return null; + } + } + + Future getInsights({String? slug, required BodyPeriod bodyPeriod, int? heightCm}) async { + try { + final (weights, circumferences) = await ( + profileRepository.getWeight(period: bodyPeriod.apiValue, slug: slug), + profileRepository.getCircumferences(period: bodyPeriod.apiValue, slug: slug), + ).wait; + return _textBuilderFactory().build(weights: weights, circumferences: circumferences, period: bodyPeriod, heightCm: heightCm); + } on DioException catch (e) { + _throwIfForbidden(e); + rethrow; + } + } + + /// Полный payload с сервера. [intraDate] — `YYYY-MM-DD`, `null` — сегодня. + Future fetchInsights({String? slug, required BodyPeriod bodyPeriod, required DailyPeriod dailyPeriod, String? intraDate}) async { + try { + final response = slug == null + ? await insightsService.getInsights(bodyPeriod: bodyPeriod.apiValue, dailyPeriod: dailyPeriod.apiValue, intraDate: intraDate) + : await insightsService.getInsightsBySlug(slug: slug, bodyPeriod: bodyPeriod.apiValue, dailyPeriod: dailyPeriod.apiValue, intraDate: intraDate); + return response.data; + } on DioException catch (e) { + _throwIfForbidden(e); + rethrow; + } + } + + /// Только вкладка «В течение дня» за [intraDate] (`YYYY-MM-DD`). + Future fetchIntra({String? slug, String? intraDate}) async { + try { + final response = slug == null + ? await insightsService.getIntra(intraDate: intraDate) + : await insightsService.getIntraBySlug(slug: slug, intraDate: intraDate); + return response.data.intra; + } on DioException catch (e) { + _throwIfForbidden(e); + rethrow; + } + } + + Future addWeight({required double weight}) { + return profileRepository.addWeight(weight: weight); + } + + Future addCircumference({required int chestCircumference, required int waistCircumference, required int hipCircumference}) { + return profileRepository.addCircumference( + chestCircumference: chestCircumference, + waistCircumference: waistCircumference, + hipCircumference: hipCircumference, + ); + } + + void _throwIfForbidden(DioException e) { + if (e.response?.statusCode == 403) { + throw const InsightsForbidden(); + } + } +} diff --git a/lib/features/insights/services/insights_service.dart b/lib/features/insights/services/insights_service.dart new file mode 100644 index 00000000..f0e64028 --- /dev/null +++ b/lib/features/insights/services/insights_service.dart @@ -0,0 +1,43 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/insights/models/insights_response_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'insights_service.g.dart'; + +/// Эндпоинты инсайтов (eatvio/eatvio#3017). Сервер приводит будущую +/// `intra_date` к сегодняшней, неверные значения периода дают 422, чужой +/// недоступный профиль — 403. +@RestApi() +abstract class InsightsService { + factory InsightsService(Dio dio, {String baseUrl}) = _InsightsService; + + /// Свои графики целиком. + @GET('/api/profile/insights') + Future getInsights({ + @Query('body_period') String? bodyPeriod, + @Query('daily_period') String? dailyPeriod, + @Query('intra_date') String? intraDate, + }); + + /// Чужие графики целиком (клиент консультанта; остальным 403). + @GET('/api/profile/insights/{slug}') + Future getInsightsBySlug({ + @Path() required String slug, + @Query('body_period') String? bodyPeriod, + @Query('daily_period') String? dailyPeriod, + @Query('intra_date') String? intraDate, + }); + + /// Только «в течение дня» для себя. + @GET('/api/profile/insights/intra') + Future getIntra({ + @Query('intra_date') String? intraDate, + }); + + /// Только «в течение дня» для другого пользователя. + @GET('/api/profile/insights/{slug}/intra') + Future getIntraBySlug({ + @Path() required String slug, + @Query('intra_date') String? intraDate, + }); +} diff --git a/lib/features/internet_connection_checker/internet_connection_checker_screen.dart b/lib/features/internet_connection_checker/internet_connection_checker_screen.dart index 576eb891..646e1988 100644 --- a/lib/features/internet_connection_checker/internet_connection_checker_screen.dart +++ b/lib/features/internet_connection_checker/internet_connection_checker_screen.dart @@ -5,7 +5,7 @@ import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart b/lib/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart index 3d5b94ed..c9e80d18 100644 --- a/lib/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart +++ b/lib/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart @@ -1,5 +1,6 @@ import 'dart:developer'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -7,7 +8,11 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart'; class MenuCubit extends Cubit { final ProfileRepository profileRepository; - MenuCubit(this.profileRepository) : super(const MenuState.initial()); + final SessionLifecycleService sessionLifecycleService; + MenuCubit(this.profileRepository, this.sessionLifecycleService) + : super(const MenuState.initial()); + + Future logout() => sessionLifecycleService.logout(); Future getMyProfile() async { emit(const MenuState.loading()); @@ -23,7 +28,10 @@ class MenuCubit extends Cubit { Future makePassKey() async { try { - final passKey = await profileRepository.getPassKey(routeName: 'product_nutritional_value.index', routeParams: {}); + final passKey = await profileRepository.getPassKey( + routeName: 'product_nutritional_value.index', + routeParams: {}, + ); return passKey; } catch (e, st) { await reportFrom(e, st, this); diff --git a/lib/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart b/lib/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart index 2c8a5fc5..e9ced3b0 100644 --- a/lib/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart +++ b/lib/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart @@ -9,9 +9,8 @@ class NotificationSettingsCubit extends Cubit { final NotificationSettingsRepository _notificationSettingsRepository; int _alertSeq = 0; - NotificationSettingsCubit({required NotificationSettingsRepository notificationSettingsRepository}) - : _notificationSettingsRepository = notificationSettingsRepository, - super(const NotificationSettingsStateLoading()); + NotificationSettingsCubit({required this._notificationSettingsRepository}) + : super(const NotificationSettingsStateLoading()); Future getNotificationSettings() async { emit(const NotificationSettingsStateLoading()); diff --git a/lib/features/menu/presentation/pages/blocked_users_screen.dart b/lib/features/menu/presentation/pages/blocked_users_screen.dart index 2f632026..37a8da6b 100644 --- a/lib/features/menu/presentation/pages/blocked_users_screen.dart +++ b/lib/features/menu/presentation/pages/blocked_users_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart'; import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart'; import 'package:eatvio_app/features/menu/presentation/widgets/blocked_user_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class BlockedUsersScreen extends StatefulWidget { diff --git a/lib/features/menu/presentation/pages/menu_screen.dart b/lib/features/menu/presentation/pages/menu_screen.dart index 84d78dbb..cfa52fd4 100644 --- a/lib/features/menu/presentation/pages/menu_screen.dart +++ b/lib/features/menu/presentation/pages/menu_screen.dart @@ -1,28 +1,22 @@ -import 'package:dio/dio.dart'; -import 'package:eatvio_app/core/app_config.dart'; -import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; import 'package:eatvio_app/core/const.dart'; -import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; -import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/core/utils/image_constant.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:eatvio_app/core/widgets/data_error_widget.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart'; import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart'; import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart'; import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart'; -import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart'; import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart'; import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart'; import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; @@ -56,6 +50,12 @@ class MenuScreen extends StatelessWidget { if (profileModel.roles.contains('consultant')) _divider(context), if (profileModel.roles.contains('consultant')) _tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)), + _divider(context), + _tile( + leading: ImageConstant.icnConsultation, + title: 'Мои консультации', + onTap: () => GoRouter.of(context).push(VideoCallRecordingsScreen.path), + ), if (!hidePlans) ...[ _divider(context), _tile( @@ -155,6 +155,7 @@ class MenuScreen extends StatelessWidget { Future Function() _onTapLogout(BuildContext context) { return () async { + final menuCubit = context.read(); showDialog( context: context, builder: (context) => CupertinoAlertDialog( @@ -162,25 +163,8 @@ class MenuScreen extends StatelessWidget { actions: [ CupertinoDialogAction( onPressed: () async { - try { - // Logout revokes the Sanctum token. Unregister first, or - // FCM / VoIP tokens stay on the server and calls still ring. - await sl().unregisterPushTokens(); - } catch (e, s) { - await sl().report(e, s, origin: 'MenuScreen'); - } - try { - await sl().post('${sl().baseUrl}/api/profile/logout'); - } catch (e, s) { - await sl().report(e, s, origin: 'MenuScreen'); - } finally { - await sl().endCall(); - await sl().clear(); - await TokenStorage.removeTokenInStorage(); - if (context.mounted) { - GoRouter.of(context).go('/auth-screen', extra: true); - } - } + Navigator.of(context).pop(); + await menuCubit.logout(); }, isDestructiveAction: true, child: const Text("Выйти"), diff --git a/lib/features/menu/presentation/pages/notifications_settings_screen.dart b/lib/features/menu/presentation/pages/notifications_settings_screen.dart index 2bce5518..b57cb600 100644 --- a/lib/features/menu/presentation/pages/notifications_settings_screen.dart +++ b/lib/features/menu/presentation/pages/notifications_settings_screen.dart @@ -4,8 +4,8 @@ import 'package:eatvio_app/features/menu/models/notification_settings_model.dart import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart'; import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/lib/features/menu/presentation/widgets/blocked_user_widget.dart b/lib/features/menu/presentation/widgets/blocked_user_widget.dart index c2971def..830c253c 100644 --- a/lib/features/menu/presentation/widgets/blocked_user_widget.dart +++ b/lib/features/menu/presentation/widgets/blocked_user_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/my_diets/presentation/cubit/my_diets_cubit.dart b/lib/features/my_diets/presentation/cubit/my_diets_cubit.dart index be5fcca9..1089146c 100644 --- a/lib/features/my_diets/presentation/cubit/my_diets_cubit.dart +++ b/lib/features/my_diets/presentation/cubit/my_diets_cubit.dart @@ -136,6 +136,11 @@ class MyDietsCubit extends Cubit { } } + void selectInitialTab(int index) { + if (index < 0 || index > 2) return; + emit(state.copyWith(selectedStateIndex: index)); + } + void changeSelectedStateIndex(int index) { emit(state.copyWith(selectedStateIndex: index)); if (state.activeDiets.isEmpty) { diff --git a/lib/features/my_diets/presentation/my_diets_screen.dart b/lib/features/my_diets/presentation/my_diets_screen.dart index 25662b1c..e00fe433 100644 --- a/lib/features/my_diets/presentation/my_diets_screen.dart +++ b/lib/features/my_diets/presentation/my_diets_screen.dart @@ -14,17 +14,24 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.d import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diet_widget.dart'; import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diets_tab.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class MyDietsScreen extends StatelessWidget { - const MyDietsScreen({super.key}); + const MyDietsScreen({super.key, this.initialTabIndex = 0}); static const name = 'myDietsScreen'; static const path = '/my-diets-screen'; + final int initialTabIndex; @override Widget build(BuildContext context) { - return BlocProvider(create: (context) => sl()..loadAllDiets(), child: MyDietsScreenContent()); + return BlocProvider( + create: (context) => + sl() + ..selectInitialTab(initialTabIndex) + ..loadAllDiets(), + child: MyDietsScreenContent(), + ); } } diff --git a/lib/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet.dart b/lib/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet.dart index 46fb0a57..6d6a697a 100644 --- a/lib/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet.dart +++ b/lib/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class DietDeletedBottomSheet extends StatelessWidget { diff --git a/lib/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart b/lib/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart index a1bd11b3..e52dad87 100644 --- a/lib/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart +++ b/lib/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class DietDraftedBottomSheet extends StatelessWidget { diff --git a/lib/features/my_diets/presentation/widgets/my_diet_widget.dart b/lib/features/my_diets/presentation/widgets/my_diet_widget.dart index e2236b96..454e6ec3 100644 --- a/lib/features/my_diets/presentation/widgets/my_diet_widget.dart +++ b/lib/features/my_diets/presentation/widgets/my_diet_widget.dart @@ -19,7 +19,7 @@ import 'package:eatvio_app/features/my_diets/presentation/widgets/diet_deleted_b import 'package:eatvio_app/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/my_finance/presentation/pages/card_settings.dart b/lib/features/my_finance/presentation/pages/card_settings.dart index fa271da6..e6d56c04 100644 --- a/lib/features/my_finance/presentation/pages/card_settings.dart +++ b/lib/features/my_finance/presentation/pages/card_settings.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cub import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_state.dart'; import 'package:eatvio_app/features/my_finance/presentation/widgets/card_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:collection/collection.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/my_finance/presentation/pages/user_finance_screen.dart b/lib/features/my_finance/presentation/pages/user_finance_screen.dart index d9f56ef6..5179f19d 100644 --- a/lib/features/my_finance/presentation/pages/user_finance_screen.dart +++ b/lib/features/my_finance/presentation/pages/user_finance_screen.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/prof import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart'; import 'package:eatvio_app/features/my_finance/entities/consultant_finance_entity.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/my_finance/presentation/widgets/card_widget.dart b/lib/features/my_finance/presentation/widgets/card_widget.dart index 58c4b1b8..5b86fc91 100644 --- a/lib/features/my_finance/presentation/widgets/card_widget.dart +++ b/lib/features/my_finance/presentation/widgets/card_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/my_plans/presentation/my_plans_screen.dart b/lib/features/my_plans/presentation/my_plans_screen.dart index f7bdb456..09a94a55 100644 --- a/lib/features/my_plans/presentation/my_plans_screen.dart +++ b/lib/features/my_plans/presentation/my_plans_screen.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.d import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart'; import 'package:eatvio_app/features/my_plans/presentation/widgets/my_plan_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/my_plans/presentation/widgets/my_plan_widget.dart b/lib/features/my_plans/presentation/widgets/my_plan_widget.dart index 6c006f34..9c80da75 100644 --- a/lib/features/my_plans/presentation/widgets/my_plan_widget.dart +++ b/lib/features/my_plans/presentation/widgets/my_plan_widget.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.dart'; import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; // Removed SVG icon usage after switching to text buttons diff --git a/lib/features/notifications/models/notification_model.dart b/lib/features/notifications/models/notification_model.dart index b178eb91..222462cd 100644 --- a/lib/features/notifications/models/notification_model.dart +++ b/lib/features/notifications/models/notification_model.dart @@ -2174,6 +2174,56 @@ class PersonalDietIsDefinedToCustomerNotification implements BaseNotificationMod } } +class PersonalDietIsDefinedToAuthorNotification implements BaseNotificationModel { + @override + final NotificationType type; + @override + final bool isRead; + @override + final DateTime createdAt; + final int chosenPlanId; + final int dietId; + final String planName; + final String userName; + final String consultantName; + final String dietName; + final String role; + final String peerSlug; + final String peerImagePath; + + PersonalDietIsDefinedToAuthorNotification({ + required this.type, + required this.isRead, + required this.createdAt, + required this.chosenPlanId, + required this.dietId, + required this.planName, + required this.userName, + required this.consultantName, + required this.dietName, + required this.role, + required this.peerSlug, + required this.peerImagePath, + }); + + factory PersonalDietIsDefinedToAuthorNotification.fromJson(Map json, NotificationType type, {bool? isRead, String? createdAt}) { + return PersonalDietIsDefinedToAuthorNotification( + type: type, + isRead: isRead ?? false, + createdAt: parseDate(createdAt ?? json['created_at'] ?? DateTime.now().toIso8601String()), + chosenPlanId: json['chosen_plan_id'] ?? 0, + dietId: json['diet_id'] ?? 0, + planName: json['plan_name'] ?? '', + userName: json['user_name'] ?? '', + consultantName: json['consultant_name'] ?? '', + dietName: json['diet_name'] ?? '', + role: json['role']?.toString() ?? '', + peerSlug: json['peer_slug'] ?? '', + peerImagePath: json['peer_image_path'] ?? '', + ); + } +} + // New Model Classes for Comprehensive Support class ConsultantEducationUpdatedNotification implements BaseNotificationModel { @@ -2480,6 +2530,7 @@ enum NotificationType { chosenPlanFinishedToConsultant, stayOnTrackToCustomer, personalDietIsDefinedToCustomer, + personalDietIsDefinedToAuthor, // Comments entityCommented, @@ -2602,6 +2653,7 @@ enum NotificationType { 'stay-on-track-to-customer' => NotificationType.stayOnTrackToCustomer, 'diary-reminder-for-users' => NotificationType.diaryReminderForUsers, 'personal-diet-is-defined-to-customer' => NotificationType.personalDietIsDefinedToCustomer, + 'personal-diet-is-defined-to-author' => NotificationType.personalDietIsDefinedToAuthor, // New additions 'consultant-education-updated' => NotificationType.consultantEducationUpdated, diff --git a/lib/features/notifications/presentation/notifications_cubit/notifications_cubit.dart b/lib/features/notifications/presentation/notifications_cubit/notifications_cubit.dart index a3c5827d..0a30a0db 100644 --- a/lib/features/notifications/presentation/notifications_cubit/notifications_cubit.dart +++ b/lib/features/notifications/presentation/notifications_cubit/notifications_cubit.dart @@ -16,6 +16,11 @@ class NotificationsCubit extends Cubit { StreamSubscription? _newNotificationsSubscription; NotificationsCubit({required this.wsManager, required this.notificationsRepository}) : super(const NotificationsState.empty()); + void reset() { + _notifications.clear(); + if (!isClosed) emit(const NotificationsState.empty()); + } + Future connectToWebSocket() async { try { await _newNotificationsSubscription?.cancel(); @@ -272,6 +277,12 @@ class NotificationsCubit extends Cubit { isRead: isRead, createdAt: createdAt, ), + NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson( + notificationJson, + type, + isRead: isRead, + createdAt: createdAt, + ), NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson( notificationJson, type, diff --git a/lib/features/notifications/presentation/notifications_screen.dart b/lib/features/notifications/presentation/notifications_screen.dart index 33a8a634..022da95f 100644 --- a/lib/features/notifications/presentation/notifications_screen.dart +++ b/lib/features/notifications/presentation/notifications_screen.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/notifications/presentation/notifications_cub import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_state.dart'; import 'package:eatvio_app/features/notifications/presentation/widgets/notification_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class NotificationsScreen extends StatefulWidget { diff --git a/lib/features/notifications/presentation/widgets/notification_widget.dart b/lib/features/notifications/presentation/widgets/notification_widget.dart index 26714425..9fb822e0 100644 --- a/lib/features/notifications/presentation/widgets/notification_widget.dart +++ b/lib/features/notifications/presentation/widgets/notification_widget.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings. import 'package:eatvio_app/features/notifications/models/notification_model.dart'; import 'package:eatvio_app/features/profile/presentation/pages/subs_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class NotificationWidget extends StatelessWidget { @@ -122,6 +122,9 @@ class NotificationWidget extends StatelessWidget { PersonalDietIsDefinedToCustomerNotification() => _PersonalDietIsDefinedToCustomerWidget( notification: notification as PersonalDietIsDefinedToCustomerNotification, ), + PersonalDietIsDefinedToAuthorNotification() => _PersonalDietIsDefinedToAuthorWidget( + notification: notification as PersonalDietIsDefinedToAuthorNotification, + ), // New Widgets ConsultantEducationUpdatedNotification() => _ConsultantEducationUpdatedWidget(notification: notification as ConsultantEducationUpdatedNotification), ComplaintRegisteredNotification() => _ComplaintRegisteredWidget(notification: notification as ComplaintRegisteredNotification), @@ -1273,6 +1276,30 @@ class _PersonalDietIsDefinedToCustomerWidget extends StatelessWidget { } } +class _PersonalDietIsDefinedToAuthorWidget extends StatelessWidget { + const _PersonalDietIsDefinedToAuthorWidget({required this.notification}); + final PersonalDietIsDefinedToAuthorNotification notification; + @override + Widget build(BuildContext context) { + final s = S.of(context); + final userName = notification.userName.isNotEmpty ? notification.userName : s.default_user_name; + final notificationsText = notification.dietName.isEmpty + ? s.personal_diet_defined_to_author(userName) + : s.personal_diet_defined_to_author_named(userName, notification.dietName); + + return _BaseNotificationWidget( + isRead: notification.isRead, + notificationsText: notificationsText, + createdAt: notification.createdAt, + onTap: notification.peerSlug.isEmpty + ? null + : () { + context.push(RouteConstants.profileScreen, extra: notification.peerSlug); + }, + ); + } +} + class _ConsultantEducationUpdatedWidget extends StatelessWidget { const _ConsultantEducationUpdatedWidget({required this.notification}); final ConsultantEducationUpdatedNotification notification; diff --git a/lib/features/notifications/service/notifications_service.dart b/lib/features/notifications/service/notifications_service.dart index c934fb53..dbe2d16c 100644 --- a/lib/features/notifications/service/notifications_service.dart +++ b/lib/features/notifications/service/notifications_service.dart @@ -413,6 +413,12 @@ class NotificationsService { isRead: readDate != null, createdAt: createdAt, ), + NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson( + notificationJson['data'], + type, + isRead: readDate != null, + createdAt: createdAt, + ), NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson( notificationJson['data'], type, diff --git a/lib/features/order_info/presentation/info_by_order_screen.dart b/lib/features/order_info/presentation/info_by_order_screen.dart index c37913f5..2b237340 100644 --- a/lib/features/order_info/presentation/info_by_order_screen.dart +++ b/lib/features/order_info/presentation/info_by_order_screen.dart @@ -6,7 +6,6 @@ import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cancel_plan_bottom_ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/author_card.dart'; -import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; import 'package:eatvio_app/features/order_info/cubit/order_info_state.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/collect_charge_banner.dart'; @@ -18,7 +17,7 @@ import 'package:eatvio_app/features/order_info/presentation/widgets/plan_status_ import 'package:eatvio_app/core/widgets/option_widget.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -106,14 +105,7 @@ class _InfoByOrderScreenContentState extends State { ), ); } - PacketOptions? chosenOption; - if (plan.optionType == 'options1') { - chosenOption = plan.plan.packet1Options; - } else if (plan.optionType == 'options2') { - chosenOption = plan.plan.packet2Options; - } else { - chosenOption = plan.plan.packet3Options; - } + final chosenOption = plan.chosenOption; PlanStatusValues planStatus; if (widget.successfulPayment == true) { @@ -164,7 +156,7 @@ class _InfoByOrderScreenContentState extends State { const SizedBox(height: 8), PlanState(state: plan.chosenPlanState, hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false), const SizedBox(height: 20), - if (widget.successfulPayment == null) + if (widget.successfulPayment == null && plan.chosenPlanState.canShowCancelAction) CustomOutlinedButton( text: s.cancelConsultation, height: 52, @@ -173,7 +165,7 @@ class _InfoByOrderScreenContentState extends State { onPressed: () async { showModalBottomSheet( context: context, - builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isStateAfterPaidState(), planId: plan.id), + builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isCancelAfterPaidState, planId: plan.id), ); }, ), diff --git a/lib/features/order_info/presentation/widgets/collect_charge_banner.dart b/lib/features/order_info/presentation/widgets/collect_charge_banner.dart index cb1eaf1d..3d5f4901 100644 --- a/lib/features/order_info/presentation/widgets/collect_charge_banner.dart +++ b/lib/features/order_info/presentation/widgets/collect_charge_banner.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class CollectChargeBanner extends StatelessWidget { diff --git a/lib/features/order_info/presentation/widgets/payment_banner.dart b/lib/features/order_info/presentation/widgets/payment_banner.dart index 5dc56d90..997baa05 100644 --- a/lib/features/order_info/presentation/widgets/payment_banner.dart +++ b/lib/features/order_info/presentation/widgets/payment_banner.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart'; import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/order_info/presentation/widgets/plan_info.dart b/lib/features/order_info/presentation/widgets/plan_info.dart index d8f91880..3755fb40 100644 --- a/lib/features/order_info/presentation/widgets/plan_info.dart +++ b/lib/features/order_info/presentation/widgets/plan_info.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class PlanInfo extends StatelessWidget { const PlanInfo({super.key, required this.title, required this.description, required this.imagePath}); diff --git a/lib/features/order_info/presentation/widgets/plan_props.dart b/lib/features/order_info/presentation/widgets/plan_props.dart index 05c5145e..a638bd7c 100644 --- a/lib/features/order_info/presentation/widgets/plan_props.dart +++ b/lib/features/order_info/presentation/widgets/plan_props.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/utils/localization_utils.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_status_box.dart'; diff --git a/lib/features/order_info/presentation/widgets/plan_state.dart b/lib/features/order_info/presentation/widgets/plan_state.dart index f65b82bb..7e792509 100644 --- a/lib/features/order_info/presentation/widgets/plan_state.dart +++ b/lib/features/order_info/presentation/widgets/plan_state.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class PlanState extends StatefulWidget { const PlanState({super.key, required this.state, required this.hasPersonalDiet}); diff --git a/lib/features/order_info/presentation/widgets/plan_status_box.dart b/lib/features/order_info/presentation/widgets/plan_status_box.dart index 70801b41..777fd37a 100644 --- a/lib/features/order_info/presentation/widgets/plan_status_box.dart +++ b/lib/features/order_info/presentation/widgets/plan_status_box.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; enum PlanStatusValues { paid, diff --git a/lib/features/payment/presentation/payment_flow.dart b/lib/features/payment/presentation/payment_flow.dart index 2764dc9e..1ae71989 100644 --- a/lib/features/payment/presentation/payment_flow.dart +++ b/lib/features/payment/presentation/payment_flow.dart @@ -7,13 +7,14 @@ import 'package:eatvio_app/features/payment/presentation/widgets/promo_code_gate import 'package:eatvio_app/features/payment/presentation/widgets/promo_code_modal.dart'; import 'package:eatvio_app/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart'; import 'package:eatvio_app/features/payment/repositories/payment_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Оркестрирует флоу оплаты консультации: /// applied rehydrate → (или гейт → форма) → apply при необходимости → SbpBanks. Future showConsultationPaymentFlow( BuildContext context, { required int planId, + double? amount, Future Function(BuildContext)? showGate, Future Function( BuildContext, { @@ -21,7 +22,7 @@ Future showConsultationPaymentFlow( Future Function()? onRemove, PromoCodeModel? initialPromo, })? showForm, - Future Function(BuildContext, {required int planId})? showSbp, + Future Function(BuildContext, {required int planId, double? amount})? showSbp, Future Function({ required int planId, required String promoCode, @@ -65,7 +66,7 @@ Future showConsultationPaymentFlow( } if (!context.mounted) return; - await sbp(context, planId: planId); + await sbp(context, planId: planId, amount: amount); return; } @@ -92,7 +93,7 @@ Future showConsultationPaymentFlow( } if (!context.mounted) return; - await sbp(context, planId: planId); + await sbp(context, planId: planId, amount: amount); } Future _showGate(BuildContext context) { @@ -113,8 +114,8 @@ Future _showForm( ); } -Future _showSbp(BuildContext context, {required int planId}) { - return showSbpBanksBottomSheet(context, planId: planId); +Future _showSbp(BuildContext context, {required int planId, double? amount}) { + return showSbpBanksBottomSheet(context, planId: planId, amount: amount); } Future _defaultValidatePromo({ diff --git a/lib/features/payment/presentation/widgets/promo_code_gate_bottom_sheet.dart b/lib/features/payment/presentation/widgets/promo_code_gate_bottom_sheet.dart index b72a3f13..885ede54 100644 --- a/lib/features/payment/presentation/widgets/promo_code_gate_bottom_sheet.dart +++ b/lib/features/payment/presentation/widgets/promo_code_gate_bottom_sheet.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Показывает bottom sheet «У вас есть промокод?» с кнопками Да/Нет. /// diff --git a/lib/features/payment/presentation/widgets/promo_code_modal.dart b/lib/features/payment/presentation/widgets/promo_code_modal.dart index 7de3eecf..0d349096 100644 --- a/lib/features/payment/presentation/widgets/promo_code_modal.dart +++ b/lib/features/payment/presentation/widgets/promo_code_modal.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/features/payment/models/promo_code_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Результат работы модалки промокода. class PromoCodeResult { diff --git a/lib/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart b/lib/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart index 5b0f95e7..9f6d149b 100644 --- a/lib/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart +++ b/lib/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart @@ -8,18 +8,23 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart'; import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart'; +import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:sbp/models/c2bmembers_model.dart'; /// Показывает bottom sheet выбора банка СБП для оплаты консультации. -Future showSbpBanksBottomSheet(BuildContext context, {required int planId}) { +Future showSbpBanksBottomSheet( + BuildContext context, { + required int planId, + double? amount, +}) { final height = MediaQuery.sizeOf(context).height * 0.55; return showBottomSheetWithBlur( context: context, height: height, - child: SbpBanksBottomSheet(planId: planId), + child: SbpBanksBottomSheet(planId: planId, amount: amount), ); } @@ -28,9 +33,13 @@ Future showSbpBanksBottomSheet(BuildContext context, {required int planId} /// При открытии вызывает [ConsultationPaymentCubit.startPayment] с [planId] /// и показывает [Loader], пока загружаются checkout_url и список банков. class SbpBanksBottomSheet extends StatefulWidget { - const SbpBanksBottomSheet({super.key, required this.planId, this.cubit}); + const SbpBanksBottomSheet({super.key, required this.planId, this.amount, this.cubit}); final int planId; + + /// Сумма к оплате в рублях — передаётся в QR-шит для отображения. + final double? amount; + final ConsultationPaymentCubit? cubit; @override @@ -77,6 +86,32 @@ class _SbpBanksBottomSheetState extends State { style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), textAlign: TextAlign.center, ), + // QR-кнопка доступна сразу после получения checkout_url, + // не дожидаясь списка банков: на устройствах без банковских + // приложений (iOS в РФ) это единственный путь оплаты. + BlocBuilder( + buildWhen: (previous, current) => + previous.checkoutUrl != current.checkoutUrl, + builder: (context, state) { + final checkoutUrl = state.checkoutUrl; + if (checkoutUrl == null || checkoutUrl.isEmpty) { + return const SizedBox.shrink(); + } + return Padding( + padding: const EdgeInsets.only(top: 16), + child: CustomOutlinedButton( + text: s.pay_by_qr_code, + height: 52, + buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700), + buttonStyle: ButtonStyle( + side: const WidgetStatePropertyAll(BorderSide.none), + backgroundColor: WidgetStatePropertyAll(appTheme.blueA400), + ), + onPressed: _onShowQrTap, + ), + ); + }, + ), const SizedBox(height: 16), Expanded( child: BlocBuilder( @@ -122,6 +157,23 @@ class _SbpBanksBottomSheetState extends State { ); } + /// Открывает QR-шит поверх шита банков; при подтверждённой оплате + /// закрывает и родительский шит. + Future _onShowQrTap() async { + final paid = await showSbpQrBottomSheet( + context, + planId: widget.planId, + cubit: _cubit, + amount: widget.amount, + ); + if (paid == true && mounted) { + final navigator = Navigator.of(context); + if (navigator.canPop()) { + navigator.pop(); + } + } + } + Future _onBankTap(C2bmemberModel bank) async { final opened = await _cubit.openBank(bank: bank); if (opened && mounted) { diff --git a/lib/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart b/lib/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart new file mode 100644 index 00000000..804892d5 --- /dev/null +++ b/lib/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart @@ -0,0 +1,316 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; +import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart'; +import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:qr_flutter/qr_flutter.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// Тестовый симулятор оплаты СБП (только для стендов разработки/stage). +const String _testPayUrlBase = 'https://testpay.alfabank.ru/sbp-page?qrcId='; +const String _nspkUrlPrefix = 'https://qr.nspk.ru/'; +const Duration _pollInterval = Duration(seconds: 3); +const Duration _autoCloseDelay = Duration(seconds: 2); + +/// Показывает bottom sheet с QR-кодом СБП для оплаты консультации +/// с другого устройства. +/// +/// Возвращает `true`, если оплата подтверждена polling-ом статуса плана. +Future showSbpQrBottomSheet( + BuildContext context, { + required int planId, + required ConsultationPaymentCubit cubit, + double? amount, +}) { + return showBottomSheetWithBlur( + context: context, + height: null, + child: SbpQrBottomSheet( + planId: planId, + cubit: cubit, + amount: amount, + ), + ); +} + +/// QR-код оплаты СБП: рендерит [ConsultationPaymentState.checkoutUrl] +/// (payload вида `https://qr.nspk.ru/{qrcId}`), ожидает оплату через +/// polling статуса chosen_plan и показывает успех. +class SbpQrBottomSheet extends StatefulWidget { + const SbpQrBottomSheet({ + super.key, + required this.planId, + required this.cubit, + this.amount, + this.chatRepository, + this.pollInterval = _pollInterval, + }); + + final int planId; + final ConsultationPaymentCubit cubit; + + /// Сумма к оплате в рублях (показывается над QR, если передана). + final double? amount; + + /// Переопределяется в тестах; по умолчанию берётся из DI. + final ChatRepository? chatRepository; + + final Duration pollInterval; + + @override + State createState() => _SbpQrBottomSheetState(); +} + +class _SbpQrBottomSheetState extends State { + late final ChatRepository _chatRepository; + late final Timer _pollTimer; + bool _paid = false; + + @override + void initState() { + super.initState(); + _chatRepository = widget.chatRepository ?? sl(); + _pollTimer = Timer.periodic(widget.pollInterval, (_) => _pollStatus()); + _pollStatus(); + } + + @override + void dispose() { + _pollTimer.cancel(); + super.dispose(); + } + + Future _pollStatus() async { + if (_paid || !mounted) return; + try { + final plan = await _chatRepository.getChosenPlan(id: widget.planId); + if (plan.chosenPlanState.isStateAfterPaidState()) { + _onPaid(); + } + } catch (_) { + // Сетевые сбои polling-а игнорируем — следующий тик повторит проверку. + } + } + + void _onPaid() { + if (_paid || !mounted) return; + setState(() => _paid = true); + Future.delayed(_autoCloseDelay, () { + if (!mounted) return; + Navigator.of(context).pop(true); + }); + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return BlocProvider.value( + value: widget.cubit, + child: BlocBuilder( + builder: (context, state) { + final checkoutUrl = state.checkoutUrl; + if (checkoutUrl == null || checkoutUrl.isEmpty) { + return const SizedBox.shrink(); + } + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 8), + const BottomSheetHandlerBar(), + const SizedBox(height: 20), + Text( + _paid ? s.sbp_qr_paid_title : s.sbp_qr_title, + style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + if (_paid) + _PaidContent(description: s.sbp_qr_paid_description) + else ...[ + if (widget.amount != null) ...[ + Text( + s.sbp_qr_amount_label, + style: TextStyles.textMMedium.copyWith(color: appTheme.gray600), + textAlign: TextAlign.center, + ), + const SizedBox(height: 4), + Text( + '${widget.amount!.toStringAsFixed(0)} ₽', + style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + ], + _QrCodeCard(checkoutUrl: checkoutUrl), + const SizedBox(height: 16), + _HowToPay( + step1: s.sbp_qr_step1, + step2: s.sbp_qr_step2, + step3: s.sbp_qr_step3, + ), + const SizedBox(height: 16), + _TestPayButton(checkoutUrl: checkoutUrl), + const SizedBox(height: 16), + Text( + s.sbp_qr_waiting_payment, + style: TextStyles.textMMedium.copyWith(color: appTheme.gray600), + textAlign: TextAlign.center, + ), + ], + const SizedBox(height: 24), + ], + ), + ); + }, + ), + ); + } +} + +class _QrCodeCard extends StatelessWidget { + const _QrCodeCard({required this.checkoutUrl}); + + final String checkoutUrl; + + @override + Widget build(BuildContext context) { + return Center( + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: appTheme.blueGray300), + ), + child: QrImageView( + key: const ValueKey('sbp_qr_code'), + data: checkoutUrl, + size: 200, + backgroundColor: Colors.white, + ), + ), + ); + } +} + +class _HowToPay extends StatelessWidget { + const _HowToPay({required this.step1, required this.step2, required this.step3}); + + final String step1; + final String step2; + final String step3; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: appTheme.blueA400.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(step1, style: TextStyles.textSMedium.copyWith(color: appTheme.black)), + const SizedBox(height: 4), + Text(step2, style: TextStyles.textSMedium.copyWith(color: appTheme.black)), + const SizedBox(height: 4), + Text(step3, style: TextStyles.textSMedium.copyWith(color: appTheme.black)), + ], + ), + ); + } +} + +/// Кнопка открытия тестового симулятора оплаты Альфа-Банка. +/// +/// Видна только когда QR выдан непродовым бэкендом: тестовый qrcId от +/// продового в приложении не отличить (формат одинаковый), различает их +/// именно то, какой бэкенд выдал checkout_url — на стендах разработки/stage +/// Альфа подключена в sandbox и выдаёт QR тестового терминала. Поэтому +/// критерий — текущий base URL API не продуктовый (см. [AppConfig.isProdApi]). +class _TestPayButton extends StatelessWidget { + const _TestPayButton({required this.checkoutUrl}); + + final String checkoutUrl; + + bool get _visible { + if (sl().isProdApi) return false; + return checkoutUrl.startsWith(_nspkUrlPrefix); + } + + @override + Widget build(BuildContext context) { + if (!_visible) return const SizedBox.shrink(); + final s = S.of(context); + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFFFFF3E0), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + Text( + s.sbp_qr_test_hint, + style: TextStyles.textXSSemibold.copyWith(color: appTheme.gray600), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + OutlinedButton( + onPressed: () => _openTestPayment(), + child: Text(s.sbp_qr_open_test_payment), + ), + ], + ), + ); + } + + Future _openTestPayment() async { + final qrcId = checkoutUrl.replaceFirst(_nspkUrlPrefix, ''); + final uri = Uri.parse('$_testPayUrlBase$qrcId'); + try { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } catch (_) { + // Не смогли открыть браузер — пользователь оплатит по QR. + } + } +} + +class _PaidContent extends StatelessWidget { + const _PaidContent({required this.description}); + + final String description; + + @override + Widget build(BuildContext context) { + return Column( + children: [ + const SizedBox(height: 8), + Container( + width: 64, + height: 64, + decoration: const BoxDecoration(color: Color(0xFFE8F5E9), shape: BoxShape.circle), + child: const Icon(Icons.check_rounded, color: Color(0xFF4CAF50), size: 40), + ), + const SizedBox(height: 12), + Text( + description, + style: TextStyles.textMMedium.copyWith(color: appTheme.gray600), + textAlign: TextAlign.center, + ), + ], + ); + } +} diff --git a/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart b/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart index 0afb7d3e..1d8f150e 100644 --- a/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart +++ b/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart @@ -9,38 +9,54 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart'; class PersonalDietSuggestionCubit extends Cubit { final DietRepository dietRepository; final PersonalDietSuggestionRepository personalDietSuggestionService; - late final int dietId; + late int dietId; PersonalDietSuggestionCubit({required this.dietRepository, required this.personalDietSuggestionService}) : super(PersonalDietSuggestionState()); Future setDietName(int dietId) async { try { - emit(state.copyWith(isLoading: true, error: null)); + if (!isClosed) { + emit(state.copyWith(isLoading: true, error: null)); + } final diet = await dietRepository.getDiet(dietId); - emit(state.copyWith(isLoading: false, dietName: diet.name)); + if (!isClosed) { + emit(state.copyWith( + isLoading: false, + dietName: diet.name, + dietDuration: diet.duration, + )); + } } catch (e, st) { await reportFrom(e, st, this); log(e.toString(), stackTrace: st); - emit(state.copyWith(isLoading: false, error: e.toString())); + if (!isClosed) { + emit(state.copyWith(isLoading: false, error: e.toString())); + } } } Future getConsultationWithPersonalDiets(int dietId) async { try { this.dietId = dietId; - emit(state.copyWith(isLoading: true, error: null)); - setDietName(dietId); + if (!isClosed) { + emit(state.copyWith(isLoading: true, error: null)); + } + await setDietName(dietId); final consultations = await personalDietSuggestionService.getConsultationWithPersonalDiets(); final consultationWithDiet = consultations.where((consultation) => consultation.personalDietId != null).toList(); final consultationWithoutDiet = consultations.where((consultation) => consultation.personalDietId == null).toList(); - emit(state.copyWith( - isLoading: false, - consultationsWithDiet: consultationWithDiet, - consultationsWithoutDiet: consultationWithoutDiet, - )); + if (!isClosed) { + emit(state.copyWith( + isLoading: false, + consultationsWithDiet: consultationWithDiet, + consultationsWithoutDiet: consultationWithoutDiet, + )); + } } catch (e, st) { await reportFrom(e, st, this); log(e.toString(), stackTrace: st); - emit(state.copyWith(isLoading: false, error: e.toString())); + if (!isClosed) { + emit(state.copyWith(isLoading: false, error: e.toString())); + } } } @@ -49,6 +65,7 @@ class PersonalDietSuggestionCubit extends Cubit { }) async { try { await personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId); + await getConsultationWithPersonalDiets(dietId); return true; } catch (e, st) { await reportFrom(e, st, this); @@ -62,6 +79,7 @@ class PersonalDietSuggestionCubit extends Cubit { }) async { try { await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId); + await getConsultationWithPersonalDiets(dietId); return true; } catch (e, st) { await reportFrom(e, st, this); diff --git a/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart b/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart index da927703..0270dc4d 100644 --- a/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart +++ b/lib/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart @@ -9,8 +9,8 @@ abstract class PersonalDietSuggestionState with _$PersonalDietSuggestionState { @Default([]) List consultationsWithDiet, @Default([]) List consultationsWithoutDiet, @Default('') String dietName, + @Default(0) int dietDuration, @Default(false) bool isLoading, @Default(null) String? error, }) = _PersonalDietSuggestionState; - -} \ No newline at end of file +} diff --git a/lib/features/personal_diet_suggestion/presentation/consultation_widget.dart b/lib/features/personal_diet_suggestion/presentation/consultation_widget.dart index a9fcef6e..adc65456 100644 --- a/lib/features/personal_diet_suggestion/presentation/consultation_widget.dart +++ b/lib/features/personal_diet_suggestion/presentation/consultation_widget.dart @@ -4,13 +4,16 @@ import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/localization_utils.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:intl/intl.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -19,9 +22,15 @@ class ConsultationWidget extends StatelessWidget { super.key, required this.consultationModel, required this.dietName, + this.dietDuration = 0, }); final ConsultationModel consultationModel; final String dietName; + final int dietDuration; + + bool get _isDurationMismatch => + dietDuration > 0 && consultationModel.duration != dietDuration; + @override Widget build(BuildContext context) { final s = S.of(context); @@ -64,7 +73,20 @@ class ConsultationWidget extends StatelessWidget { ), ), Text( - 'Старт: ${consultationModel.userName}', + s.plan_duration_label( + consultationModel.duration, + getDayForm(consultationModel.duration, s), + ), + style: TextStyles.textMMedium.copyWith( + color: const Color(0xFF88949F), + ), + ), + Text( + s.start_date_label( + DateFormat('dd.MM.yyyy').format( + consultationModel.startDate, + ), + ), style: TextStyles.textMMedium.copyWith( color: const Color(0xFF88949F), ), @@ -103,15 +125,47 @@ class ConsultationWidget extends StatelessWidget { color: const Color(0xFF88949F), ), ), + Text( + s.plan_duration_label( + consultationModel.duration, + getDayForm(consultationModel.duration, s), + ), + style: TextStyles.textMMedium.copyWith( + color: const Color(0xFF88949F), + ), + ), ], ), ], ), const SizedBox(height: 12), + if (_isDurationMismatch) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.error_outline, size: 18, color: appTheme.red), + const SizedBox(width: 8), + Expanded( + child: Text( + s.personal_diet_duration_mismatch( + dietDuration, + getDayForm(dietDuration, s), + consultationModel.duration, + getDayForm(consultationModel.duration, s), + ), + style: TextStyles.textSMedium.copyWith(color: appTheme.red), + ), + ), + ], + ), + ), if (consultationModel.personalDietId != null) CustomOutlinedButton( text: s.changeDiet, height: 52, + isDisabled: _isDurationMismatch, buttonTextStyle: TextStyles.textMSemibold.copyWith( color: appTheme.gray, ), @@ -128,35 +182,8 @@ class ConsultationWidget extends StatelessWidget { userName: consultationModel.userName, dietName: dietName, onTap: () async { - final result = await context - .read() - .attachDietToConsultation( - consultationId: consultationModel.id, - ); AppRouter.navigatorKey.currentContext?.pop(); - if (result) { - if (!context.mounted) return; - showBottomSheetWithBlur( - userRootNavigator: true, - context: context, - height: null, - child: SuggestionSuccessBottomSheet( - userName: consultationModel.userName, - dietName: dietName, - ), - ); - return; - } - if (!context.mounted) return; - showBottomSheetWithBlur( - userRootNavigator: true, - context: context, - height: null, - child: SuggestionFailureBottomSheet( - userName: consultationModel.userName, - dietName: dietName, - ), - ); + await _attachDiet(context, reattach: true); }, ), ); @@ -166,12 +193,17 @@ class ConsultationWidget extends StatelessWidget { CustomOutlinedButton( text: s.suggestDiet, height: 52, + isDisabled: _isDurationMismatch, buttonTextStyle: TextStyles.textMSemibold.copyWith( - color: appTheme.whiteA700, + color: _isDurationMismatch ? appTheme.gray : appTheme.whiteA700, ), buttonStyle: ButtonStyle( side: const WidgetStatePropertyAll(BorderSide.none), - backgroundColor: WidgetStatePropertyAll(appTheme.blueA400), + backgroundColor: WidgetStatePropertyAll( + _isDurationMismatch + ? appTheme.dividerColor + : appTheme.blueA400, + ), ), onPressed: () async { showBottomSheetWithBlur( @@ -183,34 +215,7 @@ class ConsultationWidget extends StatelessWidget { dietName: dietName, onTap: () async { AppRouter.navigatorKey.currentContext?.pop(); - final result = await context - .read() - .attachDietToConsultation( - consultationId: consultationModel.id, - ); - if (result) { - if (!context.mounted) return; - showBottomSheetWithBlur( - userRootNavigator: true, - context: context, - height: null, - child: SuggestionSuccessBottomSheet( - userName: consultationModel.userName, - dietName: dietName, - ), - ); - return; - } - if (!context.mounted) return; - showBottomSheetWithBlur( - userRootNavigator: true, - context: context, - height: null, - child: SuggestionFailureBottomSheet( - userName: consultationModel.userName, - dietName: dietName, - ), - ); + await _attachDiet(context, reattach: false); }, ), ); @@ -220,6 +225,41 @@ class ConsultationWidget extends StatelessWidget { ), ); } + + Future _attachDiet( + BuildContext context, { + required bool reattach, + }) async { + final router = GoRouter.of(context); + final chatId = consultationModel.chatId; + final noChatMessage = S.of(context).msg_something_went_wrong; + final cubit = context.read(); + final result = reattach + ? await cubit.reattachDietToConsultation( + consultationId: consultationModel.id, + ) + : await cubit.attachDietToConsultation( + consultationId: consultationModel.id, + ); + if (!result) { + if (!context.mounted) return; + showBottomSheetWithBlur( + userRootNavigator: true, + context: context, + height: null, + child: SuggestionFailureBottomSheet( + userName: consultationModel.userName, + dietName: dietName, + ), + ); + return; + } + if (chatId == null || chatId.isEmpty) { + showErrorToast(noChatMessage); + return; + } + router.goNamed('chatScreen', queryParameters: {'uuid': chatId}); + } } class SuggestDietBottomSheet extends StatefulWidget { @@ -278,65 +318,6 @@ class _SuggestDietBottomSheet extends State { } } -class SuggestionSuccessBottomSheet extends StatefulWidget { - const SuggestionSuccessBottomSheet({ - super.key, - required this.userName, - required this.dietName, - }); - final String userName; - final String dietName; - - @override - State createState() => - _SuggestionSuccessBottomSheet(); -} - -class _SuggestionSuccessBottomSheet - extends State { - @override - Widget build(BuildContext context) { - final s = S.of(context); - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 12.0), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const SizedBox(height: 8), - const BottomSheetHandlerBar(), - const SizedBox(height: 20), - Text( - 'Предложение диеты', - style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), - ), - const SizedBox(height: 16), - Text( - '«${widget.dietName}» предложена пользователю ${widget.userName}', - style: TextStyles.textSMedium.copyWith(color: appTheme.black), - textAlign: TextAlign.center, - ), - const SizedBox(height: 8), - CustomOutlinedButton( - text: s.ok, - height: 52, - buttonTextStyle: TextStyles.textMSemibold.copyWith( - color: appTheme.whiteA700, - ), - buttonStyle: ButtonStyle( - side: const WidgetStatePropertyAll(BorderSide.none), - backgroundColor: WidgetStatePropertyAll(appTheme.blueA400), - ), - onPressed: () async { - AppRouter.navigatorKey.currentContext?.pop(); - }, - ), - const SizedBox(height: 40), - ], - ), - ); - } -} - class SuggestionFailureBottomSheet extends StatefulWidget { const SuggestionFailureBottomSheet({ super.key, diff --git a/lib/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart b/lib/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart index 32398019..c02a0942 100644 --- a/lib/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart +++ b/lib/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart @@ -1,12 +1,13 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/localization_utils.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/presentation/consultation_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PersonalDietSuggestionScreen extends StatelessWidget { @@ -17,7 +18,9 @@ class PersonalDietSuggestionScreen extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => sl()..getConsultationWithPersonalDiets(dietId), + create: (context) => + sl() + ..getConsultationWithPersonalDiets(dietId), child: const PersonalDietSuggestionScreenContent(), ); } @@ -28,7 +31,10 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget { @override Widget build(BuildContext context) { final s = S.of(context); - return BlocBuilder( + return BlocBuilder< + PersonalDietSuggestionCubit, + PersonalDietSuggestionState + >( builder: (context, state) { return Scaffold( backgroundColor: appTheme.gray100, @@ -36,45 +42,97 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget { centerTitle: true, title: Text( '${s.dietSuggestion}\n«${state.dietName}»', - style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + style: TextStyles.headingXLSemibold.copyWith( + color: appTheme.black, + ), ), ), body: state.isLoading ? const Center(child: Loader()) - : (state.consultationsWithDiet.isEmpty && state.consultationsWithoutDiet.isEmpty) - ? Center( - child: Padding( - padding: const EdgeInsets.all(32.0), - child: Text( - 'Нет активных консультаций с персональной диетой', - style: TextStyles.textMSemibold.copyWith(color: appTheme.gray), - textAlign: TextAlign.center, - ), - ), - ) - : SingleChildScrollView( - child: Column( - children: [ - ...List.generate(state.consultationsWithDiet.length, (index) { - return ConsultationWidget( - consultationModel: state.consultationsWithDiet[index], - dietName: state.dietName, - ); - }), - const SizedBox( - height: 12, + : SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (state.dietDuration > 0) + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), + child: _PersonalDietDurationHint( + duration: state.dietDuration, ), - ...List.generate(state.consultationsWithoutDiet.length, (index) { + ), + if (state.consultationsWithDiet.isEmpty && + state.consultationsWithoutDiet.isEmpty) + Padding( + padding: const EdgeInsets.all(32), + child: Text( + s.no_active_personal_diet_consultations, + style: TextStyles.textMSemibold.copyWith( + color: appTheme.gray, + ), + textAlign: TextAlign.center, + ), + ) + else ...[ + ...List.generate(state.consultationsWithDiet.length, ( + index, + ) { + return ConsultationWidget( + consultationModel: + state.consultationsWithDiet[index], + dietName: state.dietName, + dietDuration: state.dietDuration, + ); + }), + const SizedBox(height: 12), + ...List.generate( + state.consultationsWithoutDiet.length, + (index) { return ConsultationWidget( - consultationModel: state.consultationsWithoutDiet[index], + consultationModel: + state.consultationsWithoutDiet[index], dietName: state.dietName, + dietDuration: state.dietDuration, ); - }) - ], - ), - ), + }, + ), + ], + ], + ), + ), ); }, ); } } + +class _PersonalDietDurationHint extends StatelessWidget { + const _PersonalDietDurationHint({required this.duration}); + + final int duration; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: appTheme.gray50, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: appTheme.dividerColor), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.info_outline, size: 20, color: appTheme.blueA400), + const SizedBox(width: 8), + Expanded( + child: Text( + s.personal_diet_duration_hint(duration, getDayForm(duration, s)), + style: TextStyles.textSMedium.copyWith(color: appTheme.gray), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart b/lib/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart index b966dafd..a622676e 100644 --- a/lib/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart +++ b/lib/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart @@ -11,13 +11,23 @@ class PersonalDietSuggestionRepository { } - Future attachPersonalDiet({required int consultationId, required int dietId}) async { - return personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId); - + Future attachPersonalDiet({ + required int consultationId, + required int dietId, + }) async { + await personalDietSuggestionService.attachPersonalDiet( + consultationId, + {'diet_id': dietId}, + ); } - Future reattachPersonalDiet({required int consultationId, required int dietId}) async { - return await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId); - + Future reattachPersonalDiet({ + required int consultationId, + required int dietId, + }) async { + await personalDietSuggestionService.reattachPersonalDiet( + consultationId, + {'diet_id': dietId}, + ); } } diff --git a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart index 0a10c26e..245cbdbd 100644 --- a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart +++ b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart @@ -1,36 +1,40 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; +import 'package:retrofit/retrofit.dart'; -class PersonalDietSuggestionService { - final Dio dio; - PersonalDietSuggestionService(this.dio); +part 'personal_diet_suggestion_service.g.dart'; - Future getConsultationWithPersonalDiets() async { - try { - final response = await dio.get('/api/consultations', queryParameters: { - 'filters[plan][has_personal_diet][\$personal_diet]': '1', - 'filters[last_state][\$notIn][]': ['done', 'charge_was_collected', 'complained', 'last_day_finished', 'canceled_by_the_initiator', 'inited'], - 'sort[]': 'start_date:desc', - }); - return ConsultationPaginationModel.fromJson(response.data); - } catch (e) { - rethrow; - } - } +@RestApi() +abstract class PersonalDietSuggestionService { + factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) = + _PersonalDietSuggestionService; - Future attachPersonalDiet({required int consultationId, required int dietId}) async { - try { - await dio.post('/api/chosen_plans/$consultationId/attach_diet', data: {'diet_id': dietId}); - } catch (e) { - rethrow; - } - } + @GET('/api/consultations') + Future getConsultationWithPersonalDiets({ + @Query('filters[plan][has_personal_diet][\$personal_diet]') + String hasPersonalDiet = '1', + @Query('filters[last_state][\$notIn][]') + List notIn = const [ + 'done', + 'charge_was_collected', + 'complained', + 'last_day_finished', + 'last_day_started', + 'canceled_by_the_initiator', + 'inited', + ], + @Query('sort[]') List sort = const ['start_date:desc'], + }); - Future reattachPersonalDiet({required int consultationId, required int dietId}) async { - try { - await dio.post('/api/chosen_plans/$consultationId/re_attach_diet', data: {'diet_id': dietId}); - } catch (e) { - rethrow; - } - } + @POST('/api/chosen_plans/{id}/attach_diet') + Future attachPersonalDiet( + @Path('id') int consultationId, + @Body() Map body, + ); + + @POST('/api/chosen_plans/{id}/re_attach_diet') + Future reattachPersonalDiet( + @Path('id') int consultationId, + @Body() Map body, + ); } diff --git a/lib/features/plans/enums/chosen_plan_state_enum.dart b/lib/features/plans/enums/chosen_plan_state_enum.dart index 2e867f38..fad8736c 100644 --- a/lib/features/plans/enums/chosen_plan_state_enum.dart +++ b/lib/features/plans/enums/chosen_plan_state_enum.dart @@ -62,6 +62,32 @@ enum ChosenPlanStateEnum { } } + bool get canShowCancelAction { + switch (this) { + case ChosenPlanStateEnum.stateInited: + case ChosenPlanStateEnum.stateInCoordination: + case ChosenPlanStateEnum.stateStartDateHasBeenSet: + case ChosenPlanStateEnum.statePendingPayment: + case ChosenPlanStateEnum.statePaid: + case ChosenPlanStateEnum.stateStarted: + case ChosenPlanStateEnum.stateInProgress: + return true; + default: + return false; + } + } + + bool get isCancelAfterPaidState { + switch (this) { + case ChosenPlanStateEnum.statePaid: + case ChosenPlanStateEnum.stateStarted: + case ChosenPlanStateEnum.stateInProgress: + return true; + default: + return false; + } + } + static List getActiveStates() { return [ ChosenPlanStateEnum.statePaid, diff --git a/lib/features/plans/enums/plan_option_type_enum.dart b/lib/features/plans/enums/plan_option_type_enum.dart new file mode 100644 index 00000000..4b231bdc --- /dev/null +++ b/lib/features/plans/enums/plan_option_type_enum.dart @@ -0,0 +1,29 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +enum PlanOptionType { + @JsonValue('options1') + options1('options1'), + @JsonValue('options2') + options2('options2'), + @JsonValue('options3') + options3('options3'); + + const PlanOptionType(this.apiValue); + + final String apiValue; + + static PlanOptionType? tryParse(String? raw) { + for (final option in values) { + if (option.apiValue == raw) { + return option; + } + } + return null; + } + + static PlanOptionType fromIndex(int index) => switch (index) { + 1 => PlanOptionType.options2, + 2 => PlanOptionType.options3, + _ => PlanOptionType.options1, + }; +} diff --git a/lib/features/plans/models/chosen_plan_model.dart b/lib/features/plans/models/chosen_plan_model.dart index f70f1cd2..73724a56 100644 --- a/lib/features/plans/models/chosen_plan_model.dart +++ b/lib/features/plans/models/chosen_plan_model.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'chosen_plan_model.freezed.dart'; @@ -7,6 +8,7 @@ part 'chosen_plan_model.g.dart'; @freezed abstract class ChosenPlanModel with _$ChosenPlanModel { + const ChosenPlanModel._(); factory ChosenPlanModel({ @JsonKey() required int id, @@ -15,10 +17,24 @@ abstract class ChosenPlanModel with _$ChosenPlanModel { @JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState, @JsonKey(name: 'chat_id') required String chatId, @JsonKey(name: 'consultant_id') required int consultantId, + @JsonKey(name: 'personal_diet_name') String? personalDietName, @JsonKey(name: 'plan') required PlanModel plan, }) = _ChosenPlanModel; factory ChosenPlanModel.fromJson(Map json) => _$ChosenPlanModelFromJson(json); + + PacketOptions? get chosenOption { + switch (PlanOptionType.tryParse(optionType)) { + case PlanOptionType.options1: + return plan.packet1Options; + case PlanOptionType.options2: + return plan.packet2Options; + case PlanOptionType.options3: + return plan.packet3Options; + case null: + return null; + } + } } ChosenPlanModel? parseChosenPlan(dynamic json) { diff --git a/lib/features/plans/presentation/cubit/about_plan_cubit.dart b/lib/features/plans/presentation/cubit/about_plan_cubit.dart index 2c5b6b72..6cd354aa 100644 --- a/lib/features/plans/presentation/cubit/about_plan_cubit.dart +++ b/lib/features/plans/presentation/cubit/about_plan_cubit.dart @@ -4,6 +4,7 @@ import 'package:dio/dio.dart'; import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart'; import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart'; import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; @@ -133,7 +134,7 @@ class AboutPlanCubit extends Cubit { final slug = state.planModel?.slug; final optionIndex = state.chosenOptionIndex; if (slug != null) { - final optionName = _getOptionNameFromIndex(optionIndex); + final optionName = PlanOptionType.fromIndex(optionIndex).apiValue; final body = {'options_type': optionName}; return (await planRepository.chosePlan(slug, body), null); } @@ -181,10 +182,4 @@ class AboutPlanCubit extends Cubit { return false; } } - - String _getOptionNameFromIndex(int index) => switch (index) { - 1 => 'options2', - 2 => 'options3', - _ => 'options1', - }; } diff --git a/lib/features/plans/presentation/pages/about_plan_screen.dart b/lib/features/plans/presentation/pages/about_plan_screen.dart index 77a98c2c..2771aa83 100644 --- a/lib/features/plans/presentation/pages/about_plan_screen.dart +++ b/lib/features/plans/presentation/pages/about_plan_screen.dart @@ -26,7 +26,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart b/lib/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart index f7ae5a64..c8e33c6e 100644 --- a/lib/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart +++ b/lib/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ConfirmStartPlanBottomSheet extends StatelessWidget { const ConfirmStartPlanBottomSheet({super.key, required this.onConfirm}); diff --git a/lib/features/plans/presentation/widgets/options_tab.dart b/lib/features/plans/presentation/widgets/options_tab.dart index 912183d7..d4547000 100644 --- a/lib/features/plans/presentation/widgets/options_tab.dart +++ b/lib/features/plans/presentation/widgets/options_tab.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/animated_option_button.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_cubit.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class OptionsTab extends StatelessWidget { diff --git a/lib/features/profile/models/circumference_model.dart b/lib/features/profile/models/circumference_model.dart index c06d5ac5..9615b2d3 100644 --- a/lib/features/profile/models/circumference_model.dart +++ b/lib/features/profile/models/circumference_model.dart @@ -9,9 +9,9 @@ abstract class CircumferenceModel with _$CircumferenceModel { const factory CircumferenceModel({ @JsonKey(name: "id") required int id, @JsonKey(name: "user_id") required int userId, - @JsonKey(name: "chest_circumference") required int chestCircumference, - @JsonKey(name: "waist_circumference") required int waistCircumference, - @JsonKey(name: "hip_circumference") required int hipCircumference, + @JsonKey(name: "chest_circumference") required double chestCircumference, + @JsonKey(name: "waist_circumference") required double waistCircumference, + @JsonKey(name: "hip_circumference") required double hipCircumference, @JsonKey(name: "created_at") required DateTime createdAt, @JsonKey(name: "updated_at") required DateTime updatedAt, }) = _CircumferenceModel; diff --git a/lib/features/profile/models/weight_model.dart b/lib/features/profile/models/weight_model.dart index 1bc45383..f31c35e8 100644 --- a/lib/features/profile/models/weight_model.dart +++ b/lib/features/profile/models/weight_model.dart @@ -9,10 +9,10 @@ abstract class WeightModel with _$WeightModel { const factory WeightModel({ @JsonKey(name: "id") required int id, @JsonKey(name: "user_id") required int userId, - @JsonKey(name: "weight") required int weight, + @JsonKey(name: "weight") required double weight, @JsonKey(name: "created_at") required DateTime createdAt, @JsonKey(name: "updated_at") required DateTime updatedAt, - @JsonKey(name: "bmi") required double bmi, + @JsonKey(name: "bmi") double? bmi, }) = _WeightModel; factory WeightModel.fromJson(Map json) => _$WeightModelFromJson(json); diff --git a/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart b/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart index 2801c2b4..bd6bd761 100644 --- a/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart +++ b/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart @@ -17,11 +17,14 @@ class ProfileCubit extends Cubit { final ProfileRepository profileRepository; final ChatRepository chatRepository; final ConsultantRepository consultantRepository; - String _currentPeriod = '1'; /// Bottom-nav / own profile instance, used to refresh posts after create/update/delete. static ProfileCubit? myProfileCubit; + static void clearMyProfileReference() { + myProfileCubit = null; + } + ProfileCubit({required this.profileRepository, required this.chatRepository, required this.consultantRepository}) : super(const ProfileState.loading()); Future getProfileBySlug(String slug) async { @@ -51,10 +54,9 @@ class ProfileCubit extends Cubit { } } - Future getMyProfile({String period = '1'}) async { + Future getMyProfile() async { myProfileCubit = this; emit(const ProfileState.loading()); - _currentPeriod = period; try { final profile = await profileRepository.getMyProfile(); List certPhotos = await consultantRepository.getConsultantCertPhotos(); @@ -65,8 +67,6 @@ class ProfileCubit extends Cubit { isMyProfile: true, profileDetails: await profileRepository.getMyProfileDetails(), blogPosts: await profileRepository.getBlogPostsByAuthorSlug(slug: profile.slug), - weightPoints: await profileRepository.getWeight(period: period), - circumferencePoints: await profileRepository.getCircumferences(period: period), consultantInfo: profile.roles.contains('consultant') ? await consultantRepository.getConsultantRequestStatus(profile.slug) : null, certPhotos: certPhotos, ), @@ -106,8 +106,6 @@ class ProfileCubit extends Cubit { profile: (state as ProfileStateLoaded).profile, profileDetails: (state as ProfileStateLoaded).profileDetails, blogPosts: feedBlogPostList, - weightPoints: (state as ProfileStateLoaded).weightPoints, - circumferencePoints: (state as ProfileStateLoaded).circumferencePoints, consultantInfo: (state as ProfileStateLoaded).consultantInfo, isMyProfile: (state as ProfileStateLoaded).isMyProfile, certPhotos: (state as ProfileStateLoaded).certPhotos, @@ -122,7 +120,6 @@ class ProfileCubit extends Cubit { waistCircumference: waistCircumference, hipCircumference: hipCircumference, ); - await getMyProfile(period: _currentPeriod); } catch (e, st) { await reportFrom(e, st, this); emit(ProfileState.error(errorMessage: e.toString())); @@ -132,7 +129,6 @@ class ProfileCubit extends Cubit { Future addWeight({required double weight}) async { try { await profileRepository.addWeight(weight: weight); - await getMyProfile(period: _currentPeriod); } catch (e, st) { await reportFrom(e, st, this); emit(ProfileState.error(errorMessage: e.toString())); @@ -141,13 +137,13 @@ class ProfileCubit extends Cubit { Future getChatRoomIdBySlug({required String slug}) async { try { - final chatIdOrError = await chatRepository.getChatByUserSlug(slug); - final userProfile = await profileRepository.getProfileBySlug(slug); - if (chatIdOrError == '404') { + final chatId = await chatRepository.getChatByUserSlug(slug); + if (chatId == null || chatId.isEmpty) { + final userProfile = await profileRepository.getProfileBySlug(slug); AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: userProfile); } else { - AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatIdOrError}); - return chatIdOrError; + AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatId}); + return chatId; } } catch (e, st) { await reportFrom(e, st, this); diff --git a/lib/features/profile/presentation/bloc/profile_cubit/profile_state.dart b/lib/features/profile/presentation/bloc/profile_cubit/profile_state.dart index 4706964e..bfc0a8fe 100644 --- a/lib/features/profile/presentation/bloc/profile_cubit/profile_state.dart +++ b/lib/features/profile/presentation/bloc/profile_cubit/profile_state.dart @@ -1,9 +1,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'profile_state.freezed.dart'; @@ -20,8 +18,6 @@ abstract class ProfileState with _$ProfileState { required List blogPosts, required bool isMyProfile, required List certPhotos, - List? weightPoints, - List? circumferencePoints, ConsultationRequestModel? consultantInfo, }) = ProfileStateLoaded; diff --git a/lib/features/profile/presentation/pages/profile_screen.dart b/lib/features/profile/presentation/pages/profile_screen.dart index b35733f0..f1d771e2 100644 --- a/lib/features/profile/presentation/pages/profile_screen.dart +++ b/lib/features/profile/presentation/pages/profile_screen.dart @@ -18,26 +18,22 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/prof import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_sheet.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/pages/subs_screen.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/expandable_page_view.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/imt_chart_widget.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/profile_blog_post_widget.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:go_router/go_router.dart'; @@ -60,21 +56,8 @@ class ProfileScreen extends StatefulWidget { class _ProfileScreenState extends State { late final ProfileCubit profileCubit = sl(); final PlansCubit plansCubit = sl(); - final List chipsLabelList = ['Вес', 'Замеры', 'ИМТ']; - final List chipsIntervalLabelList = [ - '1М', - '3М', - '6М', - '1Г', - 'ВСЁ ВРЕМЯ', - ]; - final List chipsIntervalList = ['1', '3', '6', '12', 'all']; final TextEditingController controller = TextEditingController(); - List weightPoints = []; - List circumferencePoints = []; - int _selectedChipIndex = 0; - int _selectedIntervalChipIndex = 0; late bool canSub; bool isFirstFetch = true; int _currentBullet = 0; @@ -96,10 +79,6 @@ class _ProfileScreenState extends State { bloc: profileCubit, builder: (BuildContext context, ProfileState state) { if (state is ProfileStateLoaded) { - if (state.circumferencePoints != null) { - circumferencePoints = state.circumferencePoints!; - weightPoints = state.weightPoints!; - } if (isFirstFetch) { canSub = !state.profile.isEntitySubscribedByMe; if (state.profile.roles.contains('consultant') && !hidePlans) { @@ -281,6 +260,14 @@ class _ProfileScreenState extends State { padding: const EdgeInsets.only(bottom: 16), child: _badges(state), ), + // Доступ решает сервер (UserPolicy::viewInsights): консультант видит + // клиента, пока консультация не завершена; всем остальным 403 и блок скрыт. + if (!state.profile.isBlockedByMe && + !state.profile.isBlockedByAuthor) + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: InsightsCard(slug: state.profile.slug), + ), if (state.profile.isBlockedByAuthor) Column( mainAxisAlignment: MainAxisAlignment.center, @@ -442,10 +429,11 @@ class _ProfileScreenState extends State { child: _badges(state), ), if (state.profile.roles.contains('consultant')) _socialLinks(state), - Padding( - padding: const EdgeInsets.only(bottom: 16), - child: _charts(), - ), + if (state.isMyProfile) + const Padding( + padding: EdgeInsets.only(bottom: 16), + child: InsightsCard(canAdd: true), + ), if (state.profile.roles.contains('consultant')) _education(state), if (state.profile.roles.contains('consultant')) _diplomasAndCertificates(state), @@ -1722,114 +1710,4 @@ class _ProfileScreenState extends State { ], ); } - - Material _charts() { - return Material( - color: Colors.white, - borderRadius: BorderRadius.circular(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 8), - SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 16), - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _choiceChipWidget(0), - const SizedBox(width: 8), - _choiceChipWidget(1), - const SizedBox(width: 8), - _choiceChipWidget(2), - ], - ), - ), - Builder( - builder: (context) { - switch (_selectedChipIndex) { - case 0: - return WeightChartWidget( - weightPoints: weightPoints, - profileCubit: profileCubit, - ); - case 1: - return CircumferenceChartWidget( - circumferencePoints: circumferencePoints, - profileCubit: profileCubit, - ); - case 2: - return ImtChartWidget(weightPoints: weightPoints); - default: - return const SizedBox.shrink(); - } - }, - ), - const SizedBox(height: 8), - Row( - children: [ - const SizedBox(width: 16), - _choiceIntervalChipWidget(0), - const SizedBox(width: 8), - _choiceIntervalChipWidget(1), - const SizedBox(width: 8), - _choiceIntervalChipWidget(2), - const SizedBox(width: 8), - _choiceIntervalChipWidget(3), - const SizedBox(width: 8), - _choiceIntervalChipWidget(4), - ], - ), - const SizedBox(height: 8), - ], - ), - ); - } - - ChoiceChip _choiceIntervalChipWidget(int index) { - return ChoiceChip( - selectedColor: Colors.grey.withValues(alpha: 0.1), - pressElevation: 0, - showCheckmark: false, - side: BorderSide.none, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - label: Text(chipsIntervalLabelList[index]), - labelStyle: TextStyle( - color: appTheme.gray600, - fontWeight: FontWeight.w500, - fontSize: 12, - ), - selected: _selectedIntervalChipIndex == index, - onSelected: (bool selected) { - profileCubit.getMyProfile(period: chipsIntervalList[index]); - setState(() { - _selectedIntervalChipIndex = index; - }); - }, - ); - } - - ChoiceChip _choiceChipWidget(int index) { - return ChoiceChip( - selectedColor: appTheme.blueA400, - pressElevation: 0, - showCheckmark: false, - side: BorderSide.none, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - label: Text(chipsLabelList[index]), - labelStyle: TextStyle( - color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, - fontWeight: FontWeight.w500, - fontSize: 12, - ), - selected: _selectedChipIndex == index, - backgroundColor: appTheme.gray100, - onSelected: (bool selected) { - setState(() { - _selectedChipIndex = index; - }); - }, - ); - } } diff --git a/lib/features/profile/presentation/pages/subs_screen.dart b/lib/features/profile/presentation/pages/subs_screen.dart index 6de5194e..0cb0132c 100644 --- a/lib/features/profile/presentation/pages/subs_screen.dart +++ b/lib/features/profile/presentation/pages/subs_screen.dart @@ -4,8 +4,8 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_state.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/sub_widget.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; enum SubType { subscribers, subscriptions } diff --git a/lib/features/profile/presentation/widgets/circumference_chart_widget.dart b/lib/features/profile/presentation/widgets/circumference_chart_widget.dart deleted file mode 100644 index 99d674e5..00000000 --- a/lib/features/profile/presentation/widgets/circumference_chart_widget.dart +++ /dev/null @@ -1,389 +0,0 @@ -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; -import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; -import 'package:syncfusion_flutter_charts/charts.dart'; - -class CircumferenceChartWidget extends StatefulWidget { - final List circumferencePoints; - final ProfileCubit? profileCubit; - - const CircumferenceChartWidget({ - super.key, - required this.circumferencePoints, - this.profileCubit, - }); - - @override - State createState() => _CircumferenceChartWidgetState(); -} - -class _CircumferenceChartWidgetState extends State { - late FixedExtentScrollController chestController; - late FixedExtentScrollController waistController; - late FixedExtentScrollController hipController; - late int chest; - late int waist; - late int hip; - - @override - Widget build(BuildContext context) { - return Column( - children: [ - if (widget.circumferencePoints.isNotEmpty) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - Text( - '${widget.circumferencePoints.last.chestCircumference}', - style: const TextStyle( - color: Colors.black, - fontSize: 40, - fontWeight: FontWeight.w500, - ), - ), - if (widget.circumferencePoints.length == 1) - Container( - margin: const EdgeInsets.symmetric(horizontal: 12), - width: 8, - height: 8, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: Colors.black12, - ), - ), - if (widget.circumferencePoints.length > 1) - widget.circumferencePoints.last.chestCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].chestCircumference - ? const Icon( - Icons.arrow_drop_up, - size: 40, - color: Colors.grey, - ) - : const Icon( - Icons.arrow_drop_down, - size: 40, - color: Colors.grey, - ), - Text( - '${widget.circumferencePoints.last.waistCircumference}', - style: const TextStyle( - color: Colors.black, - fontSize: 40, - fontWeight: FontWeight.w500, - ), - ), - if (widget.circumferencePoints.length == 1) - Container( - margin: const EdgeInsets.symmetric(horizontal: 12), - width: 8, - height: 8, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: Colors.black12, - ), - ), - if (widget.circumferencePoints.length > 1) - widget.circumferencePoints.last.waistCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].waistCircumference - ? const Icon( - Icons.arrow_drop_up, - size: 40, - color: Colors.grey, - ) - : const Icon( - Icons.arrow_drop_down, - size: 40, - color: Colors.grey, - ), - Text( - '${widget.circumferencePoints.last.hipCircumference}', - style: const TextStyle( - color: Colors.black, - fontSize: 40, - fontWeight: FontWeight.w500, - ), - ), - if (widget.circumferencePoints.length == 1) - Container( - margin: const EdgeInsets.symmetric(horizontal: 12), - width: 8, - height: 8, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: Colors.black12, - ), - ), - if (widget.circumferencePoints.length > 1) - widget.circumferencePoints.last.hipCircumference > widget.circumferencePoints[widget.circumferencePoints.length - 2].hipCircumference - ? const Icon( - Icons.arrow_drop_up, - size: 40, - color: Colors.grey, - ) - : const Icon( - Icons.arrow_drop_down, - size: 40, - color: Colors.grey, - ), - ], - ), - ), - Stack( - alignment: Alignment.center, - children: [ - SfCartesianChart( - margin: const EdgeInsets.symmetric(horizontal: 8), - enableAxisAnimation: true, - plotAreaBorderWidth: 0, - trackballBehavior: TrackballBehavior( - enable: true, - activationMode: ActivationMode.singleTap, - tooltipDisplayMode: TrackballDisplayMode.groupAllPoints, - tooltipSettings: const InteractiveTooltip(), - lineType: TrackballLineType.vertical, - ), - primaryXAxis: DateTimeCategoryAxis( - tickPosition: TickPosition.inside, - majorTickLines: const MajorTickLines( - size: 0, - ), - edgeLabelPlacement: EdgeLabelPlacement.shift, - dateFormat: DateFormat.MMMd('ru'), - labelStyle: const TextStyle( - color: Colors.grey, - ), - majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)), - axisLine: AxisLine( - color: Colors.grey.withValues(alpha: 0.3), - width: 0.4, - ), - ), - primaryYAxis: const NumericAxis( - isVisible: false, - labelFormat: '{value} см', - axisLine: AxisLine( - width: 1, - ), - majorTickLines: MajorTickLines(size: 0), - ), - series: _getSplineSeries(), - tooltipBehavior: TooltipBehavior(enable: true), - ), - if (widget.profileCubit != null) - Positioned( - right: 16, - bottom: 16, - child: FloatingActionButton.small( - heroTag: 'addCircumference', - onPressed: () { - if (widget.circumferencePoints.isNotEmpty) { - chest = widget.circumferencePoints.last.chestCircumference; - waist = widget.circumferencePoints.last.waistCircumference; - hip = widget.circumferencePoints.last.hipCircumference; - chestController = FixedExtentScrollController(initialItem: chest - 20); - waistController = FixedExtentScrollController(initialItem: waist - 20); - hipController = FixedExtentScrollController(initialItem: hip - 20); - } else { - chestController = FixedExtentScrollController(); - waistController = FixedExtentScrollController(); - hipController = FixedExtentScrollController(); - } - showModalBottomSheet( - useRootNavigator: true, - context: context, - builder: (context) { - return SafeArea( - child: Column( - children: [ - Expanded( - child: Row( - children: [ - Expanded( - child: CupertinoPicker( - magnification: 1.22, - squeeze: 1.2, - useMagnifier: true, - scrollController: chestController, - itemExtent: 24, - onSelectedItemChanged: (int value) { - chest = value; - }, - children: [ - for (int i = 20; i < 200; i++) Text('$i'), - ], - ), - ), - Expanded( - child: CupertinoPicker( - magnification: 1.22, - squeeze: 1.2, - useMagnifier: true, - scrollController: waistController, - itemExtent: 24, - onSelectedItemChanged: (int value) { - waist = value; - }, - children: [ - for (int i = 20; i < 200; i++) Text('$i'), - ], - ), - ), - Expanded( - child: CupertinoPicker( - magnification: 1.22, - squeeze: 1.2, - useMagnifier: true, - scrollController: hipController, - itemExtent: 24, - onSelectedItemChanged: (int value) { - hip = value; - }, - children: [ - for (int i = 20; i < 200; i++) Text('$i'), - ], - ), - ), - ], - ), - ), - InkWell( - onTap: () { - widget.profileCubit?.addCircumference( - chestCircumference: chest + 20, - waistCircumference: waist + 20, - hipCircumference: hip + 20, - ); - Navigator.of(context).pop(); - }, - borderRadius: BorderRadius.circular(16), - child: Ink( - width: MediaQuery.of(context).size.width - 32, - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: appTheme.blueA400, - borderRadius: BorderRadius.circular(16), - ), - child: const Center( - child: Text( - 'Сохранить', - style: TextStyle( - color: Colors.white, - ), - ), - ), - ), - ), - ], - ), - ); - }, - ); - }, - backgroundColor: appTheme.blueA400, - shape: const CircleBorder(), - child: const Icon( - Icons.add, - color: Colors.white, - ), - ), - ), - if (widget.circumferencePoints.isEmpty) - const Padding( - padding: EdgeInsets.symmetric(horizontal: 48), - child: Text( - 'Добавьте Ваши замеры', - textAlign: TextAlign.center, - ), - ), - ], - ), - ], - ); - } - - List> _getSplineSeries() { - const Color seriesColor1 = Colors.red; - final Color seriesColor2 = appTheme.blueA400; - const Color seriesColor3 = Colors.green; - - return >[ - SplineAreaSeries( - markerSettings: const MarkerSettings( - isVisible: true, - color: seriesColor1, - height: 8, - width: 8, - ), - dataLabelSettings: const DataLabelSettings( - labelAlignment: ChartDataLabelAlignment.top, - isVisible: true, - ), - dataSource: widget.circumferencePoints, - borderColor: seriesColor1, - gradient: LinearGradient( - colors: [ - seriesColor1.withValues(alpha: 0.14), - Colors.transparent, - ], - begin: Alignment.topCenter, - end: const Alignment(0, 0.6), - ), - name: 'Грудь', - xValueMapper: (CircumferenceModel value, int index) => value.createdAt, - yValueMapper: (CircumferenceModel value, int index) => value.chestCircumference, - ), - SplineAreaSeries( - markerSettings: MarkerSettings( - isVisible: true, - color: seriesColor2, - height: 8, - width: 8, - ), - dataLabelSettings: const DataLabelSettings( - labelAlignment: ChartDataLabelAlignment.top, - isVisible: true, - ), - dataSource: widget.circumferencePoints, - borderColor: seriesColor2, - gradient: LinearGradient( - colors: [ - seriesColor2.withValues(alpha: 0.14), - Colors.transparent, - ], - begin: Alignment.topCenter, - end: const Alignment(0, 0.6), - ), - name: 'Талия', - xValueMapper: (CircumferenceModel value, int index) => value.createdAt, - yValueMapper: (CircumferenceModel value, int index) => value.waistCircumference, - ), - SplineAreaSeries( - markerSettings: const MarkerSettings( - isVisible: true, - color: seriesColor3, - height: 8, - width: 8, - ), - dataLabelSettings: const DataLabelSettings( - labelAlignment: ChartDataLabelAlignment.top, - isVisible: true, - ), - dataSource: widget.circumferencePoints, - borderColor: seriesColor3, - gradient: LinearGradient( - colors: [ - seriesColor3.withValues(alpha: 0.14), - Colors.transparent, - ], - begin: Alignment.topCenter, - end: const Alignment(0, 0.6), - ), - name: 'Бёдра', - xValueMapper: (CircumferenceModel value, int index) => value.createdAt, - yValueMapper: (CircumferenceModel value, int index) => value.hipCircumference, - ), - ]; - } -} diff --git a/lib/features/profile/presentation/widgets/expandable_page_view.dart b/lib/features/profile/presentation/widgets/expandable_page_view.dart index 99c9ef90..eb8ca4fe 100644 --- a/lib/features/profile/presentation/widgets/expandable_page_view.dart +++ b/lib/features/profile/presentation/widgets/expandable_page_view.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ExpandablePageView extends StatefulWidget { const ExpandablePageView({ diff --git a/lib/features/profile/presentation/widgets/imt_chart_widget.dart b/lib/features/profile/presentation/widgets/imt_chart_widget.dart deleted file mode 100644 index e716c12d..00000000 --- a/lib/features/profile/presentation/widgets/imt_chart_widget.dart +++ /dev/null @@ -1,127 +0,0 @@ -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; -import 'package:syncfusion_flutter_charts/charts.dart'; -import 'package:intl/intl.dart'; - -class ImtChartWidget extends StatelessWidget { - final List weightPoints; - - const ImtChartWidget({ - super.key, - required this.weightPoints, - }); - - @override - Widget build(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - if (weightPoints.isNotEmpty) - Text( - weightPoints.last.bmi.toStringAsFixed(2), - style: const TextStyle( - color: Colors.black, - fontSize: 40, - fontWeight: FontWeight.w500, - ), - ), - if (weightPoints.length > 1) - weightPoints.last.bmi > weightPoints[weightPoints.length - 2].bmi - ? const Icon( - Icons.arrow_drop_up, - size: 40, - color: Colors.grey, - ) - : const Icon( - Icons.arrow_drop_down, - size: 40, - color: Colors.grey, - ), - ], - ), - ), - Stack( - alignment: Alignment.center, - children: [ - SfCartesianChart( - margin: const EdgeInsets.symmetric(horizontal: 8), - enableAxisAnimation: true, - plotAreaBorderWidth: 0, - trackballBehavior: TrackballBehavior( - enable: true, - activationMode: ActivationMode.singleTap, - tooltipDisplayMode: TrackballDisplayMode.groupAllPoints, - tooltipSettings: const InteractiveTooltip(), - lineType: TrackballLineType.vertical, - ), - primaryXAxis: DateTimeCategoryAxis( - tickPosition: TickPosition.inside, - majorTickLines: const MajorTickLines( - size: 0, - ), - edgeLabelPlacement: EdgeLabelPlacement.shift, - dateFormat: DateFormat.MMMd('ru'), - labelStyle: const TextStyle( - color: Colors.grey, - ), - majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)), - axisLine: AxisLine( - color: Colors.grey.withValues(alpha: 0.3), - width: 0.4, - ), - ), - primaryYAxis: const NumericAxis( - isVisible: false, - ), - series: _getSplineSeries(), - tooltipBehavior: TooltipBehavior(enable: true), - ), - if (weightPoints.isEmpty) - const Padding( - padding: EdgeInsets.symmetric(horizontal: 32), - child: Text( - 'Индекс Массы Тела рассчитывается при указанных весе и росте', - textAlign: TextAlign.center, - ), - ), - ], - ), - ], - ); - } - - List> _getSplineSeries() { - return >[ - SplineAreaSeries( - markerSettings: MarkerSettings( - isVisible: true, - color: appTheme.blueA400, - height: 8, - width: 8, - ), - dataLabelSettings: const DataLabelSettings( - labelAlignment: ChartDataLabelAlignment.top, - isVisible: true, - ), - dataSource: weightPoints, - borderColor: appTheme.blueA400, - gradient: LinearGradient( - colors: [ - appTheme.blueA400.withValues(alpha: 0.14), - Colors.transparent, - ], - begin: Alignment.topCenter, - end: const Alignment(0, 0.6), - ), - name: 'ИМТ', - xValueMapper: (WeightModel value, int index) => value.createdAt, - yValueMapper: (WeightModel value, int index) => double.parse(value.bmi.toStringAsFixed(2)), - ), - ]; - } -} diff --git a/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart b/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart index a6d3fa3a..0e266bdf 100644 --- a/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart +++ b/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart @@ -14,7 +14,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_media_content.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/profile/presentation/widgets/sub_action_button_widget.dart b/lib/features/profile/presentation/widgets/sub_action_button_widget.dart index 0e3d0e50..a8af6956 100644 --- a/lib/features/profile/presentation/widgets/sub_action_button_widget.dart +++ b/lib/features/profile/presentation/widgets/sub_action_button_widget.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/profile/presentation/widgets/sub_widget.dart b/lib/features/profile/presentation/widgets/sub_widget.dart index 2423087c..47b44dac 100644 --- a/lib/features/profile/presentation/widgets/sub_widget.dart +++ b/lib/features/profile/presentation/widgets/sub_widget.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/features/profile/models/sub_model.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/sub_action_button_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class SubWidget extends StatefulWidget { diff --git a/lib/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart b/lib/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart index 4b5bbc57..6b1c4fc5 100644 --- a/lib/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart +++ b/lib/features/profile/presentation/widgets/toggle_cert_photo_bottom_sheet.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class ToggleCertPhotoBottomSheet extends StatelessWidget { diff --git a/lib/features/profile/presentation/widgets/weight_chart_widget.dart b/lib/features/profile/presentation/widgets/weight_chart_widget.dart deleted file mode 100644 index 3084f882..00000000 --- a/lib/features/profile/presentation/widgets/weight_chart_widget.dart +++ /dev/null @@ -1,250 +0,0 @@ -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; -import 'package:syncfusion_flutter_charts/charts.dart'; - -class WeightChartWidget extends StatefulWidget { - final List weightPoints; - final ProfileCubit? profileCubit; - - const WeightChartWidget({ - super.key, - required this.weightPoints, - this.profileCubit, - }); - - @override - State createState() => _WeightChartWidgetState(); -} - -class _WeightChartWidgetState extends State { - late FixedExtentScrollController weightKiloController; - late FixedExtentScrollController weightGramsController; - int weightKilo = 20; - int weightGrams = 0; - - @override - Widget build(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (widget.weightPoints.isNotEmpty) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - Text( - '${widget.weightPoints.last.weight.toStringAsFixed(1)} кг', - style: const TextStyle( - color: Colors.black, - fontSize: 40, - fontWeight: FontWeight.w500, - ), - ), - if (widget.weightPoints.length == 1) - Container( - margin: const EdgeInsets.symmetric(horizontal: 12), - width: 8, - height: 8, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: Colors.black12, - ), - ), - if (widget.weightPoints.length > 1) - widget.weightPoints.last.weight > widget.weightPoints[widget.weightPoints.length - 2].weight - ? Icon( - Icons.arrow_drop_up, - size: 40, - color: Colors.grey.withValues(alpha: 0.4), - ) - : Icon( - Icons.arrow_drop_down, - size: 40, - color: Colors.grey.withValues(alpha: 0.4), - ), - ], - ), - ), - Stack( - alignment: Alignment.center, - children: [ - SfCartesianChart( - margin: const EdgeInsets.symmetric(horizontal: 8), - enableAxisAnimation: true, - plotAreaBorderWidth: 0, - trackballBehavior: TrackballBehavior( - enable: true, - activationMode: ActivationMode.singleTap, - tooltipDisplayMode: TrackballDisplayMode.groupAllPoints, - tooltipSettings: const InteractiveTooltip(), - lineType: TrackballLineType.vertical, - ), - primaryXAxis: DateTimeCategoryAxis( - tickPosition: TickPosition.inside, - majorTickLines: const MajorTickLines( - size: 0, - ), - edgeLabelPlacement: EdgeLabelPlacement.shift, - dateFormat: DateFormat.MMMd('ru'), - labelStyle: const TextStyle( - color: Colors.grey, - ), - majorGridLines: MajorGridLines(dashArray: const [1], color: Colors.grey.withValues(alpha: 0.3)), - axisLine: AxisLine( - color: Colors.grey.withValues(alpha: 0.3), - width: 0.4, - ), - ), - primaryYAxis: const NumericAxis( - isVisible: false, - labelFormat: '{value} кг', - majorGridLines: MajorGridLines(dashArray: [1], color: Colors.grey), - axisLine: AxisLine( - width: 1, - ), - majorTickLines: MajorTickLines(size: 0), - ), - series: _getSplineSeries(), - tooltipBehavior: TooltipBehavior(enable: true), - ), - if (widget.profileCubit != null) - Positioned( - right: 16, - bottom: 16, - child: FloatingActionButton.small( - heroTag: 'addWeight', - onPressed: () { - if (widget.weightPoints.isNotEmpty) { - try { - weightKilo = int.parse(widget.weightPoints.last.weight.toString().split('.')[0]); - weightGrams = int.parse(widget.weightPoints.last.weight.toString().split('.')[1][0]); - } catch (e) { - weightGrams = 0; - } - weightKiloController = FixedExtentScrollController(initialItem: weightKilo - 20); - weightGramsController = FixedExtentScrollController(initialItem: weightGrams); - } else { - weightKiloController = FixedExtentScrollController(); - weightGramsController = FixedExtentScrollController(); - } - showModalBottomSheet( - useRootNavigator: true, - context: context, - builder: (context) { - return SafeArea( - child: Column( - children: [ - Expanded( - child: Row( - children: [ - Expanded( - child: CupertinoPicker( - magnification: 1.22, - squeeze: 1.2, - useMagnifier: true, - scrollController: weightKiloController, - itemExtent: 24, - onSelectedItemChanged: (int value) { - weightKilo = value + 20; - }, - children: [ - for (int i = 20; i < 300; i++) Text('$i'), - ], - ), - ), - Expanded( - child: CupertinoPicker( - magnification: 1.22, - squeeze: 1.2, - useMagnifier: true, - scrollController: weightGramsController, - itemExtent: 24, - onSelectedItemChanged: (int value) { - weightGrams = value; - }, - children: [ - for (int i = 0; i < 10; i++) Text('$i'), - ], - ), - ), - ], - ), - ), - InkWell( - onTap: () { - widget.profileCubit?.addWeight(weight: double.parse('$weightKilo.$weightGrams')); - Navigator.of(context).pop(); - }, - borderRadius: BorderRadius.circular(16), - child: Ink( - width: MediaQuery.of(context).size.width - 32, - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: appTheme.blueA400, - borderRadius: BorderRadius.circular(16), - ), - child: const Center( - child: Text( - 'Сохранить', - style: TextStyle( - color: Colors.white, - ), - ), - ), - ), - ), - ], - ), - ); - }, - ); - }, - backgroundColor: appTheme.blueA400, - shape: const CircleBorder(), - child: const Icon( - Icons.add, - color: Colors.white, - ), - ), - ), - if (widget.weightPoints.isEmpty) const Text('Добавьте Ваш вес'), - ], - ), - ], - ); - } - - List> _getSplineSeries() { - return >[ - SplineAreaSeries( - markerSettings: MarkerSettings( - isVisible: true, - color: appTheme.blueA400, - height: 8, - width: 8, - ), - dataLabelSettings: const DataLabelSettings( - labelAlignment: ChartDataLabelAlignment.top, - isVisible: true, - ), - dataSource: widget.weightPoints, - borderColor: appTheme.blueA400, - gradient: LinearGradient( - colors: [ - appTheme.blueA400.withValues(alpha: 0.14), - Colors.transparent, - ], - begin: Alignment.topCenter, - end: const Alignment(0, 0.6), - ), - name: 'Вес', - xValueMapper: (WeightModel value, int index) => value.createdAt, - yValueMapper: (WeightModel value, int index) => value.weight, - ), - ]; - } -} diff --git a/lib/features/recipe/presentation/pages/about_recipe_screen.dart b/lib/features/recipe/presentation/pages/about_recipe_screen.dart index 61148644..07e63d87 100644 --- a/lib/features/recipe/presentation/pages/about_recipe_screen.dart +++ b/lib/features/recipe/presentation/pages/about_recipe_screen.dart @@ -26,7 +26,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/recipe/presentation/pages/my_recipes_screen.dart b/lib/features/recipe/presentation/pages/my_recipes_screen.dart index 36359d0b..290dfeab 100644 --- a/lib/features/recipe/presentation/pages/my_recipes_screen.dart +++ b/lib/features/recipe/presentation/pages/my_recipes_screen.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/m import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/my_recipes_state.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/my_recipe_widget.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/my_recipes_tab.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/features/create_recipe/presentation/pages/recipe_create_screen.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/recipe/presentation/widgets/ingredients_widget.dart b/lib/features/recipe/presentation/widgets/ingredients_widget.dart index 87eea49d..6bca6aa0 100644 --- a/lib/features/recipe/presentation/widgets/ingredients_widget.dart +++ b/lib/features/recipe/presentation/widgets/ingredients_widget.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class IngredientsWidget extends StatelessWidget { const IngredientsWidget({super.key, required this.recipe}); diff --git a/lib/features/recipe/presentation/widgets/my_recipe_widget.dart b/lib/features/recipe/presentation/widgets/my_recipe_widget.dart index ee6aa4ab..3c710795 100644 --- a/lib/features/recipe/presentation/widgets/my_recipe_widget.dart +++ b/lib/features/recipe/presentation/widgets/my_recipe_widget.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes import 'package:eatvio_app/features/recipe/models/my_recipe_model.dart'; import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/my_recipes_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/pages/recipe_create_screen.dart'; diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index e9260cfd..d02ec877 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -1,11 +1,9 @@ import 'dart:developer'; import 'package:eatvio_app/core/app_router.dart'; -import 'package:eatvio_app/core/firebase_api.dart'; -import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart'; import 'package:eatvio_app/core/prefs.dart'; - +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/registration/models/user_registration_model.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; @@ -18,7 +16,8 @@ import 'package:go_router/go_router.dart'; class RegistrationCubit extends Cubit with RegistrationDateCacheMixin { final RegistrationRepository registrationRepository; - RegistrationCubit({required this.registrationRepository, required Prefs prefs}) + final SessionLifecycleService sessionLifecycleService; + RegistrationCubit({required this.registrationRepository, required this.sessionLifecycleService, required Prefs prefs}) : super( const RegistrationState( sheet: UserRegistrationSheet( @@ -62,7 +61,7 @@ class RegistrationCubit extends Cubit with RegistrationDateCa state.sheet.copyWith(phone: state.sheet.phone.replaceAll(' ', '').replaceAll('(', '').replaceAll(')', ''), responseBody: '{}'), ); await TokenStorage.saveTokenInStorage(token); - await sl().registerPushToken(); + await sessionLifecycleService.onAuthenticated(); RegistrationAnalyticsService.reportRegistrationComplete(); cacheRegistrationDate(DateTime.now()); AppRouter.navigatorKey.currentContext?.replaceNamed('verifyEmailScreen'); diff --git a/lib/features/registration/presentation/pages/additional_information_screen.dart b/lib/features/registration/presentation/pages/additional_information_screen.dart index 1bcdca97..f9ded2ef 100644 --- a/lib/features/registration/presentation/pages/additional_information_screen.dart +++ b/lib/features/registration/presentation/pages/additional_information_screen.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration/presentation/pages/allergies_screen.dart b/lib/features/registration/presentation/pages/allergies_screen.dart index d65bff5f..3f06507d 100644 --- a/lib/features/registration/presentation/pages/allergies_screen.dart +++ b/lib/features/registration/presentation/pages/allergies_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AllergiesScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/blood_pressure_screen.dart b/lib/features/registration/presentation/pages/blood_pressure_screen.dart index b8c9d8fc..e7067be1 100644 --- a/lib/features/registration/presentation/pages/blood_pressure_screen.dart +++ b/lib/features/registration/presentation/pages/blood_pressure_screen.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration/presentation/pages/body_circumferences_screen.dart b/lib/features/registration/presentation/pages/body_circumferences_screen.dart index b5fba5d4..522864a9 100644 --- a/lib/features/registration/presentation/pages/body_circumferences_screen.dart +++ b/lib/features/registration/presentation/pages/body_circumferences_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart index 507fc275..ffafd2c4 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; diff --git a/lib/features/registration/presentation/pages/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart index 26b8508f..6a4864ad 100644 --- a/lib/features/registration/presentation/pages/credentials_screen.dart +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class CredentialsScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/date_of_birth_screen.dart b/lib/features/registration/presentation/pages/date_of_birth_screen.dart index f97167fd..d58de762 100644 --- a/lib/features/registration/presentation/pages/date_of_birth_screen.dart +++ b/lib/features/registration/presentation/pages/date_of_birth_screen.dart @@ -3,8 +3,8 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; diff --git a/lib/features/registration/presentation/pages/favorite_foods_screen.dart b/lib/features/registration/presentation/pages/favorite_foods_screen.dart index ab6db46a..a5ba8f80 100644 --- a/lib/features/registration/presentation/pages/favorite_foods_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_foods_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FavoriteFoodsScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/favorite_sports_screen.dart b/lib/features/registration/presentation/pages/favorite_sports_screen.dart index b711f0ab..785748ac 100644 --- a/lib/features/registration/presentation/pages/favorite_sports_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_sports_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FavoriteSportsScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/gender_screen.dart b/lib/features/registration/presentation/pages/gender_screen.dart index e58df3d4..dfde39f7 100644 --- a/lib/features/registration/presentation/pages/gender_screen.dart +++ b/lib/features/registration/presentation/pages/gender_screen.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/features/registration/models/user_registration_model.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class GenderScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/height_screen.dart b/lib/features/registration/presentation/pages/height_screen.dart index 485cf838..66c0d9b5 100644 --- a/lib/features/registration/presentation/pages/height_screen.dart +++ b/lib/features/registration/presentation/pages/height_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration/presentation/pages/language_select_screen.dart b/lib/features/registration/presentation/pages/language_select_screen.dart index cd396ea5..5642ef18 100644 --- a/lib/features/registration/presentation/pages/language_select_screen.dart +++ b/lib/features/registration/presentation/pages/language_select_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/widgets/custom_drop_down.dart'; import 'package:eatvio_app/features/registration/models/user_registration_model.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class LanguageSelectScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/medicine_intake_screen.dart b/lib/features/registration/presentation/pages/medicine_intake_screen.dart index 65560e87..03e1f8e5 100644 --- a/lib/features/registration/presentation/pages/medicine_intake_screen.dart +++ b/lib/features/registration/presentation/pages/medicine_intake_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class MedicineIntakeScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/name_screen.dart b/lib/features/registration/presentation/pages/name_screen.dart index d69e0ea9..06280533 100644 --- a/lib/features/registration/presentation/pages/name_screen.dart +++ b/lib/features/registration/presentation/pages/name_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class NameScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/phone_screen.dart b/lib/features/registration/presentation/pages/phone_screen.dart index e4f458cd..b5611ba9 100644 --- a/lib/features/registration/presentation/pages/phone_screen.dart +++ b/lib/features/registration/presentation/pages/phone_screen.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/registration/models/user_registration_model.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 759df201..e5ee24d7 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -21,7 +21,7 @@ import 'package:eatvio_app/features/registration/services/registration_analytics import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/registration/presentation/pages/verify_email_screen.dart b/lib/features/registration/presentation/pages/verify_email_screen.dart index 1628886b..36a85496 100644 --- a/lib/features/registration/presentation/pages/verify_email_screen.dart +++ b/lib/features/registration/presentation/pages/verify_email_screen.dart @@ -10,7 +10,7 @@ import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_ import 'package:eatvio_app/features/registration/presentation/widgets/change_email_dialog.dart'; import 'package:eatvio_app/features/registration/presentation/widgets/code_not_received_dialog.dart'; import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/registration/presentation/pages/verify_screen.dart b/lib/features/registration/presentation/pages/verify_screen.dart index 867af06f..9a2c5897 100644 --- a/lib/features/registration/presentation/pages/verify_screen.dart +++ b/lib/features/registration/presentation/pages/verify_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; import 'package:lottie/lottie.dart'; import 'package:webview_flutter/webview_flutter.dart'; diff --git a/lib/features/registration/presentation/pages/webview_registration_screen.dart b/lib/features/registration/presentation/pages/webview_registration_screen.dart index 6cc777d2..272ce307 100644 --- a/lib/features/registration/presentation/pages/webview_registration_screen.dart +++ b/lib/features/registration/presentation/pages/webview_registration_screen.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart'; import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:webview_flutter/webview_flutter.dart'; class WebViewRegistrationScreen extends StatefulWidget { diff --git a/lib/features/registration/presentation/pages/weight_screen.dart b/lib/features/registration/presentation/pages/weight_screen.dart index 8c5cfd8a..65b290d6 100644 --- a/lib/features/registration/presentation/pages/weight_screen.dart +++ b/lib/features/registration/presentation/pages/weight_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration/presentation/widgets/change_email_dialog.dart b/lib/features/registration/presentation/widgets/change_email_dialog.dart index 266e9f04..8d3e8283 100644 --- a/lib/features/registration/presentation/widgets/change_email_dialog.dart +++ b/lib/features/registration/presentation/widgets/change_email_dialog.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ChangeEmailDialog extends StatefulWidget { diff --git a/lib/features/registration/presentation/widgets/code_not_received_dialog.dart b/lib/features/registration/presentation/widgets/code_not_received_dialog.dart index 3baa5742..ef69f6a4 100644 --- a/lib/features/registration/presentation/widgets/code_not_received_dialog.dart +++ b/lib/features/registration/presentation/widgets/code_not_received_dialog.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/gestures.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; diff --git a/lib/features/registration_v2/cubit/registration_cubit.dart b/lib/features/registration_v2/cubit/registration_cubit.dart index 585d1c41..9246a5b1 100644 --- a/lib/features/registration_v2/cubit/registration_cubit.dart +++ b/lib/features/registration_v2/cubit/registration_cubit.dart @@ -1,6 +1,8 @@ import 'dart:developer'; import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/firebase_api.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:eatvio_app/core/utils/validation_utils.dart'; @@ -13,7 +15,13 @@ import 'package:gpassword/gpassword.dart'; class RegistrationCubitV2 extends Cubit { final RegistrationRepositoryV2 registrationRepository; - RegistrationCubitV2({required this.registrationRepository}) : super(const RegistrationStateV2()); + final FirebaseApi firebaseApi; + final SessionLifecycleService sessionLifecycleService; + RegistrationCubitV2({ + required this.registrationRepository, + required this.firebaseApi, + required this.sessionLifecycleService, + }) : super(const RegistrationStateV2()); void setFirstName(String firstName) { emit(state.copyWith(firstName: firstName)); @@ -194,9 +202,12 @@ class RegistrationCubitV2 extends Cubit { bool didApiComplainOnValidation = false; String errorMessage = ''; try { - final token = await registrationRepository.register(registrationModel: registrationModel); + final token = await registrationRepository.register( + registrationModel: registrationModel, + ); if (token != null) { - TokenStorage.saveTokenInStorage(token); + await TokenStorage.saveTokenInStorage(token); + await sessionLifecycleService.onAuthenticated(); emit(state.copyWith(registrationError: null)); return (true, false); } @@ -214,11 +225,21 @@ class RegistrationCubitV2 extends Cubit { for (var error in emailErrors) { allErrors.add(error.toString()); if (error.toString() == 'Некорректный формат email') { - emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Некорректный формат email')); + emit( + state.copyWith( + isEmailValid: false, + emailDisplayError: 'Некорректный формат email', + ), + ); didApiComplainOnValidation = true; } if (error.toString() == 'Такой Эл. почта уже существует.') { - emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Такая Эл. почта уже существует.')); + emit( + state.copyWith( + isEmailValid: false, + emailDisplayError: 'Такая Эл. почта уже существует.', + ), + ); didApiComplainOnValidation = true; } } @@ -227,7 +248,12 @@ class RegistrationCubitV2 extends Cubit { for (var error in phoneErrors) { allErrors.add(error.toString()); if (error.toString() == 'Такой phone уже существует.') { - emit(state.copyWith(isPhoneValid: false, phoneDisplayError: 'Такой номер телефона уже существует.')); + emit( + state.copyWith( + isPhoneValid: false, + phoneDisplayError: 'Такой номер телефона уже существует.', + ), + ); didApiComplainOnValidation = true; } } @@ -236,7 +262,12 @@ class RegistrationCubitV2 extends Cubit { for (var error in dateOfBirth) { allErrors.add(error.toString()); if (error.toString() == 'Некорректный формат даты рождения') { - emit(state.copyWith(isBirthdayValid: false, dateOfBirthDisplayError: 'Некорректный формат даты рождения')); + emit( + state.copyWith( + isBirthdayValid: false, + dateOfBirthDisplayError: 'Некорректный формат даты рождения', + ), + ); didApiComplainOnValidation = true; } } diff --git a/lib/features/registration_v2/presentation/pages/registration_v2_page.dart b/lib/features/registration_v2/presentation/pages/registration_v2_page.dart index d69d27c4..b2d417a7 100644 --- a/lib/features/registration_v2/presentation/pages/registration_v2_page.dart +++ b/lib/features/registration_v2/presentation/pages/registration_v2_page.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/registration_v2/presentation/widgets/first_s import 'package:eatvio_app/features/registration_v2/presentation/widgets/second_step_content.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/step_progress.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/step_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/first_step_content.dart b/lib/features/registration_v2/presentation/widgets/first_step_content.dart index dbb22951..e290b1d6 100644 --- a/lib/features/registration_v2/presentation/widgets/first_step_content.dart +++ b/lib/features/registration_v2/presentation/widgets/first_step_content.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/sex_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/password_field.dart b/lib/features/registration_v2/presentation/widgets/password_field.dart index b4fea946..46905fff 100644 --- a/lib/features/registration_v2/presentation/widgets/password_field.dart +++ b/lib/features/registration_v2/presentation/widgets/password_field.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/phisical_activity.dart b/lib/features/registration_v2/presentation/widgets/phisical_activity.dart index 86bb1fb8..650051f4 100644 --- a/lib/features/registration_v2/presentation/widgets/phisical_activity.dart +++ b/lib/features/registration_v2/presentation/widgets/phisical_activity.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:collection/collection.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/second_step_content.dart b/lib/features/registration_v2/presentation/widgets/second_step_content.dart index ab7163c1..93790b58 100644 --- a/lib/features/registration_v2/presentation/widgets/second_step_content.dart +++ b/lib/features/registration_v2/presentation/widgets/second_step_content.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/features/registration_v2/presentation/widgets/phisica import 'package:eatvio_app/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/sex_widget.dart b/lib/features/registration_v2/presentation/widgets/sex_widget.dart index 60f0944f..fadd5f61 100644 --- a/lib/features/registration_v2/presentation/widgets/sex_widget.dart +++ b/lib/features/registration_v2/presentation/widgets/sex_widget.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widge import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SexWidget extends StatelessWidget { diff --git a/lib/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart b/lib/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart index 7571a038..09aa045b 100644 --- a/lib/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart +++ b/lib/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/password_field.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/registration_v2/presentation/widgets/step_progress.dart b/lib/features/registration_v2/presentation/widgets/step_progress.dart index 7bb3497c..385accd1 100644 --- a/lib/features/registration_v2/presentation/widgets/step_progress.dart +++ b/lib/features/registration_v2/presentation/widgets/step_progress.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class StepProgress extends StatelessWidget { diff --git a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart index f468a1ce..a8479ffc 100644 --- a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart +++ b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart @@ -1,3 +1,5 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart'; @@ -17,12 +19,14 @@ class SettingsCubit extends Cubit { final SettingsRepository settingsRepository; final ConsultantRepository consultantRepository; final ConsultationsRepository consultationsRepository; + final SessionLifecycleService sessionLifecycleService; SettingsCubit({ - required this.profileRepository, - required this.settingsRepository, + required this.profileRepository, + required this.settingsRepository, required this.consultantRepository, required this.consultationsRepository, + required this.sessionLifecycleService, }) : super(const SettingsState.loading()); Future init() async { @@ -30,10 +34,12 @@ class SettingsCubit extends Cubit { late final ConsultationRequestModel? consultantInfo; late final bool hasActiveConsultation; late final OAuthAccountsDataModel? oauthAccounts; - + try { if (profile.phoneConfirmationState.contains('confirmed')) { - consultantInfo = await consultantRepository.getMyRequestStatus(profile.slug); + consultantInfo = await consultantRepository.getMyRequestStatus( + profile.slug, + ); } else { consultantInfo = null; } @@ -41,14 +47,14 @@ class SettingsCubit extends Cubit { await reportFrom(e, st, this); consultantInfo = null; } - + try { hasActiveConsultation = await _checkActiveConsultation(); } catch (e, st) { await reportFrom(e, st, this); hasActiveConsultation = false; } - + try { final oauthResponse = await settingsRepository.getOAuthAccounts(); oauthAccounts = oauthResponse.data; @@ -56,7 +62,7 @@ class SettingsCubit extends Cubit { await reportFrom(e, st, this); oauthAccounts = null; } - + try { emit( SettingsState.loaded( @@ -74,9 +80,13 @@ class SettingsCubit extends Cubit { } } - Future updateProfileDetails({required ProfileDetailsModel profileDetailsModel}) async { + Future updateProfileDetails({ + required ProfileDetailsModel profileDetailsModel, + }) async { try { - await settingsRepository.updateProfileDetails(profileDetailsModel: profileDetailsModel); + await settingsRepository.updateProfileDetails( + profileDetailsModel: profileDetailsModel, + ); } catch (e, st) { await reportFrom(e, st, this); } finally { @@ -84,9 +94,13 @@ class SettingsCubit extends Cubit { } } - Future updateProfileSettings({required ProfileSettingsModel profileSettingsModel}) async { + Future updateProfileSettings({ + required ProfileSettingsModel profileSettingsModel, + }) async { try { - await settingsRepository.updateProfileSettings(profileSettingsModel: profileSettingsModel); + await settingsRepository.updateProfileSettings( + profileSettingsModel: profileSettingsModel, + ); } catch (e, st) { await reportFrom(e, st, this); } finally { @@ -97,9 +111,15 @@ class SettingsCubit extends Cubit { Future deleteAccount() async { try { await profileRepository.deleteAccount(); + await sessionLifecycleService.endSession( + reason: SessionEndReason.accountDeleted, + ); return true; } catch (e, st) { await reportFrom(e, st, this); + if (e is DioException && e.response?.statusCode == 401) { + return true; + } return false; } } @@ -135,11 +155,14 @@ class SettingsCubit extends Cubit { Future _checkActiveConsultation() async { try { - final userPurchases = await consultationsRepository.getUserPurchases(null, null); + final userPurchases = await consultationsRepository.getUserPurchases( + null, + null, + ); final activeStates = ChosenPlanStateEnum.getActiveStates(); - - return userPurchases.any((purchase) => - activeStates.contains(purchase.chosenPlanState) + + return userPurchases.any( + (purchase) => activeStates.contains(purchase.chosenPlanState), ); } catch (e, st) { await reportFrom(e, st, this); diff --git a/lib/features/settings/presentation/pages/change_email_screen.dart b/lib/features/settings/presentation/pages/change_email_screen.dart index a71ef272..2a557a09 100644 --- a/lib/features/settings/presentation/pages/change_email_screen.dart +++ b/lib/features/settings/presentation/pages/change_email_screen.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ChangeEmailScreen extends StatefulWidget { final SettingsEntity settingsEntity; diff --git a/lib/features/settings/presentation/pages/change_password_screen.dart b/lib/features/settings/presentation/pages/change_password_screen.dart index a226ed81..905690a4 100644 --- a/lib/features/settings/presentation/pages/change_password_screen.dart +++ b/lib/features/settings/presentation/pages/change_password_screen.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ChangePasswordScreen extends StatefulWidget { final SettingsEntity settingsEntity; diff --git a/lib/features/settings/presentation/pages/general_info_screen.dart b/lib/features/settings/presentation/pages/general_info_screen.dart index 3fad0dc4..2396a54c 100644 --- a/lib/features/settings/presentation/pages/general_info_screen.dart +++ b/lib/features/settings/presentation/pages/general_info_screen.dart @@ -8,8 +8,8 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; class GeneralInfoScreen extends StatefulWidget { final SettingsEntity settingsEntity; diff --git a/lib/features/settings/presentation/pages/other_info_screen.dart b/lib/features/settings/presentation/pages/other_info_screen.dart index 839c440d..588b6e50 100644 --- a/lib/features/settings/presentation/pages/other_info_screen.dart +++ b/lib/features/settings/presentation/pages/other_info_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; class OtherInfoScreen extends StatefulWidget { diff --git a/lib/features/settings/presentation/pages/physical_activity_screen.dart b/lib/features/settings/presentation/pages/physical_activity_screen.dart index 74b6f971..86b66dd0 100644 --- a/lib/features/settings/presentation/pages/physical_activity_screen.dart +++ b/lib/features/settings/presentation/pages/physical_activity_screen.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/settings/presentation/pages/physical_form_screen.dart b/lib/features/settings/presentation/pages/physical_form_screen.dart index f806b086..a7c612b9 100644 --- a/lib/features/settings/presentation/pages/physical_form_screen.dart +++ b/lib/features/settings/presentation/pages/physical_form_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/settings/presentation/pages/pressure_screen.dart b/lib/features/settings/presentation/pages/pressure_screen.dart index b50d9a42..9f82b216 100644 --- a/lib/features/settings/presentation/pages/pressure_screen.dart +++ b/lib/features/settings/presentation/pages/pressure_screen.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/settings/presentation/pages/settings_screen.dart b/lib/features/settings/presentation/pages/settings_screen.dart index a1b0acab..5051c4f8 100644 --- a/lib/features/settings/presentation/pages/settings_screen.dart +++ b/lib/features/settings/presentation/pages/settings_screen.dart @@ -14,8 +14,8 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; @@ -698,7 +698,6 @@ class _DeleteAccountBottomSheet extends State { onPressed: () async { final result = await widget.cubit.deleteAccount(); if (result == true) { - AppRouter.navigatorKey.currentContext?.go('/auth-screen'); return; } AppRouter.navigatorKey.currentContext?.pop(); diff --git a/lib/features/support/presentation/pages/support_screen.dart b/lib/features/support/presentation/pages/support_screen.dart index a01a88af..a553029c 100644 --- a/lib/features/support/presentation/pages/support_screen.dart +++ b/lib/features/support/presentation/pages/support_screen.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/update_screen/presentation/update_screen.dart b/lib/features/update_screen/presentation/update_screen.dart index 68ec9640..78c453bb 100644 --- a/lib/features/update_screen/presentation/update_screen.dart +++ b/lib/features/update_screen/presentation/update_screen.dart @@ -1,6 +1,6 @@ import 'dart:io'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/features/user_details/presentation/cubit/user_details_cubit.dart b/lib/features/user_details/presentation/cubit/user_details_cubit.dart index 6735043b..cc44a995 100644 --- a/lib/features/user_details/presentation/cubit/user_details_cubit.dart +++ b/lib/features/user_details/presentation/cubit/user_details_cubit.dart @@ -14,23 +14,10 @@ class UserDetailsCubit extends Cubit { try { final profileDetails = await profileRepository.getProfileDetailsBySlug(slug); emit(state.copyWith(profileDetails: profileDetails, isLoading: false)); - getChartData(slug: slug); } catch (e, st) { await reportFrom(e, st, this); log(e.toString()); emit(state.copyWith(error: e.toString(), isLoading: false)); } } - - void getChartData({String period = '1', required String slug}) async { - try { - final weightPoints = await profileRepository.getWeight(period: period, slug: slug); - final circumferencePoints = await profileRepository.getCircumferences(period: period, slug: slug); - emit(state.copyWith(weightPoints: weightPoints, circumferencePoints: circumferencePoints)); - } catch (e, stackTrace) { - await reportFrom(e, stackTrace, this); - log(e.toString(), stackTrace: stackTrace); - emit(state.copyWith(error: e.toString(), isLoading: false)); - } - } } diff --git a/lib/features/user_details/presentation/cubit/user_details_state.dart b/lib/features/user_details/presentation/cubit/user_details_state.dart index 7f4d081b..39ddd4b4 100644 --- a/lib/features/user_details/presentation/cubit/user_details_state.dart +++ b/lib/features/user_details/presentation/cubit/user_details_state.dart @@ -1,6 +1,4 @@ -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'user_details_state.freezed.dart'; @@ -11,7 +9,5 @@ abstract class UserDetailsState with _$UserDetailsState { @Default(false) bool isLoading, String? error, ProfileDetailsModel? profileDetails, - List? weightPoints, - List? circumferencePoints, }) = _UserDetailsState; } \ No newline at end of file diff --git a/lib/features/user_details/presentation/user_details_screen.dart b/lib/features/user_details/presentation/user_details_screen.dart index a5552802..7216f177 100644 --- a/lib/features/user_details/presentation/user_details_screen.dart +++ b/lib/features/user_details/presentation/user_details_screen.dart @@ -8,16 +8,12 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/core/widgets/data_error_widget.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/more_options.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/imt_chart_widget.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_state.dart'; import 'package:eatvio_app/features/user_details/presentation/widgets/expandable_bouble.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_svg/svg.dart'; @@ -44,13 +40,6 @@ class UserDetailsContent extends StatefulWidget { } class _UserDetailsContentState extends State { - final List chipsLabelList = ['Вес', 'Замеры', 'ИМТ']; - final List chipsIntervalLabelList = ['1М', '3М', '6М', '1Г', 'ВСЁ ВРЕМЯ']; - final List chipsIntervalList = ['1', '3', '6', '12', 'all']; - - List weightPoints = []; - List circumferencePoints = []; int _selectedChipIndex = 0; - int _selectedIntervalChipIndex = 0; bool isMoreOptionsVisible = false; @override Widget build(BuildContext context) { @@ -59,8 +48,6 @@ class _UserDetailsContentState extends State { builder: (context, state) { final profileDetails = state.profileDetails; if (profileDetails != null && state.isLoading == false) { - weightPoints = state.weightPoints ?? []; - circumferencePoints = state.circumferencePoints ?? []; return Scaffold( backgroundColor: appTheme.gray100, appBar: AppBar( @@ -104,7 +91,7 @@ class _UserDetailsContentState extends State { spacing: 12, children: [ const SizedBox.shrink(), - _charts(), + InsightsCard(slug: widget.slug), ExpandableBouble( initiallyExpanded: true, title: s.general_info, @@ -309,92 +296,4 @@ class _UserDetailsContentState extends State { }, ); } - - Material _charts() { - return Material( - color: Colors.white, - borderRadius: BorderRadius.circular(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 8), - SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 16), - scrollDirection: Axis.horizontal, - child: Row(children: [_choiceChipWidget(0), const SizedBox(width: 8), _choiceChipWidget(1), const SizedBox(width: 8), _choiceChipWidget(2)]), - ), - Builder( - builder: (context) { - switch (_selectedChipIndex) { - case 0: - return WeightChartWidget(weightPoints: weightPoints); - case 1: - return CircumferenceChartWidget(circumferencePoints: circumferencePoints); - case 2: - return ImtChartWidget(weightPoints: weightPoints); - default: - return const SizedBox.shrink(); - } - }, - ), - const SizedBox(height: 8), - Row( - children: [ - const SizedBox(width: 16), - _choiceIntervalChipWidget(0), - const SizedBox(width: 8), - _choiceIntervalChipWidget(1), - const SizedBox(width: 8), - _choiceIntervalChipWidget(2), - const SizedBox(width: 8), - _choiceIntervalChipWidget(3), - const SizedBox(width: 8), - _choiceIntervalChipWidget(4), - ], - ), - const SizedBox(height: 8), - ], - ), - ); - } - - ChoiceChip _choiceIntervalChipWidget(int index) { - return ChoiceChip( - selectedColor: Colors.grey.withValues(alpha: 0.1), - pressElevation: 0, - showCheckmark: false, - side: BorderSide.none, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - label: Text(chipsIntervalLabelList[index]), - labelStyle: TextStyle(color: appTheme.gray600, fontWeight: FontWeight.w500, fontSize: 12), - selected: _selectedIntervalChipIndex == index, - onSelected: (bool selected) { - context.read().getChartData(period: chipsIntervalList[index], slug: widget.slug); - setState(() { - _selectedIntervalChipIndex = index; - }); - }, - ); - } - - ChoiceChip _choiceChipWidget(int index) { - return ChoiceChip( - selectedColor: appTheme.blueA400, - pressElevation: 0, - showCheckmark: false, - side: BorderSide.none, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - label: Text(chipsLabelList[index]), - labelStyle: TextStyle(color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, fontWeight: FontWeight.w500, fontSize: 12), - selected: _selectedChipIndex == index, - backgroundColor: appTheme.gray100, - onSelected: (bool selected) { - setState(() { - _selectedChipIndex = index; - }); - }, - ); - } } diff --git a/lib/features/user_details/presentation/widgets/expandable_bouble.dart b/lib/features/user_details/presentation/widgets/expandable_bouble.dart index 5689a563..df815263 100644 --- a/lib/features/user_details/presentation/widgets/expandable_bouble.dart +++ b/lib/features/user_details/presentation/widgets/expandable_bouble.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class ExpandableBouble extends StatelessWidget { const ExpandableBouble({super.key, required this.title, required this.children, this.initiallyExpanded = false}); diff --git a/lib/features/video_calls/managers/video_call_manager.dart b/lib/features/video_calls/managers/video_call_manager.dart index ff814360..37d312e2 100644 --- a/lib/features/video_calls/managers/video_call_manager.dart +++ b/lib/features/video_calls/managers/video_call_manager.dart @@ -18,7 +18,7 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_ import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:livekit_client/livekit_client.dart' as lk; @@ -29,15 +29,13 @@ typedef VideoCallManagerListener = class VideoCallManager { VideoCallManager({ - required VideoCallRepository videoCallRepository, - ProfileRepository? profileRepository, + required this._videoCallRepository, + this._profileRepository, VideoCallForegroundCoordinator? foregroundCoordinator, VideoCallLifecycleBinding? lifecycleBinding, VideoCallAudioSessionCoordinator? audioSessionCoordinator, Future Function()? resolveHwId, - }) : _videoCallRepository = videoCallRepository, - _profileRepository = profileRepository, - _foreground = foregroundCoordinator ?? VideoCallForegroundCoordinator(), + }) : _foreground = foregroundCoordinator ?? VideoCallForegroundCoordinator(), _lifecycleBinding = lifecycleBinding ?? VideoCallLifecycleBinding(), _audioSession = audioSessionCoordinator ?? VideoCallAudioSessionCoordinator(), @@ -48,7 +46,14 @@ class VideoCallManager { // LiveKit rewrites the audio session whenever a remote audio track // appears. That second configuration stops the microphone and does // not start it again. - lk.Hardware.instance.setAutomaticConfigurationEnabled(enable: false); + + unawaited( + // ignore: experimental_member_use + lk.AudioManager.instance.setAudioSessionManagementMode( + // ignore: experimental_member_use + lk.AudioSessionManagementMode.manual, + ), + ); } } diff --git a/lib/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart b/lib/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart index adb57bb0..39063c64 100644 --- a/lib/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart +++ b/lib/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart @@ -8,18 +8,17 @@ import 'package:eatvio_app/features/video_calls/services/video_call_notification import 'package:eatvio_app/features/video_calls/services/video_call_peer_departure.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_screen_wake_lock_coordinator.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_system_pip_coordinator.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:livekit_client/livekit_client.dart' as lk; import 'package:permission_handler/permission_handler.dart'; class VideoCallSessionCubit extends BaseCubit { VideoCallSessionCubit({ - required VideoCallManager videoCallManager, + required this._videoCallManager, VideoCallSystemPipCoordinator? systemPipCoordinator, VideoCallScreenWakeLockCoordinator? screenWakeLockCoordinator, - }) : _videoCallManager = videoCallManager, - _systemPipCoordinator = + }) : _systemPipCoordinator = systemPipCoordinator ?? VideoCallSystemPipCoordinator(), _screenWakeLock = screenWakeLockCoordinator ?? VideoCallScreenWakeLockCoordinator(), diff --git a/lib/features/video_calls/presentation/pages/video_call_screen.dart b/lib/features/video_calls/presentation/pages/video_call_screen.dart index 933863ab..a25f2cb7 100644 --- a/lib/features/video_calls/presentation/pages/video_call_screen.dart +++ b/lib/features/video_calls/presentation/pages/video_call_screen.dart @@ -14,7 +14,7 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_stage_layout.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/video_calls/presentation/widgets/video_call_app_shell.dart b/lib/features/video_calls/presentation/widgets/video_call_app_shell.dart index bf9d774a..41d3214f 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_app_shell.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_app_shell.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_system_pip_content.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_system_pip_listener.dart'; import 'package:floating/floating.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; /// Root overlay shell: system PiP on Android, in-app PiP fallback on iOS. diff --git a/lib/features/video_calls/presentation/widgets/video_call_banner_overlay.dart b/lib/features/video_calls/presentation/widgets/video_call_banner_overlay.dart index 9bdb2f40..24e410c4 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_banner_overlay.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_banner_overlay.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; /// Dedicated overlay layer above the app navigator for in-call banners. abstract final class VideoCallBannerOverlay { diff --git a/lib/features/video_calls/presentation/widgets/video_call_connecting_entrance_screen.dart b/lib/features/video_calls/presentation/widgets/video_call_connecting_entrance_screen.dart index 7870eac8..44305d4c 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_connecting_entrance_screen.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_connecting_entrance_screen.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_controls.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; class VideoCallConnectingEntranceScreen extends StatelessWidget { diff --git a/lib/features/video_calls/presentation/widgets/video_call_controls.dart b/lib/features/video_calls/presentation/widgets/video_call_controls.dart index 4db0b713..552eadc1 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_controls.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_controls.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; typedef VideoCallControlLabels = ({String chat, String sound, String video, String leave}); diff --git a/lib/features/video_calls/presentation/widgets/video_call_flow_placeholder_screens.dart b/lib/features/video_calls/presentation/widgets/video_call_flow_placeholder_screens.dart index 1207d56b..7eba10e0 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_flow_placeholder_screens.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_flow_placeholder_screens.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; const double _kVideoCallFlowBottomBarHeight = 132; diff --git a/lib/features/video_calls/presentation/widgets/video_call_global_pip_layer.dart b/lib/features/video_calls/presentation/widgets/video_call_global_pip_layer.dart index 9a1e4e55..461e3f73 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_global_pip_layer.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_global_pip_layer.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_ses import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/video_calls/presentation/widgets/video_call_name_chips.dart b/lib/features/video_calls/presentation/widgets/video_call_name_chips.dart index 389af26e..123d7a29 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_name_chips.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_name_chips.dart @@ -3,7 +3,7 @@ import 'dart:ui'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class VideoCallParticipantNameLabel extends StatelessWidget { const VideoCallParticipantNameLabel({ diff --git a/lib/features/video_calls/presentation/widgets/video_call_no_video_background.dart b/lib/features/video_calls/presentation/widgets/video_call_no_video_background.dart index d08f5827..b5d5a7b1 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_no_video_background.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_no_video_background.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; class VideoCallNoVideoBackground extends StatelessWidget { const VideoCallNoVideoBackground({super.key, this.logoSize = 96}); diff --git a/lib/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart b/lib/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart index c3baad4c..065d4da2 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_no_video_background.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:livekit_client/livekit_client.dart' as lk; /// Shared compact preview for both in-app and Android system PiP. diff --git a/lib/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart b/lib/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart index 3f35cd61..4074e2b1 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_livekit_track_utils.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_no_video_background.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:livekit_client/livekit_client.dart' as lk; class VideoCallRemoteVideoStage extends StatelessWidget { diff --git a/lib/features/video_calls/presentation/widgets/video_call_stage_layout.dart b/lib/features/video_calls/presentation/widgets/video_call_stage_layout.dart index 131c7a55..360213fc 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_stage_layout.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_stage_layout.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_no_video_background.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:livekit_client/livekit_client.dart' as lk; diff --git a/lib/features/video_calls/presentation/widgets/video_call_system_pip_content.dart b/lib/features/video_calls/presentation/widgets/video_call_system_pip_content.dart index 3abcb415..cb95486d 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_system_pip_content.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_system_pip_content.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_ses import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_pip_video_preview.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_room_tracks_listenable.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; /// Compact call UI rendered by [PiPSwitcher] while Android is in system PiP mode. diff --git a/lib/features/video_calls/presentation/widgets/video_call_system_pip_listener.dart b/lib/features/video_calls/presentation/widgets/video_call_system_pip_listener.dart index 7a0f8957..86565348 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_system_pip_listener.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_system_pip_listener.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_ses import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; import 'package:eatvio_app/features/video_calls/services/video_call_system_pip_coordinator.dart'; import 'package:floating/floating.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; diff --git a/lib/features/video_calls/presentation/widgets/video_call_top_overlay.dart b/lib/features/video_calls/presentation/widgets/video_call_top_overlay.dart index 8ea2ddb4..fe81000c 100644 --- a/lib/features/video_calls/presentation/widgets/video_call_top_overlay.dart +++ b/lib/features/video_calls/presentation/widgets/video_call_top_overlay.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_banner_overlay.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; abstract final class VideoCallTopOverlay { diff --git a/lib/features/video_calls/recordings/models/recording_duration_formatter.dart b/lib/features/video_calls/recordings/models/recording_duration_formatter.dart new file mode 100644 index 00000000..91b4e9c5 --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_duration_formatter.dart @@ -0,0 +1,18 @@ +String formatRecordingDuration(int? durationSeconds) { + if (durationSeconds == null || durationSeconds < 0) { + return ''; + } + + final hours = durationSeconds ~/ 3600; + final minutes = (durationSeconds % 3600) ~/ 60; + final seconds = durationSeconds % 60; + + final mm = minutes.toString().padLeft(2, '0'); + final ss = seconds.toString().padLeft(2, '0'); + + if (hours > 0) { + return '$hours:$mm:$ss'; + } + + return '$mm:$ss'; +} diff --git a/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart b/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart new file mode 100644 index 00000000..c690e4ec --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart @@ -0,0 +1,10 @@ +class RecordingNotReadyException implements Exception { + const RecordingNotReadyException({this.message}); + + final String? message; + + static const code = 'recording_not_ready'; + + @override + String toString() => message ?? 'Recording is not ready'; +} diff --git a/lib/features/video_calls/recordings/models/recording_period.dart b/lib/features/video_calls/recordings/models/recording_period.dart new file mode 100644 index 00000000..6ac5d6b4 --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_period.dart @@ -0,0 +1,13 @@ +/// Период фильтра списка записей. +/// Значение совпадает с `filters[created_at][$date_range]`. +enum RecordingPeriod { + today('today'), + week('week'), + currentMonth('current_month'), + prevMonth('prev_month'), + all('all'); + + const RecordingPeriod(this.apiValue); + + final String apiValue; +} diff --git a/lib/features/video_calls/recordings/models/recording_status.dart b/lib/features/video_calls/recordings/models/recording_status.dart new file mode 100644 index 00000000..b29970ed --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_status.dart @@ -0,0 +1,8 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +enum RecordingStatus { + @JsonValue('ready') + ready, + @JsonValue('in_progress') + inProgress, +} diff --git a/lib/features/video_calls/recordings/models/video_call_recording_model.dart b/lib/features/video_calls/recordings/models/video_call_recording_model.dart new file mode 100644 index 00000000..674559c0 --- /dev/null +++ b/lib/features/video_calls/recordings/models/video_call_recording_model.dart @@ -0,0 +1,54 @@ +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_status.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'video_call_recording_model.freezed.dart'; +part 'video_call_recording_model.g.dart'; + +@freezed +abstract class VideoCallRecordingsPagination with _$VideoCallRecordingsPagination { + const factory VideoCallRecordingsPagination({ + @JsonKey(name: 'data') required List data, + @JsonKey(name: 'links') required Links links, + @JsonKey(name: 'meta') required Meta meta, + }) = _VideoCallRecordingsPagination; + + factory VideoCallRecordingsPagination.fromJson(Map json) => + _$VideoCallRecordingsPaginationFromJson(json); +} + +@freezed +abstract class VideoCallRecordingModel with _$VideoCallRecordingModel { + const VideoCallRecordingModel._(); + + @JsonSerializable(explicitToJson: true) + const factory VideoCallRecordingModel({ + @JsonKey(name: 'id') required int id, + @JsonKey(name: 'status') required RecordingStatus status, + @JsonKey(name: 'duration_seconds') int? durationSeconds, + @JsonKey(name: 'size_bytes') int? sizeBytes, + @JsonKey(name: 'created_at') required DateTime createdAt, + @JsonKey(name: 'preview_url') required String previewUrl, + @JsonKey(name: 'file_url') String? fileUrl, + @JsonKey(name: 'counterpart') VideoCallRecordingCounterpartModel? counterpart, + }) = _VideoCallRecordingModel; + + factory VideoCallRecordingModel.fromJson(Map json) => + _$VideoCallRecordingModelFromJson(json); + + bool get isReady => status == RecordingStatus.ready; + + bool get isInProgress => status == RecordingStatus.inProgress; +} + +@freezed +abstract class VideoCallRecordingCounterpartModel with _$VideoCallRecordingCounterpartModel { + const factory VideoCallRecordingCounterpartModel({ + @JsonKey(name: 'name') required String name, + @JsonKey(name: 'slug') required String slug, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl, + }) = _VideoCallRecordingCounterpartModel; + + factory VideoCallRecordingCounterpartModel.fromJson(Map json) => + _$VideoCallRecordingCounterpartModelFromJson(json); +} diff --git a/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart new file mode 100644 index 00000000..38071247 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart @@ -0,0 +1,191 @@ +import 'dart:developer'; + +import 'package:eatvio_app/core/error_reporting/report_from.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +sealed class RecordingDownloadResult { + const RecordingDownloadResult(); +} + +class RecordingDownloadSaved extends RecordingDownloadResult { + const RecordingDownloadSaved(this.path); + + final String path; +} + +class RecordingDownloadAlreadyInProgress extends RecordingDownloadResult { + const RecordingDownloadAlreadyInProgress(); +} + +class RecordingDownloadFailed extends RecordingDownloadResult { + const RecordingDownloadFailed(); +} + +class VideoCallRecordingsCubit extends Cubit { + VideoCallRecordingsCubit({required this.repository}) + : super(const VideoCallRecordingsState()); + + final VideoCallRecordingsRepository repository; + int _loadGeneration = 0; + + Future load({bool refresh = false}) async { + if (state.isLoading && !refresh && state.recordings.isNotEmpty) { + return; + } + + final generation = ++_loadGeneration; + final period = state.period; + + emit( + state.copyWith( + isLoading: true, + isLoadingMore: false, + error: null, + currentPage: 1, + ), + ); + + try { + final page = await repository.getRecordings( + page: 1, + period: period == RecordingPeriod.all ? null : period, + ); + if (isClosed || generation != _loadGeneration) { + return; + } + + emit( + state.copyWith( + isLoading: false, + recordings: page.data, + currentPage: page.meta.currentPage, + lastPage: page.meta.lastPage, + error: null, + ), + ); + } catch (error, stackTrace) { + if (isClosed || generation != _loadGeneration) { + return; + } + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + emit( + state.copyWith( + isLoading: false, + error: error.toString(), + ), + ); + } + } + + Future setPeriod(RecordingPeriod period) async { + if (state.period == period) { + return; + } + + emit(state.copyWith(period: period)); + await load(refresh: true); + } + + Future loadNextPage() async { + if (state.isLoading || state.isLoadingMore || state.currentPage >= state.lastPage) { + return; + } + + final generation = _loadGeneration; + final period = state.period; + final nextPage = state.currentPage + 1; + emit(state.copyWith(isLoadingMore: true, error: null)); + + try { + final page = await repository.getRecordings( + page: nextPage, + period: period == RecordingPeriod.all ? null : period, + ); + if (isClosed || generation != _loadGeneration) { + return; + } + + emit( + state.copyWith( + isLoadingMore: false, + recordings: [...state.recordings, ...page.data], + currentPage: page.meta.currentPage, + lastPage: page.meta.lastPage, + ), + ); + } catch (error, stackTrace) { + if (isClosed || generation != _loadGeneration) { + return; + } + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + emit( + state.copyWith( + isLoadingMore: false, + error: error.toString(), + ), + ); + } + } + + /// Скачивает запись в «Загрузки»/Documents. + Future downloadRecording({ + required int recordingId, + required String fileUrl, + }) async { + if (state.downloadingRecordingId != null) { + return const RecordingDownloadAlreadyInProgress(); + } + + emit( + state.copyWith( + downloadingRecordingId: recordingId, + downloadProgress: 0, + downloadError: null, + ), + ); + + try { + final savedPath = await repository.downloadRecordingFile( + fileUrl: fileUrl, + recordingId: recordingId, + onProgress: (received, total) { + if (isClosed || state.downloadingRecordingId != recordingId) { + return; + } + emit( + state.copyWith( + downloadProgress: total > 0 ? (received / total).clamp(0.0, 1.0) : null, + ), + ); + }, + ); + if (!isClosed) { + emit( + state.copyWith( + downloadingRecordingId: null, + downloadProgress: null, + ), + ); + } + return RecordingDownloadSaved(savedPath); + } catch (error, stackTrace) { + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + if (!isClosed) { + emit( + state.copyWith( + downloadingRecordingId: null, + downloadProgress: null, + downloadError: error.toString(), + ), + ); + } + return const RecordingDownloadFailed(); + } + } +} diff --git a/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart new file mode 100644 index 00000000..07e3beef --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart @@ -0,0 +1,22 @@ +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'video_call_recordings_state.freezed.dart'; + +@freezed +abstract class VideoCallRecordingsState with _$VideoCallRecordingsState { + const factory VideoCallRecordingsState({ + @Default(true) bool isLoading, + @Default(false) bool isLoadingMore, + @Default([]) List recordings, + @Default(RecordingPeriod.all) RecordingPeriod period, + @Default(1) int currentPage, + @Default(1) int lastPage, + int? downloadingRecordingId, + /// `0..1` при известном размере; `null` — indeterminate / нет загрузки. + double? downloadProgress, + String? error, + String? downloadError, + }) = _VideoCallRecordingsState; +} diff --git a/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart b/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart new file mode 100644 index 00000000..14459725 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart @@ -0,0 +1,393 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/core/widgets/loader.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/services.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:video_player/video_player.dart'; + +class VideoCallRecordingPlayerScreen extends StatefulWidget { + const VideoCallRecordingPlayerScreen({super.key, this.recording}); + + static const name = 'videoCallRecordingPlayerScreen'; + static const path = '/video-call-recording-player-screen'; + + final VideoCallRecordingModel? recording; + + @override + State createState() => _VideoCallRecordingPlayerScreenState(); +} + +class _VideoCallRecordingPlayerScreenState extends State { + static const _background = Color(0xFF0B0B0F); + static const _chromeHideDelay = Duration(seconds: 5); + static const _darkOverlayStyle = SystemUiOverlayStyle( + statusBarColor: _background, + statusBarIconBrightness: Brightness.light, + statusBarBrightness: Brightness.dark, + systemNavigationBarColor: _background, + systemNavigationBarIconBrightness: Brightness.light, + ); + + VideoPlayerController? _controller; + bool _isInitializing = true; + bool _hasError = false; + bool _isFullscreen = false; + bool _showChrome = true; + Timer? _hideChromeTimer; + + @override + void initState() { + super.initState(); + SystemChrome.setSystemUIOverlayStyle(_darkOverlayStyle); + _scheduleHideChrome(); + _initPlayer(); + } + + Future _initPlayer() async { + final fileUrl = widget.recording?.fileUrl; + if (fileUrl == null || fileUrl.isEmpty) { + setState(() { + _isInitializing = false; + _hasError = true; + }); + return; + } + + VideoPlayerController? created; + try { + final token = await TokenStorage.getTokenFromStorage(); + final controller = VideoPlayerController.networkUrl( + Uri.parse(fileUrl), + httpHeaders: { + if (token != null && token.isNotEmpty) 'Authorization': 'Bearer $token', + }, + ); + created = controller; + await controller.initialize(); + await controller.play(); + if (!mounted) { + await controller.dispose(); + return; + } + setState(() { + _controller = controller; + _isInitializing = false; + }); + _scheduleHideChrome(); + } catch (_) { + await created?.dispose(); + if (!mounted) { + return; + } + setState(() { + _isInitializing = false; + _hasError = true; + }); + } + } + + void _scheduleHideChrome() { + _hideChromeTimer?.cancel(); + if (!_showChrome) { + return; + } + _hideChromeTimer = Timer(_chromeHideDelay, () { + if (!mounted || !_showChrome) { + return; + } + setState(() => _showChrome = false); + }); + } + + void _revealChrome() { + setState(() => _showChrome = true); + _scheduleHideChrome(); + } + + void _onPlayerTap() { + if (_showChrome) { + _hideChromeTimer?.cancel(); + setState(() => _showChrome = false); + return; + } + _revealChrome(); + } + + Future _enterFullscreen() async { + _revealChrome(); + setState(() => _isFullscreen = true); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); + await SystemChrome.setPreferredOrientations(const [ + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + } + + Future _exitFullscreen() async { + _revealChrome(); + setState(() => _isFullscreen = false); + await SystemChrome.setPreferredOrientations(const [ + DeviceOrientation.portraitUp, + ]); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + SystemChrome.setSystemUIOverlayStyle(_darkOverlayStyle); + } + + Future _toggleFullscreen() async { + if (_isFullscreen) { + await _exitFullscreen(); + } else { + await _enterFullscreen(); + } + } + + Future _restoreSystemUi() async { + await SystemChrome.setPreferredOrientations(const []); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + + @override + void dispose() { + _hideChromeTimer?.cancel(); + _controller?.dispose(); + unawaited(_restoreSystemUi()); + super.dispose(); + } + + double get _aspectRatio { + final controller = _controller; + if (controller == null || controller.value.aspectRatio == 0) { + return 16 / 9; + } + return controller.value.aspectRatio; + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final title = widget.recording?.counterpart?.name ?? s.video_call_recordings_title; + final controller = _controller; + + return PopScope( + canPop: !_isFullscreen, + onPopInvokedWithResult: (didPop, _) async { + if (!didPop && _isFullscreen) { + await _exitFullscreen(); + } + }, + child: AnnotatedRegion( + value: _darkOverlayStyle, + child: Scaffold( + backgroundColor: _background, + extendBodyBehindAppBar: true, + appBar: _isFullscreen || !_showChrome + ? null + : AppBar( + backgroundColor: _background, + foregroundColor: Colors.white, + elevation: 0, + scrolledUnderElevation: 0, + centerTitle: true, + systemOverlayStyle: _darkOverlayStyle, + iconTheme: const IconThemeData(color: Colors.white), + title: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyles.headingXLSemibold.copyWith(color: Colors.white), + ), + ), + body: ColoredBox( + color: _background, + child: _isInitializing + ? const Center(child: Loader()) + : _hasError || controller == null + ? Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text( + s.video_call_recordings_player_error, + textAlign: TextAlign.center, + style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), + ), + ), + ) + : _VideoSurface( + controller: controller, + aspectRatio: _aspectRatio, + isFullscreen: _isFullscreen, + showControls: _showChrome, + onTap: _onPlayerTap, + onToggleFullscreen: _toggleFullscreen, + onUserInteraction: _revealChrome, + ), + ), + ), + ), + ); + } +} + +class _VideoSurface extends StatelessWidget { + const _VideoSurface({ + required this.controller, + required this.aspectRatio, + required this.isFullscreen, + required this.showControls, + required this.onTap, + required this.onToggleFullscreen, + required this.onUserInteraction, + }); + + final VideoPlayerController controller; + final double aspectRatio; + final bool isFullscreen; + final bool showControls; + final VoidCallback onTap; + final VoidCallback onToggleFullscreen; + final VoidCallback onUserInteraction; + + @override + Widget build(BuildContext context) { + final player = ColoredBox( + color: Colors.black, + child: Center( + child: AspectRatio( + aspectRatio: aspectRatio, + child: VideoPlayer(controller), + ), + ), + ); + + final content = GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: Stack( + fit: StackFit.expand, + children: [ + if (isFullscreen) + player + else + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Center( + child: AspectRatio( + aspectRatio: aspectRatio, + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: ColoredBox( + color: Colors.black, + child: VideoPlayer(controller), + ), + ), + ), + ), + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + child: AnimatedOpacity( + opacity: showControls ? 1 : 0, + duration: const Duration(milliseconds: 200), + child: IgnorePointer( + ignoring: !showControls, + child: SafeArea( + top: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + isFullscreen ? 8 : 16, + 0, + isFullscreen ? 8 : 16, + isFullscreen ? 8 : 16, + ), + child: _PlayerControls( + controller: controller, + isFullscreen: isFullscreen, + onToggleFullscreen: onToggleFullscreen, + onUserInteraction: onUserInteraction, + ), + ), + ), + ), + ), + ), + ], + ), + ); + + return content; + } +} + +class _PlayerControls extends StatelessWidget { + const _PlayerControls({ + required this.controller, + required this.isFullscreen, + required this.onToggleFullscreen, + required this.onUserInteraction, + }); + + final VideoPlayerController controller; + final bool isFullscreen; + final VoidCallback onToggleFullscreen; + final VoidCallback onUserInteraction; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) { + return Material( + color: Colors.black.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(10), + child: Row( + children: [ + IconButton( + onPressed: () { + onUserInteraction(); + if (controller.value.isPlaying) { + controller.pause(); + } else { + controller.play(); + } + }, + icon: Icon( + controller.value.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded, + color: Colors.white, + ), + ), + Expanded( + child: VideoProgressIndicator( + controller, + allowScrubbing: true, + padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 4), + colors: VideoProgressColors( + playedColor: appTheme.blueA400, + bufferedColor: Colors.white38, + backgroundColor: Colors.white24, + ), + ), + ), + IconButton( + onPressed: () { + onUserInteraction(); + onToggleFullscreen(); + }, + icon: Icon( + isFullscreen ? Icons.fullscreen_exit_rounded : Icons.fullscreen_rounded, + color: Colors.white, + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart new file mode 100644 index 00000000..1ec87312 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart @@ -0,0 +1,213 @@ +import 'dart:io'; + +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:eatvio_app/core/widgets/data_error_widget.dart'; +import 'package:eatvio_app/core/widgets/loader.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:go_router/go_router.dart'; + +class VideoCallRecordingsScreen extends StatelessWidget { + const VideoCallRecordingsScreen({super.key}); + + static const name = 'videoCallRecordingsScreen'; + static const path = '/video-call-recordings-screen'; + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (_) => sl()..load(), + child: const _VideoCallRecordingsView(), + ); + } +} + +class _VideoCallRecordingsView extends StatefulWidget { + const _VideoCallRecordingsView(); + + @override + State<_VideoCallRecordingsView> createState() => _VideoCallRecordingsViewState(); +} + +class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> { + final _scrollController = ScrollController(); + + @override + void initState() { + super.initState(); + _scrollController.addListener(_onScroll); + } + + @override + void dispose() { + _scrollController + ..removeListener(_onScroll) + ..dispose(); + super.dispose(); + } + + void _onScroll() { + if (!_scrollController.hasClients) { + return; + } + final position = _scrollController.position; + if (position.pixels >= position.maxScrollExtent - 200) { + context.read().loadNextPage(); + } + } + + Future _download(VideoCallRecordingModel recording) async { + final fileUrl = recording.fileUrl; + if (fileUrl == null) { + return; + } + + final result = await context.read().downloadRecording( + recordingId: recording.id, + fileUrl: fileUrl, + ); + if (!mounted) { + return; + } + + final s = S.of(context); + switch (result) { + case RecordingDownloadSaved(): + showSuccessToast( + Platform.isIOS + ? s.video_call_recordings_download_success_ios + : s.video_call_recordings_download_success, + ); + case RecordingDownloadAlreadyInProgress(): + return; + case RecordingDownloadFailed(): + showErrorToast(s.video_call_recordings_download_error); + } + } + + void _openPlayer(VideoCallRecordingModel recording) { + final fileUrl = recording.fileUrl; + if (fileUrl == null) { + return; + } + GoRouter.of(context).push( + VideoCallRecordingPlayerScreen.path, + extra: recording.toJson(), + ); + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + + return Scaffold( + backgroundColor: appTheme.whiteA700, + appBar: AppBar( + centerTitle: true, + title: Text( + s.video_call_recordings_title, + style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + ), + actions: [ + IconButton( + tooltip: s.video_call_recordings_retention_tooltip, + onPressed: () { + showDialog( + context: context, + builder: (context) => AlertDialog( + content: Text(s.video_call_recordings_retention_tooltip), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('OK'), + ), + ], + ), + ); + }, + icon: Icon(Icons.help_outline, color: appTheme.blueA400), + ), + ], + ), + body: BlocBuilder( + builder: (context, state) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: RecordingPeriodDropdown( + value: state.period, + onChanged: (period) => context.read().setPeriod(period), + ), + ), + Expanded(child: _buildBody(context, state, s)), + ], + ); + }, + ), + ); + } + + Widget _buildBody(BuildContext context, VideoCallRecordingsState state, S s) { + if (state.isLoading && state.recordings.isEmpty) { + return const Loader(); + } + + if (state.error != null && state.recordings.isEmpty) { + return DataErrorWidget( + onReload: () => context.read().load(refresh: true), + ); + } + + if (state.recordings.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + s.video_call_recordings_empty, + textAlign: TextAlign.center, + style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), + ), + ), + ); + } + + return RefreshIndicator( + onRefresh: () => context.read().load(refresh: true), + child: ListView.separated( + controller: _scrollController, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), + itemCount: state.recordings.length + (state.isLoadingMore ? 1 : 0), + separatorBuilder: (_, _) => const SizedBox(height: 16), + itemBuilder: (context, index) { + if (index >= state.recordings.length) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center(child: CircularProgressIndicator()), + ); + } + + final recording = state.recordings[index]; + final isDownloading = state.downloadingRecordingId == recording.id; + return RecordingCard( + recording: recording, + isDownloading: isDownloading, + downloadProgress: isDownloading ? state.downloadProgress : null, + onPlay: () => _openPlayer(recording), + onDownload: () => _download(recording), + ); + }, + ), + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart b/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart new file mode 100644 index 00000000..61b6ea39 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart @@ -0,0 +1,271 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/date_time_utils.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_duration_formatter.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +class RecordingCard extends StatelessWidget { + const RecordingCard({ + super.key, + required this.recording, + required this.onPlay, + required this.onDownload, + this.isDownloading = false, + this.downloadProgress, + }); + + final VideoCallRecordingModel recording; + final VoidCallback onPlay; + final VoidCallback onDownload; + final bool isDownloading; + /// `0..1` when total size is known; `null` while indeterminate. + final double? downloadProgress; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final isReady = recording.isReady; + + return Container( + decoration: BoxDecoration( + color: appTheme.whiteA700, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.15), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AspectRatio( + aspectRatio: 1.775, + child: Stack( + fit: StackFit.expand, + children: [ + ColoredBox( + color: appTheme.dividerColor, + child: CachedNetworkImage( + imageUrl: recording.previewUrl, + fit: BoxFit.cover, + errorWidget: (_, _, _) => ColoredBox(color: appTheme.dividerColor), + ), + ), + if (isReady) ...[ + Center( + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: onPlay, + customBorder: const CircleBorder(), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: appTheme.blueA400, + shape: BoxShape.circle, + ), + child: const Icon(Icons.play_arrow, color: Colors.white, size: 28), + ), + ), + ), + ), + if (recording.durationSeconds != null) + Positioned( + right: 8, + bottom: 8, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + formatRecordingDuration(recording.durationSeconds), + style: TextStyles.textSMedium.copyWith( + color: Colors.white, + fontSize: 10, + ), + ), + ), + ), + ] else + ColoredBox( + color: Colors.white.withValues(alpha: 0.72), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator( + strokeWidth: 2.5, + color: appTheme.blueA400, + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + s.video_call_recordings_processing, + textAlign: TextAlign.center, + style: TextStyles.textSMedium.copyWith(color: appTheme.black), + ), + ), + ], + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + s.video_call_recordings_card_title, + style: TextStyles.textMMedium.copyWith( + color: appTheme.black900, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + _CounterpartAvatar(counterpart: recording.counterpart), + const SizedBox(width: 8), + Expanded( + child: Text( + recording.counterpart?.name ?? s.video_call_counterpart_default, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyles.textSMedium.copyWith( + color: const Color(0xFF666666), + fontSize: 12, + ), + ), + ), + Container( + width: 3, + height: 3, + margin: const EdgeInsets.symmetric(horizontal: 6), + decoration: const BoxDecoration( + color: Color(0xFF666666), + shape: BoxShape.circle, + ), + ), + Text( + recording.createdAt.format( + 'd MMMM yyyy, HH:mm', + Localizations.localeOf(context).languageCode, + ), + style: TextStyles.textSMedium.copyWith( + color: const Color(0xFF666666), + fontSize: 12, + ), + ), + ], + ), + if (isReady) ...[ + const SizedBox(height: 12), + if (isDownloading) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: downloadProgress, + minHeight: 6, + backgroundColor: appTheme.transparentBlue, + color: appTheme.blueA400, + ), + ), + const SizedBox(height: 8), + Text( + downloadProgress != null + ? s.video_call_recordings_downloading_percent( + (downloadProgress! * 100).round(), + ) + : s.video_call_recordings_downloading, + style: TextStyles.textSMedium.copyWith( + color: appTheme.blueGray400, + fontSize: 12, + ), + ), + ] else + SizedBox( + width: double.infinity, + height: 40, + child: ElevatedButton( + onPressed: onDownload, + style: ElevatedButton.styleFrom( + backgroundColor: appTheme.blueA400, + foregroundColor: Colors.white, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + s.video_call_recordings_download, + style: TextStyles.textSMedium.copyWith( + color: Colors.white, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(width: 8), + const Icon(Icons.download, size: 20), + ], + ), + ), + ), + ], + ], + ), + ), + ], + ), + ); + } +} + +class _CounterpartAvatar extends StatelessWidget { + const _CounterpartAvatar({required this.counterpart}); + + final VideoCallRecordingCounterpartModel? counterpart; + + @override + Widget build(BuildContext context) { + final url = counterpart?.profilePhotoUrl; + return ClipOval( + child: SizedBox( + width: 24, + height: 24, + child: url != null && url.isNotEmpty + ? CachedNetworkImage( + imageUrl: url, + fit: BoxFit.cover, + errorWidget: (_, _, _) => _placeholder(), + ) + : _placeholder(), + ), + ); + } + + Widget _placeholder() { + return ColoredBox( + color: appTheme.backgroundAvatar, + child: Icon(Icons.person, size: 16, color: appTheme.blueGray400), + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart b/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart new file mode 100644 index 00000000..0bfe2cb6 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart @@ -0,0 +1,52 @@ +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; + +class RecordingPeriodDropdown extends StatelessWidget { + const RecordingPeriodDropdown({ + super.key, + required this.value, + required this.onChanged, + }); + + final RecordingPeriod value; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + + String label(RecordingPeriod period) => switch (period) { + RecordingPeriod.today => s.video_call_recordings_period_today, + RecordingPeriod.week => s.video_call_recordings_period_week, + RecordingPeriod.currentMonth => s.video_call_recordings_period_current_month, + RecordingPeriod.prevMonth => s.video_call_recordings_period_prev_month, + RecordingPeriod.all => s.video_call_recordings_period_all, + }; + + return CustomDropDownButton( + key: ValueKey(value), + isExpanded: true, + value: value, + onChanged: (period) { + if (period != null) { + onChanged(period); + } + }, + items: RecordingPeriod.values + .map( + (period) => DropdownMenuItem( + value: period, + child: Text( + label(period), + style: TextStyles.textMMedium.copyWith(color: appTheme.black), + ), + ), + ) + .toList(), + ); + } +} diff --git a/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart b/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart new file mode 100644 index 00000000..a669e2c7 --- /dev/null +++ b/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart @@ -0,0 +1,37 @@ +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/video_call_recording_file_service.dart'; +import 'package:eatvio_app/features/video_calls/services/video_call_service.dart'; + +class VideoCallRecordingsRepository { + VideoCallRecordingsRepository({ + required this.videoCallService, + required this.fileService, + }); + + final VideoCallService videoCallService; + final VideoCallRecordingFileService fileService; + + Future getRecordings({ + required int page, + RecordingPeriod? period, + }) { + return videoCallService.getRecordings( + page: page, + dateRange: period?.apiValue, + ); + } + + /// Возвращает путь/URI сохранённого файла в пользовательском хранилище. + Future downloadRecordingFile({ + required String fileUrl, + required int recordingId, + RecordingDownloadProgress? onProgress, + }) { + return fileService.downloadRecordingFile( + fileUrl: fileUrl, + recordingId: recordingId, + onProgress: onProgress, + ); + } +} diff --git a/lib/features/video_calls/recordings/services/public_downloads_saver.dart b/lib/features/video_calls/recordings/services/public_downloads_saver.dart new file mode 100644 index 00000000..d0cda3ed --- /dev/null +++ b/lib/features/video_calls/recordings/services/public_downloads_saver.dart @@ -0,0 +1,57 @@ +import 'dart:io'; + +import 'package:file_saver/file_saver.dart'; + +/// Сохраняет файл в публичную папку «Загрузки/{subfolder}» (Android) +/// или в Documents приложения (iOS, видно в Files при UIFileSharingEnabled). +class PublicDownloadsSaver { + const PublicDownloadsSaver(); + + /// Имя папки приложения в Загрузках / Files. + static const appFolderName = 'Itvio'; + + Future saveToDownloads({ + required String sourcePath, + required String fileName, + String mimeType = 'video/mp4', + String subfolder = appFolderName, + }) async { + final nameWithoutExt = fileName.contains('.') + ? fileName.substring(0, fileName.lastIndexOf('.')) + : fileName; + final extension = fileName.contains('.') + ? fileName.substring(fileName.lastIndexOf('.') + 1) + : 'mp4'; + + final resolvedMime = MimeType.values.firstWhere( + (type) => type.type == mimeType, + orElse: () => MimeType.mp4Video, + ); + + if (Platform.isAndroid) { + final saved = await FileSaver.instance.saveToDownloads( + name: nameWithoutExt, + filePath: sourcePath, + fileExtension: extension, + mimeType: resolvedMime, + subfolder: subfolder, + ); + if (saved == null || saved.isEmpty) { + throw StateError('Failed to save file to Downloads/$subfolder'); + } + return saved; + } + + // iOS: общего Downloads нет — saveFile кладёт в Documents (Files → On My iPhone). + final saved = await FileSaver.instance.saveFile( + name: nameWithoutExt, + file: File(sourcePath), + fileExtension: extension, + mimeType: resolvedMime, + ); + if (saved.isEmpty) { + throw StateError('Failed to save file to app Documents'); + } + return saved; + } +} diff --git a/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart b/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart new file mode 100644 index 00000000..8bc1c751 --- /dev/null +++ b/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart @@ -0,0 +1,140 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_not_ready_exception.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/public_downloads_saver.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; + +typedef RecordingDownloadProgress = void Function(int received, int total); + +class VideoCallRecordingFileService { + VideoCallRecordingFileService({ + required this.dio, + required this.downloadsSaver, + }); + + final Dio dio; + final PublicDownloadsSaver downloadsSaver; + + /// Скачивает запись и сохраняет в `Загрузки/Itvio` (Android) + /// или Documents приложения (iOS, видно в Files). + Future downloadRecordingFile({ + required String fileUrl, + required int recordingId, + RecordingDownloadProgress? onProgress, + CancelToken? cancelToken, + }) async { + String? tempPath; + try { + await _ensureStoragePermissionIfNeeded(); + + final parsed = Uri.parse(fileUrl); + final uri = parsed.replace( + queryParameters: { + ...parsed.queryParameters, + 'download': '1', + }, + ); + + final fileName = 'recording_$recordingId.mp4'; + final tempDir = await getTemporaryDirectory(); + final path = '${tempDir.path}/$fileName'; + tempPath = path; + + await dio.download( + uri.toString(), + path, + cancelToken: cancelToken, + onReceiveProgress: onProgress, + options: Options( + responseType: ResponseType.bytes, + validateStatus: (status) => status != null && status < 400, + ), + ); + + final tempFile = File(path); + try { + return await downloadsSaver.saveToDownloads( + sourcePath: path, + fileName: fileName, + ); + } finally { + if (await tempFile.exists()) { + await tempFile.delete(); + } + } + } on DioException catch (error) { + await _deleteIfExists(tempPath); + _throwIfNotReady(error); + rethrow; + } + } + + Future _ensureStoragePermissionIfNeeded() async { + if (!Platform.isAndroid) { + return; + } + + final androidInfo = await DeviceInfoPlugin().androidInfo; + if (androidInfo.version.sdkInt >= 29) { + return; + } + + final status = await Permission.storage.request(); + if (!status.isGranted) { + throw StateError('Storage permission denied'); + } + } + + Future _deleteIfExists(String? path) async { + if (path == null) { + return; + } + final file = File(path); + if (await file.exists()) { + await file.delete(); + } + } + + void _throwIfNotReady(DioException error) { + if (error.response?.statusCode != 409) { + return; + } + + final payload = _jsonObject(error.response?.data); + final message = payload?['message']?.toString(); + final code = payload?['code']?.toString(); + + if (code == RecordingNotReadyException.code || code == null) { + throw RecordingNotReadyException(message: message); + } + } + + Map? _jsonObject(Object? data) { + if (data is Map) { + return Map.from(data); + } + + final raw = switch (data) { + String value => value, + List value => utf8.decode(value), + _ => null, + }; + if (raw == null || raw.isEmpty) { + return null; + } + + try { + final decoded = jsonDecode(raw); + if (decoded is Map) { + return Map.from(decoded); + } + } on FormatException { + return null; + } + return null; + } +} diff --git a/lib/features/video_calls/services/video_call_callkit_coordinator.dart b/lib/features/video_calls/services/video_call_callkit_coordinator.dart index 5d9b456a..a93a611d 100644 --- a/lib/features/video_calls/services/video_call_callkit_coordinator.dart +++ b/lib/features/video_calls/services/video_call_callkit_coordinator.dart @@ -22,12 +22,10 @@ import 'package:sentry_flutter/sentry_flutter.dart'; class VideoCallCallKitCoordinator { VideoCallCallKitCoordinator({ - required FirebaseApi firebaseApi, - VideoCallManager? videoCallManager, - VideoCallSessionCubit? videoCallSessionCubit, - }) : _firebaseApi = firebaseApi, - _videoCallManager = videoCallManager, - _videoCallSessionCubit = videoCallSessionCubit; + required this._firebaseApi, + this._videoCallManager, + this._videoCallSessionCubit, + }); final FirebaseApi _firebaseApi; final VideoCallManager? _videoCallManager; @@ -52,6 +50,7 @@ class VideoCallCallKitCoordinator { _PendingIncomingAccept? _pendingIncomingAccept; _AndroidAcceptResumeObserver? _androidResumeObserver; + _AppResumeObserver? _iosResumeObserver; bool _pendingAcceptDrainScheduled = false; Future initialize() async { @@ -86,6 +85,12 @@ class VideoCallCallKitCoordinator { } }); await _firebaseApi.registerPushToken(); + _iosResumeObserver = _AppResumeObserver( + onResumed: () { + unawaited(_drainPendingNativeAcceptedVoipCall()); + }, + ); + WidgetsBinding.instance.addObserver(_iosResumeObserver!); await _drainPendingNativeAcceptedVoipCall(); WidgetsBinding.instance.addPostFrameCallback((_) { _scheduleNativeVoipDiagnosticsDrain(); @@ -257,6 +262,11 @@ class VideoCallCallKitCoordinator { WidgetsBinding.instance.removeObserver(observer); _androidResumeObserver = null; } + final iosObserver = _iosResumeObserver; + if (iosObserver != null) { + WidgetsBinding.instance.removeObserver(iosObserver); + _iosResumeObserver = null; + } unawaited(_eventSubscription?.cancel()); _eventSubscription = null; _callKitParamsById.clear(); @@ -1228,6 +1238,19 @@ class _PendingIncomingAccept { final bool? counterpartIsConsultant; } +class _AppResumeObserver with WidgetsBindingObserver { + _AppResumeObserver({required this.onResumed}); + + final VoidCallback onResumed; + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + onResumed(); + } + } +} + class _AndroidAcceptResumeObserver with WidgetsBindingObserver { _AndroidAcceptResumeObserver({required this.onResumed}); diff --git a/lib/features/video_calls/services/video_call_notification_navigator.dart b/lib/features/video_calls/services/video_call_notification_navigator.dart index 2ec1ce0b..5390b907 100644 --- a/lib/features/video_calls/services/video_call_notification_navigator.dart +++ b/lib/features/video_calls/services/video_call_notification_navigator.dart @@ -199,7 +199,7 @@ class VideoCallNotificationNavigator { return false; } - return _waitForCallRouteVisible(); + return await _waitForCallRouteVisible(); } finally { _pushInFlight = false; } diff --git a/lib/features/video_calls/services/video_call_service.dart b/lib/features/video_calls/services/video_call_service.dart index b87fc03a..88768381 100644 --- a/lib/features/video_calls/services/video_call_service.dart +++ b/lib/features/video_calls/services/video_call_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/video_calls/models/video_call_models.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; import 'package:retrofit/retrofit.dart'; part 'video_call_service.g.dart'; @@ -36,4 +37,10 @@ abstract class VideoCallService { @Path('conversation') required String conversationUuid, @Body() required Map body, }); + + @GET('/api/video-call/recordings') + Future getRecordings({ + @Query('page') required int page, + @Query(r'filters[created_at][$date_range]') String? dateRange, + }); } diff --git a/lib/features/welcome/presentation/pages/welcome_screen.dart b/lib/features/welcome/presentation/pages/welcome_screen.dart index e6f48dc9..2cf27602 100644 --- a/lib/features/welcome/presentation/pages/welcome_screen.dart +++ b/lib/features/welcome/presentation/pages/welcome_screen.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/prefs_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/token_storage.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; diff --git a/lib/generated/intl/messages_en.dart b/lib/generated/intl/messages_en.dart index 8929ab56..d54c3c65 100644 --- a/lib/generated/intl/messages_en.dart +++ b/lib/generated/intl/messages_en.dart @@ -22,32 +22,82 @@ class MessageLookup extends MessageLookupByLibrary { static String m0(date) => "Консультант прокомментировал день ${date}"; - static String m1(planName) => "План «${planName}» начался"; + static String m1(value, period, category) => + "BMI higher by ${value} over ${period} · ${category}"; - static String m2(planName, name) => + static String m2(height) => + "Green zone is normal (18.5–25), yellow is overweight, pink is obesity. Calculated for a height of ${height} cm."; + + static String m3(value, period, category) => + "BMI lower by ${value} over ${period} · ${category}"; + + static String m4(period, category) => + "BMI unchanged over ${period} · ${category}"; + + static String m5(name, value) => "${name} down ${value} cm"; + + static String m6(name, value) => "${name} up ${value} cm"; + + static String m7(name) => "${name} unchanged"; + + static String m8(parts, period) => "${parts} over ${period}"; + + static String m9(time) => "Bedtime at ${time}"; + + static String m10(time) => "Wake-up at ${time}"; + + static String m11(value, period) => "Gained ${value} kg over ${period}"; + + static String m12(value, period) => "Lost ${value} kg over ${period}"; + + static String m13(period) => "Weight unchanged over ${period}"; + + static String m14(userName) => + "You have proposed a personal diet to ${userName}"; + + static String m15(userName, dietName) => + "You have proposed a personal diet to ${userName}, selected diet: «${dietName}»"; + + static String m16(duration, dayWord) => + "The diet lasts ${duration} ${dayWord}. It can only be offered for a plan with the same duration."; + + static String m17(dietDuration, dietDayWord, planDuration, planDayWord) => + "Not suitable: diet lasts ${dietDuration} ${dietDayWord}, plan lasts ${planDuration} ${planDayWord}."; + + static String m18(name) => "Diet «${name}» proposed"; + + static String m19(planName) => "План «${planName}» начался"; + + static String m20(planName, name) => "План «${planName}» с пользователем ${name} начался"; - static String m3(percent, amount) => + static String m21(duration, dayWord) => "Plan for ${duration} ${dayWord}"; + + static String m22(percent, amount) => "Discount ${percent}% — you save ${amount} ₽"; - static String m4(step) => "шаг ${step} из 2"; + static String m23(date) => "Start: ${date}"; - static String m5(planName, name) => + static String m24(step) => "шаг ${step} из 2"; + + static String m25(planName, name) => "Завтра начинается план «${planName}» с пользователем ${name}"; - static String m6(planName) => + static String m26(planName) => "Завтра начнется прохождение плана «${planName}»"; - static String m7(name, planName) => + static String m27(name, planName) => "Пользователь ${name} отменил подписку на план «${planName}»"; - static String m8(name, planName) => + static String m28(name, planName) => "Пользователь ${name} оплатил план «${planName}»"; - static String m9(name, planName) => + static String m29(name, planName) => "Пользователь ${name} подписался на план «${planName}»"; - static String m10(planName) => "Вы отменили подписку на план «${planName}»"; + static String m30(percent) => "Downloading… ${percent}%"; + + static String m31(planName) => "Вы отменили подписку на план «${planName}»"; final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { @@ -170,6 +220,9 @@ class MessageLookup extends MessageLookupByLibrary { ), "carbohydrates": MessageLookupByLibrary.simpleMessage("Углеводы"), "changeDiet": MessageLookupByLibrary.simpleMessage("Заменить диету"), + "change_personal_diet": MessageLookupByLibrary.simpleMessage( + "Change personal diet", + ), "chargeApproved": MessageLookupByLibrary.simpleMessage("Выплата одобрена"), "chargeCollectionFailed": MessageLookupByLibrary.simpleMessage( "Не удалось оформить выплату", @@ -317,6 +370,7 @@ class MessageLookup extends MessageLookupByLibrary { ), "days": MessageLookupByLibrary.simpleMessage("дней"), "deception": MessageLookupByLibrary.simpleMessage("Обман"), + "default_user_name": MessageLookupByLibrary.simpleMessage("User"), "delete": MessageLookupByLibrary.simpleMessage("Удалить"), "deleteComment": MessageLookupByLibrary.simpleMessage( "Удалить комментарий", @@ -503,6 +557,126 @@ class MessageLookup extends MessageLookupByLibrary { "initial_measurements": MessageLookupByLibrary.simpleMessage( "Первичные замеры", ), + "insights_add_measures_empty": MessageLookupByLibrary.simpleMessage( + "Add your measurements", + ), + "insights_add_record": MessageLookupByLibrary.simpleMessage("Add entry"), + "insights_add_weight_empty": MessageLookupByLibrary.simpleMessage( + "Add your weight", + ), + "insights_bmi_higher": m1, + "insights_bmi_hint": m2, + "insights_bmi_lower": m3, + "insights_bmi_normal": MessageLookupByLibrary.simpleMessage("normal"), + "insights_bmi_obesity_1": MessageLookupByLibrary.simpleMessage( + "obesity class I", + ), + "insights_bmi_obesity_2": MessageLookupByLibrary.simpleMessage( + "obesity class II", + ), + "insights_bmi_obesity_3": MessageLookupByLibrary.simpleMessage( + "obesity class III", + ), + "insights_bmi_overweight": MessageLookupByLibrary.simpleMessage( + "overweight", + ), + "insights_bmi_same": m4, + "insights_bmi_severe_underweight": MessageLookupByLibrary.simpleMessage( + "severe underweight", + ), + "insights_bmi_underweight": MessageLookupByLibrary.simpleMessage( + "underweight", + ), + "insights_intra_hint": MessageLookupByLibrary.simpleMessage( + "Bars show what each meal consists of: protein, fat and carbs in kcal. Lines show satiety and mood on a 0–5 scale.", + ), + "insights_load_error": MessageLookupByLibrary.simpleMessage( + "Failed to load analytics", + ), + "insights_measure_less": m5, + "insights_measure_more": m6, + "insights_measure_same": m7, + "insights_measures_summary": m8, + "insights_need_height": MessageLookupByLibrary.simpleMessage( + "Set your height to calculate BMI.", + ), + "insights_next_day": MessageLookupByLibrary.simpleMessage("Next day"), + "insights_not_enough": MessageLookupByLibrary.simpleMessage( + "Not enough data", + ), + "insights_period_1m": MessageLookupByLibrary.simpleMessage("1M"), + "insights_period_1w": MessageLookupByLibrary.simpleMessage("1W"), + "insights_period_1y": MessageLookupByLibrary.simpleMessage("1Y"), + "insights_period_2w": MessageLookupByLibrary.simpleMessage("2W"), + "insights_period_3m": MessageLookupByLibrary.simpleMessage("3M"), + "insights_period_6m": MessageLookupByLibrary.simpleMessage("6M"), + "insights_period_all": MessageLookupByLibrary.simpleMessage("All time"), + "insights_period_label_1": MessageLookupByLibrary.simpleMessage("month"), + "insights_period_label_12": MessageLookupByLibrary.simpleMessage("year"), + "insights_period_label_3": MessageLookupByLibrary.simpleMessage("3 months"), + "insights_period_label_6": MessageLookupByLibrary.simpleMessage("6 months"), + "insights_period_label_all": MessageLookupByLibrary.simpleMessage( + "all time", + ), + "insights_pick_date": MessageLookupByLibrary.simpleMessage("Pick a date"), + "insights_prev_day": MessageLookupByLibrary.simpleMessage("Previous day"), + "insights_retry": MessageLookupByLibrary.simpleMessage("Retry"), + "insights_save_error": MessageLookupByLibrary.simpleMessage( + "Failed to save the entry", + ), + "insights_series_calories": MessageLookupByLibrary.simpleMessage( + "Calories", + ), + "insights_series_carbs": MessageLookupByLibrary.simpleMessage("Carbs"), + "insights_series_chest": MessageLookupByLibrary.simpleMessage("Chest"), + "insights_series_fats": MessageLookupByLibrary.simpleMessage("Fat"), + "insights_series_hips": MessageLookupByLibrary.simpleMessage("Hips"), + "insights_series_mood": MessageLookupByLibrary.simpleMessage("Mood"), + "insights_series_proteins": MessageLookupByLibrary.simpleMessage("Protein"), + "insights_series_satiety": MessageLookupByLibrary.simpleMessage("Satiety"), + "insights_series_sleep": MessageLookupByLibrary.simpleMessage( + "Sleep and wake-up", + ), + "insights_series_waist": MessageLookupByLibrary.simpleMessage("Waist"), + "insights_sleep_at": m9, + "insights_sleep_shade": MessageLookupByLibrary.simpleMessage( + "Shading — sleep time", + ), + "insights_subtitle_closed": MessageLookupByLibrary.simpleMessage( + "tap to see your progress", + ), + "insights_subtitle_open": MessageLookupByLibrary.simpleMessage( + "weight, measurements and nutrition", + ), + "insights_tab_bmi": MessageLookupByLibrary.simpleMessage("BMI"), + "insights_tab_daily": MessageLookupByLibrary.simpleMessage( + "Nutrition by day", + ), + "insights_tab_intra": MessageLookupByLibrary.simpleMessage( + "Throughout the day", + ), + "insights_tab_measures": MessageLookupByLibrary.simpleMessage( + "Measurements", + ), + "insights_tab_weight": MessageLookupByLibrary.simpleMessage("Weight"), + "insights_title": MessageLookupByLibrary.simpleMessage("Analytics"), + "insights_today": MessageLookupByLibrary.simpleMessage("Today"), + "insights_unit_bmi": MessageLookupByLibrary.simpleMessage("BMI"), + "insights_unit_cm": MessageLookupByLibrary.simpleMessage("cm"), + "insights_unit_cm_waist": MessageLookupByLibrary.simpleMessage("cm waist"), + "insights_unit_grams": MessageLookupByLibrary.simpleMessage("grams"), + "insights_unit_kcal": MessageLookupByLibrary.simpleMessage("kcal"), + "insights_unit_kcal_avg": MessageLookupByLibrary.simpleMessage( + "kcal on average", + ), + "insights_unit_kcal_per_meal": MessageLookupByLibrary.simpleMessage( + "kcal per meal", + ), + "insights_unit_kg": MessageLookupByLibrary.simpleMessage("kg"), + "insights_wake_at": m10, + "insights_weight_gained": m11, + "insights_weight_lost": m12, + "insights_weight_same": m13, "invite": MessageLookupByLibrary.simpleMessage("Пригласить"), "invited_people_count": MessageLookupByLibrary.simpleMessage( "Количество приглашенных", @@ -604,6 +778,10 @@ class MessageLookup extends MessageLookupByLibrary { "nicotine": MessageLookupByLibrary.simpleMessage("Никотин"), "no": MessageLookupByLibrary.simpleMessage("Нет"), "no_account": MessageLookupByLibrary.simpleMessage("У меня нет аккаунта"), + "no_active_personal_diet_consultations": + MessageLookupByLibrary.simpleMessage( + "No active consultations with a personal diet", + ), "no_default_cards": MessageLookupByLibrary.simpleMessage( "У вас нет привязанных карт. Что бы начать работу, привяжите карту", ), @@ -635,6 +813,9 @@ class MessageLookup extends MessageLookupByLibrary { "order": MessageLookupByLibrary.simpleMessage("Порядок"), "orderCanceled": MessageLookupByLibrary.simpleMessage("Заказ отменен"), "order_created": MessageLookupByLibrary.simpleMessage("Заказ создан"), + "order_in_progress": MessageLookupByLibrary.simpleMessage( + "Order in progress", + ), "order_paid": MessageLookupByLibrary.simpleMessage("Заказ оплачен"), "order_price": MessageLookupByLibrary.simpleMessage("Сумма заказа"), "order_status": MessageLookupByLibrary.simpleMessage("Статус заказа"), @@ -658,6 +839,9 @@ class MessageLookup extends MessageLookupByLibrary { "В пароле должно быть минимум 6 символов", ), "pay": MessageLookupByLibrary.simpleMessage("Оплатить"), + "pay_by_qr_code": MessageLookupByLibrary.simpleMessage( + "Оплатить по QR-коду", + ), "payment_failed": MessageLookupByLibrary.simpleMessage("Оплата не прошла"), "pcs": MessageLookupByLibrary.simpleMessage("шт"), "pending_payment": MessageLookupByLibrary.simpleMessage("Ожидается оплата"), @@ -665,6 +849,20 @@ class MessageLookup extends MessageLookupByLibrary { "personalDietCreating": MessageLookupByLibrary.simpleMessage( "Составление индивидуальной диеты", ), + "personal_diet_defined_to_author": m14, + "personal_diet_defined_to_author_named": m15, + "personal_diet_duration_hint": m16, + "personal_diet_duration_mismatch": m17, + "personal_diet_not_proposed": MessageLookupByLibrary.simpleMessage( + "Personal diet not proposed", + ), + "personal_diet_proposed": MessageLookupByLibrary.simpleMessage( + "Personal diet proposed", + ), + "personal_diet_proposed_named": m18, + "personal_diet_replaces_tomorrow": MessageLookupByLibrary.simpleMessage( + "The change takes effect tomorrow", + ), "personal_diet_set": MessageLookupByLibrary.simpleMessage( "Персональная диета установлена", ), @@ -681,17 +879,18 @@ class MessageLookup extends MessageLookupByLibrary { "Физическая форма", ), "place_of_living": MessageLookupByLibrary.simpleMessage("Место проживания"), - "planStarted": m1, + "planStarted": m19, "planWillBeConfirmedAfterThreeDays": MessageLookupByLibrary.simpleMessage( "Если вы не подтвердите, то план через три дня подтвердится автоматически", ), - "planWithUserStarted": m2, + "planWithUserStarted": m20, "plan_author": MessageLookupByLibrary.simpleMessage("Автор плана"), "plan_desc": MessageLookupByLibrary.simpleMessage("Описание плана"), "plan_desc_example": MessageLookupByLibrary.simpleMessage( "Большое подробное, привлекательное описание плана", ), "plan_duration": MessageLookupByLibrary.simpleMessage("Срок плана"), + "plan_duration_label": m21, "plan_label_desc": MessageLookupByLibrary.simpleMessage( "План для поддержания формы", ), @@ -728,7 +927,7 @@ class MessageLookup extends MessageLookupByLibrary { "Promo code applied!", ), "promo_code": MessageLookupByLibrary.simpleMessage("Promo code"), - "promo_discount_hint": m3, + "promo_discount_hint": m22, "promo_invalid": MessageLookupByLibrary.simpleMessage( "Promo code not found or expired", ), @@ -777,6 +976,34 @@ class MessageLookup extends MessageLookupByLibrary { "sbp_payment_error": MessageLookupByLibrary.simpleMessage( "Не удалось начать оплату. Попробуйте позже", ), + "sbp_qr_amount_label": MessageLookupByLibrary.simpleMessage( + "Сумма к оплате", + ), + "sbp_qr_open_test_payment": MessageLookupByLibrary.simpleMessage( + "Открыть тестовую оплату", + ), + "sbp_qr_paid_description": MessageLookupByLibrary.simpleMessage( + "Консультация оплачена. Можно вернуться в чат.", + ), + "sbp_qr_paid_title": MessageLookupByLibrary.simpleMessage( + "Оплата прошла успешно!", + ), + "sbp_qr_step1": MessageLookupByLibrary.simpleMessage( + "Откройте приложение банка на телефоне", + ), + "sbp_qr_step2": MessageLookupByLibrary.simpleMessage( + "Выберите «Оплата по QR-коду»", + ), + "sbp_qr_step3": MessageLookupByLibrary.simpleMessage( + "Наведите камеру на код", + ), + "sbp_qr_test_hint": MessageLookupByLibrary.simpleMessage( + "Симуляция оплаты на тестовом стенде Альфа-Банка", + ), + "sbp_qr_title": MessageLookupByLibrary.simpleMessage("Оплата по QR-коду"), + "sbp_qr_waiting_payment": MessageLookupByLibrary.simpleMessage( + "Ожидание оплаты…", + ), "send": MessageLookupByLibrary.simpleMessage("Отправить"), "send_complain": MessageLookupByLibrary.simpleMessage("Отправить жалобу"), "services": MessageLookupByLibrary.simpleMessage("Оказание услуг"), @@ -821,12 +1048,13 @@ class MessageLookup extends MessageLookupByLibrary { "Выбрана дата старта", ), "startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"), + "start_date_label": m23, "statistic": MessageLookupByLibrary.simpleMessage("Статистика"), "step": MessageLookupByLibrary.simpleMessage("Шаг"), "step_by_step_photo_recipe": MessageLookupByLibrary.simpleMessage( "Пошаговый фоторецепт", ), - "step_widget": m4, + "step_widget": m24, "successfully_published": MessageLookupByLibrary.simpleMessage( "успешно опубликован", ), @@ -851,8 +1079,8 @@ class MessageLookup extends MessageLookupByLibrary { "toOffer": MessageLookupByLibrary.simpleMessage("Предложить"), "to_draft": MessageLookupByLibrary.simpleMessage("В черновик"), "to_order": MessageLookupByLibrary.simpleMessage("Заказать"), - "tommorowPlanWithUserWillStart": m5, - "tomorrowYourPlanWillStart": m6, + "tommorowPlanWithUserWillStart": m25, + "tomorrowYourPlanWillStart": m26, "try_again": MessageLookupByLibrary.simpleMessage("Попробовать снова"), "try_again_2": MessageLookupByLibrary.simpleMessage("Попробуйте ещё раз"), "typeAmoutOfReturn": MessageLookupByLibrary.simpleMessage( @@ -886,7 +1114,7 @@ class MessageLookup extends MessageLookupByLibrary { "Верхние показатели давления:", ), "upper": MessageLookupByLibrary.simpleMessage("Верхнее"), - "userCanceldThePlanSubscription": m7, + "userCanceldThePlanSubscription": m27, "userConfirmedPlanCompletion": MessageLookupByLibrary.simpleMessage( "Пользователь подтвердил прохождения плана. В ближайшее время Вы получите", ), @@ -894,8 +1122,8 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage( "Пользователь подтвердил прохождения плана.", ), - "userPaidThePlan": m8, - "userSubscribedToPlan": m9, + "userPaidThePlan": m28, + "userSubscribedToPlan": m29, "user_authorization": MessageLookupByLibrary.simpleMessage( "Аутентификация", ), @@ -961,6 +1189,57 @@ class MessageLookup extends MessageLookupByLibrary { "video_call_recording_notice": MessageLookupByLibrary.simpleMessage( "The video call will be recorded.\nThe consultation may be reviewed by Eatvio staff for quality assurance.", ), + "video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage( + "Video consultation with a nutrition specialist", + ), + "video_call_recordings_download": MessageLookupByLibrary.simpleMessage( + "Download", + ), + "video_call_recordings_download_error": + MessageLookupByLibrary.simpleMessage( + "Could not download the recording. Please try again later.", + ), + "video_call_recordings_download_success": + MessageLookupByLibrary.simpleMessage( + "Recording saved to Downloads/Itvio", + ), + "video_call_recordings_download_success_ios": + MessageLookupByLibrary.simpleMessage( + "Recording saved to the Files app", + ), + "video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage( + "Downloading…", + ), + "video_call_recordings_downloading_percent": m30, + "video_call_recordings_empty": MessageLookupByLibrary.simpleMessage( + "No video consultations yet", + ), + "video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage( + "All time", + ), + "video_call_recordings_period_current_month": + MessageLookupByLibrary.simpleMessage("Current month"), + "video_call_recordings_period_prev_month": + MessageLookupByLibrary.simpleMessage("Previous month"), + "video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage( + "Today", + ), + "video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage( + "7 days", + ), + "video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage( + "Could not play the recording", + ), + "video_call_recordings_processing": MessageLookupByLibrary.simpleMessage( + "Recording is being processed…", + ), + "video_call_recordings_retention_tooltip": + MessageLookupByLibrary.simpleMessage( + "Video consultation recordings are stored on Eatvio servers for 1 year.", + ), + "video_call_recordings_title": MessageLookupByLibrary.simpleMessage( + "My consultations", + ), "video_call_role_consultant": MessageLookupByLibrary.simpleMessage( "Eatvio consultant", ), @@ -1025,7 +1304,7 @@ class MessageLookup extends MessageLookupByLibrary { "youCanComplain": MessageLookupByLibrary.simpleMessage( "Если вас что-то не устроило, вы можете подать жалобу", ), - "youCanceledSubscriptionToPlan": m10, + "youCanceledSubscriptionToPlan": m31, "youShureYouWantToCancelOrder": MessageLookupByLibrary.simpleMessage( "Вы уверены, что хотите отменить заказ?", ), diff --git a/lib/generated/intl/messages_ru.dart b/lib/generated/intl/messages_ru.dart index 91ba0fac..cd2d772c 100644 --- a/lib/generated/intl/messages_ru.dart +++ b/lib/generated/intl/messages_ru.dart @@ -20,9 +20,59 @@ typedef String MessageIfAbsent(String messageStr, List args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'ru'; - static String m3(percent, amount) => + static String m1(value, period, category) => + "ИМТ выше на ${value} за ${period} · ${category}"; + + static String m2(height) => + "Зелёная зона — норма (18.5–25), жёлтая — избыточный вес, розовая — ожирение. Считаем при росте ${height} см."; + + static String m3(value, period, category) => + "ИМТ ниже на ${value} за ${period} · ${category}"; + + static String m4(period, category) => + "ИМТ не изменился за ${period} · ${category}"; + + static String m5(name, value) => "${name} меньше на ${value} см"; + + static String m6(name, value) => "${name} больше на ${value} см"; + + static String m7(name) => "${name} без изменений"; + + static String m8(parts, period) => "${parts} за ${period}"; + + static String m9(time) => "Отход ко сну в ${time}"; + + static String m10(time) => "Подъём в ${time}"; + + static String m11(value, period) => "Набрали ${value} кг за ${period}"; + + static String m12(value, period) => "Снизили на ${value} кг за ${period}"; + + static String m13(period) => "Вес не изменился за ${period}"; + + static String m14(userName) => + "Вы предложили персональную диету пользователю ${userName}"; + + static String m15(userName, dietName) => + "Вы предложили персональную диету пользователю ${userName}, выбранная диета: «${dietName}»"; + + static String m16(duration, dayWord) => + "Диета рассчитана на ${duration} ${dayWord}. Предложить её можно только для плана с такой же длительностью."; + + static String m17(dietDuration, dietDayWord, planDuration, planDayWord) => + "Не подходит: диета на ${dietDuration} ${dietDayWord}, план на ${planDuration} ${planDayWord}."; + + static String m18(name) => "Диета «${name}» предложена"; + + static String m21(duration, dayWord) => "План на ${duration} ${dayWord}"; + + static String m22(percent, amount) => "Скидка ${percent}% — вы экономите ${amount} ₽"; + static String m23(date) => "Старт: ${date}"; + + static String m30(percent) => "Скачивание… ${percent}%"; + final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { "Moscow": MessageLookupByLibrary.simpleMessage("Москва"), @@ -66,6 +116,10 @@ class MessageLookup extends MessageLookupByLibrary { "Если вы любите мучные продукты, но хотите придерживаться диеты, вам подходит диета с добавленим мучных блюд на основе цельнозерновых вариантов. В них больше сложных углеводов и клетчатки, что способствует длительному чувству сытости и поддерживает здоровье пищеварительной системы.", ), "carbohydrates": MessageLookupByLibrary.simpleMessage("Углеводы"), + "changeDiet": MessageLookupByLibrary.simpleMessage("Заменить диету"), + "change_personal_diet": MessageLookupByLibrary.simpleMessage( + "Заменить диету", + ), "chat": MessageLookupByLibrary.simpleMessage("Чат"), "chest": MessageLookupByLibrary.simpleMessage("Грудь"), "chest_circumference": MessageLookupByLibrary.simpleMessage("Обхват груди"), @@ -78,6 +132,10 @@ class MessageLookup extends MessageLookupByLibrary { "choose_plan_duration": MessageLookupByLibrary.simpleMessage( "Выберите срок плана", ), + "choose_plan_start_date_with_personal_diet": + MessageLookupByLibrary.simpleMessage( + "Выберите дату старта плана питания с учетом составления персональной диеты", + ), "choose_start_diet_date": MessageLookupByLibrary.simpleMessage( "Выберите дату старты диеты. Она отобразиться у Вас в дневнике", ), @@ -110,6 +168,7 @@ class MessageLookup extends MessageLookupByLibrary { "date_of_birth": MessageLookupByLibrary.simpleMessage("Дата рождения"), "day": MessageLookupByLibrary.simpleMessage("День"), "days": MessageLookupByLibrary.simpleMessage("дней"), + "default_user_name": MessageLookupByLibrary.simpleMessage("Пользователь"), "deleted": MessageLookupByLibrary.simpleMessage("Удалена"), "diary": MessageLookupByLibrary.simpleMessage("Дневник"), "diet": MessageLookupByLibrary.simpleMessage("Диета"), @@ -126,6 +185,7 @@ class MessageLookup extends MessageLookupByLibrary { "do_you_take_pills": MessageLookupByLibrary.simpleMessage( "Принимаете ли вы лекарства или бады?", ), + "done": MessageLookupByLibrary.simpleMessage("Завершен"), "down_pressure": MessageLookupByLibrary.simpleMessage( "Нижние показатели давления:", ), @@ -192,6 +252,9 @@ class MessageLookup extends MessageLookupByLibrary { "from_a_to_z": MessageLookupByLibrary.simpleMessage("Название: А-Я"), "from_z_to_a": MessageLookupByLibrary.simpleMessage("Название: Я-А"), "gallery": MessageLookupByLibrary.simpleMessage("Галерея"), + "goToMyDiets": MessageLookupByLibrary.simpleMessage( + "Перейти к моим диетам", + ), "gr": MessageLookupByLibrary.simpleMessage("гр"), "grams": MessageLookupByLibrary.simpleMessage("гр"), "have_promo_code": MessageLookupByLibrary.simpleMessage( @@ -212,6 +275,124 @@ class MessageLookup extends MessageLookupByLibrary { "initial_measurements": MessageLookupByLibrary.simpleMessage( "Первичные замеры", ), + "insights_add_measures_empty": MessageLookupByLibrary.simpleMessage( + "Добавьте Ваши замеры", + ), + "insights_add_record": MessageLookupByLibrary.simpleMessage( + "Добавить запись", + ), + "insights_add_weight_empty": MessageLookupByLibrary.simpleMessage( + "Добавьте Ваш вес", + ), + "insights_bmi_higher": m1, + "insights_bmi_hint": m2, + "insights_bmi_lower": m3, + "insights_bmi_normal": MessageLookupByLibrary.simpleMessage("норма"), + "insights_bmi_obesity_1": MessageLookupByLibrary.simpleMessage( + "ожирение I ст.", + ), + "insights_bmi_obesity_2": MessageLookupByLibrary.simpleMessage( + "ожирение II ст.", + ), + "insights_bmi_obesity_3": MessageLookupByLibrary.simpleMessage( + "ожирение III ст.", + ), + "insights_bmi_overweight": MessageLookupByLibrary.simpleMessage( + "избыточная масса", + ), + "insights_bmi_same": m4, + "insights_bmi_severe_underweight": MessageLookupByLibrary.simpleMessage( + "выраженный дефицит массы", + ), + "insights_bmi_underweight": MessageLookupByLibrary.simpleMessage( + "недостаточная масса", + ), + "insights_intra_hint": MessageLookupByLibrary.simpleMessage( + "Столбики показывают, из чего состоят приёмы пищи: белки, жиры и углеводы в ккал. Линии — сытость и настроение по шкале от 0 до 5.", + ), + "insights_load_error": MessageLookupByLibrary.simpleMessage( + "Не удалось загрузить аналитику", + ), + "insights_measure_less": m5, + "insights_measure_more": m6, + "insights_measure_same": m7, + "insights_measures_summary": m8, + "insights_need_height": MessageLookupByLibrary.simpleMessage( + "Укажите рост, чтобы посчитать ИМТ.", + ), + "insights_next_day": MessageLookupByLibrary.simpleMessage("Следующий день"), + "insights_not_enough": MessageLookupByLibrary.simpleMessage( + "Недостаточно данных", + ), + "insights_period_1m": MessageLookupByLibrary.simpleMessage("1М"), + "insights_period_1w": MessageLookupByLibrary.simpleMessage("1Н"), + "insights_period_1y": MessageLookupByLibrary.simpleMessage("1Г"), + "insights_period_2w": MessageLookupByLibrary.simpleMessage("2Н"), + "insights_period_3m": MessageLookupByLibrary.simpleMessage("3М"), + "insights_period_6m": MessageLookupByLibrary.simpleMessage("6М"), + "insights_period_all": MessageLookupByLibrary.simpleMessage("Всё время"), + "insights_period_label_1": MessageLookupByLibrary.simpleMessage("месяц"), + "insights_period_label_12": MessageLookupByLibrary.simpleMessage("год"), + "insights_period_label_3": MessageLookupByLibrary.simpleMessage("3 месяца"), + "insights_period_label_6": MessageLookupByLibrary.simpleMessage( + "6 месяцев", + ), + "insights_period_label_all": MessageLookupByLibrary.simpleMessage( + "всё время", + ), + "insights_pick_date": MessageLookupByLibrary.simpleMessage("Выбрать дату"), + "insights_prev_day": MessageLookupByLibrary.simpleMessage( + "Предыдущий день", + ), + "insights_retry": MessageLookupByLibrary.simpleMessage("Повторить"), + "insights_save_error": MessageLookupByLibrary.simpleMessage( + "Не удалось сохранить запись", + ), + "insights_series_calories": MessageLookupByLibrary.simpleMessage("Калории"), + "insights_series_carbs": MessageLookupByLibrary.simpleMessage("Углеводы"), + "insights_series_chest": MessageLookupByLibrary.simpleMessage("Грудь"), + "insights_series_fats": MessageLookupByLibrary.simpleMessage("Жиры"), + "insights_series_hips": MessageLookupByLibrary.simpleMessage("Бёдра"), + "insights_series_mood": MessageLookupByLibrary.simpleMessage("Настроение"), + "insights_series_proteins": MessageLookupByLibrary.simpleMessage("Белки"), + "insights_series_satiety": MessageLookupByLibrary.simpleMessage("Сытость"), + "insights_series_sleep": MessageLookupByLibrary.simpleMessage( + "Сон и подъём", + ), + "insights_series_waist": MessageLookupByLibrary.simpleMessage("Талия"), + "insights_sleep_at": m9, + "insights_sleep_shade": MessageLookupByLibrary.simpleMessage( + "Затемнение — время сна", + ), + "insights_subtitle_closed": MessageLookupByLibrary.simpleMessage( + "нажмите, чтобы посмотреть прогресс", + ), + "insights_subtitle_open": MessageLookupByLibrary.simpleMessage( + "вес, замеры и питание", + ), + "insights_tab_bmi": MessageLookupByLibrary.simpleMessage("ИМТ"), + "insights_tab_daily": MessageLookupByLibrary.simpleMessage("КБЖУ по дням"), + "insights_tab_intra": MessageLookupByLibrary.simpleMessage("В течение дня"), + "insights_tab_measures": MessageLookupByLibrary.simpleMessage("Замеры"), + "insights_tab_weight": MessageLookupByLibrary.simpleMessage("Вес"), + "insights_title": MessageLookupByLibrary.simpleMessage("Аналитика"), + "insights_today": MessageLookupByLibrary.simpleMessage("Сегодня"), + "insights_unit_bmi": MessageLookupByLibrary.simpleMessage("ИМТ"), + "insights_unit_cm": MessageLookupByLibrary.simpleMessage("см"), + "insights_unit_cm_waist": MessageLookupByLibrary.simpleMessage("см талия"), + "insights_unit_grams": MessageLookupByLibrary.simpleMessage("граммы"), + "insights_unit_kcal": MessageLookupByLibrary.simpleMessage("ккал"), + "insights_unit_kcal_avg": MessageLookupByLibrary.simpleMessage( + "ккал в среднем", + ), + "insights_unit_kcal_per_meal": MessageLookupByLibrary.simpleMessage( + "ккал за приём", + ), + "insights_unit_kg": MessageLookupByLibrary.simpleMessage("кг"), + "insights_wake_at": m10, + "insights_weight_gained": m11, + "insights_weight_lost": m12, + "insights_weight_same": m13, "label": MessageLookupByLibrary.simpleMessage("Название"), "language": MessageLookupByLibrary.simpleMessage("Язык"), "last_name": MessageLookupByLibrary.simpleMessage("Фамилия"), @@ -262,6 +443,10 @@ class MessageLookup extends MessageLookupByLibrary { ), "no": MessageLookupByLibrary.simpleMessage("Нет"), "no_account": MessageLookupByLibrary.simpleMessage("У меня нет аккаунта"), + "no_active_personal_diet_consultations": + MessageLookupByLibrary.simpleMessage( + "Нет активных консультаций с персональной диетой", + ), "no_installed_banks": MessageLookupByLibrary.simpleMessage( "Нет установленных банков", ), @@ -284,6 +469,9 @@ class MessageLookup extends MessageLookupByLibrary { ), "option_title": MessageLookupByLibrary.simpleMessage("Заголовок опции"), "order": MessageLookupByLibrary.simpleMessage("Порядок"), + "orderCanceled": MessageLookupByLibrary.simpleMessage("Заказ отменен"), + "order_in_progress": MessageLookupByLibrary.simpleMessage("Заказ в работе"), + "order_paid": MessageLookupByLibrary.simpleMessage("Заказ оплачен"), "password": MessageLookupByLibrary.simpleMessage("Пароль"), "password_confirmation": MessageLookupByLibrary.simpleMessage( "Подтвердите пароль", @@ -297,8 +485,29 @@ class MessageLookup extends MessageLookupByLibrary { "password_short": MessageLookupByLibrary.simpleMessage( "В пароле должно быть минимум 6 символов", ), + "pay_by_qr_code": MessageLookupByLibrary.simpleMessage( + "Оплатить по QR-коду", + ), + "payment_failed": MessageLookupByLibrary.simpleMessage("Оплата не прошла"), "pcs": MessageLookupByLibrary.simpleMessage("шт"), "personal": MessageLookupByLibrary.simpleMessage("Персональные"), + "personal_diet_defined_to_author": m14, + "personal_diet_defined_to_author_named": m15, + "personal_diet_duration_hint": m16, + "personal_diet_duration_mismatch": m17, + "personal_diet_not_proposed": MessageLookupByLibrary.simpleMessage( + "Диета не предложена", + ), + "personal_diet_proposed": MessageLookupByLibrary.simpleMessage( + "Диета предложена", + ), + "personal_diet_proposed_named": m18, + "personal_diet_replaces_tomorrow": MessageLookupByLibrary.simpleMessage( + "Замена действует со следующего дня", + ), + "personal_diet_set": MessageLookupByLibrary.simpleMessage( + "Персональная диета установлена", + ), "personal_diet_state": MessageLookupByLibrary.simpleMessage("Персональная"), "photo": MessageLookupByLibrary.simpleMessage("Фото"), "place_of_living": MessageLookupByLibrary.simpleMessage("Место проживания"), @@ -308,6 +517,7 @@ class MessageLookup extends MessageLookupByLibrary { "Большое подробное, привлекательное описание плана", ), "plan_duration": MessageLookupByLibrary.simpleMessage("Срок плана"), + "plan_duration_label": m21, "plan_label_desc": MessageLookupByLibrary.simpleMessage( "План для поддержания формы", ), @@ -335,7 +545,7 @@ class MessageLookup extends MessageLookupByLibrary { "Промокод применён!", ), "promo_code": MessageLookupByLibrary.simpleMessage("Промокод"), - "promo_discount_hint": m3, + "promo_discount_hint": m22, "promo_invalid": MessageLookupByLibrary.simpleMessage( "Промокод не найден или истёк", ), @@ -354,6 +564,34 @@ class MessageLookup extends MessageLookupByLibrary { "sbp_payment_error": MessageLookupByLibrary.simpleMessage( "Не удалось начать оплату. Попробуйте позже", ), + "sbp_qr_amount_label": MessageLookupByLibrary.simpleMessage( + "Сумма к оплате", + ), + "sbp_qr_open_test_payment": MessageLookupByLibrary.simpleMessage( + "Открыть тестовую оплату", + ), + "sbp_qr_paid_description": MessageLookupByLibrary.simpleMessage( + "Консультация оплачена. Можно вернуться в чат.", + ), + "sbp_qr_paid_title": MessageLookupByLibrary.simpleMessage( + "Оплата прошла успешно!", + ), + "sbp_qr_step1": MessageLookupByLibrary.simpleMessage( + "Откройте приложение банка на телефоне", + ), + "sbp_qr_step2": MessageLookupByLibrary.simpleMessage( + "Выберите «Оплата по QR-коду»", + ), + "sbp_qr_step3": MessageLookupByLibrary.simpleMessage( + "Наведите камеру на код", + ), + "sbp_qr_test_hint": MessageLookupByLibrary.simpleMessage( + "Симуляция оплаты на тестовом стенде Альфа-Банка", + ), + "sbp_qr_title": MessageLookupByLibrary.simpleMessage("Оплата по QR-коду"), + "sbp_qr_waiting_payment": MessageLookupByLibrary.simpleMessage( + "Ожидание оплаты…", + ), "services": MessageLookupByLibrary.simpleMessage("Оказание услуг"), "settings": MessageLookupByLibrary.simpleMessage("Настройки"), "share": MessageLookupByLibrary.simpleMessage("Поделиться"), @@ -364,7 +602,12 @@ class MessageLookup extends MessageLookupByLibrary { "План питания для похудения должен быть разработан с учётом индивидуальных особенностей организма, возраста, пола, уровня физической активности и состояния здоровья. Общие принципы: \n● Снижение калорийности; \n● Сбалансированный рацион; \n● Разнообразие продуктов; \n● Питьевой режим; \n● Ограничение вредных продуктов;", ), "standard": MessageLookupByLibrary.simpleMessage("Стандарт"), + "startDateHasBeenSet": MessageLookupByLibrary.simpleMessage( + "Выбрана дата старта", + ), "startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"), + "start_date_label": m23, + "suggestDiet": MessageLookupByLibrary.simpleMessage("Предложить диету"), "tell_your_schedule": MessageLookupByLibrary.simpleMessage( "Расскажите в свободной форме о том как просыпаетесь, когда едите, когда ложитесь спать:", ), @@ -441,6 +684,57 @@ class MessageLookup extends MessageLookupByLibrary { "video_call_recording_notice": MessageLookupByLibrary.simpleMessage( "Видеозвонок будет записан.\nКонсультация может быть проверена сотрудниками Итвио, на предмет качества оказания услуг.", ), + "video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage( + "Видеоконсультация со специалистом по питанию", + ), + "video_call_recordings_download": MessageLookupByLibrary.simpleMessage( + "Скачать", + ), + "video_call_recordings_download_error": + MessageLookupByLibrary.simpleMessage( + "Не удалось скачать запись. Попробуйте позже.", + ), + "video_call_recordings_download_success": + MessageLookupByLibrary.simpleMessage( + "Запись сохранена в Загрузки/Itvio", + ), + "video_call_recordings_download_success_ios": + MessageLookupByLibrary.simpleMessage( + "Запись сохранена в приложении «Файлы»", + ), + "video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage( + "Скачивание…", + ), + "video_call_recordings_downloading_percent": m30, + "video_call_recordings_empty": MessageLookupByLibrary.simpleMessage( + "Пока нет видеоконсультаций", + ), + "video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage( + "Всё время", + ), + "video_call_recordings_period_current_month": + MessageLookupByLibrary.simpleMessage("Текущий месяц"), + "video_call_recordings_period_prev_month": + MessageLookupByLibrary.simpleMessage("Прошлый месяц"), + "video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage( + "Сегодня", + ), + "video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage( + "7 дней", + ), + "video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage( + "Не удалось воспроизвести запись", + ), + "video_call_recordings_processing": MessageLookupByLibrary.simpleMessage( + "Запись обрабатывается…", + ), + "video_call_recordings_retention_tooltip": + MessageLookupByLibrary.simpleMessage( + "Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.", + ), + "video_call_recordings_title": MessageLookupByLibrary.simpleMessage( + "Мои консультации", + ), "video_call_role_consultant": MessageLookupByLibrary.simpleMessage( "Консультант Итвио", ), diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index f6d24a07..fcafdb73 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -2689,6 +2689,116 @@ class S { ); } + /// `Оплатить по QR-коду` + String get pay_by_qr_code { + return Intl.message( + 'Оплатить по QR-коду', + name: 'pay_by_qr_code', + desc: '', + args: [], + ); + } + + /// `Оплата по QR-коду` + String get sbp_qr_title { + return Intl.message( + 'Оплата по QR-коду', + name: 'sbp_qr_title', + desc: '', + args: [], + ); + } + + /// `Сумма к оплате` + String get sbp_qr_amount_label { + return Intl.message( + 'Сумма к оплате', + name: 'sbp_qr_amount_label', + desc: '', + args: [], + ); + } + + /// `Откройте приложение банка на телефоне` + String get sbp_qr_step1 { + return Intl.message( + 'Откройте приложение банка на телефоне', + name: 'sbp_qr_step1', + desc: '', + args: [], + ); + } + + /// `Выберите «Оплата по QR-коду»` + String get sbp_qr_step2 { + return Intl.message( + 'Выберите «Оплата по QR-коду»', + name: 'sbp_qr_step2', + desc: '', + args: [], + ); + } + + /// `Наведите камеру на код` + String get sbp_qr_step3 { + return Intl.message( + 'Наведите камеру на код', + name: 'sbp_qr_step3', + desc: '', + args: [], + ); + } + + /// `Ожидание оплаты…` + String get sbp_qr_waiting_payment { + return Intl.message( + 'Ожидание оплаты…', + name: 'sbp_qr_waiting_payment', + desc: '', + args: [], + ); + } + + /// `Оплата прошла успешно!` + String get sbp_qr_paid_title { + return Intl.message( + 'Оплата прошла успешно!', + name: 'sbp_qr_paid_title', + desc: '', + args: [], + ); + } + + /// `Консультация оплачена. Можно вернуться в чат.` + String get sbp_qr_paid_description { + return Intl.message( + 'Консультация оплачена. Можно вернуться в чат.', + name: 'sbp_qr_paid_description', + desc: '', + args: [], + ); + } + + /// `Открыть тестовую оплату` + String get sbp_qr_open_test_payment { + return Intl.message( + 'Открыть тестовую оплату', + name: 'sbp_qr_open_test_payment', + desc: '', + args: [], + ); + } + + /// `Симуляция оплаты на тестовом стенде Альфа-Банка` + String get sbp_qr_test_hint { + return Intl.message( + 'Симуляция оплаты на тестовом стенде Альфа-Банка', + name: 'sbp_qr_test_hint', + desc: '', + args: [], + ); + } + /// `Подробнее о заказе` String get more_about_order { return Intl.message( @@ -4443,6 +4553,974 @@ class S { args: [], ); } + + /// `Analytics` + String get insights_title { + return Intl.message( + 'Analytics', + name: 'insights_title', + desc: '', + args: [], + ); + } + + /// `tap to see your progress` + String get insights_subtitle_closed { + return Intl.message( + 'tap to see your progress', + name: 'insights_subtitle_closed', + desc: '', + args: [], + ); + } + + /// `weight, measurements and nutrition` + String get insights_subtitle_open { + return Intl.message( + 'weight, measurements and nutrition', + name: 'insights_subtitle_open', + desc: '', + args: [], + ); + } + + /// `Weight` + String get insights_tab_weight { + return Intl.message( + 'Weight', + name: 'insights_tab_weight', + desc: '', + args: [], + ); + } + + /// `BMI` + String get insights_tab_bmi { + return Intl.message('BMI', name: 'insights_tab_bmi', desc: '', args: []); + } + + /// `Measurements` + String get insights_tab_measures { + return Intl.message( + 'Measurements', + name: 'insights_tab_measures', + desc: '', + args: [], + ); + } + + /// `Nutrition by day` + String get insights_tab_daily { + return Intl.message( + 'Nutrition by day', + name: 'insights_tab_daily', + desc: '', + args: [], + ); + } + + /// `Throughout the day` + String get insights_tab_intra { + return Intl.message( + 'Throughout the day', + name: 'insights_tab_intra', + desc: '', + args: [], + ); + } + + /// `1M` + String get insights_period_1m { + return Intl.message('1M', name: 'insights_period_1m', desc: '', args: []); + } + + /// `3M` + String get insights_period_3m { + return Intl.message('3M', name: 'insights_period_3m', desc: '', args: []); + } + + /// `6M` + String get insights_period_6m { + return Intl.message('6M', name: 'insights_period_6m', desc: '', args: []); + } + + /// `1Y` + String get insights_period_1y { + return Intl.message('1Y', name: 'insights_period_1y', desc: '', args: []); + } + + /// `All time` + String get insights_period_all { + return Intl.message( + 'All time', + name: 'insights_period_all', + desc: '', + args: [], + ); + } + + /// `1W` + String get insights_period_1w { + return Intl.message('1W', name: 'insights_period_1w', desc: '', args: []); + } + + /// `2W` + String get insights_period_2w { + return Intl.message('2W', name: 'insights_period_2w', desc: '', args: []); + } + + /// `Waist` + String get insights_series_waist { + return Intl.message( + 'Waist', + name: 'insights_series_waist', + desc: '', + args: [], + ); + } + + /// `Chest` + String get insights_series_chest { + return Intl.message( + 'Chest', + name: 'insights_series_chest', + desc: '', + args: [], + ); + } + + /// `Hips` + String get insights_series_hips { + return Intl.message( + 'Hips', + name: 'insights_series_hips', + desc: '', + args: [], + ); + } + + /// `Calories` + String get insights_series_calories { + return Intl.message( + 'Calories', + name: 'insights_series_calories', + desc: '', + args: [], + ); + } + + /// `Protein` + String get insights_series_proteins { + return Intl.message( + 'Protein', + name: 'insights_series_proteins', + desc: '', + args: [], + ); + } + + /// `Fat` + String get insights_series_fats { + return Intl.message( + 'Fat', + name: 'insights_series_fats', + desc: '', + args: [], + ); + } + + /// `Carbs` + String get insights_series_carbs { + return Intl.message( + 'Carbs', + name: 'insights_series_carbs', + desc: '', + args: [], + ); + } + + /// `Satiety` + String get insights_series_satiety { + return Intl.message( + 'Satiety', + name: 'insights_series_satiety', + desc: '', + args: [], + ); + } + + /// `Mood` + String get insights_series_mood { + return Intl.message( + 'Mood', + name: 'insights_series_mood', + desc: '', + args: [], + ); + } + + /// `Sleep and wake-up` + String get insights_series_sleep { + return Intl.message( + 'Sleep and wake-up', + name: 'insights_series_sleep', + desc: '', + args: [], + ); + } + + /// `kg` + String get insights_unit_kg { + return Intl.message('kg', name: 'insights_unit_kg', desc: '', args: []); + } + + /// `BMI` + String get insights_unit_bmi { + return Intl.message('BMI', name: 'insights_unit_bmi', desc: '', args: []); + } + + /// `cm` + String get insights_unit_cm { + return Intl.message('cm', name: 'insights_unit_cm', desc: '', args: []); + } + + /// `cm waist` + String get insights_unit_cm_waist { + return Intl.message( + 'cm waist', + name: 'insights_unit_cm_waist', + desc: '', + args: [], + ); + } + + /// `kcal` + String get insights_unit_kcal { + return Intl.message('kcal', name: 'insights_unit_kcal', desc: '', args: []); + } + + /// `kcal on average` + String get insights_unit_kcal_avg { + return Intl.message( + 'kcal on average', + name: 'insights_unit_kcal_avg', + desc: '', + args: [], + ); + } + + /// `grams` + String get insights_unit_grams { + return Intl.message( + 'grams', + name: 'insights_unit_grams', + desc: '', + args: [], + ); + } + + /// `kcal per meal` + String get insights_unit_kcal_per_meal { + return Intl.message( + 'kcal per meal', + name: 'insights_unit_kcal_per_meal', + desc: '', + args: [], + ); + } + + /// `month` + String get insights_period_label_1 { + return Intl.message( + 'month', + name: 'insights_period_label_1', + desc: '', + args: [], + ); + } + + /// `3 months` + String get insights_period_label_3 { + return Intl.message( + '3 months', + name: 'insights_period_label_3', + desc: '', + args: [], + ); + } + + /// `6 months` + String get insights_period_label_6 { + return Intl.message( + '6 months', + name: 'insights_period_label_6', + desc: '', + args: [], + ); + } + + /// `year` + String get insights_period_label_12 { + return Intl.message( + 'year', + name: 'insights_period_label_12', + desc: '', + args: [], + ); + } + + /// `all time` + String get insights_period_label_all { + return Intl.message( + 'all time', + name: 'insights_period_label_all', + desc: '', + args: [], + ); + } + + /// `Not enough data` + String get insights_not_enough { + return Intl.message( + 'Not enough data', + name: 'insights_not_enough', + desc: '', + args: [], + ); + } + + /// `Set your height to calculate BMI.` + String get insights_need_height { + return Intl.message( + 'Set your height to calculate BMI.', + name: 'insights_need_height', + desc: '', + args: [], + ); + } + + /// `Lost {value} kg over {period}` + String insights_weight_lost(String value, String period) { + return Intl.message( + 'Lost $value kg over $period', + name: 'insights_weight_lost', + desc: '', + args: [value, period], + ); + } + + /// `Gained {value} kg over {period}` + String insights_weight_gained(String value, String period) { + return Intl.message( + 'Gained $value kg over $period', + name: 'insights_weight_gained', + desc: '', + args: [value, period], + ); + } + + /// `Weight unchanged over {period}` + String insights_weight_same(String period) { + return Intl.message( + 'Weight unchanged over $period', + name: 'insights_weight_same', + desc: '', + args: [period], + ); + } + + /// `BMI lower by {value} over {period} · {category}` + String insights_bmi_lower(String value, String period, String category) { + return Intl.message( + 'BMI lower by $value over $period · $category', + name: 'insights_bmi_lower', + desc: '', + args: [value, period, category], + ); + } + + /// `BMI higher by {value} over {period} · {category}` + String insights_bmi_higher(String value, String period, String category) { + return Intl.message( + 'BMI higher by $value over $period · $category', + name: 'insights_bmi_higher', + desc: '', + args: [value, period, category], + ); + } + + /// `BMI unchanged over {period} · {category}` + String insights_bmi_same(String period, String category) { + return Intl.message( + 'BMI unchanged over $period · $category', + name: 'insights_bmi_same', + desc: '', + args: [period, category], + ); + } + + /// `Green zone is normal (18.5–25), yellow is overweight, pink is obesity. Calculated for a height of {height} cm.` + String insights_bmi_hint(String height) { + return Intl.message( + 'Green zone is normal (18.5–25), yellow is overweight, pink is obesity. Calculated for a height of $height cm.', + name: 'insights_bmi_hint', + desc: '', + args: [height], + ); + } + + /// `severe underweight` + String get insights_bmi_severe_underweight { + return Intl.message( + 'severe underweight', + name: 'insights_bmi_severe_underweight', + desc: '', + args: [], + ); + } + + /// `underweight` + String get insights_bmi_underweight { + return Intl.message( + 'underweight', + name: 'insights_bmi_underweight', + desc: '', + args: [], + ); + } + + /// `normal` + String get insights_bmi_normal { + return Intl.message( + 'normal', + name: 'insights_bmi_normal', + desc: '', + args: [], + ); + } + + /// `overweight` + String get insights_bmi_overweight { + return Intl.message( + 'overweight', + name: 'insights_bmi_overweight', + desc: '', + args: [], + ); + } + + /// `obesity class I` + String get insights_bmi_obesity_1 { + return Intl.message( + 'obesity class I', + name: 'insights_bmi_obesity_1', + desc: '', + args: [], + ); + } + + /// `obesity class II` + String get insights_bmi_obesity_2 { + return Intl.message( + 'obesity class II', + name: 'insights_bmi_obesity_2', + desc: '', + args: [], + ); + } + + /// `obesity class III` + String get insights_bmi_obesity_3 { + return Intl.message( + 'obesity class III', + name: 'insights_bmi_obesity_3', + desc: '', + args: [], + ); + } + + /// `{name} down {value} cm` + String insights_measure_less(String name, String value) { + return Intl.message( + '$name down $value cm', + name: 'insights_measure_less', + desc: '', + args: [name, value], + ); + } + + /// `{name} up {value} cm` + String insights_measure_more(String name, String value) { + return Intl.message( + '$name up $value cm', + name: 'insights_measure_more', + desc: '', + args: [name, value], + ); + } + + /// `{name} unchanged` + String insights_measure_same(String name) { + return Intl.message( + '$name unchanged', + name: 'insights_measure_same', + desc: '', + args: [name], + ); + } + + /// `{parts} over {period}` + String insights_measures_summary(String parts, String period) { + return Intl.message( + '$parts over $period', + name: 'insights_measures_summary', + desc: '', + args: [parts, period], + ); + } + + /// `Add entry` + String get insights_add_record { + return Intl.message( + 'Add entry', + name: 'insights_add_record', + desc: '', + args: [], + ); + } + + /// `Add your weight` + String get insights_add_weight_empty { + return Intl.message( + 'Add your weight', + name: 'insights_add_weight_empty', + desc: '', + args: [], + ); + } + + /// `Add your measurements` + String get insights_add_measures_empty { + return Intl.message( + 'Add your measurements', + name: 'insights_add_measures_empty', + desc: '', + args: [], + ); + } + + /// `Failed to load analytics` + String get insights_load_error { + return Intl.message( + 'Failed to load analytics', + name: 'insights_load_error', + desc: '', + args: [], + ); + } + + /// `Retry` + String get insights_retry { + return Intl.message('Retry', name: 'insights_retry', desc: '', args: []); + } + + /// `Bars show what each meal consists of: protein, fat and carbs in kcal. Lines show satiety and mood on a 0–5 scale.` + String get insights_intra_hint { + return Intl.message( + 'Bars show what each meal consists of: protein, fat and carbs in kcal. Lines show satiety and mood on a 0–5 scale.', + name: 'insights_intra_hint', + desc: '', + args: [], + ); + } + + /// `Shading — sleep time` + String get insights_sleep_shade { + return Intl.message( + 'Shading — sleep time', + name: 'insights_sleep_shade', + desc: '', + args: [], + ); + } + + /// `Wake-up at {time}` + String insights_wake_at(String time) { + return Intl.message( + 'Wake-up at $time', + name: 'insights_wake_at', + desc: '', + args: [time], + ); + } + + /// `Bedtime at {time}` + String insights_sleep_at(String time) { + return Intl.message( + 'Bedtime at $time', + name: 'insights_sleep_at', + desc: '', + args: [time], + ); + } + + /// `Previous day` + String get insights_prev_day { + return Intl.message( + 'Previous day', + name: 'insights_prev_day', + desc: '', + args: [], + ); + } + + /// `Next day` + String get insights_next_day { + return Intl.message( + 'Next day', + name: 'insights_next_day', + desc: '', + args: [], + ); + } + + /// `Pick a date` + String get insights_pick_date { + return Intl.message( + 'Pick a date', + name: 'insights_pick_date', + desc: '', + args: [], + ); + } + + /// `Today` + String get insights_today { + return Intl.message('Today', name: 'insights_today', desc: '', args: []); + } + + /// `Failed to save the entry` + String get insights_save_error { + return Intl.message( + 'Failed to save the entry', + name: 'insights_save_error', + desc: '', + args: [], + ); + } + + /// `Order in progress` + String get order_in_progress { + return Intl.message( + 'Order in progress', + name: 'order_in_progress', + desc: '', + args: [], + ); + } + + /// `Personal diet proposed` + String get personal_diet_proposed { + return Intl.message( + 'Personal diet proposed', + name: 'personal_diet_proposed', + desc: '', + args: [], + ); + } + + /// `Diet «{name}» proposed` + String personal_diet_proposed_named(String name) { + return Intl.message( + 'Diet «$name» proposed', + name: 'personal_diet_proposed_named', + desc: '', + args: [name], + ); + } + + /// `User` + String get default_user_name { + return Intl.message('User', name: 'default_user_name', desc: '', args: []); + } + + /// `You have proposed a personal diet to {userName}` + String personal_diet_defined_to_author(String userName) { + return Intl.message( + 'You have proposed a personal diet to $userName', + name: 'personal_diet_defined_to_author', + desc: '', + args: [userName], + ); + } + + /// `You have proposed a personal diet to {userName}, selected diet: «{dietName}»` + String personal_diet_defined_to_author_named( + String userName, + String dietName, + ) { + return Intl.message( + 'You have proposed a personal diet to $userName, selected diet: «$dietName»', + name: 'personal_diet_defined_to_author_named', + desc: '', + args: [userName, dietName], + ); + } + + /// `Personal diet not proposed` + String get personal_diet_not_proposed { + return Intl.message( + 'Personal diet not proposed', + name: 'personal_diet_not_proposed', + desc: '', + args: [], + ); + } + + /// `Change personal diet` + String get change_personal_diet { + return Intl.message( + 'Change personal diet', + name: 'change_personal_diet', + desc: '', + args: [], + ); + } + + /// `The change takes effect tomorrow` + String get personal_diet_replaces_tomorrow { + return Intl.message( + 'The change takes effect tomorrow', + name: 'personal_diet_replaces_tomorrow', + desc: '', + args: [], + ); + } + + /// `Start: {date}` + String start_date_label(String date) { + return Intl.message( + 'Start: $date', + name: 'start_date_label', + desc: '', + args: [date], + ); + } + + /// `The diet lasts {duration} {dayWord}. It can only be offered for a plan with the same duration.` + String personal_diet_duration_hint(int duration, String dayWord) { + return Intl.message( + 'The diet lasts $duration $dayWord. It can only be offered for a plan with the same duration.', + name: 'personal_diet_duration_hint', + desc: '', + args: [duration, dayWord], + ); + } + + /// `Not suitable: diet lasts {dietDuration} {dietDayWord}, plan lasts {planDuration} {planDayWord}.` + String personal_diet_duration_mismatch( + int dietDuration, + String dietDayWord, + int planDuration, + String planDayWord, + ) { + return Intl.message( + 'Not suitable: diet lasts $dietDuration $dietDayWord, plan lasts $planDuration $planDayWord.', + name: 'personal_diet_duration_mismatch', + desc: '', + args: [dietDuration, dietDayWord, planDuration, planDayWord], + ); + } + + /// `Plan for {duration} {dayWord}` + String plan_duration_label(int duration, String dayWord) { + return Intl.message( + 'Plan for $duration $dayWord', + name: 'plan_duration_label', + desc: '', + args: [duration, dayWord], + ); + } + + /// `No active consultations with a personal diet` + String get no_active_personal_diet_consultations { + return Intl.message( + 'No active consultations with a personal diet', + name: 'no_active_personal_diet_consultations', + desc: '', + args: [], + ); + } + + /// `My consultations` + String get video_call_recordings_title { + return Intl.message( + 'My consultations', + name: 'video_call_recordings_title', + desc: '', + args: [], + ); + } + + /// `Video consultation recordings are stored on Eatvio servers for 1 year.` + String get video_call_recordings_retention_tooltip { + return Intl.message( + 'Video consultation recordings are stored on Eatvio servers for 1 year.', + name: 'video_call_recordings_retention_tooltip', + desc: '', + args: [], + ); + } + + /// `No video consultations yet` + String get video_call_recordings_empty { + return Intl.message( + 'No video consultations yet', + name: 'video_call_recordings_empty', + desc: '', + args: [], + ); + } + + /// `Recording is being processed…` + String get video_call_recordings_processing { + return Intl.message( + 'Recording is being processed…', + name: 'video_call_recordings_processing', + desc: '', + args: [], + ); + } + + /// `Download` + String get video_call_recordings_download { + return Intl.message( + 'Download', + name: 'video_call_recordings_download', + desc: '', + args: [], + ); + } + + /// `Downloading…` + String get video_call_recordings_downloading { + return Intl.message( + 'Downloading…', + name: 'video_call_recordings_downloading', + desc: '', + args: [], + ); + } + + /// `Downloading… {percent}%` + String video_call_recordings_downloading_percent(int percent) { + return Intl.message( + 'Downloading… $percent%', + name: 'video_call_recordings_downloading_percent', + desc: '', + args: [percent], + ); + } + + /// `Could not download the recording. Please try again later.` + String get video_call_recordings_download_error { + return Intl.message( + 'Could not download the recording. Please try again later.', + name: 'video_call_recordings_download_error', + desc: '', + args: [], + ); + } + + /// `Recording saved to Downloads/Itvio` + String get video_call_recordings_download_success { + return Intl.message( + 'Recording saved to Downloads/Itvio', + name: 'video_call_recordings_download_success', + desc: '', + args: [], + ); + } + + /// `Recording saved to the Files app` + String get video_call_recordings_download_success_ios { + return Intl.message( + 'Recording saved to the Files app', + name: 'video_call_recordings_download_success_ios', + desc: '', + args: [], + ); + } + + /// `Could not play the recording` + String get video_call_recordings_player_error { + return Intl.message( + 'Could not play the recording', + name: 'video_call_recordings_player_error', + desc: '', + args: [], + ); + } + + /// `Video consultation with a nutrition specialist` + String get video_call_recordings_card_title { + return Intl.message( + 'Video consultation with a nutrition specialist', + name: 'video_call_recordings_card_title', + desc: '', + args: [], + ); + } + + /// `Today` + String get video_call_recordings_period_today { + return Intl.message( + 'Today', + name: 'video_call_recordings_period_today', + desc: '', + args: [], + ); + } + + /// `7 days` + String get video_call_recordings_period_week { + return Intl.message( + '7 days', + name: 'video_call_recordings_period_week', + desc: '', + args: [], + ); + } + + /// `Current month` + String get video_call_recordings_period_current_month { + return Intl.message( + 'Current month', + name: 'video_call_recordings_period_current_month', + desc: '', + args: [], + ); + } + + /// `Previous month` + String get video_call_recordings_period_prev_month { + return Intl.message( + 'Previous month', + name: 'video_call_recordings_period_prev_month', + desc: '', + args: [], + ); + } + + /// `All time` + String get video_call_recordings_period_all { + return Intl.message( + 'All time', + name: 'video_call_recordings_period_all', + desc: '', + args: [], + ); + } } class AppLocalizationDelegate extends LocalizationsDelegate { diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index bd2406d8..f7da7936 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -210,27 +210,27 @@ "personal": "Персональные", "edit": "Редактировать", "toOffer": "Предложить", - "removeFromActive": "Снять с публикации", + "removeFromActive": "Снять с публикации", "diet": "Диета", "deleted": "Удалена", "my_plans": "Мои планы", - "from": "от", + "from": "от", "user_data": "Данные пользователя", "general_info": "Общая информация", "sex": "Пол", - "physical_fitness": "Физическая форма", + "physical_fitness": "Физическая форма", "height": "Рост", "pressure": "Давление", "upper": "Верхнее", "lower": "Нижнее", "has_hypo": "Склонность к гипотонии", - "has_hyper": "Склонность к гипертонии", + "has_hyper": "Склонность к гипертонии", "other_info": "Прочая информация", "has_alergy": "Наличие аллергии", "takes_pills": "Принимает лекарства", "sport_hobbies": "Спортивные увлечения", "liked_groceries": "Любимые продукты", - "not_liked_groceries": "Не любимые продукты", + "not_liked_groceries": "Не любимые продукты", "diet_started": "Диета уже начата", "cancel_diet": "Отменить диету?", "confirm": "Подтвердить", @@ -239,7 +239,7 @@ "hour": "час", "another_form_of_hour": "часа", "minutes": "минуты", - "minute": "минута", + "minute": "минута", "another_form_of_minute": "минут", "there_is_a_video": "Есть видео", "recipe_author": "Автор рецепта", @@ -323,22 +323,33 @@ "can_not_choose_start_date": "Дату старта плана невозможно выбрать, пока Вы не привяжите карту", "add_card": "Привязать карту", "choose_plan_start_date": "Выберите дату старта плана питания", - "choose_date": "Выбрать дату", - "date_has_ben_set": "Дата старта начала консультации установлена", + "choose_date": "Выбрать дату", + "date_has_ben_set": "Дата старта начала консультации установлена", "tap_on_link_to_pay": "Перейдите по ссылке для оплаты консультации", "pay": "Оплатить", "choose_bank_for_payment": "Выберите банк", "no_installed_banks": "Нет установленных банков", "sbp_payment_error": "Не удалось начать оплату. Попробуйте позже", + "pay_by_qr_code": "Оплатить по QR-коду", + "sbp_qr_title": "Оплата по QR-коду", + "sbp_qr_amount_label": "Сумма к оплате", + "sbp_qr_step1": "Откройте приложение банка на телефоне", + "sbp_qr_step2": "Выберите «Оплата по QR-коду»", + "sbp_qr_step3": "Наведите камеру на код", + "sbp_qr_waiting_payment": "Ожидание оплаты…", + "sbp_qr_paid_title": "Оплата прошла успешно!", + "sbp_qr_paid_description": "Консультация оплачена. Можно вернуться в чат.", + "sbp_qr_open_test_payment": "Открыть тестовую оплату", + "sbp_qr_test_hint": "Симуляция оплаты на тестовом стенде Альфа-Банка", "more_about_order": "Подробнее о заказе", "cancel_order": "Отменить заказ", - "refuse_order":"Отказаться от заказа", + "refuse_order": "Отказаться от заказа", "user_info": "Анкета пользователя", "pending_payment": "Ожидается оплата", "my_cards": "Мои карты", "new_card": "Добавить карту", "no_default_cards": "У вас нет привязанных карт. Что бы начать работу, привяжите карту", - "chose_plan_start_date_2":"Выберите дату старты плана. Она отобразиться в дневнике пользователя", + "chose_plan_start_date_2": "Выберите дату старты плана. Она отобразиться в дневнике пользователя", "plan_seller": "Продавец плана", "payment_failed": "Оплата не прошла", "order_paid": "Заказ оплачен", @@ -385,7 +396,7 @@ "chargeApproved": "Выплата одобрена", "moneySentToCard": "Средства отправлены на карту", "chargeCollectionFailed": "Не удалось оформить выплату", - "contactSupport": "Обратитесь в поддержку", + "contactSupport": "Обратитесь в поддержку", "atLeast3Symbols": "Минимум 3 символа", "chosePlanType": "Выберите тип плана", "minPlanPrice": "Минимальная сумма 1200₽", @@ -403,13 +414,13 @@ "tomorrowYourPlanWillStart": "Завтра начнется прохождение плана «{planName}»", "planStarted": "План «{planName}» начался", "userCanceldThePlanSubscription": "Пользователь {name} отменил подписку на план «{planName}»", - "userSubscribedToPlan": "Пользователь {name} подписался на план «{planName}»", + "userSubscribedToPlan": "Пользователь {name} подписался на план «{planName}»", "markAsRead": "Отметить всё прочитанным", "allowAcessToGalery": "Разрешите доступ к фото", "allowAcessToGaleryDescription": "Предоставление доступа позволит вам добавлять фото к записям", "allowAccessToCamera": "Разрешите доступ к камере", "allowAccessToCameraDescription": "Предоставление доступа позволит вам делать фотографии и добавлять к записям", - "allowAccess": "Разрешить доступ" , + "allowAccess": "Разрешить доступ", "copy": "Скопировать", "reply": "Ответить", "deleteComment": "Удалить комментарий", @@ -420,7 +431,7 @@ "choose_plan_start_date_with_personal_diet": "Выберите дату старта плана питания с учетом составления персональной диеты", "chosenPlanStartDateDescr": "Дату старта плана можно выбрать не ранее, чем через два. Такое ограничение дается на создание персональной диеты", "createPersonalDiet": "Составьте персональную диету", - "goToMyDiets": "Перейти к моим диетам", + "goToMyDiets": "Перейти к моим диетам", "accountDeleting": "Удаление аккаунта", "youShureYouWantToDeleteAccount": "Вы уверены, что хотите удалить аккаунт?", "itCantBeRecovered": "Его нельзя будет восстановить", @@ -428,11 +439,11 @@ "cannotDeleteAccount": "Не получилось удалить ваш аккаунт", "resend": "Отправить повторно", "notifications": "Уведомления", - "step_widget": "шаг {step} из 2", + "step_widget": "шаг {step} из 2", "your_name": "Ваше имя", "your_last_name": "Ваша фамилия", "type_email": "Введите email", - "phone": "Телефон", + "phone": "Телефон", "male_short": "М", "female_short": "Ж", "next": "Далее", @@ -445,19 +456,19 @@ "activity_second_value": "1,375 — низкий (тренировки не менее 20 мин 1–3 раза в неделю)", "activity_third_value": "1,55 — умеренный (тренировки 30–60 мин 3–4 раза в неделю)", "activity_fourth_value": "1,7 — высокий (тренировки 30–60 мин 5–7 раза в неделю; тяжёлая физическая работа)", - "activity_fifth_value": "1,9 — экстремальный (несколько интенсивных тренировок в день)", + "activity_fifth_value": "1,9 — экстремальный (несколько интенсивных тренировок в день)", "registration_completed": "Регистрация завершена!", "acc_has_been_created": "Ваш аккаунт создан. Для входа используйте этот пароль:", "password_desc": "Сохраните его в надежном месте! Вы сможете изменить пароль в настройках профиля", "acc_has_been_created_btn": "Войти в аккаунт", - "first_name_validation_error": "Имя обязательно к заполнению", + "first_name_validation_error": "Имя обязательно к заполнению", "last_name_error": "Фамилия обязательна для заполнения", "email_error": "Некорректный адрес электронной почты", "phone_error": "Некорректный номер телефона", "gender_error": "Выберите пол", "date_of_birth_error": "Некорректная дата рождения", "height_error": "Введите рост", - "weight_error": "Введите вес", + "weight_error": "Введите вес", "phisical_activity": "Уровень физической активности", "copied2": "Скопировано!", "login": "Войти в аккаунт", @@ -472,7 +483,7 @@ "letsInvite": "Давайте пригласим близких в итвио", "eatvioIsAHelthyHabbit": "Итвио — это полезная привычка", "invite": "Пригласить", - "comment_hint": "Комментарий", + "comment_hint": "Комментарий", "hide_photo_title": "Спрятать фото?", "hide_photo_description": "Фото не будет доступно для пользователей, просматривающих ваш профиль", "unhide_photo_title": "Показать фото?", @@ -509,8 +520,12 @@ "promo_discount_hint": "Discount {percent}% — you save {amount} ₽", "@promo_discount_hint": { "placeholders": { - "percent": {"type": "int"}, - "amount": {"type": "String"} + "percent": { + "type": "int" + }, + "amount": { + "type": "String" + } } }, "promo_remove_failed": "Could not remove the promo code. Try again later", @@ -526,6 +541,301 @@ "video_call_close": "Close", "video_call_notification_in_progress": "Call in progress", "video_call_notification_return": "Return to call", - "video_call_notification_end": "End call" + "video_call_notification_end": "End call", + "insights_title": "Analytics", + "insights_subtitle_closed": "tap to see your progress", + "insights_subtitle_open": "weight, measurements and nutrition", + "insights_tab_weight": "Weight", + "insights_tab_bmi": "BMI", + "insights_tab_measures": "Measurements", + "insights_tab_daily": "Nutrition by day", + "insights_tab_intra": "Throughout the day", + "insights_period_1m": "1M", + "insights_period_3m": "3M", + "insights_period_6m": "6M", + "insights_period_1y": "1Y", + "insights_period_all": "All time", + "insights_period_1w": "1W", + "insights_period_2w": "2W", + "insights_series_waist": "Waist", + "insights_series_chest": "Chest", + "insights_series_hips": "Hips", + "insights_series_calories": "Calories", + "insights_series_proteins": "Protein", + "insights_series_fats": "Fat", + "insights_series_carbs": "Carbs", + "insights_series_satiety": "Satiety", + "insights_series_mood": "Mood", + "insights_series_sleep": "Sleep and wake-up", + "insights_unit_kg": "kg", + "insights_unit_bmi": "BMI", + "insights_unit_cm": "cm", + "insights_unit_cm_waist": "cm waist", + "insights_unit_kcal": "kcal", + "insights_unit_kcal_avg": "kcal on average", + "insights_unit_grams": "grams", + "insights_unit_kcal_per_meal": "kcal per meal", + "insights_period_label_1": "month", + "insights_period_label_3": "3 months", + "insights_period_label_6": "6 months", + "insights_period_label_12": "year", + "insights_period_label_all": "all time", + "insights_not_enough": "Not enough data", + "insights_need_height": "Set your height to calculate BMI.", + "insights_weight_lost": "Lost {value} kg over {period}", + "@insights_weight_lost": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_weight_gained": "Gained {value} kg over {period}", + "@insights_weight_gained": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_weight_same": "Weight unchanged over {period}", + "@insights_weight_same": { + "placeholders": { + "period": { + "type": "String" + } + } + }, + "insights_bmi_lower": "BMI lower by {value} over {period} · {category}", + "@insights_bmi_lower": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_higher": "BMI higher by {value} over {period} · {category}", + "@insights_bmi_higher": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_same": "BMI unchanged over {period} · {category}", + "@insights_bmi_same": { + "placeholders": { + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_hint": "Green zone is normal (18.5–25), yellow is overweight, pink is obesity. Calculated for a height of {height} cm.", + "@insights_bmi_hint": { + "placeholders": { + "height": { + "type": "String" + } + } + }, + "insights_bmi_severe_underweight": "severe underweight", + "insights_bmi_underweight": "underweight", + "insights_bmi_normal": "normal", + "insights_bmi_overweight": "overweight", + "insights_bmi_obesity_1": "obesity class I", + "insights_bmi_obesity_2": "obesity class II", + "insights_bmi_obesity_3": "obesity class III", + "insights_measure_less": "{name} down {value} cm", + "@insights_measure_less": { + "placeholders": { + "name": { + "type": "String" + }, + "value": { + "type": "String" + } + } + }, + "insights_measure_more": "{name} up {value} cm", + "@insights_measure_more": { + "placeholders": { + "name": { + "type": "String" + }, + "value": { + "type": "String" + } + } + }, + "insights_measure_same": "{name} unchanged", + "@insights_measure_same": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "insights_measures_summary": "{parts} over {period}", + "@insights_measures_summary": { + "placeholders": { + "parts": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_add_record": "Add entry", + "insights_add_weight_empty": "Add your weight", + "insights_add_measures_empty": "Add your measurements", + "insights_load_error": "Failed to load analytics", + "insights_retry": "Retry", + "insights_intra_hint": "Bars show what each meal consists of: protein, fat and carbs in kcal. Lines show satiety and mood on a 0–5 scale.", + "insights_sleep_shade": "Shading — sleep time", + "insights_wake_at": "Wake-up at {time}", + "@insights_wake_at": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "insights_sleep_at": "Bedtime at {time}", + "@insights_sleep_at": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "insights_prev_day": "Previous day", + "insights_next_day": "Next day", + "insights_pick_date": "Pick a date", + "insights_today": "Today", + "insights_save_error": "Failed to save the entry", + "order_in_progress": "Order in progress", + "personal_diet_proposed": "Personal diet proposed", + "personal_diet_proposed_named": "Diet «{name}» proposed", + "@personal_diet_proposed_named": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "default_user_name": "User", + "personal_diet_defined_to_author": "You have proposed a personal diet to {userName}", + "@personal_diet_defined_to_author": { + "placeholders": { + "userName": { + "type": "String" + } + } + }, + "personal_diet_defined_to_author_named": "You have proposed a personal diet to {userName}, selected diet: «{dietName}»", + "@personal_diet_defined_to_author_named": { + "placeholders": { + "userName": { + "type": "String" + }, + "dietName": { + "type": "String" + } + } + }, + "personal_diet_not_proposed": "Personal diet not proposed", + "change_personal_diet": "Change personal diet", + "personal_diet_replaces_tomorrow": "The change takes effect tomorrow", + "start_date_label": "Start: {date}", + "@start_date_label": { + "placeholders": { + "date": { + "type": "String" + } + } + }, + "personal_diet_duration_hint": "The diet lasts {duration} {dayWord}. It can only be offered for a plan with the same duration.", + "@personal_diet_duration_hint": { + "placeholders": { + "duration": { + "type": "int" + }, + "dayWord": { + "type": "String" + } + } + }, + "personal_diet_duration_mismatch": "Not suitable: diet lasts {dietDuration} {dietDayWord}, plan lasts {planDuration} {planDayWord}.", + "@personal_diet_duration_mismatch": { + "placeholders": { + "dietDuration": { + "type": "int" + }, + "dietDayWord": { + "type": "String" + }, + "planDuration": { + "type": "int" + }, + "planDayWord": { + "type": "String" + } + } + }, + "plan_duration_label": "Plan for {duration} {dayWord}", + "@plan_duration_label": { + "placeholders": { + "duration": { + "type": "int" + }, + "dayWord": { + "type": "String" + } + } + }, + "no_active_personal_diet_consultations": "No active consultations with a personal diet", + "video_call_recordings_title": "My consultations", + "video_call_recordings_retention_tooltip": "Video consultation recordings are stored on Eatvio servers for 1 year.", + "video_call_recordings_empty": "No video consultations yet", + "video_call_recordings_processing": "Recording is being processed…", + "video_call_recordings_download": "Download", + "video_call_recordings_downloading": "Downloading…", + "video_call_recordings_downloading_percent": "Downloading… {percent}%", + "@video_call_recordings_downloading_percent": { + "placeholders": { + "percent": {"type": "int"} + } + }, + "video_call_recordings_download_error": "Could not download the recording. Please try again later.", + "video_call_recordings_download_success": "Recording saved to Downloads/Itvio", + "video_call_recordings_download_success_ios": "Recording saved to the Files app", + "video_call_recordings_player_error": "Could not play the recording", + "video_call_recordings_card_title": "Video consultation with a nutrition specialist", + "video_call_recordings_period_today": "Today", + "video_call_recordings_period_week": "7 days", + "video_call_recordings_period_current_month": "Current month", + "video_call_recordings_period_prev_month": "Previous month", + "video_call_recordings_period_all": "All time" } - diff --git a/lib/l10n/intl_ru.arb b/lib/l10n/intl_ru.arb index 5d729fe6..b46e31e9 100644 --- a/lib/l10n/intl_ru.arb +++ b/lib/l10n/intl_ru.arb @@ -239,6 +239,17 @@ "choose_bank_for_payment": "Выберите банк", "no_installed_banks": "Нет установленных банков", "sbp_payment_error": "Не удалось начать оплату. Попробуйте позже", + "pay_by_qr_code": "Оплатить по QR-коду", + "sbp_qr_title": "Оплата по QR-коду", + "sbp_qr_amount_label": "Сумма к оплате", + "sbp_qr_step1": "Откройте приложение банка на телефоне", + "sbp_qr_step2": "Выберите «Оплата по QR-коду»", + "sbp_qr_step3": "Наведите камеру на код", + "sbp_qr_waiting_payment": "Ожидание оплаты…", + "sbp_qr_paid_title": "Оплата прошла успешно!", + "sbp_qr_paid_description": "Консультация оплачена. Можно вернуться в чат.", + "sbp_qr_open_test_payment": "Открыть тестовую оплату", + "sbp_qr_test_hint": "Симуляция оплаты на тестовом стенде Альфа-Банка", "yes": "Да", "apply": "Применить", "have_promo_code": "У вас есть промокод?", @@ -252,8 +263,12 @@ "promo_discount_hint": "Скидка {percent}% — вы экономите {amount} ₽", "@promo_discount_hint": { "placeholders": { - "percent": {"type": "int"}, - "amount": {"type": "String"} + "percent": { + "type": "int" + }, + "amount": { + "type": "String" + } } }, "promo_remove_failed": "Не удалось убрать промокод. Попробуйте позже", @@ -271,5 +286,311 @@ "video_call_notification_in_progress": "Звонок идёт", "video_call_notification_return": "Вернуться к звонку", "video_call_notification_end": "Завершить звонок", - "blog_post_image_min_size_error": "Минимальный размер изображения — 500×500 px" + "blog_post_image_min_size_error": "Минимальный размер изображения — 500×500 px", + "insights_title": "Аналитика", + "insights_subtitle_closed": "нажмите, чтобы посмотреть прогресс", + "insights_subtitle_open": "вес, замеры и питание", + "insights_tab_weight": "Вес", + "insights_tab_bmi": "ИМТ", + "insights_tab_measures": "Замеры", + "insights_tab_daily": "КБЖУ по дням", + "insights_tab_intra": "В течение дня", + "insights_period_1m": "1М", + "insights_period_3m": "3М", + "insights_period_6m": "6М", + "insights_period_1y": "1Г", + "insights_period_all": "Всё время", + "insights_period_1w": "1Н", + "insights_period_2w": "2Н", + "insights_series_waist": "Талия", + "insights_series_chest": "Грудь", + "insights_series_hips": "Бёдра", + "insights_series_calories": "Калории", + "insights_series_proteins": "Белки", + "insights_series_fats": "Жиры", + "insights_series_carbs": "Углеводы", + "insights_series_satiety": "Сытость", + "insights_series_mood": "Настроение", + "insights_series_sleep": "Сон и подъём", + "insights_unit_kg": "кг", + "insights_unit_bmi": "ИМТ", + "insights_unit_cm": "см", + "insights_unit_cm_waist": "см талия", + "insights_unit_kcal": "ккал", + "insights_unit_kcal_avg": "ккал в среднем", + "insights_unit_grams": "граммы", + "insights_unit_kcal_per_meal": "ккал за приём", + "insights_period_label_1": "месяц", + "insights_period_label_3": "3 месяца", + "insights_period_label_6": "6 месяцев", + "insights_period_label_12": "год", + "insights_period_label_all": "всё время", + "insights_not_enough": "Недостаточно данных", + "insights_need_height": "Укажите рост, чтобы посчитать ИМТ.", + "insights_weight_lost": "Снизили на {value} кг за {period}", + "@insights_weight_lost": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_weight_gained": "Набрали {value} кг за {period}", + "@insights_weight_gained": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_weight_same": "Вес не изменился за {period}", + "@insights_weight_same": { + "placeholders": { + "period": { + "type": "String" + } + } + }, + "insights_bmi_lower": "ИМТ ниже на {value} за {period} · {category}", + "@insights_bmi_lower": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_higher": "ИМТ выше на {value} за {period} · {category}", + "@insights_bmi_higher": { + "placeholders": { + "value": { + "type": "String" + }, + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_same": "ИМТ не изменился за {period} · {category}", + "@insights_bmi_same": { + "placeholders": { + "period": { + "type": "String" + }, + "category": { + "type": "String" + } + } + }, + "insights_bmi_hint": "Зелёная зона — норма (18.5–25), жёлтая — избыточный вес, розовая — ожирение. Считаем при росте {height} см.", + "@insights_bmi_hint": { + "placeholders": { + "height": { + "type": "String" + } + } + }, + "insights_bmi_severe_underweight": "выраженный дефицит массы", + "insights_bmi_underweight": "недостаточная масса", + "insights_bmi_normal": "норма", + "insights_bmi_overweight": "избыточная масса", + "insights_bmi_obesity_1": "ожирение I ст.", + "insights_bmi_obesity_2": "ожирение II ст.", + "insights_bmi_obesity_3": "ожирение III ст.", + "insights_measure_less": "{name} меньше на {value} см", + "@insights_measure_less": { + "placeholders": { + "name": { + "type": "String" + }, + "value": { + "type": "String" + } + } + }, + "insights_measure_more": "{name} больше на {value} см", + "@insights_measure_more": { + "placeholders": { + "name": { + "type": "String" + }, + "value": { + "type": "String" + } + } + }, + "insights_measure_same": "{name} без изменений", + "@insights_measure_same": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "insights_measures_summary": "{parts} за {period}", + "@insights_measures_summary": { + "placeholders": { + "parts": { + "type": "String" + }, + "period": { + "type": "String" + } + } + }, + "insights_add_record": "Добавить запись", + "insights_add_weight_empty": "Добавьте Ваш вес", + "insights_add_measures_empty": "Добавьте Ваши замеры", + "insights_load_error": "Не удалось загрузить аналитику", + "insights_retry": "Повторить", + "insights_intra_hint": "Столбики показывают, из чего состоят приёмы пищи: белки, жиры и углеводы в ккал. Линии — сытость и настроение по шкале от 0 до 5.", + "insights_sleep_shade": "Затемнение — время сна", + "insights_wake_at": "Подъём в {time}", + "@insights_wake_at": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "insights_sleep_at": "Отход ко сну в {time}", + "@insights_sleep_at": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "insights_prev_day": "Предыдущий день", + "insights_next_day": "Следующий день", + "insights_pick_date": "Выбрать дату", + "insights_today": "Сегодня", + "insights_save_error": "Не удалось сохранить запись", + "startDateHasBeenSet": "Выбрана дата старта", + "order_paid": "Заказ оплачен", + "done": "Завершен", + "orderCanceled": "Заказ отменен", + "payment_failed": "Оплата не прошла", + "personal_diet_set": "Персональная диета установлена", + "suggestDiet": "Предложить диету", + "changeDiet": "Заменить диету", + "goToMyDiets": "Перейти к моим диетам", + "choose_plan_start_date_with_personal_diet": "Выберите дату старта плана питания с учетом составления персональной диеты", + "order_in_progress": "Заказ в работе", + "personal_diet_proposed": "Диета предложена", + "personal_diet_proposed_named": "Диета «{name}» предложена", + "@personal_diet_proposed_named": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "default_user_name": "Пользователь", + "personal_diet_defined_to_author": "Вы предложили персональную диету пользователю {userName}", + "@personal_diet_defined_to_author": { + "placeholders": { + "userName": { + "type": "String" + } + } + }, + "personal_diet_defined_to_author_named": "Вы предложили персональную диету пользователю {userName}, выбранная диета: «{dietName}»", + "@personal_diet_defined_to_author_named": { + "placeholders": { + "userName": { + "type": "String" + }, + "dietName": { + "type": "String" + } + } + }, + "personal_diet_not_proposed": "Диета не предложена", + "change_personal_diet": "Заменить диету", + "personal_diet_replaces_tomorrow": "Замена действует со следующего дня", + "start_date_label": "Старт: {date}", + "@start_date_label": { + "placeholders": { + "date": { + "type": "String" + } + } + }, + "personal_diet_duration_hint": "Диета рассчитана на {duration} {dayWord}. Предложить её можно только для плана с такой же длительностью.", + "@personal_diet_duration_hint": { + "placeholders": { + "duration": { + "type": "int" + }, + "dayWord": { + "type": "String" + } + } + }, + "personal_diet_duration_mismatch": "Не подходит: диета на {dietDuration} {dietDayWord}, план на {planDuration} {planDayWord}.", + "@personal_diet_duration_mismatch": { + "placeholders": { + "dietDuration": { + "type": "int" + }, + "dietDayWord": { + "type": "String" + }, + "planDuration": { + "type": "int" + }, + "planDayWord": { + "type": "String" + } + } + }, + "plan_duration_label": "План на {duration} {dayWord}", + "@plan_duration_label": { + "placeholders": { + "duration": { + "type": "int" + }, + "dayWord": { + "type": "String" + } + } + }, + "no_active_personal_diet_consultations": "Нет активных консультаций с персональной диетой", + "video_call_recordings_title": "Мои консультации", + "video_call_recordings_retention_tooltip": "Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.", + "video_call_recordings_empty": "Пока нет видеоконсультаций", + "video_call_recordings_processing": "Запись обрабатывается…", + "video_call_recordings_download": "Скачать", + "video_call_recordings_downloading": "Скачивание…", + "video_call_recordings_downloading_percent": "Скачивание… {percent}%", + "@video_call_recordings_downloading_percent": { + "placeholders": { + "percent": {"type": "int"} + } + }, + "video_call_recordings_download_error": "Не удалось скачать запись. Попробуйте позже.", + "video_call_recordings_download_success": "Запись сохранена в Загрузки/Itvio", + "video_call_recordings_download_success_ios": "Запись сохранена в приложении «Файлы»", + "video_call_recordings_player_error": "Не удалось воспроизвести запись", + "video_call_recordings_card_title": "Видеоконсультация со специалистом по питанию", + "video_call_recordings_period_today": "Сегодня", + "video_call_recordings_period_week": "7 дней", + "video_call_recordings_period_current_month": "Текущий месяц", + "video_call_recordings_period_prev_month": "Прошлый месяц", + "video_call_recordings_period_all": "Всё время" } diff --git a/lib/main.dart b/lib/main.dart index 2813a4d0..bbc8e5d4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/video_calls/services/video_call_foreground_b import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_app_shell.dart'; import 'dart:async'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_portal/flutter_portal.dart'; diff --git a/pubspec.yaml b/pubspec.yaml index 70b070f0..dad171d6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,10 +1,10 @@ name: eatvio_app description: A new Flutter project. -version: 1.3.67+156 +version: 1.3.72+161 publish_to: 'none' environment: - sdk: ^3.10.4 + sdk: ^3.12.0 dependencies: flutter: @@ -27,7 +27,7 @@ dependencies: flutter_typeahead: ^5.2.0 go_router: ^17.0.1 keyboard_dismisser: ^3.0.0 - retrofit: 4.7.2 + retrofit: ^4.10.0 get_it: ^9.2.0 dio: ^5.10.0 dart_pusher_channels: ^1.2.3 @@ -82,18 +82,25 @@ dependencies: rxdart: ^0.27.7 gpassword: ^1.0.0 webview_flutter_platform_interface: ^2.14.0 - flutter_inappwebview: ^6.1.5 + # 6.1.x breaks on AGP 9 (proguard-android.txt removed); fixed in 6.2 beta. + flutter_inappwebview: ^6.2.0-beta.3 + intl_utils: ^2.8.13 sentry_dio: ^9.10.0 - livekit_client: ^2.6.1 + livekit_client: ^2.13.2 + video_player: ^2.10.0 audio_session: ^0.1.25 flutter_foreground_task: ^9.2.1 flutter_callkit_incoming: ^3.1.1 floating: ^6.0.0 wakelock_plus: ^1.5.2 sbp: 0.1.0 + qr_flutter: ^4.1.0 + file_saver: ^0.7.0 # html 0.15.7 removed top-level query_selector.matches used by flutter_html 3.0.0. + material_ui: ^1.11.0 + cupertino_ui: ^1.1.6 dependency_overrides: html: 0.15.6 @@ -101,7 +108,7 @@ dev_dependencies: build_runner: ^2.10.4 freezed: ^3.2.0 json_serializable: ^6.11.2 - retrofit_generator: 10.0.6 + retrofit_generator: ^10.2.3 mockito: ^5.6.1 mocktail: ^1.0.4 network_image_mock: ^2.1.1 @@ -113,6 +120,7 @@ dev_dependencies: integration_test: sdk: flutter + flutter_webrtc: 1.6.3 flutter: uses-material-design: true assets: @@ -175,14 +183,14 @@ flutter_intl: flutter_native_splash: android: true ios: true - color: "#FFFFFF" - image_android: "assets/splash/splash.png" - image_dark_android: "assets/splash/splash.png" - image_ios: "assets/splash/splash.png" - image_dark_ios: "assets/splash/splash.png" - branding_android: "assets/splash/branding.png" - branding_dark_android: "assets/splash/branding.png" + color: '#FFFFFF' + image_android: 'assets/splash/splash.png' + image_dark_android: 'assets/splash/splash.png' + image_ios: 'assets/splash/splash.png' + image_dark_ios: 'assets/splash/splash.png' + branding_android: 'assets/splash/branding.png' + branding_dark_android: 'assets/splash/branding.png' android_12: - image: "assets/splash/splash.png" - image_dark: "assets/splash/splash.png" - branding: "assets/splash/branding.png" + image: 'assets/splash/splash.png' + image_dark: 'assets/splash/splash.png' + branding: 'assets/splash/branding.png' diff --git a/test/common/widgets/markdown_editor_test.dart b/test/common/widgets/markdown_editor_test.dart index 09d6fc4f..36517640 100644 --- a/test/common/widgets/markdown_editor_test.dart +++ b/test/common/widgets/markdown_editor_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/common/widgets/markdown_editor.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/app_router_test.dart b/test/core/app_router_test.dart index bdeef9c1..d803c3bf 100644 --- a/test/core/app_router_test.dart +++ b/test/core/app_router_test.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/routing/route_constants.dart'; import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; diff --git a/test/core/comments/presentation/comments_actions_bottom_sheet_test.dart b/test/core/comments/presentation/comments_actions_bottom_sheet_test.dart index 20663f6e..5d237728 100644 --- a/test/core/comments/presentation/comments_actions_bottom_sheet_test.dart +++ b/test/core/comments/presentation/comments_actions_bottom_sheet_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/comments/presentation/comments_actions_bottom_sh import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -25,12 +24,7 @@ void main() { ); return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); @@ -352,12 +346,7 @@ void main() { ); return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); diff --git a/test/core/interceptors/token_interceptor_session_test.dart b/test/core/interceptors/token_interceptor_session_test.dart new file mode 100644 index 00000000..4c82bd40 --- /dev/null +++ b/test/core/interceptors/token_interceptor_session_test.dart @@ -0,0 +1,118 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/interceptors/token_interceptor.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../fixtures/doubles/session_doubles.dart'; + +class _RecordingErrorInterceptorHandler extends ErrorInterceptorHandler { + int nextCalls = 0; + DioException? nextError; + + @override + void next(DioException error) { + nextCalls++; + nextError = error; + } + + @override + void resolve(Response response) { + throw UnimplementedError('resolve should not be called'); + } + + @override + void reject( + DioException error, [ + bool callFollowingErrorInterceptor = false, + ]) { + throw UnimplementedError('reject should not be called'); + } +} + +DioException _unauthorized(RequestOptions options) { + return DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: 401), + type: DioExceptionType.badResponse, + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late FakeSessionLifecycleService sessionLifecycleService; + late TokenInterceptor interceptor; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + TokenStorage.clearCache(); + await sl.reset(); + + sessionLifecycleService = FakeSessionLifecycleService(); + sl.registerSingleton(sessionLifecycleService); + interceptor = TokenInterceptor(); + }); + + tearDown(() async { + await sl.reset(); + TokenStorage.clearCache(); + }); + + group('TokenInterceptor.onError 401', () { + test('request without Authorization does not end the session', () async { + await TokenStorage.saveTokenInStorage('current-token'); + + final options = RequestOptions(path: '/api/profile/index'); + final error = _unauthorized(options); + final handler = _RecordingErrorInterceptorHandler(); + + await interceptor.onError(error, handler); + + expect(handler.nextCalls, 1); + expect(handler.nextError, same(error)); + expect(sessionLifecycleService.endSessionCalls, 0); + }); + + test('stale request token does not end the new session', () async { + await TokenStorage.saveTokenInStorage('new-token'); + + final options = RequestOptions(path: '/api/profile/index'); + options.headers['Authorization'] = 'Bearer old-token'; + options.extra['authToken'] = 'old-token'; + + final error = _unauthorized(options); + final handler = _RecordingErrorInterceptorHandler(); + + await interceptor.onError(error, handler); + + expect(handler.nextCalls, 1); + expect(sessionLifecycleService.endSessionCalls, 0); + }); + + test( + 'current request token ends the session once as unauthorized', + () async { + await TokenStorage.saveTokenInStorage('current-token'); + + final options = RequestOptions(path: '/api/profile/index'); + options.headers['Authorization'] = 'Bearer current-token'; + options.extra['authToken'] = 'current-token'; + + final error = _unauthorized(options); + final handler = _RecordingErrorInterceptorHandler(); + + await interceptor.onError(error, handler); + + expect(handler.nextCalls, 1); + expect(sessionLifecycleService.endSessionCalls, 1); + expect( + sessionLifecycleService.lastEndReason, + SessionEndReason.unauthorized, + ); + }, + ); + }); +} diff --git a/test/core/interceptors/token_interceptor_test.dart b/test/core/interceptors/token_interceptor_test.dart index 5995d4a5..d997a13a 100644 --- a/test/core/interceptors/token_interceptor_test.dart +++ b/test/core/interceptors/token_interceptor_test.dart @@ -1,22 +1,24 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/core/interceptors/token_interceptor.dart'; -import 'package:eatvio_app/core/token_storage.dart'; -import 'package:eatvio_app/core/websockets/ws_manager.dart'; import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; +import 'package:eatvio_app/core/token_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../../fixtures/doubles/session_doubles.dart'; + class MockRequestOptions extends Mock implements RequestOptions {} -class MockRequestInterceptorHandler extends Mock implements RequestInterceptorHandler {} +class MockRequestInterceptorHandler extends Mock + implements RequestInterceptorHandler {} -class MockErrorInterceptorHandler extends Mock implements ErrorInterceptorHandler {} +class MockErrorInterceptorHandler extends Mock + implements ErrorInterceptorHandler {} class MockResponse extends Mock implements Response {} -class MockWsManager extends Mock implements WsManager {} - class MockDioException extends Mock implements DioException {} class FakeRequestOptions extends Fake implements RequestOptions {} @@ -32,23 +34,18 @@ void main() { }); group('TokenInterceptor', () { late TokenInterceptor interceptor; + late FakeSessionLifecycleService fakeSession; setUp(() async { SharedPreferences.setMockInitialValues({}); - - final mockWsManager = MockWsManager(); - when(() => mockWsManager.clear()).thenAnswer((_) async {}); - - await sl.reset(); // Сбрасываем sl перед каждым тестом - sl.registerSingleton(mockWsManager); - + TokenStorage.clearCache(); + + await sl.reset(); + fakeSession = FakeSessionLifecycleService(); + sl.registerSingleton(fakeSession); + interceptor = TokenInterceptor(); - // Сбрасываем токен перед каждым тестом - try { - await TokenStorage.removeTokenInStorage(); - } catch (e) { - // Игнорируем ошибки при очистке - } + await TokenStorage.removeTokenInStorage(); }); group('onRequest', () { @@ -59,6 +56,7 @@ void main() { final headers = {}; final options = MockRequestOptions(); when(() => options.headers).thenReturn(headers); + when(() => options.extra).thenReturn({}); final handler = MockRequestInterceptorHandler(); when(() => handler.next(any())).thenReturn(null); @@ -73,6 +71,7 @@ void main() { final headers = {}; final options = MockRequestOptions(); when(() => options.headers).thenReturn(headers); + when(() => options.extra).thenReturn({}); final handler = MockRequestInterceptorHandler(); when(() => handler.next(any())).thenReturn(null); @@ -89,6 +88,7 @@ void main() { final headers = {}; final options = MockRequestOptions(); when(() => options.headers).thenReturn(headers); + when(() => options.extra).thenReturn({}); final handler = MockRequestInterceptorHandler(); when(() => handler.next(any())).thenReturn(null); @@ -101,11 +101,16 @@ void main() { }); group('onError', () { - test('удаляет токен и перенаправляет на auth при 401', () async { + test('завершает сессию при 401 для текущего токена', () async { const token = 'test-token'; await TokenStorage.saveTokenInStorage(token); final options = MockRequestOptions(); + when( + () => options.headers, + ).thenReturn({'Authorization': 'Bearer $token'}); + when(() => options.extra).thenReturn({'authToken': token}); + final response = MockResponse(); when(() => response.statusCode).thenReturn(401); @@ -116,14 +121,10 @@ void main() { final handler = MockErrorInterceptorHandler(); when(() => handler.next(any())).thenReturn(null); - // Проверяем, что токен был удален - final tokenBefore = await TokenStorage.getTokenFromStorage(); - expect(tokenBefore, token); - await interceptor.onError(error, handler); - final tokenAfter = await TokenStorage.getTokenFromStorage(); - expect(tokenAfter, null); + expect(fakeSession.endSessionCalls, 1); + expect(fakeSession.lastEndReason, SessionEndReason.unauthorized); verify(() => handler.next(error)).called(1); }); diff --git a/test/core/permission_handler/permission_handler_test.dart b/test/core/permission_handler/permission_handler_test.dart index e0084f2a..38f3eb6f 100644 --- a/test/core/permission_handler/permission_handler_test.dart +++ b/test/core/permission_handler/permission_handler_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/permission_handler/permission_handler.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:permission_handler/permission_handler.dart'; diff --git a/test/core/session/session_lifecycle_service_test.dart b/test/core/session/session_lifecycle_service_test.dart new file mode 100644 index 00000000..ce991a17 --- /dev/null +++ b/test/core/session/session_lifecycle_service_test.dart @@ -0,0 +1,223 @@ +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/core/websockets/ws_manager.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; +import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; +import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart'; +import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _FakeWsManager implements WsManager { + int clearCalls = 0; + + @override + Future clear() async { + clearCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('WsManager.${invocation.memberName}'); + } +} + +class _FakeErrorReporter implements ErrorReporter { + int reportCalls = 0; + + @override + Future report( + Object error, + StackTrace? stackTrace, { + String? origin, + Map? extras, + }) async { + reportCalls++; + } +} + +class _FakeProfileAvatarCubit implements ProfileAvatarCubit { + int resetCalls = 0; + + @override + void reset() { + resetCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('ProfileAvatarCubit.${invocation.memberName}'); + } +} + +class _FakeChatsCubit implements ChatsCubit { + int resetCalls = 0; + + @override + void reset() { + resetCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('ChatsCubit.${invocation.memberName}'); + } +} + +class _FakeNotificationsCubit implements NotificationsCubit { + int resetCalls = 0; + + @override + void reset() { + resetCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('NotificationsCubit.${invocation.memberName}'); + } +} + +class _FakeNewMessagesCubit implements NewMessagesCubit { + int resetCalls = 0; + + @override + void reset() { + resetCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('NewMessagesCubit.${invocation.memberName}'); + } +} + +class _FakeFeedCubit implements FeedCubit { + int resetCalls = 0; + + @override + void reset() { + resetCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('FeedCubit.${invocation.memberName}'); + } +} + +class _FakeVideoCallSessionCubit implements VideoCallSessionCubit { + int endCallCalls = 0; + + @override + Future endCall() async { + endCallCalls++; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + throw UnimplementedError('VideoCallSessionCubit.${invocation.memberName}'); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _FakeWsManager wsManager; + late _FakeProfileAvatarCubit profileAvatarCubit; + late _FakeChatsCubit chatsCubit; + late _FakeNotificationsCubit notificationsCubit; + late _FakeNewMessagesCubit newMessagesCubit; + late _FakeFeedCubit feedCubit; + late _FakeVideoCallSessionCubit videoCallSessionCubit; + late SessionLifecycleService service; + + setUp(() async { + SharedPreferences.setMockInitialValues({ + 'token': 'token-a', + 'socketId': 'socket-a', + PrefsKeys.customBaseUrl.name: 'https://old.example', + PrefsKeys.isEmailVerificationSkipped.name: true, + PrefsKeys.registrationDate.name: '2024-01-01', + PrefsKeys.welcomeScreenWasShowed.name: true, + }); + TokenStorage.clearCache(); + await sl.reset(); + + wsManager = _FakeWsManager(); + profileAvatarCubit = _FakeProfileAvatarCubit(); + chatsCubit = _FakeChatsCubit(); + notificationsCubit = _FakeNotificationsCubit(); + newMessagesCubit = _FakeNewMessagesCubit(); + feedCubit = _FakeFeedCubit(); + videoCallSessionCubit = _FakeVideoCallSessionCubit(); + + sl.registerSingleton(profileAvatarCubit); + sl.registerSingleton(chatsCubit); + sl.registerSingleton(notificationsCubit); + sl.registerSingleton(newMessagesCubit); + sl.registerSingleton(feedCubit); + sl.registerSingleton(videoCallSessionCubit); + sl.registerSingleton(Prefs(await SharedPreferences.getInstance())); + + service = SessionLifecycleService( + wsManager: wsManager, + errorReporter: _FakeErrorReporter(), + ); + }); + + tearDown(() async { + await sl.reset(); + TokenStorage.clearCache(); + }); + + group('SessionLifecycleService.endSession', () { + test( + 'resets user-scoped state and clears only session-scoped keys', + () async { + await service.endSession(reason: SessionEndReason.logout); + + expect(wsManager.clearCalls, 1); + expect(profileAvatarCubit.resetCalls, 1); + expect(chatsCubit.resetCalls, 1); + expect(notificationsCubit.resetCalls, 1); + expect(newMessagesCubit.resetCalls, 1); + expect(feedCubit.resetCalls, 1); + expect(videoCallSessionCubit.endCallCalls, 1); + + expect(await TokenStorage.getTokenFromStorage(), isNull); + expect(await SocketIdStorage.getSocketIdFromStorage(), isNull); + + final prefs = sl(); + expect(prefs.getString(PrefsKeys.customBaseUrl), 'https://old.example'); + expect(prefs.getBool(PrefsKeys.isEmailVerificationSkipped), isNull); + expect(prefs.getString(PrefsKeys.registrationDate), isNull); + expect(prefs.getBool(PrefsKeys.welcomeScreenWasShowed), isTrue); + }, + ); + + test('is idempotent for concurrent calls', () async { + final first = service.endSession(reason: SessionEndReason.logout); + final second = service.endSession(reason: SessionEndReason.unauthorized); + + await Future.wait([first, second]); + + expect(wsManager.clearCalls, 1); + expect(profileAvatarCubit.resetCalls, 1); + expect(chatsCubit.resetCalls, 1); + expect(notificationsCubit.resetCalls, 1); + expect(newMessagesCubit.resetCalls, 1); + expect(feedCubit.resetCalls, 1); + expect(videoCallSessionCubit.endCallCalls, 1); + + expect(await TokenStorage.getTokenFromStorage(), isNull); + expect(await SocketIdStorage.getSocketIdFromStorage(), isNull); + }); + }); +} diff --git a/test/core/theme/app_decoration_test.dart b/test/core/theme/app_decoration_test.dart index 7b7033c2..05f70c9e 100644 --- a/test/core/theme/app_decoration_test.dart +++ b/test/core/theme/app_decoration_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/app_decoration.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/theme/custom_text_style_test.dart b/test/core/theme/custom_text_style_test.dart index 297344e1..b4fe1957 100644 --- a/test/core/theme/custom_text_style_test.dart +++ b/test/core/theme/custom_text_style_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/theme/theme_helper_test.dart b/test/core/theme/theme_helper_test.dart index 75583933..ec4f3244 100644 --- a/test/core/theme/theme_helper_test.dart +++ b/test/core/theme/theme_helper_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/utils/localization_utils_test.dart b/test/core/utils/localization_utils_test.dart index f5ad7f7f..8e637ea4 100644 --- a/test/core/utils/localization_utils_test.dart +++ b/test/core/utils/localization_utils_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/utils/localization_utils.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -98,12 +97,7 @@ void main() { testWidgets('returns correct form for 1 minute', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -119,12 +113,7 @@ void main() { testWidgets('returns correct form for 2-4 minutes', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -144,12 +133,7 @@ void main() { testWidgets('returns correct form for 5+ minutes', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -165,12 +149,7 @@ void main() { testWidgets('returns correct form for 11 minutes', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -188,12 +167,7 @@ void main() { testWidgets('returns correct form for 1 hour', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -209,12 +183,7 @@ void main() { testWidgets('returns correct form for 2-4 hours', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -234,12 +203,7 @@ void main() { testWidgets('returns correct form for 5+ hours', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -255,12 +219,7 @@ void main() { testWidgets('returns correct form for 11 hours', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -278,12 +237,7 @@ void main() { testWidgets('returns correct form for 1 step', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -299,12 +253,7 @@ void main() { testWidgets('returns correct form for 2-4 steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -324,12 +273,7 @@ void main() { testWidgets('returns correct form for 5+ steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -345,12 +289,7 @@ void main() { testWidgets('returns correct form for 11 steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -366,12 +305,7 @@ void main() { testWidgets('returns correct form for 21-24 steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -419,12 +353,7 @@ void main() { testWidgets('getMinuteForm handles 0 minutes', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -440,12 +369,7 @@ void main() { testWidgets('getMinuteForm handles 100+ minutes', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -463,12 +387,7 @@ void main() { testWidgets('getHourForm handles 0 hours', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -484,12 +403,7 @@ void main() { testWidgets('getHourForm handles 100+ hours', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -507,12 +421,7 @@ void main() { testWidgets('getStepForm handles 0 steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -528,12 +437,7 @@ void main() { testWidgets('getStepForm handles 100+ steps', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { diff --git a/test/core/utils/pagination_utils_test.dart b/test/core/utils/pagination_utils_test.dart index 8af3a7f9..e67655f5 100644 --- a/test/core/utils/pagination_utils_test.dart +++ b/test/core/utils/pagination_utils_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/utils/pagination_utils.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/add_item_button_test.dart b/test/core/widgets/add_item_button_test.dart index 720f4715..46fb86a1 100644 --- a/test/core/widgets/add_item_button_test.dart +++ b/test/core/widgets/add_item_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/add_item_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; diff --git a/test/core/widgets/animated_option_button_test.dart b/test/core/widgets/animated_option_button_test.dart index d5f27e02..91ba4932 100644 --- a/test/core/widgets/animated_option_button_test.dart +++ b/test/core/widgets/animated_option_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/animated_option_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/base_button_test.dart b/test/core/widgets/base_button_test.dart index d975e404..d53adb85 100644 --- a/test/core/widgets/base_button_test.dart +++ b/test/core/widgets/base_button_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/core/widgets/base_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/bookmark_button_test.dart b/test/core/widgets/bookmark_button_test.dart index e44383ad..2c19c468 100644 --- a/test/core/widgets/bookmark_button_test.dart +++ b/test/core/widgets/bookmark_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bookmark_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/bottom_sheet_action_widget_test.dart b/test/core/widgets/bottom_sheet_action_widget_test.dart index af9a861f..41333749 100644 --- a/test/core/widgets/bottom_sheet_action_widget_test.dart +++ b/test/core/widgets/bottom_sheet_action_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_action_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/core/widgets/bottom_sheet_handler_bar_test.dart b/test/core/widgets/bottom_sheet_handler_bar_test.dart index 7feff6da..1b22914a 100644 --- a/test/core/widgets/bottom_sheet_handler_bar_test.dart +++ b/test/core/widgets/bottom_sheet_handler_bar_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/bottom_sheet_with_blur_test.dart b/test/core/widgets/bottom_sheet_with_blur_test.dart index 7b9b7884..edc85a2b 100644 --- a/test/core/widgets/bottom_sheet_with_blur_test.dart +++ b/test/core/widgets/bottom_sheet_with_blur_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/cpfc_container_test.dart b/test/core/widgets/cpfc_container_test.dart index 6babc283..e97fa116 100644 --- a/test/core/widgets/cpfc_container_test.dart +++ b/test/core/widgets/cpfc_container_test.dart @@ -1,59 +1,53 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/core/widgets/cpfc_container.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('CpfcContainer smoke', () { - Widget wrap(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru')], - home: Scaffold(body: child), - ); - } - - testWidgets('renders cpfc container', (tester) async { - await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); - await tester.pump(); - - expect(find.byType(CpfcContainer), findsOneWidget); - }); - - testWidgets('displays calories value', (tester) async { - await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); - await tester.pump(); - - expect(find.text('2000.0'), findsOneWidget); - }); - - testWidgets('displays proteins value', (tester) async { - await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); - await tester.pump(); - - expect(find.text('150.0'), findsOneWidget); - }); - - testWidgets('displays fats value', (tester) async { - await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); - await tester.pump(); - - expect(find.text('80.0'), findsOneWidget); - }); - - testWidgets('displays carbohydrates value', (tester) async { - await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); - await tester.pump(); - - expect(find.text('250.0'), findsOneWidget); - }); - }); -} +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/cpfc_container.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('CpfcContainer smoke', () { + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: child), + ); + } + + testWidgets('renders cpfc container', (tester) async { + await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); + await tester.pump(); + + expect(find.byType(CpfcContainer), findsOneWidget); + }); + + testWidgets('displays calories value', (tester) async { + await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); + await tester.pump(); + + expect(find.text('2000.0'), findsOneWidget); + }); + + testWidgets('displays proteins value', (tester) async { + await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); + await tester.pump(); + + expect(find.text('150.0'), findsOneWidget); + }); + + testWidgets('displays fats value', (tester) async { + await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); + await tester.pump(); + + expect(find.text('80.0'), findsOneWidget); + }); + + testWidgets('displays carbohydrates value', (tester) async { + await tester.pumpWidget(wrap(const CpfcContainer(calories: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0))); + await tester.pump(); + + expect(find.text('250.0'), findsOneWidget); + }); + }); +} diff --git a/test/core/widgets/custom_divider_test.dart b/test/core/widgets/custom_divider_test.dart index 5bf9e0ec..313f2675 100644 --- a/test/core/widgets/custom_divider_test.dart +++ b/test/core/widgets/custom_divider_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_divider.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/custom_drop_down_button_test.dart b/test/core/widgets/custom_drop_down_button_test.dart index c456bcce..690ea9ae 100644 --- a/test/core/widgets/custom_drop_down_button_test.dart +++ b/test/core/widgets/custom_drop_down_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/custom_drop_down_test.dart b/test/core/widgets/custom_drop_down_test.dart index 50759f01..034e13c9 100644 --- a/test/core/widgets/custom_drop_down_test.dart +++ b/test/core/widgets/custom_drop_down_test.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_drop_down.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/custom_outlined_button_test.dart b/test/core/widgets/custom_outlined_button_test.dart index b2769b88..3b64de57 100644 --- a/test/core/widgets/custom_outlined_button_test.dart +++ b/test/core/widgets/custom_outlined_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/custom_popup_test.dart b/test/core/widgets/custom_popup_test.dart index a8434ece..18506e8d 100644 --- a/test/core/widgets/custom_popup_test.dart +++ b/test/core/widgets/custom_popup_test.dart @@ -9,9 +9,8 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class _FakeAssetBundle extends CachingAssetBundle { @@ -67,12 +66,7 @@ void main() { bundle: fakeBundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold(body: Center(child: child)), ), diff --git a/test/core/widgets/custom_search_bar_test.dart b/test/core/widgets/custom_search_bar_test.dart index 1923aa78..44ae8dc7 100644 --- a/test/core/widgets/custom_search_bar_test.dart +++ b/test/core/widgets/custom_search_bar_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_search_bar.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/custom_text_form_field_test.dart b/test/core/widgets/custom_text_form_field_test.dart index cda05148..ad0fc0b6 100644 --- a/test/core/widgets/custom_text_form_field_test.dart +++ b/test/core/widgets/custom_text_form_field_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/core/widgets/data_error_widget_test.dart b/test/core/widgets/data_error_widget_test.dart index d5e6fde6..7561b2c0 100644 --- a/test/core/widgets/data_error_widget_test.dart +++ b/test/core/widgets/data_error_widget_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/data_error_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,12 +9,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/core/widgets/feed_icon_button_test.dart b/test/core/widgets/feed_icon_button_test.dart index a978d554..9303939e 100644 --- a/test/core/widgets/feed_icon_button_test.dart +++ b/test/core/widgets/feed_icon_button_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/feed_icon_button.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/info_row_test.dart b/test/core/widgets/info_row_test.dart index 318c4280..24938528 100644 --- a/test/core/widgets/info_row_test.dart +++ b/test/core/widgets/info_row_test.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -15,12 +14,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal(child: Scaffold(body: child)), ); diff --git a/test/core/widgets/item_widget_test.dart b/test/core/widgets/item_widget_test.dart index 64f00960..bd643d16 100644 --- a/test/core/widgets/item_widget_test.dart +++ b/test/core/widgets/item_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/item_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/core/widgets/loader_test.dart b/test/core/widgets/loader_test.dart index 16132361..cf40c866 100644 --- a/test/core/widgets/loader_test.dart +++ b/test/core/widgets/loader_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/main_background_bouble_test.dart b/test/core/widgets/main_background_bouble_test.dart index 25bac88d..e22fe21f 100644 --- a/test/core/widgets/main_background_bouble_test.dart +++ b/test/core/widgets/main_background_bouble_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/main_background_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/markdown_html_widget_test.dart b/test/core/widgets/markdown_html_widget_test.dart index c7654a3f..ee1825a3 100644 --- a/test/core/widgets/markdown_html_widget_test.dart +++ b/test/core/widgets/markdown_html_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/markdown_html_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/core/widgets/marketing_bottom_sheet_test.dart b/test/core/widgets/marketing_bottom_sheet_test.dart index acff0214..ba04f299 100644 --- a/test/core/widgets/marketing_bottom_sheet_test.dart +++ b/test/core/widgets/marketing_bottom_sheet_test.dart @@ -1,139 +1,128 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; -import 'package:eatvio_app/core/widgets/marketing_bottom_sheet.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('MarketingBottomSheet', () { - Widget createTestWidget(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: S.delegate.supportedLocales, - home: Scaffold( - body: child, - ), - ); - } - - testWidgets('displays marketing bottom sheet', (tester) async { - await tester.pumpWidget( - createTestWidget( - const MarketingBottomSheet(), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(MarketingBottomSheet), findsOneWidget); - }); - - testWidgets('shows marketing bottom sheet via function', (tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: S.delegate.supportedLocales, - home: Builder( - builder: (context) { - return Scaffold( - body: ElevatedButton( - onPressed: () { - showMarketingBottomSheet(context); - }, - child: const Text('Show'), - ), - ); - }, - ), - ), - ); - - await tester.pump(); - await tester.tap(find.text('Show')); - await tester.pumpAndSettle(); - - expect(find.byType(MarketingBottomSheet), findsOneWidget); - }); - - testWidgets('displays marketing bottom sheet with congratulations text', (tester) async { - await tester.pumpWidget( - createTestWidget( - const MarketingBottomSheet(), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(MarketingBottomSheet), findsOneWidget); - expect(find.textContaining('Поздравляем'), findsWidgets); - }); - - testWidgets('displays marketing bottom sheet with invite button', (tester) async { - await tester.pumpWidget( - createTestWidget( - const MarketingBottomSheet(), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(MarketingBottomSheet), findsOneWidget); - expect(find.byType(CustomOutlinedButton), findsOneWidget); - }); - - testWidgets('displays marketing bottom sheet with logo', (tester) async { - await tester.pumpWidget( - createTestWidget( - const MarketingBottomSheet(), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(MarketingBottomSheet), findsOneWidget); - expect(find.byType(ClipRRect), findsWidgets); - }); - }); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/core/widgets/marketing_bottom_sheet.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('MarketingBottomSheet', () { + Widget createTestWidget(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: S.delegate.supportedLocales, + home: Scaffold( + body: child, + ), + ); + } + + testWidgets('displays marketing bottom sheet', (tester) async { + await tester.pumpWidget( + createTestWidget( + const MarketingBottomSheet(), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(MarketingBottomSheet), findsOneWidget); + }); + + testWidgets('shows marketing bottom sheet via function', (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: S.delegate.supportedLocales, + home: Builder( + builder: (context) { + return Scaffold( + body: ElevatedButton( + onPressed: () { + showMarketingBottomSheet(context); + }, + child: const Text('Show'), + ), + ); + }, + ), + ), + ); + + await tester.pump(); + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + + expect(find.byType(MarketingBottomSheet), findsOneWidget); + }); + + testWidgets('displays marketing bottom sheet with congratulations text', (tester) async { + await tester.pumpWidget( + createTestWidget( + const MarketingBottomSheet(), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(MarketingBottomSheet), findsOneWidget); + expect(find.textContaining('Поздравляем'), findsWidgets); + }); + + testWidgets('displays marketing bottom sheet with invite button', (tester) async { + await tester.pumpWidget( + createTestWidget( + const MarketingBottomSheet(), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(MarketingBottomSheet), findsOneWidget); + expect(find.byType(CustomOutlinedButton), findsOneWidget); + }); + + testWidgets('displays marketing bottom sheet with logo', (tester) async { + await tester.pumpWidget( + createTestWidget( + const MarketingBottomSheet(), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(MarketingBottomSheet), findsOneWidget); + expect(find.byType(ClipRRect), findsWidgets); + }); + }); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/core/widgets/option_widget_test.dart b/test/core/widgets/option_widget_test.dart index 12236ef6..68f9008b 100644 --- a/test/core/widgets/option_widget_test.dart +++ b/test/core/widgets/option_widget_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/option_widget.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -11,12 +10,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold(body: child), ); diff --git a/test/core/widgets/show_error_dialog_test.dart b/test/core/widgets/show_error_dialog_test.dart index edab0e88..4f140b43 100644 --- a/test/core/widgets/show_error_dialog_test.dart +++ b/test/core/widgets/show_error_dialog_test.dart @@ -1,7 +1,6 @@ import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -9,12 +8,7 @@ void main() { testWidgets('displays error dialog with default title and description', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -43,12 +37,7 @@ void main() { testWidgets('displays error dialog with custom title and description', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -80,12 +69,7 @@ void main() { testWidgets('displays error dialog with custom button title', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -115,12 +99,7 @@ void main() { testWidgets('closes dialog when button is tapped', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { @@ -156,12 +135,7 @@ void main() { testWidgets('displays error dialog with needToOpenSettings', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Builder( builder: (context) { diff --git a/test/core/widgets/success_published_diet_bottom_sheet_test.dart b/test/core/widgets/success_published_diet_bottom_sheet_test.dart index 20b6b9c7..e8860467 100644 --- a/test/core/widgets/success_published_diet_bottom_sheet_test.dart +++ b/test/core/widgets/success_published_diet_bottom_sheet_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/success_published_diet_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -38,12 +37,7 @@ void main() { ), ], ), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], ); } diff --git a/test/core/widgets/success_published_recipe_bottom_sheet_test.dart b/test/core/widgets/success_published_recipe_bottom_sheet_test.dart index e4903383..945c52ae 100644 --- a/test/core/widgets/success_published_recipe_bottom_sheet_test.dart +++ b/test/core/widgets/success_published_recipe_bottom_sheet_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/success_published_recipe_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -38,12 +37,7 @@ void main() { ), ], ), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], ); } diff --git a/test/features/auth/presentation/bloc/auth_cubit/auth_cubit_test.dart b/test/features/auth/presentation/bloc/auth_cubit/auth_cubit_test.dart index 65bb710e..27f3c737 100644 --- a/test/features/auth/presentation/bloc/auth_cubit/auth_cubit_test.dart +++ b/test/features/auth/presentation/bloc/auth_cubit/auth_cubit_test.dart @@ -12,6 +12,7 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../../../../../fixtures/doubles/session_doubles.dart'; import 'auth_cubit_test.mocks.dart'; @GenerateNiceMocks([ @@ -75,6 +76,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); expect(cubit!.state, isA()); @@ -86,6 +88,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); const email = 'test@example.com'; @@ -116,6 +119,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); const email = 'test@example.com'; @@ -140,6 +144,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); when(mockPrefs.getBool(any)).thenReturn(false); @@ -159,6 +164,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); when(mockPrefs.getBool(any)).thenReturn(true); @@ -174,6 +180,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); when(mockFirebaseApi.registerPushToken()) @@ -190,6 +197,7 @@ void main() { profileRepository: mockProfileRepository, firebaseApi: mockFirebaseApi, prefs: mockPrefs, + sessionLifecycleService: FakeSessionLifecycleService(), ); // TokenStorage.haveTokenInStorage() вернет false diff --git a/test/features/auth/presentation/bloc/auth_cubit_test.dart b/test/features/auth/presentation/bloc/auth_cubit_test.dart index 790775b0..cc57e231 100644 --- a/test/features/auth/presentation/bloc/auth_cubit_test.dart +++ b/test/features/auth/presentation/bloc/auth_cubit_test.dart @@ -13,6 +13,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../../../fixtures/doubles/auth_doubles.dart'; import '../../../../fixtures/doubles/profile_doubles.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import '../../../../fixtures/fixture_reader.dart'; import 'auth_cubit_test.mocks.dart'; @@ -26,6 +27,7 @@ void main() { late FixtureProfileRepository profileRepository; late MockPrefs mockPrefs; late MockFirebaseApi mockFirebaseApi; + late FakeSessionLifecycleService fakeSession; late Map credentialsFixture; late TokenModel tokenFixture; @@ -37,6 +39,7 @@ void main() { profileRepository = FixtureProfileRepository(); mockPrefs = MockPrefs(); mockFirebaseApi = MockFirebaseApi(); + fakeSession = FakeSessionLifecycleService(); SharedPreferences.setMockInitialValues({}); // Mock Fluttertoast plugin @@ -59,12 +62,12 @@ void main() { }); test('начальное состояние - AuthState', () { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); expect(authCubit!.state, const AuthState()); }); test('getTokenByCredentials - успешная авторизация', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); final result = await authCubit!.getTokenByCredentials(credentialsFixture['email'] as String, credentialsFixture['password'] as String); @@ -77,7 +80,7 @@ void main() { }); test('getTokenByCredentials - переход в состояние loading', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); authRepository.responseDelay = const Duration(milliseconds: 50); final future = authCubit!.getTokenByCredentials(credentialsFixture['email'] as String, credentialsFixture['password'] as String); @@ -88,7 +91,7 @@ void main() { }); test('getTokenByCredentials - обработка ошибки авторизации', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); authRepository.error = Exception('Неверный адрес электронной почты или пароль'); final result = await authCubit!.getTokenByCredentials('wrong@example.com', 'wrongpassword'); @@ -102,7 +105,7 @@ void main() { }); test('getTokenByCredentials - обработка различных типов ошибок', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); authRepository.error = const FormatException('Invalid credentials format'); final result = await authCubit!.getTokenByCredentials('invalid', 'pass'); @@ -115,7 +118,7 @@ void main() { }); test('getTokenByCredentials - проверка вызова с правильными параметрами', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); await authCubit!.getTokenByCredentials('user@test.com', 'securePassword123'); @@ -124,7 +127,7 @@ void main() { }); test('getTokenByCredentials - множественные вызовы', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); await authCubit!.getTokenByCredentials('first@test.com', 'password1'); await Future.delayed(const Duration(milliseconds: 100)); @@ -138,7 +141,7 @@ void main() { }); test('registerAnonymousPushToken - регистрирует токен если не был отправлен', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(false); when(mockFirebaseApi.registerAnonymousPushToken()).thenAnswer((_) async => {}); when(mockPrefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true)).thenAnswer((_) async => {}); @@ -150,7 +153,7 @@ void main() { }); test('registerAnonymousPushToken - не регистрирует токен если уже был отправлен', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(true); await authCubit!.registerAnonymousPushToken(); @@ -159,7 +162,7 @@ void main() { }); test('registerPushToken - регистрирует push токен', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); when(mockFirebaseApi.registerPushToken()).thenAnswer((_) async => {}); await authCubit!.registerPushToken(); @@ -168,7 +171,7 @@ void main() { }); test('registerAnonymousPushToken - обрабатывает null значение hasAnonymousTokenBeenSent', () async { - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession); when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(null); when(mockFirebaseApi.registerAnonymousPushToken()).thenAnswer((_) async => {}); when(mockPrefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true)).thenAnswer((_) async => {}); diff --git a/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart b/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart index 94401422..443ee7e6 100644 --- a/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart +++ b/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/auth/models/oauth_verification_confirm_response.dart'; @@ -13,9 +14,21 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../../../../../fixtures/doubles/session_doubles.dart'; import '../../../../../fixtures/fixture_reader.dart'; import 'oauth_cubit_test.mocks.dart'; +class _RecordingFirebaseApi extends Fake implements FirebaseApi { + int registerPushTokenCalls = 0; + bool hadAuthToken = false; + + @override + Future registerPushToken() async { + registerPushTokenCalls++; + hadAuthToken = await TokenStorage.haveTokenInStorage(); + } +} + @GenerateNiceMocks([MockSpec(), MockSpec()]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -24,26 +37,38 @@ void main() { OAuthCubit? oauthCubit; late MockAuthRepository mockAuthRepository; late MockPrefs mockPrefs; + late _RecordingFirebaseApi firebaseApi; + late FakeSessionLifecycleService fakeSession; late TokenModel tokenFixture; late Map signInRequestFixture; late Map signUpRequestFixture; setUp(() async { - tokenFixture = TokenModel.fromJson(FixtureReader.readAsMap('auth/token_response.json')); - signInRequestFixture = FixtureReader.readAsMap('auth/oauth_signin_request.json'); - signUpRequestFixture = FixtureReader.readAsMap('auth/oauth_signup_request.json'); + tokenFixture = TokenModel.fromJson( + FixtureReader.readAsMap('auth/token_response.json'), + ); + signInRequestFixture = FixtureReader.readAsMap( + 'auth/oauth_signin_request.json', + ); + signUpRequestFixture = FixtureReader.readAsMap( + 'auth/oauth_signup_request.json', + ); mockAuthRepository = MockAuthRepository(); mockPrefs = MockPrefs(); + firebaseApi = _RecordingFirebaseApi(); + fakeSession = FakeSessionLifecycleService(); SharedPreferences.setMockInitialValues({}); // Mock Fluttertoast plugin - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('PonnamKarthik/fluttertoast'), ( - MethodCall methodCall, - ) async { - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + return null; + }, + ); }); tearDown(() async { @@ -52,18 +77,31 @@ void main() { oauthCubit!.close(); oauthCubit = null; } + TokenStorage.clearCache(); // Clear mock handlers - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('PonnamKarthik/fluttertoast'), null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); test('начальное состояние - OAuthState', () { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); expect(oauthCubit!.state, const OAuthState()); }); test('signInViaSocialMedia - успешный вход через соцсеть', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); when( mockAuthRepository.signInViaSocialMedia( @@ -92,7 +130,11 @@ void main() { }); test('signInViaSocialMedia - переход в состояние loading', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); when( mockAuthRepository.signInViaSocialMedia( @@ -119,7 +161,11 @@ void main() { }); test('signInViaSocialMedia - обработка ошибки', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); when( mockAuthRepository.signInViaSocialMedia( @@ -144,7 +190,11 @@ void main() { }); test('signUpViaSocialMedia - успешная регистрация через соцсеть', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); when( mockAuthRepository.signUpViaSocialMedia( @@ -164,7 +214,9 @@ void main() { ), ).thenAnswer((_) async => tokenFixture.token); - when(mockPrefs.setString(any, any)).thenAnswer((_) async => Future.value()); + when( + mockPrefs.setString(any, any), + ).thenAnswer((_) async => Future.value()); final result = await oauthCubit!.signUpViaSocialMedia( provider: signUpRequestFixture['provider'] as String, @@ -187,48 +239,61 @@ void main() { expect(oauthCubit!.state, isA()); final loadedState = oauthCubit!.state as OAuthStateLoaded; expect(loadedState.token, tokenFixture.token); + expect(await TokenStorage.getTokenFromStorage(), tokenFixture.token); + expect(fakeSession.onAuthenticatedCalls, 1); }); - test('signInViaSocialMedia - обработка ошибки валидации email/phone', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + test( + 'signInViaSocialMedia - обработка ошибки валидации email/phone', + () async { + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); - final dioException = DioException( - requestOptions: RequestOptions(path: '/api/auth/oauth/signin'), - response: Response( - statusCode: 422, - data: { - 'errors': { - 'email': ['Некорректный формат email'], - }, - }, + final dioException = DioException( requestOptions: RequestOptions(path: '/api/auth/oauth/signin'), - ), - ); + response: Response( + statusCode: 422, + data: { + 'errors': { + 'email': ['Некорректный формат email'], + }, + }, + requestOptions: RequestOptions(path: '/api/auth/oauth/signin'), + ), + ); - when( - mockAuthRepository.signInViaSocialMedia( - provider: anyNamed('provider'), - accessToken: anyNamed('accessToken'), - refreshToken: anyNamed('refreshToken'), - clientId: anyNamed('clientId'), - ), - ).thenThrow(dioException); + when( + mockAuthRepository.signInViaSocialMedia( + provider: anyNamed('provider'), + accessToken: anyNamed('accessToken'), + refreshToken: anyNamed('refreshToken'), + clientId: anyNamed('clientId'), + ), + ).thenThrow(dioException); - await oauthCubit!.signInViaSocialMedia( - provider: signInRequestFixture['provider'] as String, - accessToken: signInRequestFixture['access_token'] as String, - refreshToken: signInRequestFixture['refresh_token'] as String, - clientId: signInRequestFixture['client_id'] as String, - ); + await oauthCubit!.signInViaSocialMedia( + provider: signInRequestFixture['provider'] as String, + accessToken: signInRequestFixture['access_token'] as String, + refreshToken: signInRequestFixture['refresh_token'] as String, + clientId: signInRequestFixture['client_id'] as String, + ); - await Future.delayed(const Duration(milliseconds: 100)); - expect(oauthCubit!.state, isA()); - final errorState = oauthCubit!.state as OAuthStateError; - expect(errorState.errorMessage, 'validation_error'); - }); + await Future.delayed(const Duration(milliseconds: 100)); + expect(oauthCubit!.state, isA()); + final errorState = oauthCubit!.state as OAuthStateError; + expect(errorState.errorMessage, 'validation_error'); + }, + ); test('signUpViaSocialMedia - обработка ошибки валидации email', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); final dioException = DioException( requestOptions: RequestOptions(path: '/api/auth/oauth/signup'), @@ -282,82 +347,129 @@ void main() { expect(result[0], RegistrationValidationErrors.incorrectEmailFormat); }); - test('requestOAuthVerification - успешный запрос кода верификации', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + test( + 'requestOAuthVerification - успешный запрос кода верификации', + () async { + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); - const verificationResponse = OAuthVerificationRequestResponse(email: 't***@example.com', status: 'sent'); + const verificationResponse = OAuthVerificationRequestResponse( + email: 't***@example.com', + status: 'sent', + ); - when(mockAuthRepository.requestOAuthVerification(email: anyNamed('email'), phone: anyNamed('phone'))).thenAnswer((_) async => verificationResponse); + when( + mockAuthRepository.requestOAuthVerification( + email: anyNamed('email'), + phone: anyNamed('phone'), + ), + ).thenAnswer((_) async => verificationResponse); - final result = await oauthCubit!.requestOAuthVerification(email: 'test@example.com'); + final result = await oauthCubit!.requestOAuthVerification( + email: 'test@example.com', + ); - expect(result, isNotNull); - expect(result!.email, 't***@example.com'); - expect(oauthCubit!.state, isA()); - }); + expect(result, isNotNull); + expect(result!.email, 't***@example.com'); + expect(oauthCubit!.state, isA()); + }, + ); test('requestOAuthVerification - обработка ошибки', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); - when(mockAuthRepository.requestOAuthVerification(email: anyNamed('email'), phone: anyNamed('phone'))).thenThrow(Exception('Ошибка запроса')); + when( + mockAuthRepository.requestOAuthVerification( + email: anyNamed('email'), + phone: anyNamed('phone'), + ), + ).thenThrow(Exception('Ошибка запроса')); - final result = await oauthCubit!.requestOAuthVerification(email: 'test@example.com'); + final result = await oauthCubit!.requestOAuthVerification( + email: 'test@example.com', + ); expect(result, isNull); expect(oauthCubit!.state, isA()); }); - test('confirmOAuthVerification - успешное подтверждение верификации', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + test( + 'confirmOAuthVerification - успешное подтверждение верификации', + () async { + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); - final verificationResponse = OAuthVerificationConfirmResponse(success: true, message: 'Success', token: tokenFixture.token, user: {}, isNewUser: false); + final verificationResponse = OAuthVerificationConfirmResponse( + success: true, + message: 'Success', + token: tokenFixture.token, + user: {}, + isNewUser: false, + ); - when( - mockAuthRepository.confirmOAuthVerification( - provider: anyNamed('provider'), - accessToken: anyNamed('accessToken'), - refreshToken: anyNamed('refreshToken'), - clientId: anyNamed('clientId'), - id: anyNamed('id'), - email: anyNamed('email'), - phone: anyNamed('phone'), - code: anyNamed('code'), - verificationType: anyNamed('verificationType'), - firstName: anyNamed('firstName'), - lastName: anyNamed('lastName'), - dateOfBirth: anyNamed('dateOfBirth'), - gender: anyNamed('gender'), - weight: anyNamed('weight'), - height: anyNamed('height'), - ), - ).thenAnswer((_) async => verificationResponse); + when( + mockAuthRepository.confirmOAuthVerification( + provider: anyNamed('provider'), + accessToken: anyNamed('accessToken'), + refreshToken: anyNamed('refreshToken'), + clientId: anyNamed('clientId'), + id: anyNamed('id'), + email: anyNamed('email'), + phone: anyNamed('phone'), + code: anyNamed('code'), + verificationType: anyNamed('verificationType'), + firstName: anyNamed('firstName'), + lastName: anyNamed('lastName'), + dateOfBirth: anyNamed('dateOfBirth'), + gender: anyNamed('gender'), + weight: anyNamed('weight'), + height: anyNamed('height'), + ), + ).thenAnswer((_) async => verificationResponse); - await oauthCubit!.confirmOAuthVerification( - provider: 'google', - accessToken: 'access_token', - refreshToken: 'refresh_token', - clientId: 'client_id', - id: 'id', - email: 'test@example.com', - phone: null, - code: '123456', - verificationType: 'email', - firstName: 'Test', - lastName: 'User', - dateOfBirth: '2000-01-01', - gender: 'male', - weight: 70, - height: 175, - ); + await oauthCubit!.confirmOAuthVerification( + provider: 'google', + accessToken: 'access_token', + refreshToken: 'refresh_token', + clientId: 'client_id', + id: 'id', + email: 'test@example.com', + phone: null, + code: '123456', + verificationType: 'email', + firstName: 'Test', + lastName: 'User', + dateOfBirth: '2000-01-01', + gender: 'male', + weight: 70, + height: 175, + ); - await Future.delayed(const Duration(milliseconds: 100)); - expect(oauthCubit!.state, isA()); - final loadedState = oauthCubit!.state as OAuthStateLoaded; - expect(loadedState.token, tokenFixture.token); - }); + await Future.delayed(const Duration(milliseconds: 100)); + expect(oauthCubit!.state, isA()); + final loadedState = oauthCubit!.state as OAuthStateLoaded; + expect(loadedState.token, tokenFixture.token); + expect(await TokenStorage.getTokenFromStorage(), tokenFixture.token); + expect(fakeSession.onAuthenticatedCalls, 1); + }, + ); test('confirmOAuthVerification - обработка ошибки', () async { - oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + oauthCubit = OAuthCubit( + authRepository: mockAuthRepository, + firebaseApi: firebaseApi, sessionLifecycleService: fakeSession, + prefs: mockPrefs, + ); when( mockAuthRepository.confirmOAuthVerification( diff --git a/test/features/auth/presentation/pages/auth_screen_smoke_test.dart b/test/features/auth/presentation/pages/auth_screen_smoke_test.dart index 030613cd..522986fe 100644 --- a/test/features/auth/presentation/pages/auth_screen_smoke_test.dart +++ b/test/features/auth/presentation/pages/auth_screen_smoke_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart'; import 'package:eatvio_app/features/auth/presentation/pages/auth_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -30,12 +29,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/auth/presentation/pages/forget_password_screen_smoke_test.dart b/test/features/auth/presentation/pages/forget_password_screen_smoke_test.dart index 714f75c7..4704dfce 100644 --- a/test/features/auth/presentation/pages/forget_password_screen_smoke_test.dart +++ b/test/features/auth/presentation/pages/forget_password_screen_smoke_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_state.dart'; import 'package:eatvio_app/features/auth/presentation/pages/forget_password_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/auth/presentation/pages/forget_password_screen_test.dart b/test/features/auth/presentation/pages/forget_password_screen_test.dart index 4af21add..3789b846 100644 --- a/test/features/auth/presentation/pages/forget_password_screen_test.dart +++ b/test/features/auth/presentation/pages/forget_password_screen_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart'; import 'package:eatvio_app/features/auth/presentation/pages/forget_password_screen.dart'; import 'package:eatvio_app/features/auth/repositories/reset_password_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/auth/presentation/pages/register_via_social_screen_smoke_test.dart b/test/features/auth/presentation/pages/register_via_social_screen_smoke_test.dart index 4696da59..add38e1a 100644 --- a/test/features/auth/presentation/pages/register_via_social_screen_smoke_test.dart +++ b/test/features/auth/presentation/pages/register_via_social_screen_smoke_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart'; import 'package:eatvio_app/features/auth/presentation/pages/register_via_social_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/auth/presentation/pages/scan_qr_code_screen_smoke_test.dart b/test/features/auth/presentation/pages/scan_qr_code_screen_smoke_test.dart index 116d2d85..844aa482 100644 --- a/test/features/auth/presentation/pages/scan_qr_code_screen_smoke_test.dart +++ b/test/features/auth/presentation/pages/scan_qr_code_screen_smoke_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/auth/presentation/pages/scan_qr_code_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/auth/presentation/widgets/basic_widget_test.dart b/test/features/auth/presentation/widgets/basic_widget_test.dart index 05c2e2e3..a9410ac8 100644 --- a/test/features/auth/presentation/widgets/basic_widget_test.dart +++ b/test/features/auth/presentation/widgets/basic_widget_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/auth/models/token_model.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -15,6 +15,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../../../fixtures/doubles/auth_doubles.dart'; import '../../../../fixtures/doubles/profile_doubles.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import '../../../../fixtures/fixture_reader.dart'; import 'basic_widget_test.mocks.dart'; @@ -36,7 +37,7 @@ void main() { mockFirebaseApi = MockFirebaseApi(); SharedPreferences.setMockInitialValues({}); - authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: FakeSessionLifecycleService()); }); tearDown(() { @@ -55,7 +56,7 @@ void main() { testWidgets('should create AuthCubit successfully', (WidgetTester tester) async { // Arrange & Act - final cubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi); + final cubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: FakeSessionLifecycleService()); // Assert expect(cubit, isA()); diff --git a/test/features/auth/sdk/social_auth_facade_test.dart b/test/features/auth/sdk/social_auth_facade_test.dart index 3c0ec83e..c5c555c9 100644 --- a/test/features/auth/sdk/social_auth_facade_test.dart +++ b/test/features/auth/sdk/social_auth_facade_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/app_router.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/auth/sdk/social_auth_facade.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/blog_post/presentation/pages/blog_post_screen_smoke_test.dart b/test/features/blog_post/presentation/pages/blog_post_screen_smoke_test.dart index f4253129..aff21487 100644 --- a/test/features/blog_post/presentation/pages/blog_post_screen_smoke_test.dart +++ b/test/features/blog_post/presentation/pages/blog_post_screen_smoke_test.dart @@ -10,10 +10,9 @@ import 'package:eatvio_app/features/blog_post/presentation/pages/blog_post_scree import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_media_content.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -72,12 +71,7 @@ void main() { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); diff --git a/test/features/blog_post_create/advanced_widget_test.dart b/test/features/blog_post_create/advanced_widget_test.dart index aafb9aa8..97e62189 100644 --- a/test/features/blog_post_create/advanced_widget_test.dart +++ b/test/features/blog_post_create/advanced_widget_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_state.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/blog_post_create/basic_widget_test.dart b/test/features/blog_post_create/basic_widget_test.dart index 3cd4aa38..82a69068 100644 --- a/test/features/blog_post_create/basic_widget_test.dart +++ b/test/features/blog_post_create/basic_widget_test.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/blog_post_create/integration_widget_test.dart b/test/features/blog_post_create/integration_widget_test.dart index 1eaad104..42cbed6f 100644 --- a/test/features/blog_post_create/integration_widget_test.dart +++ b/test/features/blog_post_create/integration_widget_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_state.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/blog_post_create/presentation/pages/blog_post_create_screen_test.dart b/test/features/blog_post_create/presentation/pages/blog_post_create_screen_test.dart index cd17183e..13b6f1e7 100644 --- a/test/features/blog_post_create/presentation/pages/blog_post_create_screen_test.dart +++ b/test/features/blog_post_create/presentation/pages/blog_post_create_screen_test.dart @@ -15,10 +15,9 @@ import 'package:eatvio_app/features/feed/models/post_feed_pagination_model.dart' import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mocktail/mocktail.dart'; @@ -95,12 +94,7 @@ void main() { return MaterialApp.router( routerConfig: router, theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), ); diff --git a/test/features/bottom_navigation_bar/bottom_nav_scope_test.dart b/test/features/bottom_navigation_bar/bottom_nav_scope_test.dart index de852443..4916fd51 100644 --- a/test/features/bottom_navigation_bar/bottom_nav_scope_test.dart +++ b/test/features/bottom_navigation_bar/bottom_nav_scope_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_session_test.dart b/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_session_test.dart new file mode 100644 index 00000000..0535e564 --- /dev/null +++ b/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_session_test.dart @@ -0,0 +1,204 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class MockProfileRepository extends Mock implements ProfileRepository {} + +const _profileA = ProfileModel( + id: 1, + slug: 'user-a', + name: 'User A', + email: 'a@example.com', + phoneConfirmationState: 'confirmed', + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: 'avatars/a.png', + roles: [], + badges: [], + subscriptions: [], + subscribers: [], +); + +const _profileB = ProfileModel( + id: 2, + slug: 'user-b', + name: 'User B', + email: 'b@example.com', + phoneConfirmationState: 'confirmed', + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: 'avatars/b.png', + roles: [], + badges: [], + subscriptions: [], + subscribers: [], +); + +const _details = ProfileDetailsModel( + firstName: 'User', + lastName: 'Test', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '-', + aboutTakingPils: '-', + aboutSportHobbies: '-', + favoriteFoods: '-', + unfavoriteFoods: '-', + additionalInfo: '-', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MockProfileRepository repository; + ProfileAvatarCubit? cubit; + + setUp(() async { + await sl.reset(); + SharedPreferences.setMockInitialValues({'token': 'token-a'}); + TokenStorage.clearCache(); + repository = MockProfileRepository(); + }); + + tearDown(() async { + if (cubit != null && !cubit!.isClosed) { + await cubit!.close(); + } + cubit = null; + await sl.reset(); + TokenStorage.clearCache(); + }); + + void stubSuccessfulProfile(ProfileModel profile) { + when(() => repository.getMyProfile()).thenAnswer((_) async => profile); + when( + () => repository.getMyProfileDetails(), + ).thenAnswer((_) async => _details); + } + + test('reset emits loading and clears the cached profile', () async { + stubSuccessfulProfile(_profileA); + cubit = ProfileAvatarCubit(profileRepository: repository); + + await cubit!.ensureFreshForCurrentSession(); + expect(cubit!.state, isA()); + + cubit!.reset(); + expect(cubit!.state, isA()); + + await cubit!.ensureFreshForCurrentSession(); + + verify(() => repository.getMyProfile()).called(2); + expect(cubit!.state, isA()); + }); + + test('late getMyProfile completion after reset is ignored', () async { + final profileCompleter = Completer(); + when( + () => repository.getMyProfile(), + ).thenAnswer((_) => profileCompleter.future); + when( + () => repository.getMyProfileDetails(), + ).thenAnswer((_) async => _details); + + cubit = ProfileAvatarCubit(profileRepository: repository); + + final pendingRequest = cubit!.getMyProfile(); + await pumpEventQueue(); + expect(cubit!.state, isA()); + + cubit!.reset(); + profileCompleter.complete(_profileA); + await pendingRequest; + await pumpEventQueue(); + + expect(cubit!.state, isA()); + verifyNever(() => repository.getMyProfileDetails()); + }); + + test( + 'ensureFreshForCurrentSession does not refetch for the same token', + () async { + stubSuccessfulProfile(_profileA); + cubit = ProfileAvatarCubit(profileRepository: repository); + + await cubit!.ensureFreshForCurrentSession(); + await cubit!.ensureFreshForCurrentSession(); + + verify(() => repository.getMyProfile()).called(1); + expect(cubit!.state, isA()); + }, + ); + + test( + 'ensureFreshForCurrentSession refetches after the token changes', + () async { + final profiles = [_profileA, _profileB]; + when( + () => repository.getMyProfile(), + ).thenAnswer((_) async => profiles.removeAt(0)); + when( + () => repository.getMyProfileDetails(), + ).thenAnswer((_) async => _details); + + cubit = ProfileAvatarCubit(profileRepository: repository); + + await cubit!.ensureFreshForCurrentSession(); + final firstState = cubit!.state as ProfileAvatarStateLoaded; + expect(firstState.profile.id, _profileA.id); + + await TokenStorage.saveTokenInStorage('token-b'); + await cubit!.ensureFreshForCurrentSession(); + + final secondState = cubit!.state as ProfileAvatarStateLoaded; + expect(secondState.profile.id, _profileB.id); + expect(secondState.profile.profilePhotoUrl, _profileB.profilePhotoUrl); + verify(() => repository.getMyProfile()).called(2); + }, + ); + + test('errors emit ProfileAvatarStateError and do not navigate', () async { + when( + () => repository.getMyProfile(), + ).thenAnswer((_) async => throw Exception('profile request failed')); + + cubit = ProfileAvatarCubit(profileRepository: repository); + + await cubit!.getMyProfile(); + + expect(cubit!.state, isA()); + expect( + (cubit!.state as ProfileAvatarStateError).errorMessage, + contains('profile request failed'), + ); + }); +} diff --git a/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_test.dart b/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_test.dart index 61d515c1..981bfff4 100644 --- a/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_test.dart +++ b/test/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit_test.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; @@ -5,6 +6,7 @@ import 'package:eatvio_app/features/profile/repositories/profile_repository.dart import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'profile_avatar_cubit_test.mocks.dart'; @@ -16,6 +18,8 @@ void main() { late MockProfileRepository mockRepository; setUp(() { + SharedPreferences.setMockInitialValues({'token': 'test-token'}); + TokenStorage.clearCache(); mockRepository = MockProfileRepository(); }); diff --git a/test/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget_test.dart b/test/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget_test.dart index 85850c2e..864e3948 100644 --- a/test/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget_test.dart +++ b/test/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget_test.dart @@ -11,10 +11,9 @@ import 'package:eatvio_app/features/notifications/presentation/notifications_cub import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_state.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -73,12 +72,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/calendar/presentation/pages/calendar_screen_smoke_test.dart b/test/features/calendar/presentation/pages/calendar_screen_smoke_test.dart index 33719fee..82e06f54 100644 --- a/test/features/calendar/presentation/pages/calendar_screen_smoke_test.dart +++ b/test/features/calendar/presentation/pages/calendar_screen_smoke_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; import 'package:eatvio_app/features/calendar/presentation/pages/calendar_screen.dart'; import 'package:eatvio_app/features/calendar/repositories/calendar_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:intl/date_symbol_data_local.dart'; diff --git a/test/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet_test.dart b/test/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet_test.dart index 0449fbb6..76dc2a31 100644 --- a/test/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet_test.dart +++ b/test/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cancel_plan_bottom_sheet.dart'; import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cubit/cancel_plan_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -33,12 +32,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: BlocProvider.value( diff --git a/test/features/chat/presentation/bloc/chat_room_cubit_test.dart b/test/features/chat/presentation/bloc/chat_room_cubit_test.dart index 7250b6d1..1453e8c2 100644 --- a/test/features/chat/presentation/bloc/chat_room_cubit_test.dart +++ b/test/features/chat/presentation/bloc/chat_room_cubit_test.dart @@ -78,6 +78,66 @@ void main() { meta: const ChatMetaModel(lastPage: 1), ); + const planForChosenPlanUpdates = PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: 'https://example.com/image.jpg', + duration: 7, + state: 'active', + type: PlanType( + fit: true, + slim: false, + behavior: false, + wellness: false, + ), + details: 'Test details', + packetsCount: 3, + author: Author( + authorSlug: 'author', + authorName: 'Author Name', + authorProfileIcon: 'https://example.com/icon.jpg', + authorIsMe: false, + ), + totalLikes: 10, + totalViews: 100, + totalComments: 5, + isFavorite: false, + minPriceOfOptions: 1000, + maxPriceOfOptions: 2000, + wasLikedByMe: false, + ); + + ChosenPlanModel buildChosenPlan( + int id, + ChosenPlanStateEnum chosenPlanState, + ) { + return ChosenPlanModel( + id: id, + optionType: 'options1', + startDate: DateTime.now(), + chosenPlanState: chosenPlanState, + chatId: 'chat-id', + consultantId: 1, + plan: planForChosenPlanUpdates, + ); + } + + void stubChatChannel({ + required Stream chosenPlanStream, + }) { + when(mockWsManager.client).thenReturn(MockPusherChannelsClient()); + when( + mockWsManager.directChatStream, + ).thenAnswer((_) => const Stream.empty()); + when( + mockWsManager.clientTypingStream, + ).thenAnswer((_) => const Stream.empty()); + when( + mockWsManager.chosenPlanStateChangedStream, + ).thenAnswer((_) => chosenPlanStream); + } + setUp(() { mockChatRepository = MockChatRepository(); mockCardsRepository = MockCardsRepository(); @@ -721,6 +781,160 @@ void main() { }, ); + test( + 'chosenPlanStateChangedStream - перезапрашивает план и обновляет state', + () async { + const uuid = 'room-uuid'; + const planId = 321; + final chosenPlan = buildChosenPlan( + planId, + ChosenPlanStateEnum.stateStarted, + ); + final updatedPlan = chosenPlan.copyWith( + chosenPlanState: ChosenPlanStateEnum.statePaid, + ); + final controller = StreamController.broadcast(); + + when( + mockChatRepository.getChatRoom(uuid), + ).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId)); + when( + mockChatRepository.getChatMessages(uuid, 1), + ).thenAnswer((_) async => testChatMessages); + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => chosenPlan); + stubChatChannel(chosenPlanStream: controller.stream); + + await chatRoomCubit.initChat(uuid); + expect(chatRoomCubit.state, isA()); + + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => updatedPlan); + clearInteractions(mockChatRepository); + + controller.add(_FakeChannelReadEvent()); + await Future.delayed(const Duration(milliseconds: 350)); + + verify(mockChatRepository.getChosenPlan(id: planId)).called(1); + final state = chatRoomCubit.state as ChatRoomStateLoaded; + expect( + state.chatRoom.chosenPlan?.chosenPlanState, + ChosenPlanStateEnum.statePaid, + ); + + await controller.close(); + }, + ); + + test( + 'chosenPlanStateChangedStream - использует chosenPlan.id если chosenPlanId null', + () async { + const orderId = 'alfa_c29_k15138_t1712345678_r1234'; + const conversationUuid = 'fbd81429-8019-499a-80e8-e3933cc4d872'; + const planId = 654; + final chosenPlan = buildChosenPlan( + planId, + ChosenPlanStateEnum.stateStarted, + ); + final updatedPlan = chosenPlan.copyWith( + chosenPlanState: ChosenPlanStateEnum.statePaid, + ); + final controller = StreamController.broadcast(); + + when( + mockChatRepository.resolveOrderIdToConversation(orderId: orderId), + ).thenAnswer( + (_) async => OrderIdToConversationModel( + chosenPlanId: planId, + conversationUuid: conversationUuid, + ), + ); + when( + mockChatRepository.getChatRoom(conversationUuid), + ).thenAnswer((_) async => testChatRoom); + when( + mockChatRepository.getChatMessages(conversationUuid, 1), + ).thenAnswer((_) async => testChatMessages); + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => chosenPlan); + stubChatChannel(chosenPlanStream: controller.stream); + + await chatRoomCubit.initChat(null, orderId: orderId); + final loaded = chatRoomCubit.state as ChatRoomStateLoaded; + expect(loaded.chatRoom.chosenPlanId, isNull); + expect(loaded.chatRoom.chosenPlan?.id, planId); + + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => updatedPlan); + clearInteractions(mockChatRepository); + + controller.add(_FakeChannelReadEvent()); + await Future.delayed(const Duration(milliseconds: 350)); + + verify(mockChatRepository.getChosenPlan(id: planId)).called(1); + final state = chatRoomCubit.state as ChatRoomStateLoaded; + expect( + state.chatRoom.chosenPlan?.chosenPlanState, + ChosenPlanStateEnum.statePaid, + ); + + await controller.close(); + }, + ); + + test( + 'chosenPlanStateChangedStream - дебаунсит повторные события', + () async { + const uuid = 'room-uuid'; + const planId = 987; + final chosenPlan = buildChosenPlan( + planId, + ChosenPlanStateEnum.stateStarted, + ); + final updatedPlan = chosenPlan.copyWith( + chosenPlanState: ChosenPlanStateEnum.statePaid, + ); + final controller = StreamController.broadcast(); + + when( + mockChatRepository.getChatRoom(uuid), + ).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId)); + when( + mockChatRepository.getChatMessages(uuid, 1), + ).thenAnswer((_) async => testChatMessages); + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => chosenPlan); + stubChatChannel(chosenPlanStream: controller.stream); + + await chatRoomCubit.initChat(uuid); + expect(chatRoomCubit.state, isA()); + + when( + mockChatRepository.getChosenPlan(id: planId), + ).thenAnswer((_) async => updatedPlan); + clearInteractions(mockChatRepository); + + controller + ..add(_FakeChannelReadEvent()) + ..add(_FakeChannelReadEvent()); + await Future.delayed(const Duration(milliseconds: 350)); + + verify(mockChatRepository.getChosenPlan(id: planId)).called(1); + final state = chatRoomCubit.state as ChatRoomStateLoaded; + expect( + state.chatRoom.chosenPlan?.chosenPlanState, + ChosenPlanStateEnum.statePaid, + ); + + await controller.close(); + }, + ); + test('choseStartPlanDate - устанавливает дату начала плана', () async { const uuid = 'room-uuid'; const planId = 123; @@ -2578,3 +2792,8 @@ void main() { ); }); } + +class _FakeChannelReadEvent extends Fake implements ChannelReadEvent { + @override + dynamic get data => null; +} diff --git a/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart b/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart index c3031f4b..8e7cc997 100644 --- a/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart +++ b/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter/services.dart'; diff --git a/test/features/chat/presentation/pages/chat_screen_loading_smoke_test.dart b/test/features/chat/presentation/pages/chat_screen_loading_smoke_test.dart index cf6d27cf..e94b1d30 100644 --- a/test/features/chat/presentation/pages/chat_screen_loading_smoke_test.dart +++ b/test/features/chat/presentation/pages/chat_screen_loading_smoke_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/chat/presentation/pages/chats_screen_smoke_test.dart b/test/features/chat/presentation/pages/chats_screen_smoke_test.dart index ac3953b7..4205b2da 100644 --- a/test/features/chat/presentation/pages/chats_screen_smoke_test.dart +++ b/test/features/chat/presentation/pages/chats_screen_smoke_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cub import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -19,12 +18,7 @@ void main() { Widget wrap(Widget child, ChatsCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value(value: cubit, child: child), ); diff --git a/test/features/chat/presentation/pages/chats_screen_test.dart b/test/features/chat/presentation/pages/chats_screen_test.dart index 4a2ec4a6..d9c5c6e7 100644 --- a/test/features/chat/presentation/pages/chats_screen_test.dart +++ b/test/features/chat/presentation/pages/chats_screen_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cub import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -39,12 +38,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => mockChatsCubit, diff --git a/test/features/chat/presentation/pages/empty_chat_screen_smoke_test.dart b/test/features/chat/presentation/pages/empty_chat_screen_smoke_test.dart index df2d8889..13ac4a2f 100644 --- a/test/features/chat/presentation/pages/empty_chat_screen_smoke_test.dart +++ b/test/features/chat/presentation/pages/empty_chat_screen_smoke_test.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/pages/empty_chat_screen.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; diff --git a/test/features/chat/presentation/pages/empty_chat_screen_test.dart b/test/features/chat/presentation/pages/empty_chat_screen_test.dart index 87784474..c00439e7 100644 --- a/test/features/chat/presentation/pages/empty_chat_screen_test.dart +++ b/test/features/chat/presentation/pages/empty_chat_screen_test.dart @@ -8,9 +8,8 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -39,12 +38,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/chat/presentation/pages/payment_screen_test.dart b/test/features/chat/presentation/pages/payment_screen_test.dart index b2b8810e..df79f2fc 100644 --- a/test/features/chat/presentation/pages/payment_screen_test.dart +++ b/test/features/chat/presentation/pages/payment_screen_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import '../../../../helpers/webview_test_helper.dart'; diff --git a/test/features/chat/presentation/pages/photo_view_screen_smoke_test.dart b/test/features/chat/presentation/pages/photo_view_screen_smoke_test.dart index 4381d1d7..158c6a1c 100644 --- a/test/features/chat/presentation/pages/photo_view_screen_smoke_test.dart +++ b/test/features/chat/presentation/pages/photo_view_screen_smoke_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/chat/presentation/pages/photo_view_screen_test.dart b/test/features/chat/presentation/pages/photo_view_screen_test.dart index 5b4f1347..4c709f6f 100644 --- a/test/features/chat/presentation/pages/photo_view_screen_test.dart +++ b/test/features/chat/presentation/pages/photo_view_screen_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/chat/presentation/utils/chat_banner_resolver_test.dart b/test/features/chat/presentation/utils/chat_banner_resolver_test.dart new file mode 100644 index 00000000..7f9a11a4 --- /dev/null +++ b/test/features/chat/presentation/utils/chat_banner_resolver_test.dart @@ -0,0 +1,232 @@ +import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart'; +import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:flutter_test/flutter_test.dart'; + +ConsultationProgress _progress( + ChosenPlanStateEnum state, { + bool hasPersonalDiet = false, +}) { + return mapConsultationProgress( + state: state, + hasPersonalDiet: hasPersonalDiet, + ); +} + +void main() { + group('resolveChatBanner — карта консультанта', () { + test('in_coordination без карты просит добавить карту', () { + final banner = resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.stateInCoordination), + amIConsultant: true, + hasCard: false, + state: ChosenPlanStateEnum.stateInCoordination, + ); + + expect(banner, BannerType.card); + }); + + test('in_coordination с картой просит выбрать дату', () { + final banner = resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.stateInCoordination), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.stateInCoordination, + ); + + expect(banner, BannerType.date); + }); + + test('paid + notProposed + диета просит предложить диету', () { + final banner = resolveChatBanner( + progress: _progress( + ChosenPlanStateEnum.statePaid, + hasPersonalDiet: true, + ), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.statePaid, + ); + + expect(banner, BannerType.setPersonalDiet); + }); + + test( + 'personal_diet_setted/started/in_progress + proposed просят сменить диету', + () { + const states = [ + ChosenPlanStateEnum.personalDietSet, + ChosenPlanStateEnum.stateStarted, + ChosenPlanStateEnum.stateInProgress, + ]; + + for (final state in states) { + final banner = resolveChatBanner( + progress: _progress(state, hasPersonalDiet: true), + amIConsultant: true, + hasCard: true, + state: state, + ); + + expect( + banner, + BannerType.changePersonalDiet, + reason: 'state=${state.name}', + ); + } + }, + ); + + test('last_day_finished не просит менять диету (нет баннера)', () { + final banner = resolveChatBanner( + progress: _progress( + ChosenPlanStateEnum.stateLastDayFinished, + hasPersonalDiet: true, + ), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.stateLastDayFinished, + ); + + expect(banner, isNot(BannerType.changePersonalDiet)); + expect(banner, isNull); + }); + + test('done не просит менять диету (collectCharge)', () { + final banner = resolveChatBanner( + progress: _progress( + ChosenPlanStateEnum.stateDone, + hasPersonalDiet: true, + ), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.stateDone, + ); + + expect(banner, isNot(BannerType.changePersonalDiet)); + expect(banner, BannerType.collectCharge); + }); + }); + + group('resolveChatBanner — карта клиента', () { + test('start_date_has_been_set просит оплатить', () { + final banner = resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.stateStartDateHasBeenSet), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.stateStartDateHasBeenSet, + ); + + expect(banner, BannerType.payment); + }); + + test('pending_payment просит оплатить', () { + final banner = resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.statePendingPayment), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.statePendingPayment, + ); + + expect(banner, BannerType.payment); + }); + + test('paid + notProposed не показывает diet-баннер клиенту', () { + final banner = resolveChatBanner( + progress: _progress( + ChosenPlanStateEnum.statePaid, + hasPersonalDiet: true, + ), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.statePaid, + ); + + expect(banner, isNull); + }); + + test( + 'personal_diet_setted + proposed не показывает diet-баннер клиенту', + () { + final banner = resolveChatBanner( + progress: _progress( + ChosenPlanStateEnum.personalDietSet, + hasPersonalDiet: true, + ), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.personalDietSet, + ); + + expect(banner, isNull); + }, + ); + }); + + group('resolveChatBanner — терминальные фазы', () { + test('canceled не показывает баннер', () { + expect( + resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.stateCanceledByTheInitiator, + ), + isNull, + ); + expect( + resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.stateCanceledByTheInitiator, + ), + isNull, + ); + }); + + test('payment_failed не показывает баннер', () { + expect( + resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.statePaymentFailed), + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.statePaymentFailed, + ), + isNull, + ); + expect( + resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.statePaymentFailed), + amIConsultant: false, + hasCard: true, + state: ChosenPlanStateEnum.statePaymentFailed, + ), + isNull, + ); + }); + + test('нет progress или state — нет баннера', () { + expect( + resolveChatBanner( + progress: null, + amIConsultant: true, + hasCard: true, + state: ChosenPlanStateEnum.statePaid, + ), + isNull, + ); + expect( + resolveChatBanner( + progress: _progress(ChosenPlanStateEnum.statePaid), + amIConsultant: true, + hasCard: true, + state: null, + ), + isNull, + ); + }); + }); +} diff --git a/test/features/chat/presentation/widgets/about_order_button_test.dart b/test/features/chat/presentation/widgets/about_order_button_test.dart index 7dce9f00..cf652f3c 100644 --- a/test/features/chat/presentation/widgets/about_order_button_test.dart +++ b/test/features/chat/presentation/widgets/about_order_button_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,12 +9,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/chat/presentation/widgets/basic_widget_test.dart b/test/features/chat/presentation/widgets/basic_widget_test.dart index b34b6f6b..72641b90 100644 --- a/test/features/chat/presentation/widgets/basic_widget_test.dart +++ b/test/features/chat/presentation/widgets/basic_widget_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -11,12 +10,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: SingleChildScrollView(child: child)), ); diff --git a/test/features/chat/presentation/widgets/chat_bottom_sheets_smoke_test.dart b/test/features/chat/presentation/widgets/chat_bottom_sheets_smoke_test.dart index 1646550f..1880dd75 100644 --- a/test/features/chat/presentation/widgets/chat_bottom_sheets_smoke_test.dart +++ b/test/features/chat/presentation/widgets/chat_bottom_sheets_smoke_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/chat/presentation/widgets/chose_plan_date_wi import 'package:eatvio_app/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:go_router/go_router.dart'; @@ -76,12 +75,7 @@ void main() { child: Portal( child: MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ), @@ -144,12 +138,7 @@ void main() { child: Portal( child: MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ), diff --git a/test/features/chat/presentation/widgets/chat_bubble_widget_smoke_test.dart b/test/features/chat/presentation/widgets/chat_bubble_widget_smoke_test.dart index ba51e3c1..72530fac 100644 --- a/test/features/chat/presentation/widgets/chat_bubble_widget_smoke_test.dart +++ b/test/features/chat/presentation/widgets/chat_bubble_widget_smoke_test.dart @@ -4,7 +4,7 @@ import 'dart:io'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/chat/presentation/widgets/chat_consultation_header_test.dart b/test/features/chat/presentation/widgets/chat_consultation_header_test.dart new file mode 100644 index 00000000..e984ef15 --- /dev/null +++ b/test/features/chat/presentation/widgets/chat_consultation_header_test.dart @@ -0,0 +1,80 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: Center(child: child)), + ); +} + +void main() { + group('ChatConsultationHeader', () { + testWidgets('вызывает onInfoTap по тапу на info', (tester) async { + var tapped = 0; + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateInited, + hasPersonalDiet: false, + ); + + await tester.pumpWidget( + _wrap( + ChatConsultationHeader( + progress: progress, + showInfoButton: true, + onInfoTap: () => tapped++, + ), + ), + ); + + await tester.tap(find.byIcon(Icons.info_outline_rounded)); + await tester.pump(); + + expect(tapped, 1); + }); + + testWidgets( + 'personal_diet_setted показывает плашку и чип вместе с баннером замены', + (tester) async { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.personalDietSet, + hasPersonalDiet: true, + personalDietName: 'Индивидуальный план питания', + ); + expect(progress.showProgressPlank, isTrue); + expect(progress.dietStatus, PersonalDietStatus.proposed); + + await tester.pumpWidget( + _wrap( + ChatConsultationHeader( + progress: progress, + showInfoButton: false, + onInfoTap: () {}, + ), + ), + ); + + final s = S.of(tester.element(find.byType(ChatConsultationHeader))); + + expect(find.text(s.order_in_progress), findsNWidgets(2)); + expect(find.byType(PersonalDietStatusChip), findsOneWidget); + expect( + find.text(s.personal_diet_proposed_named('Индивидуальный план питания')), + findsOneWidget, + ); + expect(find.byType(ConsultationProgressPlank), findsOneWidget); + expect(find.byIcon(Icons.check), findsNWidgets(2)); + }, + ); + }); +} diff --git a/test/features/chat/presentation/widgets/chat_entry_widget_test.dart b/test/features/chat/presentation/widgets/chat_entry_widget_test.dart index cf12990a..b269803b 100644 --- a/test/features/chat/presentation/widgets/chat_entry_widget_test.dart +++ b/test/features/chat/presentation/widgets/chat_entry_widget_test.dart @@ -3,8 +3,7 @@ import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_pagination_model.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_entry_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:network_image_mock/network_image_mock.dart'; @@ -16,12 +15,7 @@ void main() { Widget createTestWidget(ChatRoom chatRoom) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), routerConfig: GoRouter( diff --git a/test/features/chat/presentation/widgets/chat_list_widgets_smoke_test.dart b/test/features/chat/presentation/widgets/chat_list_widgets_smoke_test.dart index 06c4cd71..82b109a0 100644 --- a/test/features/chat/presentation/widgets/chat_list_widgets_smoke_test.dart +++ b/test/features/chat/presentation/widgets/chat_list_widgets_smoke_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/features/chat/models/chat_room_pagination_model.dart' import 'package:eatvio_app/features/chat/presentation/widgets/chat_entry_widget.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_search_bar_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:network_image_mock/network_image_mock.dart'; @@ -37,12 +36,7 @@ void main() { ); return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); diff --git a/test/features/chat/presentation/widgets/chat_misc_widgets_smoke_test.dart b/test/features/chat/presentation/widgets/chat_misc_widgets_smoke_test.dart index 4b6a29b4..095ff770 100644 --- a/test/features/chat/presentation/widgets/chat_misc_widgets_smoke_test.dart +++ b/test/features/chat/presentation/widgets/chat_misc_widgets_smoke_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button import 'package:eatvio_app/features/chat/presentation/widgets/message_action_bottom_sheet.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -49,12 +48,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MediaQuery( data: const MediaQueryData(size: Size(500, 900)), @@ -153,12 +147,7 @@ void main() { bundle: bundle, child: MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ), diff --git a/test/features/chat/presentation/widgets/chat_search_bar_widget_test.dart b/test/features/chat/presentation/widgets/chat_search_bar_widget_test.dart index 672c1f7d..4c2db8e2 100644 --- a/test/features/chat/presentation/widgets/chat_search_bar_widget_test.dart +++ b/test/features/chat/presentation/widgets/chat_search_bar_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_search_bar_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/chat/presentation/widgets/chose_plan_date_widget_test.dart b/test/features/chat/presentation/widgets/chose_plan_date_widget_test.dart index 20850ab0..ed8f415a 100644 --- a/test/features/chat/presentation/widgets/chose_plan_date_widget_test.dart +++ b/test/features/chat/presentation/widgets/chose_plan_date_widget_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chose_plan_date_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -21,12 +20,7 @@ void main() { Widget createTestWidget(Widget child, ChatRoomCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: BlocProvider( diff --git a/test/features/chat/presentation/widgets/complete_plan_bottom_sheet_test.dart b/test/features/chat/presentation/widgets/complete_plan_bottom_sheet_test.dart index a5b2e534..0cefb25e 100644 --- a/test/features/chat/presentation/widgets/complete_plan_bottom_sheet_test.dart +++ b/test/features/chat/presentation/widgets/complete_plan_bottom_sheet_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/complete_plan_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -18,12 +17,7 @@ void main() { Widget createTestWidget(Widget child, ChatRoomCubit cubit) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( routes: [ diff --git a/test/features/chat/presentation/widgets/message_action_bottom_sheet_test.dart b/test/features/chat/presentation/widgets/message_action_bottom_sheet_test.dart index 1b90c35e..4de4260e 100644 --- a/test/features/chat/presentation/widgets/message_action_bottom_sheet_test.dart +++ b/test/features/chat/presentation/widgets/message_action_bottom_sheet_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_action_widget.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/message_action_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -11,12 +10,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/chat/presentation/widgets/notification_banner_test.dart b/test/features/chat/presentation/widgets/notification_banner_test.dart index 19dd3242..1d29f98f 100644 --- a/test/features/chat/presentation/widgets/notification_banner_test.dart +++ b/test/features/chat/presentation/widgets/notification_banner_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -18,12 +17,7 @@ void main() { Widget wrap(Widget child, ChatRoomCubit? cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: cubit != null ? BlocProvider.value(value: cubit, child: child) : child, diff --git a/test/features/chat/presentation/widgets/order_card_smoke_test.dart b/test/features/chat/presentation/widgets/order_card_smoke_test.dart index 459d3ee7..c3215509 100644 --- a/test/features/chat/presentation/widgets/order_card_smoke_test.dart +++ b/test/features/chat/presentation/widgets/order_card_smoke_test.dart @@ -9,9 +9,8 @@ import 'package:eatvio_app/features/chat/presentation/widgets/order_card.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class _FakeHttpClient implements HttpClient { @@ -143,12 +142,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: SingleChildScrollView(child: child)), ); diff --git a/test/features/chat/presentation/widgets/plan_complain_bottom_sheet_test.dart b/test/features/chat/presentation/widgets/plan_complain_bottom_sheet_test.dart index 58153597..dffedc7b 100644 --- a/test/features/chat/presentation/widgets/plan_complain_bottom_sheet_test.dart +++ b/test/features/chat/presentation/widgets/plan_complain_bottom_sheet_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/plan_complain_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -18,12 +17,7 @@ void main() { Widget createTestWidget(Widget child, ChatRoomCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (_) => cubit, diff --git a/test/features/chat/presentation/widgets/plan_order_message_widget_test.dart b/test/features/chat/presentation/widgets/plan_order_message_widget_test.dart index 5540ac32..67cca5f7 100644 --- a/test/features/chat/presentation/widgets/plan_order_message_widget_test.dart +++ b/test/features/chat/presentation/widgets/plan_order_message_widget_test.dart @@ -1,7 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/plan_order_message_widget.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:intl/date_symbol_data_local.dart'; @@ -25,7 +24,7 @@ void main() { return MaterialApp.router( theme: ThemeHelper().themeData(), routerConfig: router, - localizationsDelegates: const [GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate], + localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const [Locale('ru')], ); } diff --git a/test/features/chat/repositories/chat_repository_test.dart b/test/features/chat/repositories/chat_repository_test.dart index 247d1311..e0c271ab 100644 --- a/test/features/chat/repositories/chat_repository_test.dart +++ b/test/features/chat/repositories/chat_repository_test.dart @@ -526,11 +526,11 @@ void main() { }, ); - test('getChatByUserSlug - возвращает 404 при отсутствии чата', () async { + test('getChatByUserSlug - возвращает null, если в ответе нет id', () async { const slug = 'user-slug'; final response = HttpResponse( {}, - Response(requestOptions: RequestOptions(path: ''), statusCode: 404), + Response(requestOptions: RequestOptions(path: ''), statusCode: 200), ); when( @@ -539,7 +539,7 @@ void main() { final result = await chatRepository.getChatByUserSlug(slug); - expect(result, '404'); + expect(result, isNull); verify(mockChatService.getChatByUserSlug(slug: slug)).called(1); }); diff --git a/test/features/complaining/presentation/complaining_bottom_sheet_smoke_test.dart b/test/features/complaining/presentation/complaining_bottom_sheet_smoke_test.dart index b678c863..49e6f403 100644 --- a/test/features/complaining/presentation/complaining_bottom_sheet_smoke_test.dart +++ b/test/features/complaining/presentation/complaining_bottom_sheet_smoke_test.dart @@ -10,9 +10,8 @@ import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_ import 'package:eatvio_app/features/complaining/presentation/cubit/complaining_cubit.dart'; import 'package:eatvio_app/features/complaining/repositories/complaining_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -40,12 +39,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/consultant/become_consultant/entities/diploma_entity_test.dart b/test/features/consultant/become_consultant/entities/diploma_entity_test.dart index 3604a737..f5fa3be5 100644 --- a/test/features/consultant/become_consultant/entities/diploma_entity_test.dart +++ b/test/features/consultant/become_consultant/entities/diploma_entity_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/consultant/become_consultant/entities/diploma_entity.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/consultant/become_consultant/presentation/pages/additional_settings_screen_test.dart b/test/features/consultant/become_consultant/presentation/pages/additional_settings_screen_test.dart index c4fc2eb9..be735884 100644 --- a/test/features/consultant/become_consultant/presentation/pages/additional_settings_screen_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/additional_settings_screen_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/models/consulta import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/additional_settings_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/consultant/become_consultant/presentation/pages/become_consultant_screen_test.dart b/test/features/consultant/become_consultant/presentation/pages/become_consultant_screen_test.dart index 128c3225..a5b4b2db 100644 --- a/test/features/consultant/become_consultant/presentation/pages/become_consultant_screen_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/become_consultant_screen_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -16,5 +16,29 @@ void main() { expect(find.byType(BecomeConsultantScreen), findsOneWidget); expect(find.text('Стать консультантом'), findsOneWidget); }); + + testWidgets('keeps the bottom action above the system navigation area', (tester) async { + const bottomInset = 34.0; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeHelper().themeData(), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(bottom: bottomInset)), + child: child!, + ), + home: const BecomeConsultantScreen(), + ), + ); + await tester.pumpAndSettle(); + + final buttonRect = tester.getRect( + find.ancestor(of: find.text('Начать регистрацию'), matching: find.byType(Ink)).first, + ); + final viewHeight = tester.view.physicalSize.height / tester.view.devicePixelRatio; + + expect(buttonRect.bottom, lessThanOrEqualTo(viewHeight - bottomInset)); + expect(tester.takeException(), isNull); + }); }); } diff --git a/test/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen_smoke_test.dart b/test/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen_smoke_test.dart index 5288e170..82234669 100644 --- a/test/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen_smoke_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen_smoke_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/certificates_and_diplomas_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -38,12 +37,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/consultant/become_consultant/presentation/pages/last_step_screen_test.dart b/test/features/consultant/become_consultant/presentation/pages/last_step_screen_test.dart index 800f7430..a2bf3127 100644 --- a/test/features/consultant/become_consultant/presentation/pages/last_step_screen_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/last_step_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/models/consulta import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/last_step_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/consultant/become_consultant/presentation/pages/passport_data_screen_test.dart b/test/features/consultant/become_consultant/presentation/pages/passport_data_screen_test.dart index 1385a5a7..972dcc28 100644 --- a/test/features/consultant/become_consultant/presentation/pages/passport_data_screen_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/passport_data_screen_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/passport_data_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; diff --git a/test/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen_smoke_test.dart b/test/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen_smoke_test.dart index 5086cf86..4ec668c3 100644 --- a/test/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen_smoke_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen_smoke_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; @@ -36,12 +35,7 @@ void main() { Widget wrap(Widget child, RegisterConsultantCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value( diff --git a/test/features/consultant/become_consultant/presentation/pages/registration_as_screen_test.dart b/test/features/consultant/become_consultant/presentation/pages/registration_as_screen_test.dart index 28d432f6..05e78c3c 100644 --- a/test/features/consultant/become_consultant/presentation/pages/registration_as_screen_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/registration_as_screen_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/registration_as_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; diff --git a/test/features/consultant/become_consultant/presentation/pages/social_networks_screen_smoke_test.dart b/test/features/consultant/become_consultant/presentation/pages/social_networks_screen_smoke_test.dart index 7db759e2..329a4414 100644 --- a/test/features/consultant/become_consultant/presentation/pages/social_networks_screen_smoke_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/social_networks_screen_smoke_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/bl import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/social_networks_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -38,12 +37,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen_smoke_test.dart b/test/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen_smoke_test.dart index d663ea7e..7297aa3b 100644 --- a/test/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen_smoke_test.dart +++ b/test/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen_smoke_test.dart @@ -9,9 +9,8 @@ import 'package:eatvio_app/features/consultant/become_consultant/presentation/pa import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -38,12 +37,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/consultant_rating/presentation/consultant_rating_screen_test.dart b/test/features/consultant_rating/presentation/consultant_rating_screen_test.dart index 16c8d613..0a591967 100644 --- a/test/features/consultant_rating/presentation/consultant_rating_screen_test.dart +++ b/test/features/consultant_rating/presentation/consultant_rating_screen_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/consultant_rating/presentation/consultant_ra import 'package:eatvio_app/features/consultant_rating/presentation/cubit/consultant_rating_cubit.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/cubit/consultant_rating_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -35,12 +34,7 @@ void main() { Widget wrap(Widget child, ConsultantRatingCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value(value: cubit, child: child), diff --git a/test/features/consultant_rating/presentation/widgets/rating_history_item_test.dart b/test/features/consultant_rating/presentation/widgets/rating_history_item_test.dart index 1382e529..1139fb64 100644 --- a/test/features/consultant_rating/presentation/widgets/rating_history_item_test.dart +++ b/test/features/consultant_rating/presentation/widgets/rating_history_item_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/rating_history_item.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/consultant_rating/presentation/widgets/rating_history_widget_test.dart b/test/features/consultant_rating/presentation/widgets/rating_history_widget_test.dart index 4095d408..6d238dc9 100644 --- a/test/features/consultant_rating/presentation/widgets/rating_history_widget_test.dart +++ b/test/features/consultant_rating/presentation/widgets/rating_history_widget_test.dart @@ -6,8 +6,7 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/consultant_rating/models/rating_model.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/rating_history_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -23,12 +22,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/consultant_rating/presentation/widgets/rating_widget_test.dart b/test/features/consultant_rating/presentation/widgets/rating_widget_test.dart index cdcc7536..47b2b4c9 100644 --- a/test/features/consultant_rating/presentation/widgets/rating_widget_test.dart +++ b/test/features/consultant_rating/presentation/widgets/rating_widget_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/rating_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,12 +9,7 @@ void main() { Widget createTestWidget(int rating) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: RatingWidget(rating: rating), diff --git a/test/features/consultant_rating/presentation/widgets/statistic_bouble_test.dart b/test/features/consultant_rating/presentation/widgets/statistic_bouble_test.dart index a82c9750..bc59266b 100644 --- a/test/features/consultant_rating/presentation/widgets/statistic_bouble_test.dart +++ b/test/features/consultant_rating/presentation/widgets/statistic_bouble_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/statistic_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/consultant_rating/presentation/widgets/statistic_widget_test.dart b/test/features/consultant_rating/presentation/widgets/statistic_widget_test.dart index e85e4624..4cf9191f 100644 --- a/test/features/consultant_rating/presentation/widgets/statistic_widget_test.dart +++ b/test/features/consultant_rating/presentation/widgets/statistic_widget_test.dart @@ -6,8 +6,7 @@ import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/consultant_rating/models/statistics_model.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/widgets/statistic_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -23,12 +22,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/consultations/models/consultation_model_test.dart b/test/features/consultations/models/consultation_model_test.dart index 6d927618..bd00e5c8 100644 --- a/test/features/consultations/models/consultation_model_test.dart +++ b/test/features/consultations/models/consultation_model_test.dart @@ -156,6 +156,57 @@ void main() { }); group('ConsultationModel', () { + test('fromJson parses chat_id', () { + final json = { + 'id': 1, + 'chat_id': 'direct-chat-uuid', + 'last_state': 'started', + 'plan_title': 'Test Plan', + 'user_name': 'User 1', + 'user_slug': 'user-1', + 'consultant_payment': 1000.0, + 'duration': 30, + 'current_diary_day': 5, + 'user_profile_photo_url': 'photo.jpg', + 'consultation_option_price': 2000, + 'start_date': '2024-01-01T00:00:00Z', + 'end_date': '2024-01-31T00:00:00Z', + 'consultant_id': 1, + 'diaries': [], + 'personal_diet_id': null, + 'personal_diet_name': 'Индивидуальный план питания', + }; + + final model = ConsultationModel.fromJson(json); + + expect(model.chatId, 'direct-chat-uuid'); + expect(model.personalDietName, 'Индивидуальный план питания'); + }); + + test('fromJson allows missing chat_id', () { + final json = { + 'id': 1, + 'last_state': 'started', + 'plan_title': 'Test Plan', + 'user_name': 'User 1', + 'user_slug': 'user-1', + 'consultant_payment': 1000.0, + 'duration': 30, + 'current_diary_day': 5, + 'user_profile_photo_url': 'photo.jpg', + 'consultation_option_price': 2000, + 'start_date': '2024-01-01T00:00:00Z', + 'end_date': '2024-01-31T00:00:00Z', + 'consultant_id': 1, + 'diaries': [], + 'personal_diet_id': null, + }; + + final model = ConsultationModel.fromJson(json); + + expect(model.chatId, isNull); + }); + test('toJson serializes ConsultationModel correctly', () { final model = ConsultationModel( id: 1, diff --git a/test/features/consultations/presentation/cubit/consultations_cubit_test.dart b/test/features/consultations/presentation/cubit/consultations_cubit_test.dart index 26ab5974..0e3fe5ef 100644 --- a/test/features/consultations/presentation/cubit/consultations_cubit_test.dart +++ b/test/features/consultations/presentation/cubit/consultations_cubit_test.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/core/enums/base_state.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart'; import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart'; @@ -8,14 +9,21 @@ import 'package:mocktail/mocktail.dart'; class MockConsultationsRepository extends Mock implements ConsultationsRepository {} +class MockChatRepository extends Mock implements ChatRepository {} + void main() { group('ConsultationsCubit', () { late ConsultationsCubit cubit; late MockConsultationsRepository mockRepository; + late MockChatRepository mockChatRepository; setUp(() { mockRepository = MockConsultationsRepository(); - cubit = ConsultationsCubit(consultationsRepository: mockRepository); + mockChatRepository = MockChatRepository(); + cubit = ConsultationsCubit( + consultationsRepository: mockRepository, + chatRepository: mockChatRepository, + ); }); tearDown(() { @@ -47,5 +55,33 @@ void main() { expect(cubit.state.state, BaseState.error); }); + + test('getChatIdByUserSlug - возвращает id чата', () async { + when(() => mockChatRepository.getChatByUserSlug('john-doe')) + .thenAnswer((_) async => 'chat-uuid'); + + final chatId = await cubit.getChatIdByUserSlug('john-doe'); + + expect(chatId, 'chat-uuid'); + verify(() => mockChatRepository.getChatByUserSlug('john-doe')).called(1); + }); + + test('getChatIdByUserSlug - возвращает null при ошибке', () async { + when(() => mockChatRepository.getChatByUserSlug(any())) + .thenThrow(Exception('Error')); + + final chatId = await cubit.getChatIdByUserSlug('john-doe'); + + expect(chatId, isNull); + }); + + test('getChatIdByUserSlug - возвращает null когда чата нет', () async { + when(() => mockChatRepository.getChatByUserSlug(any())) + .thenAnswer((_) async => null); + + final chatId = await cubit.getChatIdByUserSlug('john-doe'); + + expect(chatId, isNull); + }); }); } diff --git a/test/features/consultations/presentation/pages/consultations_screen_smoke_test.dart b/test/features/consultations/presentation/pages/consultations_screen_smoke_test.dart index 22e83fe7..456efe9c 100644 --- a/test/features/consultations/presentation/pages/consultations_screen_smoke_test.dart +++ b/test/features/consultations/presentation/pages/consultations_screen_smoke_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart'; import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart'; import 'package:eatvio_app/features/consultations/presentation/pages/consultations_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/consultations/presentation/widgets/consultation_card_widget_test.dart b/test/features/consultations/presentation/widgets/consultation_card_widget_test.dart index c897d8e2..3809a3dd 100644 --- a/test/features/consultations/presentation/widgets/consultation_card_widget_test.dart +++ b/test/features/consultations/presentation/widgets/consultation_card_widget_test.dart @@ -1,18 +1,25 @@ +import 'dart:async'; + import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; +import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart'; import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_card_widget.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:network_image_mock/network_image_mock.dart'; +class MockConsultationsCubit extends Mock implements ConsultationsCubit {} + void main() { group('ConsultationCardWidget smoke', () { setUpAll(() async { @@ -28,6 +35,20 @@ void main() { AppConfig(buildType: AppBuildType.tests) ..setBaseUrl('http://localhost'), ); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async => null, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); final mockConsultation = ConsultationModel( @@ -64,20 +85,29 @@ void main() { personalDietId: null, ); - Widget wrap(Widget child) { + Widget wrap(Widget child, {ConsultationsCubit? cubit}) { + final consultationsCubit = cubit ?? MockConsultationsCubit(); return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', routes: [ - GoRoute(path: '/', builder: (context, state) => child), + GoRoute( + path: '/', + builder: (context, state) => BlocProvider.value( + value: consultationsCubit, + child: child, + ), + ), + GoRoute( + path: '/chat-screen', + name: 'chatScreen', + builder: (context, state) => Scaffold( + body: Text('chat:${(state.extra as Map)['uuid']}'), + ), + ), GoRoute( path: '/profile-screen', name: 'profileScreen', @@ -117,6 +147,29 @@ void main() { }); }); + testWidgets('shows personal diet name in status chip', (tester) async { + final consultation = mockConsultation.copyWith( + personalDietId: 1, + personalDietName: 'Индивидуальный план питания', + ); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap(ConsultationCardWidget(consultationsModel: consultation)), + ); + await tester.pumpAndSettle(); + + final s = S.of(tester.element(find.byType(ConsultationCardWidget))); + + expect( + find.text( + s.personal_diet_proposed_named('Индивидуальный план питания'), + ), + findsOneWidget, + ); + }); + }); + testWidgets('renders diary days', (tester) async { await mockNetworkImagesFor(() async { await tester.pumpWidget( @@ -163,5 +216,118 @@ void main() { }); }, ); + + testWidgets('opens chat with consultation user when chat icon tapped', ( + tester, + ) async { + final cubit = MockConsultationsCubit(); + when(() => cubit.stream).thenAnswer((_) => const Stream.empty()); + when(() => cubit.getChatIdByUserSlug('john-doe')) + .thenAnswer((_) async => 'chat-uuid'); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap( + ConsultationCardWidget(consultationsModel: mockConsultation), + cubit: cubit, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.chat_outlined)); + await tester.pumpAndSettle(); + + expect(find.text('chat:chat-uuid'), findsOneWidget); + verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1); + }); + }); + + testWidgets( + 'opens chat directly with chat id without requesting it again', + (tester) async { + final cubit = MockConsultationsCubit(); + when(() => cubit.stream).thenAnswer((_) => const Stream.empty()); + final consultationWithChatId = mockConsultation.copyWith( + chatId: 'direct-chat-uuid', + ); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap( + ConsultationCardWidget( + consultationsModel: consultationWithChatId, + ), + cubit: cubit, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.chat_outlined)); + await tester.pumpAndSettle(); + + expect(find.text('chat:direct-chat-uuid'), findsOneWidget); + verifyNever(() => cubit.getChatIdByUserSlug(any())); + }); + }, + ); + + testWidgets('shows error and stays on card when chat id is null', ( + tester, + ) async { + final cubit = MockConsultationsCubit(); + when(() => cubit.stream).thenAnswer((_) => const Stream.empty()); + when(() => cubit.getChatIdByUserSlug('john-doe')) + .thenAnswer((_) async => null); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap( + ConsultationCardWidget(consultationsModel: mockConsultation), + cubit: cubit, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.chat_outlined)); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 3)); + + expect(find.textContaining('chat:'), findsNothing); + expect( + find.byType(ConsultationCardWidget), + findsOneWidget, + ); + verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1); + }); + }); + + testWidgets('does not request chat id twice while first is pending', ( + tester, + ) async { + final cubit = MockConsultationsCubit(); + when(() => cubit.stream).thenAnswer((_) => const Stream.empty()); + final completer = Completer(); + when(() => cubit.getChatIdByUserSlug('john-doe')) + .thenAnswer((_) => completer.future); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap( + ConsultationCardWidget(consultationsModel: mockConsultation), + cubit: cubit, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.chat_outlined)); + await tester.tap(find.byIcon(Icons.chat_outlined)); + + completer.complete('chat-uuid'); + await tester.pumpAndSettle(); + + expect(find.text('chat:chat-uuid'), findsOneWidget); + verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1); + }); + }); }); } diff --git a/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart b/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart new file mode 100644 index 00000000..364a1dc0 --- /dev/null +++ b/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart @@ -0,0 +1,93 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: Center(child: child)), + ); +} + +void main() { + group('ConsultationProgressPlank', () { + testWidgets('не строит шаги при showProgressPlank=false', (tester) async { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateConfirmedByConsultant, + hasPersonalDiet: true, + ); + expect(progress.showProgressPlank, isFalse); + + await tester.pumpWidget( + _wrap(ConsultationProgressPlank(progress: progress)), + ); + + expect( + find.descendant( + of: find.byType(ConsultationProgressPlank), + matching: find.byType(SizedBox), + ), + findsOneWidget, + ); + expect(find.byIcon(Icons.check), findsNothing); + expect(find.byType(Text), findsNothing); + }); + + testWidgets( + 'рисует 4 шага с иконками и подписями при showProgressPlank=true', + (tester) async { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateDone, + hasPersonalDiet: false, + ); + expect(progress.showProgressPlank, isTrue); + + await tester.pumpWidget( + _wrap(ConsultationProgressPlank(progress: progress)), + ); + + final s = S.of(tester.element(find.byType(ConsultationProgressPlank))); + + expect(find.byIcon(Icons.check), findsNWidgets(4)); + expect(find.text(s.startDateHasBeenSet), findsOneWidget); + expect(find.text(s.order_paid), findsOneWidget); + expect(find.text(s.order_in_progress), findsOneWidget); + expect(find.text(s.done), findsOneWidget); + }, + ); + + testWidgets('подписи шагов центрированы под своими кружками', ( + tester, + ) async { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateDone, + hasPersonalDiet: false, + ); + + await tester.pumpWidget( + _wrap( + SizedBox( + width: 360, + child: ConsultationProgressPlank(progress: progress), + ), + ), + ); + + for (var index = 0; index < 4; index++) { + final circle = tester.getCenter( + find.byKey(ValueKey('consultation_step_circle_$index')), + ); + final label = tester.getCenter( + find.byKey(ValueKey('consultation_step_label_$index')), + ); + expect(label.dx, closeTo(circle.dx, 0.5)); + } + }); + }); +} diff --git a/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart b/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart new file mode 100644 index 00000000..50786729 --- /dev/null +++ b/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart @@ -0,0 +1,105 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: Center(child: child)), + ); +} + +Widget _chip( + ChosenPlanStateEnum state, { + bool hasPersonalDiet = true, + String? personalDietName, +}) { + return PersonalDietStatusChip( + progress: mapConsultationProgress( + state: state, + hasPersonalDiet: hasPersonalDiet, + personalDietName: personalDietName, + ), + ); +} + +void main() { + group('PersonalDietStatusChip', () { + testWidgets('notRequired + active ничего не показывает', (tester) async { + await tester.pumpWidget( + _wrap(_chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)), + ); + + expect( + find.descendant( + of: find.byType(PersonalDietStatusChip), + matching: find.byType(SizedBox), + ), + findsOneWidget, + ); + expect(find.byType(Text), findsNothing); + }); + + testWidgets('proposed показывает personal_diet_proposed', (tester) async { + await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.stateStarted))); + + final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); + + expect(find.text(s.personal_diet_proposed), findsOneWidget); + }); + + testWidgets('proposed с названием показывает имя диеты', (tester) async { + await tester.pumpWidget( + _wrap( + _chip( + ChosenPlanStateEnum.stateStarted, + personalDietName: 'Индивидуальный план питания', + ), + ), + ); + + final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); + + expect( + find.text(s.personal_diet_proposed_named('Индивидуальный план питания')), + findsOneWidget, + ); + }); + + testWidgets('notProposed показывает personal_diet_not_proposed', ( + tester, + ) async { + await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.statePaid))); + + final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); + + expect(find.text(s.personal_diet_not_proposed), findsOneWidget); + }); + + testWidgets('canceled показывает orderCanceled', (tester) async { + await tester.pumpWidget( + _wrap(_chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)), + ); + + final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); + + expect(find.text(s.orderCanceled), findsOneWidget); + }); + + testWidgets('paymentFailed показывает payment_failed', (tester) async { + await tester.pumpWidget( + _wrap(_chip(ChosenPlanStateEnum.statePaymentFailed)), + ); + + final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); + + expect(find.text(s.payment_failed), findsOneWidget); + }); + }); +} diff --git a/test/features/consultations/utils/consultation_progress_mapper_test.dart b/test/features/consultations/utils/consultation_progress_mapper_test.dart new file mode 100644 index 00000000..ac0ded6c --- /dev/null +++ b/test/features/consultations/utils/consultation_progress_mapper_test.dart @@ -0,0 +1,289 @@ +import 'package:eatvio_app/features/consultations/models/consultation_progress.dart'; +import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:flutter_test/flutter_test.dart'; + +typedef _Expected = ({ + Set steps, + bool plank, + PersonalDietStatus diet, + ConsultationPhase phase, +}); + +const _startDate = ConsultationStep.startDate; +const _paid = ConsultationStep.paid; +const _inProgress = ConsultationStep.inProgress; +const _finished = ConsultationStep.finished; + +final Map _expectations = { + ChosenPlanStateEnum.stateInited: ( + steps: {}, + plank: false, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateStartDateHasBeenSet: ( + steps: {_startDate}, + plank: true, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateInCoordination: ( + steps: {}, + plank: true, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateStarted: ( + steps: {_startDate, _paid, _inProgress}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateInProgress: ( + steps: {_startDate, _paid, _inProgress}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.statePendingPayment: ( + steps: {_startDate}, + plank: true, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateConfirmedByConsultant: ( + steps: {}, + plank: false, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.statePaid: ( + steps: {_startDate, _paid}, + plank: true, + diet: PersonalDietStatus.notProposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateCanceledByTheInitiator: ( + steps: {}, + plank: false, + diet: PersonalDietStatus.notRequired, + phase: ConsultationPhase.canceled, + ), + ChosenPlanStateEnum.stateLastDayStarted: ( + steps: {_startDate, _paid, _inProgress}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateLastDayFinished: ( + steps: {_startDate, _paid, _inProgress}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateComplained: ( + steps: {_startDate, _paid, _inProgress}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateDone: ( + steps: {_startDate, _paid, _inProgress, _finished}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.personalDietSet: ( + steps: {_startDate, _paid}, + plank: true, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.stateChargeWasCollected: ( + steps: {_startDate, _paid, _inProgress, _finished}, + plank: false, + diet: PersonalDietStatus.proposed, + phase: ConsultationPhase.active, + ), + ChosenPlanStateEnum.statePaymentFailed: ( + steps: {_startDate}, + plank: false, + diet: PersonalDietStatus.notRequired, + phase: ConsultationPhase.paymentFailed, + ), +}; + +void main() { + group('mapConsultationProgress — все состояния', () { + test('таблица покрывает ровно все 16 состояний', () { + expect(_expectations.length, 16); + expect(_expectations.keys.toSet(), ChosenPlanStateEnum.values.toSet()); + }); + + for (final entry in _expectations.entries) { + test('${entry.key.name} маппится во все поля ConsultationProgress', () { + final progress = mapConsultationProgress( + state: entry.key, + hasPersonalDiet: true, + ); + + expect(progress.completedSteps, unorderedEquals(entry.value.steps)); + expect(progress.showProgressPlank, entry.value.plank); + expect(progress.dietStatus, entry.value.diet); + expect(progress.phase, entry.value.phase); + }); + } + }); + + group('mapConsultationProgress — ключевые сценарии', () { + test('in_coordination показывает плашку без завершённых шагов', () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateInCoordination, + hasPersonalDiet: true, + ); + + expect(progress.showProgressPlank, isTrue); + expect(progress.completedSteps, isEmpty); + }); + + test( + 'personal_diet_setted показывает плашку и завершает startDate+paid', + () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.personalDietSet, + hasPersonalDiet: true, + ); + + expect(progress.showProgressPlank, isTrue); + expect(progress.completedSteps, unorderedEquals([_startDate, _paid])); + }, + ); + + test( + 'started/in_progress/last_day_started/last_day_finished/complained — 3 шага', + () { + const states = [ + ChosenPlanStateEnum.stateStarted, + ChosenPlanStateEnum.stateInProgress, + ChosenPlanStateEnum.stateLastDayStarted, + ChosenPlanStateEnum.stateLastDayFinished, + ChosenPlanStateEnum.stateComplained, + ]; + + for (final state in states) { + final progress = mapConsultationProgress( + state: state, + hasPersonalDiet: true, + ); + + expect( + progress.completedSteps, + unorderedEquals([_startDate, _paid, _inProgress]), + reason: 'state=${state.name}', + ); + } + }, + ); + + test('done/charge_was_collected — 4 шага', () { + const states = [ + ChosenPlanStateEnum.stateDone, + ChosenPlanStateEnum.stateChargeWasCollected, + ]; + + for (final state in states) { + final progress = mapConsultationProgress( + state: state, + hasPersonalDiet: true, + ); + + expect( + progress.completedSteps, + unorderedEquals([_startDate, _paid, _inProgress, _finished]), + reason: 'state=${state.name}', + ); + } + }); + + test( + 'canceled — фаза canceled и dietStatus notRequired даже при диете', + () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.stateCanceledByTheInitiator, + hasPersonalDiet: true, + ); + + expect(progress.phase, ConsultationPhase.canceled); + expect(progress.isCanceled, isTrue); + expect(progress.dietStatus, PersonalDietStatus.notRequired); + }, + ); + + test('payment_failed — фаза paymentFailed и только startDate', () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.statePaymentFailed, + hasPersonalDiet: true, + ); + + expect(progress.phase, ConsultationPhase.paymentFailed); + expect(progress.isPaymentFailed, isTrue); + expect(progress.completedSteps, unorderedEquals([_startDate])); + }); + + test('hasPersonalDiet=false даёт notRequired для любого состояния', () { + for (final state in ChosenPlanStateEnum.values) { + final progress = mapConsultationProgress( + state: state, + hasPersonalDiet: false, + ); + + expect( + progress.dietStatus, + PersonalDietStatus.notRequired, + reason: 'state=${state.name}', + ); + expect(progress.hasDietChip, isFalse, reason: 'state=${state.name}'); + } + }); + + test('paid с диетой даёт notProposed', () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.statePaid, + hasPersonalDiet: true, + ); + + expect(progress.dietStatus, PersonalDietStatus.notProposed); + }); + + test('personal_diet_setted/started/proposed дают proposed', () { + const states = [ + ChosenPlanStateEnum.personalDietSet, + ChosenPlanStateEnum.stateStarted, + ]; + + for (final state in states) { + final progress = mapConsultationProgress( + state: state, + hasPersonalDiet: true, + ); + + expect( + progress.dietStatus, + PersonalDietStatus.proposed, + reason: 'state=${state.name}', + ); + } + }); + + test('personalDietName передаётся в ConsultationProgress', () { + final progress = mapConsultationProgress( + state: ChosenPlanStateEnum.personalDietSet, + hasPersonalDiet: true, + personalDietName: 'Индивидуальный план питания', + ); + + expect(progress.personalDietName, 'Индивидуальный план питания'); + }); + }); +} diff --git a/test/features/create_diet/advanced_widget_test.dart b/test/features/create_diet/advanced_widget_test.dart index 838d9fa9..de3352c8 100644 --- a/test/features/create_diet/advanced_widget_test.dart +++ b/test/features/create_diet/advanced_widget_test.dart @@ -6,8 +6,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/status_drop import 'package:eatvio_app/features/create_diet/repositories/create_diet_repository.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -41,12 +40,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => createDietCubit, @@ -181,12 +175,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider(create: (context) => createDietCubit, child: screenLayout), ), diff --git a/test/features/create_diet/basic_widget_test.dart b/test/features/create_diet/basic_widget_test.dart index 6812d414..e23f5e1a 100644 --- a/test/features/create_diet/basic_widget_test.dart +++ b/test/features/create_diet/basic_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_diet/integration_widget_test.dart b/test/features/create_diet/integration_widget_test.dart index 0d8c7b31..b96e3db9 100644 --- a/test/features/create_diet/integration_widget_test.dart +++ b/test/features/create_diet/integration_widget_test.dart @@ -8,7 +8,6 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/diet_type_c import 'package:eatvio_app/features/create_diet/presentation/widgets/diet_image_picker_widget.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_cubit.dart'; import 'package:eatvio_app/features/create_diet/presentation/create_diet_screen.dart'; @@ -16,7 +15,7 @@ import 'package:eatvio_app/features/create_diet/repositories/create_diet_reposit import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -57,12 +56,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider(create: (context) => createDietCubit, child: const CreateDietScreen()), ); @@ -291,12 +285,7 @@ void main() { Widget editWidget = MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => createDietCubit, diff --git a/test/features/create_diet/presentation/create_diet_screen_test.dart b/test/features/create_diet/presentation/create_diet_screen_test.dart index 6f3de99c..a9e79599 100644 --- a/test/features/create_diet/presentation/create_diet_screen_test.dart +++ b/test/features/create_diet/presentation/create_diet_screen_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_c import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/create_diet_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -36,12 +35,7 @@ void main() { Widget wrap(Widget child, CreateDietCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/create_diet/presentation/diet_preview_screen_smoke_test.dart b/test/features/create_diet/presentation/diet_preview_screen_smoke_test.dart index b8b89a3b..1163a5f0 100644 --- a/test/features/create_diet/presentation/diet_preview_screen_smoke_test.dart +++ b/test/features/create_diet/presentation/diet_preview_screen_smoke_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_diet/presentation/diet_preview_screen.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; @@ -25,12 +24,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_diet/presentation/widgets/add_meal_widget_test.dart b/test/features/create_diet/presentation/widgets/add_meal_widget_test.dart index 83e81f50..f770be21 100644 --- a/test/features/create_diet/presentation/widgets/add_meal_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/add_meal_widget_test.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/add_meal_wi import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_diet/presentation/widgets/day_widget_test.dart b/test/features/create_diet/presentation/widgets/day_widget_test.dart index 1e2ffbb9..e223de80 100644 --- a/test/features/create_diet/presentation/widgets/day_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/day_widget_test.dart @@ -11,10 +11,9 @@ import 'package:eatvio_app/features/create_diet/presentation/widgets/day_widget. import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/choice_chip_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -36,12 +35,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_diet/presentation/widgets/diet_duration_drop_down_widget_test.dart b/test/features/create_diet/presentation/widgets/diet_duration_drop_down_widget_test.dart index fc46e86f..6512d4bc 100644 --- a/test/features/create_diet/presentation/widgets/diet_duration_drop_down_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/diet_duration_drop_down_widget_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_c import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/diet_duration_drop_down_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_diet/presentation/widgets/diet_type_choice_widget_test.dart b/test/features/create_diet/presentation/widgets/diet_type_choice_widget_test.dart index c3623f05..e1184296 100644 --- a/test/features/create_diet/presentation/widgets/diet_type_choice_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/diet_type_choice_widget_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_c import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/diet_type_choice_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_diet/presentation/widgets/error_widget_test.dart b/test/features/create_diet/presentation/widgets/error_widget_test.dart index 9c423e6a..61ace20a 100644 --- a/test/features/create_diet/presentation/widgets/error_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/error_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/create_diet/presentation/widgets/status_drop_down_widget_test.dart b/test/features/create_diet/presentation/widgets/status_drop_down_widget_test.dart index 7c712f85..99e52e77 100644 --- a/test/features/create_diet/presentation/widgets/status_drop_down_widget_test.dart +++ b/test/features/create_diet/presentation/widgets/status_drop_down_widget_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_s import 'package:eatvio_app/features/create_diet/presentation/widgets/status_drop_down_widget.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -32,12 +31,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_plan/advanced_widget_test.dart b/test/features/create_plan/advanced_widget_test.dart index 2a0530a7..b276b80f 100644 --- a/test/features/create_plan/advanced_widget_test.dart +++ b/test/features/create_plan/advanced_widget_test.dart @@ -1,5 +1,4 @@ import 'package:flutter_portal/flutter_portal.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/di/app_config_registration.dart'; @@ -9,7 +8,7 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_type_choice_widget.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/option_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -34,12 +33,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: SizedBox( width: 800, diff --git a/test/features/create_plan/basic_widget_test.dart b/test/features/create_plan/basic_widget_test.dart index 1c33d588..9f42963b 100644 --- a/test/features/create_plan/basic_widget_test.dart +++ b/test/features/create_plan/basic_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_plan/integration_widget_test.dart b/test/features/create_plan/integration_widget_test.dart index 9ec3b2ad..f5334496 100644 --- a/test/features/create_plan/integration_widget_test.dart +++ b/test/features/create_plan/integration_widget_test.dart @@ -3,8 +3,7 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/create_plan_screen.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -33,12 +32,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => createPlanCubit, @@ -275,12 +269,7 @@ void main() { Widget editWidget = MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => createPlanCubit, diff --git a/test/features/create_plan/presentation/create_plan_screen_test.dart b/test/features/create_plan/presentation/create_plan_screen_test.dart index 1fdea634..9d1f4b79 100644 --- a/test/features/create_plan/presentation/create_plan_screen_test.dart +++ b/test/features/create_plan/presentation/create_plan_screen_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/features/create_plan/presentation/create_plan_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -36,12 +35,7 @@ void main() { Widget wrap(Widget child, CreatePlanCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/create_plan/presentation/widgets/add_item_widget_test.dart b/test/features/create_plan/presentation/widgets/add_item_widget_test.dart index 9342356a..3f7f5799 100644 --- a/test/features/create_plan/presentation/widgets/add_item_widget_test.dart +++ b/test/features/create_plan/presentation/widgets/add_item_widget_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/add_item_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_plan/presentation/widgets/option_widget_test.dart b/test/features/create_plan/presentation/widgets/option_widget_test.dart index 782738a9..1fd42244 100644 --- a/test/features/create_plan/presentation/widgets/option_widget_test.dart +++ b/test/features/create_plan/presentation/widgets/option_widget_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/create_plan/presentation/widgets/option_widg import 'package:eatvio_app/features/create_plan/presentation/widgets/select_exact_option_widget.dart'; import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -28,12 +27,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal(child: Scaffold(body: child)), ); diff --git a/test/features/create_plan/presentation/widgets/options_count_button_test.dart b/test/features/create_plan/presentation/widgets/options_count_button_test.dart index d03e16a7..c42af71e 100644 --- a/test/features/create_plan/presentation/widgets/options_count_button_test.dart +++ b/test/features/create_plan/presentation/widgets/options_count_button_test.dart @@ -3,10 +3,9 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/options_count_button.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -23,12 +22,7 @@ void main() { Widget wrap(Widget child, CreatePlanCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold( body: BlocProvider.value(value: cubit, child: child), diff --git a/test/features/create_plan/presentation/widgets/plan_duration_drop_down_widget_test.dart b/test/features/create_plan/presentation/widgets/plan_duration_drop_down_widget_test.dart index 9301d619..7377def8 100644 --- a/test/features/create_plan/presentation/widgets/plan_duration_drop_down_widget_test.dart +++ b/test/features/create_plan/presentation/widgets/plan_duration_drop_down_widget_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_plan/presentation/widgets/plan_type_choice_widget_test.dart b/test/features/create_plan/presentation/widgets/plan_type_choice_widget_test.dart index a52e1901..ae62132e 100644 --- a/test/features/create_plan/presentation/widgets/plan_type_choice_widget_test.dart +++ b/test/features/create_plan/presentation/widgets/plan_type_choice_widget_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_state.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_type_choice_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/create_plan/presentation/widgets/select_exact_option_widget_test.dart b/test/features/create_plan/presentation/widgets/select_exact_option_widget_test.dart index 238b13df..6bce4856 100644 --- a/test/features/create_plan/presentation/widgets/select_exact_option_widget_test.dart +++ b/test/features/create_plan/presentation/widgets/select_exact_option_widget_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/select_exact_option_widget.dart'; import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/create_recipe/basic_widget_test.dart b/test/features/create_recipe/basic_widget_test.dart index 385a17c8..62118978 100644 --- a/test/features/create_recipe/basic_widget_test.dart +++ b/test/features/create_recipe/basic_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/reporitories/recipe_repository.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/create_recipe/presentation/pages/recipe_create_screen_test.dart b/test/features/create_recipe/presentation/pages/recipe_create_screen_test.dart index 9b8825de..0f41392b 100644 --- a/test/features/create_recipe/presentation/pages/recipe_create_screen_test.dart +++ b/test/features/create_recipe/presentation/pages/recipe_create_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recip import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/pages/recipe_create_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -37,12 +36,7 @@ void main() { Widget wrap(Widget child, CreateRecipeCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/create_recipe/presentation/widgets/add_portion_widget_test.dart b/test/features/create_recipe/presentation/widgets/add_portion_widget_test.dart index 28415699..5f2ca337 100644 --- a/test/features/create_recipe/presentation/widgets/add_portion_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/add_portion_widget_test.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recip import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/add_portion_widget.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/presentation/widgets/info_about_recipe_widget_test.dart b/test/features/create_recipe/presentation/widgets/info_about_recipe_widget_test.dart index c0c64155..cd6c41ff 100644 --- a/test/features/create_recipe/presentation/widgets/info_about_recipe_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/info_about_recipe_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity. import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/info_about_recipe_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/presentation/widgets/portion_widget_test.dart b/test/features/create_recipe/presentation/widgets/portion_widget_test.dart index 2c0dd822..7d43609b 100644 --- a/test/features/create_recipe/presentation/widgets/portion_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/portion_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity. import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/portion_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/presentation/widgets/steps_widget_test.dart b/test/features/create_recipe/presentation/widgets/steps_widget_test.dart index 450d56fd..f8d9ef9b 100644 --- a/test/features/create_recipe/presentation/widgets/steps_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/steps_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity. import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/steps_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/presentation/widgets/tags_widget_test.dart b/test/features/create_recipe/presentation/widgets/tags_widget_test.dart index 4e4ddbfd..37f83530 100644 --- a/test/features/create_recipe/presentation/widgets/tags_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/tags_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity. import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/tags_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/presentation/widgets/time_of_cook_widget_test.dart b/test/features/create_recipe/presentation/widgets/time_of_cook_widget_test.dart index d6d4cc0c..ef936c7e 100644 --- a/test/features/create_recipe/presentation/widgets/time_of_cook_widget_test.dart +++ b/test/features/create_recipe/presentation/widgets/time_of_cook_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity. import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart'; import 'package:eatvio_app/features/create_recipe/presentation/widgets/time_of_cook_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/create_recipe/simple_widget_test.dart b/test/features/create_recipe/simple_widget_test.dart index 1cbced01..9ed893e0 100644 --- a/test/features/create_recipe/simple_widget_test.dart +++ b/test/features/create_recipe/simple_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/create_recipe/presentation/widgets/ingredien import 'package:eatvio_app/features/create_recipe/presentation/widgets/steps_widget.dart'; import 'package:eatvio_app/features/create_recipe/reporitories/recipe_repository.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/create_recipe/widget_test.dart b/test/features/create_recipe/widget_test.dart index 6a60b0b3..4261abd3 100644 --- a/test/features/create_recipe/widget_test.dart +++ b/test/features/create_recipe/widget_test.dart @@ -2,7 +2,6 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:flutter_portal/flutter_portal.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart'; @@ -14,7 +13,7 @@ import 'package:eatvio_app/features/create_recipe/reporitories/recipe_repository import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -51,12 +50,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider( create: (context) => createRecipeCubit, diff --git a/test/features/dev_tools/presentation/dev_tools_screen_smoke_test.dart b/test/features/dev_tools/presentation/dev_tools_screen_smoke_test.dart index 4f7e70ec..08a416f1 100644 --- a/test/features/dev_tools/presentation/dev_tools_screen_smoke_test.dart +++ b/test/features/dev_tools/presentation/dev_tools_screen_smoke_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart'; import 'package:dio/dio.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/diary/models/diary_day_model_test.dart b/test/features/diary/models/diary_day_model_test.dart index 8de1266d..3ecb0713 100644 --- a/test/features/diary/models/diary_day_model_test.dart +++ b/test/features/diary/models/diary_day_model_test.dart @@ -31,24 +31,70 @@ void main() { }; test('parses commented_from_diet state', () { - final model = PortionModel.fromJson(portionJson(state: 'commented_from_diet')); + final model = PortionModel.fromJson( + portionJson(state: 'commented_from_diet'), + ); expect(model.portionState, PortionState.commentedFromDiet); }); test('parses reviewed_from_diet state', () { - final model = PortionModel.fromJson(portionJson(state: 'reviewed_from_diet')); + final model = PortionModel.fromJson( + portionJson(state: 'reviewed_from_diet'), + ); expect(model.portionState, PortionState.reviewedFromDiet); }); test('does not throw on unknown state from backend', () { - final model = PortionModel.fromJson(portionJson(state: 'some_future_state')); + final model = PortionModel.fromJson( + portionJson(state: 'some_future_state'), + ); expect(model.portionState, PortionState.unknown); }); }); + group('DiaryDayModel.user (владелец дневника)', () { + Map diaryJson({Object? user}) => { + 'id': 1, + 'date': '2026-11-09', + 'closed': 0, + 'comment': '', + 'state': { + 'has_chosen_diet': false, + 'has_chosen_plan': false, + 'last_state': null, + }, + 'meals': [], + 'chosen_plan_id': null, + 'day_of_chosen_diet': null, + 'chosen_diet': null, + 'user': ?user, + }; + + test('user.slug попадает в entity как ownerSlug', () { + final model = DiaryDayModel.fromJson( + diaryJson(user: {'id': 3577, 'slug': 'id-3577'}), + ); + + expect(model.owner?.id, 3577); + expect(model.toEntity()!.ownerSlug, 'id-3577'); + }); + + test('старый ответ без user: ownerSlug == null', () { + expect(DiaryDayModel.fromJson(diaryJson()).toEntity()!.ownerSlug, isNull); + }); + + test('user.slug == null (у владельца нет slug): ownerSlug == null', () { + final model = DiaryDayModel.fromJson( + diaryJson(user: {'id': 1, 'slug': null}), + ); + + expect(model.toEntity()!.ownerSlug, isNull); + }); + }); + group('DiaryDayWrapperModel', () { test('fromJson parses diary correctly', () { final json = { @@ -57,7 +103,11 @@ void main() { 'date': '2024-01-15', 'closed': 0, 'comment': 'Test comment', - 'state': {'has_chosen_diet': false, 'has_chosen_plan': false, 'last_state': null}, + 'state': { + 'has_chosen_diet': false, + 'has_chosen_plan': false, + 'last_state': null, + }, 'meals': [], 'chosen_plan_id': null, 'day_of_chosen_diet': null, @@ -78,7 +128,11 @@ void main() { date: '2024-01-15', closed: 0, comment: 'Test comment', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), meals: [], chosenPlanId: null, dayOfChosenDiet: null, @@ -119,7 +173,12 @@ void main() { group('DiaryPhotoModel', () { test('fromJson parses all fields correctly', () { - final json = {'id': 10, 'original_name': 'photo.jpg', 'path': '/path/to/photo.jpg', 'size': 1024}; + final json = { + 'id': 10, + 'original_name': 'photo.jpg', + 'path': '/path/to/photo.jpg', + 'size': 1024, + }; final model = DiaryPhotoModel.fromJson(json); @@ -130,7 +189,12 @@ void main() { }); test('toJson serializes all fields correctly', () { - const model = DiaryPhotoModel(id: 10, originalName: 'photo.jpg', path: '/path/to/photo.jpg', size: 1024); + const model = DiaryPhotoModel( + id: 10, + originalName: 'photo.jpg', + path: '/path/to/photo.jpg', + size: 1024, + ); final json = model.toJson(); @@ -201,7 +265,11 @@ void main() { group('ProductInMeal', () { test('fromJson parses all fields correctly', () { - final json = {'product_name': 'Banana', 'portion': '1 piece', 'quantity': 2}; + final json = { + 'product_name': 'Banana', + 'portion': '1 piece', + 'quantity': 2, + }; final model = ProductInMeal.fromJson(json); @@ -211,7 +279,11 @@ void main() { }); test('toJson serializes all fields correctly', () { - const model = ProductInMeal(productName: 'Banana', portion: '1 piece', quantity: 2); + const model = ProductInMeal( + productName: 'Banana', + portion: '1 piece', + quantity: 2, + ); final json = model.toJson(); @@ -228,7 +300,11 @@ void main() { date: '2024-01-15', closed: 0, comment: 'Test', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), meals: [], chosenPlanId: null, dayOfChosenDiet: null, @@ -248,7 +324,11 @@ void main() { retire: '22:00', closed: 0, comment: 'Test comment', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), meals: [], chosenPlanId: null, dayOfChosenDiet: null, @@ -272,7 +352,11 @@ void main() { date: '2024-01-15', closed: 0, comment: 'Test', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: true, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: null, + ), meals: [], chosenPlanId: null, dayOfChosenDiet: 5, diff --git a/test/features/diary/presentation/pages/barcode_scanner_screen_smoke_test.dart b/test/features/diary/presentation/pages/barcode_scanner_screen_smoke_test.dart index e3aacfeb..e43a54ea 100644 --- a/test/features/diary/presentation/pages/barcode_scanner_screen_smoke_test.dart +++ b/test/features/diary/presentation/pages/barcode_scanner_screen_smoke_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/pages/barcode_scanner_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/diary/presentation/pages/diary_screen_smoke_test.dart b/test/features/diary/presentation/pages/diary_screen_smoke_test.dart index cf2f669a..e2c1e4a0 100644 --- a/test/features/diary/presentation/pages/diary_screen_smoke_test.dart +++ b/test/features/diary/presentation/pages/diary_screen_smoke_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; @@ -15,14 +17,16 @@ import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; import 'package:eatvio_app/features/diary/models/nutrition_model.dart'; import 'package:eatvio_app/core/widgets/data_error_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_widget.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import '../../../../fixtures/doubles/insights_doubles.dart'; import 'diary_screen_smoke_test.mocks.dart'; @GenerateNiceMocks([ @@ -44,17 +48,15 @@ void main() { AppConfig(buildType: AppBuildType.tests) ..setBaseUrl('http://localhost'), ); + sl.registerLazySingleton( + () => FakeInsightsRepository(), + ); }); Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); @@ -66,11 +68,13 @@ void main() { bool isDiaryFinished = false, bool isDiaryCommented = false, int closed = 0, + String? ownerSlug, + String wakeup = '07:00', }) { final diary = DiaryDayEntity( id: 1, date: date, - wakeup: '07:00', + wakeup: wakeup, retire: '23:00', closed: closed, comment: '', @@ -93,6 +97,7 @@ void main() { chosenPlanId: hasChosenPlan ? 10 : null, dayOfChosenDiet: null, diet: null, + ownerSlug: ownerSlug, ); const nutrition = NutritionDataModel( dailyNutritionIntake: NutritionModel( @@ -383,6 +388,241 @@ void main() { expect(find.byType(Text), findsWidgets); }); + Future pumpDiaryWithInsights( + WidgetTester tester, { + required bool isConsultantView, + String? ownerSlug, + String? diaryOwnerSlug, + Stream? diaryStates, + required FakeInsightsRepository insightsRepository, + }) async { + final diaryCubit = MockDiaryCubit(); + final state = loadedState( + hasChosenPlan: false, + ownerSlug: diaryOwnerSlug, + ).copyWith(isConsultantView: isConsultantView); + when(diaryCubit.state).thenReturn(state); + when( + diaryCubit.stream, + ).thenAnswer((_) => diaryStates ?? const Stream.empty()); + when(diaryCubit.close()).thenAnswer((_) async => Future.value()); + when( + diaryCubit.fetchDiaryV2( + needLoading: anyNamed('needLoading'), + diaryId: anyNamed('diaryId'), + ), + ).thenAnswer((_) async => true); + + final commentsCubit = MockConsultantCommentsCubit(); + when(commentsCubit.state).thenReturn( + ConsultantCommentsState( + commentsModel: ConsultantCommentModel(comment: ''), + ), + ); + when( + commentsCubit.stream, + ).thenAnswer((_) => const Stream.empty()); + when(commentsCubit.close()).thenAnswer((_) async => Future.value()); + + sl.registerFactory(() => diaryCubit); + sl.registerFactory(() => commentsCubit); + sl.unregister(); + sl.registerLazySingleton(() => insightsRepository); + + await tester.pumpWidget( + wrap( + isConsultantView + ? UserDiaryScreen(diaryId: 1, ownerSlug: ownerSlug) + : DiaryScreen(date: DateTime(2025, 1, 1)), + ), + ); + await tester.pump(const Duration(milliseconds: 200)); + } + + testWidgets( + 'own diary shows insights card for own data with add button enabled', + (tester) async { + final insightsRepository = FakeInsightsRepository(); + + await pumpDiaryWithInsights( + tester, + isConsultantView: false, + insightsRepository: insightsRepository, + ); + + expect(find.byType(InsightsCard), findsOneWidget); + final card = tester.widget(find.byType(InsightsCard)); + expect(card.slug, isNull); + expect(card.canAdd, isTrue); + expect(card.initialIntraDate, '2025-01-01'); + expect(insightsRepository.serverRequests.single.slug, isNull); + expect( + insightsRepository.serverRequests.single.intraDate, + '2025-01-01', + ); + }, + ); + + testWidgets( + 'consultant view shows insights card of the client without add button', + (tester) async { + final insightsRepository = FakeInsightsRepository(); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + ownerSlug: 'client', + insightsRepository: insightsRepository, + ); + + final card = tester.widget(find.byType(InsightsCard)); + expect(card.slug, 'client'); + expect(card.canAdd, isFalse); + expect(insightsRepository.serverRequests.single.slug, 'client'); + }, + ); + + testWidgets( + 'consultant view takes the owner slug from the diary (user.slug)', + (tester) async { + final insightsRepository = FakeInsightsRepository(); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + diaryOwnerSlug: 'client-from-diary', + insightsRepository: insightsRepository, + ); + + expect( + tester.widget(find.byType(InsightsCard)).slug, + 'client-from-diary', + ); + expect( + insightsRepository.serverRequests.single.slug, + 'client-from-diary', + ); + }, + ); + + testWidgets('diary owner slug wins over the route parameter', ( + tester, + ) async { + final insightsRepository = FakeInsightsRepository(); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + ownerSlug: 'from-route', + diaryOwnerSlug: 'from-diary', + insightsRepository: insightsRepository, + ); + + expect( + tester.widget(find.byType(InsightsCard)).slug, + 'from-diary', + ); + }); + + testWidgets( + 'own diary refreshes insights when meals or wake-up time change', + (tester) async { + final insightsRepository = FakeInsightsRepository(); + final states = StreamController.broadcast(); + addTearDown(states.close); + + await pumpDiaryWithInsights( + tester, + isConsultantView: false, + diaryStates: states.stream, + insightsRepository: insightsRepository, + ); + expect(insightsRepository.serverRequests, hasLength(1)); + + states.add(loadedState(hasChosenPlan: false, wakeup: '06:30')); + await tester.pump(const Duration(milliseconds: 200)); + + expect(insightsRepository.serverRequests, hasLength(2)); + }, + ); + + testWidgets( + 'own diary does not refresh insights when nothing relevant changed', + (tester) async { + final insightsRepository = FakeInsightsRepository(); + final states = StreamController.broadcast(); + addTearDown(states.close); + + await pumpDiaryWithInsights( + tester, + isConsultantView: false, + diaryStates: states.stream, + insightsRepository: insightsRepository, + ); + + states.add(loadedState(hasChosenPlan: false)); + await tester.pump(const Duration(milliseconds: 200)); + + expect(insightsRepository.serverRequests, hasLength(1)); + }, + ); + + testWidgets('consultant view does not refresh insights on diary changes', ( + tester, + ) async { + final insightsRepository = FakeInsightsRepository(); + final states = StreamController.broadcast(); + addTearDown(states.close); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + ownerSlug: 'client', + diaryStates: states.stream, + insightsRepository: insightsRepository, + ); + + states.add( + loadedState( + hasChosenPlan: false, + wakeup: '06:30', + ).copyWith(isConsultantView: true), + ); + await tester.pump(const Duration(milliseconds: 200)); + + expect(insightsRepository.serverRequests, hasLength(1)); + }); + + testWidgets('consultant view without owner slug hides insights card', ( + tester, + ) async { + final insightsRepository = FakeInsightsRepository(); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + insightsRepository: insightsRepository, + ); + + expect(find.byType(InsightsCard), findsNothing); + expect(insightsRepository.serverRequests, isEmpty); + }); + + testWidgets('consultant view hides insights card on 403', (tester) async { + final insightsRepository = FakeInsightsRepository( + error: const InsightsForbidden(), + ); + + await pumpDiaryWithInsights( + tester, + isConsultantView: true, + ownerSlug: 'client', + insightsRepository: insightsRepository, + ); + + expect(find.byKey(const Key('insights_card')), findsNothing); + }); + testWidgets('shows add button for a finished day inside the edit window', ( tester, ) async { diff --git a/test/features/diary/presentation/widgets/add_product_button_widget_test.dart b/test/features/diary/presentation/widgets/add_product_button_widget_test.dart index 9f161f48..f9574b4a 100644 --- a/test/features/diary/presentation/widgets/add_product_button_widget_test.dart +++ b/test/features/diary/presentation/widgets/add_product_button_widget_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/add_product_button_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/add_product_modal_smoke_test.dart b/test/features/diary/presentation/widgets/add_product_modal_smoke_test.dart index 78dbde4c..3f363364 100644 --- a/test/features/diary/presentation/widgets/add_product_modal_smoke_test.dart +++ b/test/features/diary/presentation/widgets/add_product_modal_smoke_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/add_product_modal.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/basic_widget_test.dart b/test/features/diary/presentation/widgets/basic_widget_test.dart index aa9c23f5..d7fc2419 100644 --- a/test/features/diary/presentation/widgets/basic_widget_test.dart +++ b/test/features/diary/presentation/widgets/basic_widget_test.dart @@ -18,8 +18,7 @@ import 'package:eatvio_app/features/glossary/repositories/glossary_repository.da import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -108,12 +107,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MultiBlocProvider( providers: [ diff --git a/test/features/diary/presentation/widgets/calendar_widget_smoke_test.dart b/test/features/diary/presentation/widgets/calendar_widget_smoke_test.dart index 5bd61bda..874d2a29 100644 --- a/test/features/diary/presentation/widgets/calendar_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/calendar_widget_smoke_test.dart @@ -3,10 +3,9 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/calendar_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:table_calendar/table_calendar.dart'; @@ -33,12 +32,7 @@ void main() { child: appChild!, ); }, - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value( value: cubit, diff --git a/test/features/diary/presentation/widgets/calories_chart_widget_smoke_test.dart b/test/features/diary/presentation/widgets/calories_chart_widget_smoke_test.dart index 93c430b0..d60093f5 100644 --- a/test/features/diary/presentation/widgets/calories_chart_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/calories_chart_widget_smoke_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/models/nutrition_model.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/calories_chart_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/diary/presentation/widgets/chosen_diet_widget_content_test.dart b/test/features/diary/presentation/widgets/chosen_diet_widget_content_test.dart index 0ef9081a..feaf2592 100644 --- a/test/features/diary/presentation/widgets/chosen_diet_widget_content_test.dart +++ b/test/features/diary/presentation/widgets/chosen_diet_widget_content_test.dart @@ -1,107 +1,98 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/diary/presentation/widgets/chosen_diet_widget.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('ChosenDietWidgetContent', () { - Widget createTestWidget(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: S.delegate.supportedLocales, - home: Scaffold( - body: child, - ), - ); - } - - testWidgets('displays chosen diet widget content', (tester) async { - await tester.pumpWidget( - createTestWidget( - const ChosenDietWidgetContent( - currentDietDay: 5, - dietName: 'Test Diet', - dietDuration: 14, - dietId: 1, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(ChosenDietWidgetContent), findsOneWidget); - expect(find.text('Test Diet'), findsOneWidget); - }); - - testWidgets('displays current day and duration', (tester) async { - await tester.pumpWidget( - createTestWidget( - const ChosenDietWidgetContent( - currentDietDay: 7, - dietName: 'Test Diet', - dietDuration: 21, - dietId: 1, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(ChosenDietWidgetContent), findsOneWidget); - }); - - testWidgets('displays diet name with underline', (tester) async { - await tester.pumpWidget( - createTestWidget( - const ChosenDietWidgetContent( - currentDietDay: 1, - dietName: 'My Diet', - dietDuration: 7, - dietId: 1, - ), - ), - ); - await tester.pumpAndSettle(); - - expect(find.text('My Diet'), findsOneWidget); - }); - }); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/diary/presentation/widgets/chosen_diet_widget.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('ChosenDietWidgetContent', () { + Widget createTestWidget(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: S.delegate.supportedLocales, + home: Scaffold( + body: child, + ), + ); + } + + testWidgets('displays chosen diet widget content', (tester) async { + await tester.pumpWidget( + createTestWidget( + const ChosenDietWidgetContent( + dietName: 'Test Diet', + dietId: 1, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(ChosenDietWidgetContent), findsOneWidget); + expect(find.text('Test Diet'), findsOneWidget); + expect(find.textContaining('из 14'), findsNothing); + }); + + testWidgets('does not display current day and duration', (tester) async { + await tester.pumpWidget( + createTestWidget( + const ChosenDietWidgetContent( + dietName: 'Test Diet', + dietId: 1, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(ChosenDietWidgetContent), findsOneWidget); + expect(find.textContaining('из 21'), findsNothing); + }); + + testWidgets('displays diet name with underline', (tester) async { + await tester.pumpWidget( + createTestWidget( + const ChosenDietWidgetContent( + dietName: 'My Diet', + dietId: 1, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('My Diet'), findsOneWidget); + expect(find.textContaining('из 7'), findsNothing); + }); + }); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/features/diary/presentation/widgets/chosen_plan_widget_content_test.dart b/test/features/diary/presentation/widgets/chosen_plan_widget_content_test.dart index 9050dcd3..fcde9462 100644 --- a/test/features/diary/presentation/widgets/chosen_plan_widget_content_test.dart +++ b/test/features/diary/presentation/widgets/chosen_plan_widget_content_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/chosen_plan_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -14,12 +13,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: ChosenPlanWidgetContent( diff --git a/test/features/diary/presentation/widgets/comment_container_test.dart b/test/features/diary/presentation/widgets/comment_container_test.dart index b71a1fb5..eec613b1 100644 --- a/test/features/diary/presentation/widgets/comment_container_test.dart +++ b/test/features/diary/presentation/widgets/comment_container_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/comment_container.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/diary/presentation/widgets/comment_for_consultant_widget_test.dart b/test/features/diary/presentation/widgets/comment_for_consultant_widget_test.dart index 4d222587..68119a98 100644 --- a/test/features/diary/presentation/widgets/comment_for_consultant_widget_test.dart +++ b/test/features/diary/presentation/widgets/comment_for_consultant_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/comment_for_consultant_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/comment_widgets_smoke_test.dart b/test/features/diary/presentation/widgets/comment_widgets_smoke_test.dart index f24627c6..47eeb39f 100644 --- a/test/features/diary/presentation/widgets/comment_widgets_smoke_test.dart +++ b/test/features/diary/presentation/widgets/comment_widgets_smoke_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/comment_for_consultant_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/day_comment_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeDiaryCubit extends Cubit implements DiaryCubit { @@ -29,12 +28,7 @@ void main() { Widget wrap(Widget child, {DiaryCubit? diaryCubit, ConsultantCommentsCubit? commentsCubit}) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MultiBlocProvider( providers: [ diff --git a/test/features/diary/presentation/widgets/day_comment_widget_test.dart b/test/features/diary/presentation/widgets/day_comment_widget_test.dart index 4623d7b0..eb33b671 100644 --- a/test/features/diary/presentation/widgets/day_comment_widget_test.dart +++ b/test/features/diary/presentation/widgets/day_comment_widget_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_ import 'package:eatvio_app/features/diary/presentation/widgets/day_comment_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -19,12 +18,7 @@ void main() { Widget wrap(Widget child, ConsultantCommentsCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value(value: cubit, child: child), diff --git a/test/features/diary/presentation/widgets/diary_chosen_widgets_smoke_test.dart b/test/features/diary/presentation/widgets/diary_chosen_widgets_smoke_test.dart index dd7bc0f9..ecf40338 100644 --- a/test/features/diary/presentation/widgets/diary_chosen_widgets_smoke_test.dart +++ b/test/features/diary/presentation/widgets/diary_chosen_widgets_smoke_test.dart @@ -10,9 +10,8 @@ import 'package:eatvio_app/features/diary/presentation/widgets/add_product_butto import 'package:eatvio_app/features/diary/presentation/widgets/chosen_diet_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/chosen_plan_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -39,12 +38,7 @@ void main() { ); return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); @@ -100,6 +94,17 @@ void main() { await tester.pumpWidget(wrap(const ChosenDietWidget(), cubit)); await tester.pump(); expect(find.text('Diet'), findsOneWidget); + expect(find.textContaining('из 7'), findsNothing); + }); + + testWidgets('ChosenDietWidget hides diet day while plan keeps its day', (tester) async { + final cubit = FakeDiaryCubit(loadedState(hasDiet: true, hasPlan: true)); + await tester.pumpWidget(wrap(const Column(children: [ChosenPlanWidget(), ChosenDietWidget()]), cubit)); + await tester.pump(); + expect(find.text('Plan'), findsOneWidget); + expect(find.textContaining('из 30'), findsOneWidget); + expect(find.text('Diet'), findsOneWidget); + expect(find.textContaining('из 7'), findsNothing); }); testWidgets('AddProductButtonWidget renders for loaded state', (tester) async { diff --git a/test/features/diary/presentation/widgets/diary_ratings_and_time_widgets_smoke_test.dart b/test/features/diary/presentation/widgets/diary_ratings_and_time_widgets_smoke_test.dart index 027e6026..11f44410 100644 --- a/test/features/diary/presentation/widgets/diary_ratings_and_time_widgets_smoke_test.dart +++ b/test/features/diary/presentation/widgets/diary_ratings_and_time_widgets_smoke_test.dart @@ -15,10 +15,9 @@ import 'package:eatvio_app/features/diary/presentation/widgets/mood_rating_widge import 'package:eatvio_app/features/diary/presentation/widgets/satiety_rating_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/time_of_meal_picker_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeDiaryCubit extends Cubit implements DiaryCubit { @@ -105,12 +104,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MediaQuery( data: const MediaQueryData(size: Size(500, 900)), diff --git a/test/features/diary/presentation/widgets/diary_time_and_rating_interactions_test.dart b/test/features/diary/presentation/widgets/diary_time_and_rating_interactions_test.dart index 0060ecb5..298cb6d8 100644 --- a/test/features/diary/presentation/widgets/diary_time_and_rating_interactions_test.dart +++ b/test/features/diary/presentation/widgets/diary_time_and_rating_interactions_test.dart @@ -14,10 +14,9 @@ import 'package:eatvio_app/features/diary/presentation/widgets/mood_rating_widge import 'package:eatvio_app/features/diary/presentation/widgets/satiety_rating_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/time_of_meal_picker_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -96,12 +95,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MediaQuery( data: const MediaQueryData(size: Size(500, 900)), diff --git a/test/features/diary/presentation/widgets/finish_day_button_widget_test.dart b/test/features/diary/presentation/widgets/finish_day_button_widget_test.dart index 7b6f29bb..df50e452 100644 --- a/test/features/diary/presentation/widgets/finish_day_button_widget_test.dart +++ b/test/features/diary/presentation/widgets/finish_day_button_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/features/diary/presentation/widgets/finish_day_button_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/diary/presentation/widgets/glossary_moderation_request_modal_widget_test.dart b/test/features/diary/presentation/widgets/glossary_moderation_request_modal_widget_test.dart index b1e8534b..f2245085 100644 --- a/test/features/diary/presentation/widgets/glossary_moderation_request_modal_widget_test.dart +++ b/test/features/diary/presentation/widgets/glossary_moderation_request_modal_widget_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; diff --git a/test/features/diary/presentation/widgets/meal_button_widget_test.dart b/test/features/diary/presentation/widgets/meal_button_widget_test.dart index 469ceeec..2f444778 100644 --- a/test/features/diary/presentation/widgets/meal_button_widget_test.dart +++ b/test/features/diary/presentation/widgets/meal_button_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_button_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/meal_comment_widget_test.dart b/test/features/diary/presentation/widgets/meal_comment_widget_test.dart index eed20765..64b89124 100644 --- a/test/features/diary/presentation/widgets/meal_comment_widget_test.dart +++ b/test/features/diary/presentation/widgets/meal_comment_widget_test.dart @@ -5,10 +5,9 @@ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_comment_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeConsultantCommentsCubit extends Cubit implements ConsultantCommentsCubit { @@ -61,12 +60,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value( value: cubit, diff --git a/test/features/diary/presentation/widgets/meal_summary_widget_test.dart b/test/features/diary/presentation/widgets/meal_summary_widget_test.dart index 8ddb9676..17515117 100644 --- a/test/features/diary/presentation/widgets/meal_summary_widget_test.dart +++ b/test/features/diary/presentation/widgets/meal_summary_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_summary_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/diary/presentation/widgets/meal_widget_smoke_test.dart b/test/features/diary/presentation/widgets/meal_widget_smoke_test.dart index 4ec58013..f3aa9d46 100644 --- a/test/features/diary/presentation/widgets/meal_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/meal_widget_smoke_test.dart @@ -12,10 +12,9 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeDiaryCubit extends Cubit implements DiaryCubit { @@ -71,12 +70,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MediaQuery( data: const MediaQueryData(size: Size(500, 900)), diff --git a/test/features/diary/presentation/widgets/mood_rating_widget_test.dart b/test/features/diary/presentation/widgets/mood_rating_widget_test.dart index 868ba018..440d9d1a 100644 --- a/test/features/diary/presentation/widgets/mood_rating_widget_test.dart +++ b/test/features/diary/presentation/widgets/mood_rating_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/mood_rating_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/photo_gallery_widget_smoke_test.dart b/test/features/diary/presentation/widgets/photo_gallery_widget_smoke_test.dart index 52ee9ca9..2093ef4c 100644 --- a/test/features/diary/presentation/widgets/photo_gallery_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/photo_gallery_widget_smoke_test.dart @@ -12,10 +12,9 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/photo_gallery_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_svg/flutter_svg.dart'; @@ -156,12 +155,7 @@ void main() { Widget wrap(DiaryCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value( value: cubit, diff --git a/test/features/diary/presentation/widgets/portion_comment_widget_test.dart b/test/features/diary/presentation/widgets/portion_comment_widget_test.dart index 9e21550b..6f1501a5 100644 --- a/test/features/diary/presentation/widgets/portion_comment_widget_test.dart +++ b/test/features/diary/presentation/widgets/portion_comment_widget_test.dart @@ -5,10 +5,9 @@ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_ import 'package:eatvio_app/features/diary/presentation/bloc/consultant_comments_cubit/consultant_comments_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/portion_comment_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeConsultantCommentsCubit extends Cubit implements ConsultantCommentsCubit { @@ -51,12 +50,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value( value: cubit, diff --git a/test/features/diary/presentation/widgets/product_loader_widget_test.dart b/test/features/diary/presentation/widgets/product_loader_widget_test.dart index e8c586f3..9809da43 100644 --- a/test/features/diary/presentation/widgets/product_loader_widget_test.dart +++ b/test/features/diary/presentation/widgets/product_loader_widget_test.dart @@ -1,66 +1,66 @@ -import 'package:eatvio_app/features/diary/presentation/widgets/product_loader_widget.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('ProductLoaderWidget', () { - testWidgets('displays product loader widget', (tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Scaffold( - body: ProductLoaderWidget(), - ), - ), - ); - - expect(find.byType(ProductLoaderWidget), findsOneWidget); - expect(find.byType(CupertinoActivityIndicator), findsOneWidget); - }); - - testWidgets('displays ListTile with activity indicator', (tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Scaffold( - body: ProductLoaderWidget(), - ), - ), - ); - - expect(find.byType(ListTile), findsOneWidget); - expect(find.byType(CupertinoActivityIndicator), findsOneWidget); - }); - }); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +import 'package:eatvio_app/features/diary/presentation/widgets/product_loader_widget.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('ProductLoaderWidget', () { + testWidgets('displays product loader widget', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ProductLoaderWidget(), + ), + ), + ); + + expect(find.byType(ProductLoaderWidget), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + }); + + testWidgets('displays ListTile with activity indicator', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ProductLoaderWidget(), + ), + ), + ); + + expect(find.byType(ListTile), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + }); + }); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/features/diary/presentation/widgets/product_widget_smoke_test.dart b/test/features/diary/presentation/widgets/product_widget_smoke_test.dart index 89ac08cd..31c17e6a 100644 --- a/test/features/diary/presentation/widgets/product_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/product_widget_smoke_test.dart @@ -14,10 +14,9 @@ import 'package:eatvio_app/features/diary/presentation/widgets/comment_container import 'package:eatvio_app/features/diary/presentation/widgets/portion_comment_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/product_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeDiaryCubit extends Cubit implements DiaryCubit { @@ -74,12 +73,7 @@ void main() { bundle: bundle, child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MultiBlocProvider( providers: [ diff --git a/test/features/diary/presentation/widgets/products_list_widget_smoke_test.dart b/test/features/diary/presentation/widgets/products_list_widget_smoke_test.dart index ff25b5a8..79a0061c 100644 --- a/test/features/diary/presentation/widgets/products_list_widget_smoke_test.dart +++ b/test/features/diary/presentation/widgets/products_list_widget_smoke_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/meal_summary_widget.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/products_list_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/diary/presentation/widgets/satiety_rating_widget_test.dart b/test/features/diary/presentation/widgets/satiety_rating_widget_test.dart index 77a674af..c9f64885 100644 --- a/test/features/diary/presentation/widgets/satiety_rating_widget_test.dart +++ b/test/features/diary/presentation/widgets/satiety_rating_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/satiety_rating_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/time_of_meal_picker_widget_test.dart b/test/features/diary/presentation/widgets/time_of_meal_picker_widget_test.dart index f08b109b..334d17a3 100644 --- a/test/features/diary/presentation/widgets/time_of_meal_picker_widget_test.dart +++ b/test/features/diary/presentation/widgets/time_of_meal_picker_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/time_of_meal_picker_widget.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/diary/presentation/widgets/wakeup_and_retire_widget_test.dart b/test/features/diary/presentation/widgets/wakeup_and_retire_widget_test.dart index c93f7ccd..ce80265e 100644 --- a/test/features/diary/presentation/widgets/wakeup_and_retire_widget_test.dart +++ b/test/features/diary/presentation/widgets/wakeup_and_retire_widget_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/features/diary/models/nutrition_model.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/wakeup_and_retire_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/diets/presentation/pages/about_diet_screen_smoke_test.dart b/test/features/diets/presentation/pages/about_diet_screen_smoke_test.dart index 18546734..3c9282ad 100644 --- a/test/features/diets/presentation/pages/about_diet_screen_smoke_test.dart +++ b/test/features/diets/presentation/pages/about_diet_screen_smoke_test.dart @@ -10,10 +10,9 @@ import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart'; import 'package:eatvio_app/core/comments/comments_cubit/comments_state.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -67,12 +66,7 @@ void main() { Widget wrap(AboutDietCubit cubit, FeedCubit feedCubit, CommentsCubit commentsCubit, Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: MultiBlocProvider( providers: [ diff --git a/test/features/diets/presentation/widgets/basic_widget_test.dart b/test/features/diets/presentation/widgets/basic_widget_test.dart index 5a780360..1d1e1b54 100644 --- a/test/features/diets/presentation/widgets/basic_widget_test.dart +++ b/test/features/diets/presentation/widgets/basic_widget_test.dart @@ -10,9 +10,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/diets.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/diets_widget.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -76,12 +75,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); @@ -90,12 +84,7 @@ void main() { Widget createDietsTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/diets/presentation/widgets/cancel_diet_bottom_sheet_test.dart b/test/features/diets/presentation/widgets/cancel_diet_bottom_sheet_test.dart index ae4b24e0..27c12014 100644 --- a/test/features/diets/presentation/widgets/cancel_diet_bottom_sheet_test.dart +++ b/test/features/diets/presentation/widgets/cancel_diet_bottom_sheet_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/diets/presentation/cubit/about_diet_cubit.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/cancel_diet_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -28,12 +27,7 @@ void main() { Widget createTestWidget(Widget child, AboutDietCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: BlocProvider( diff --git a/test/features/diets/presentation/widgets/expandable_text_test.dart b/test/features/diets/presentation/widgets/expandable_text_test.dart index 5e19d9c7..e93f3e39 100644 --- a/test/features/diets/presentation/widgets/expandable_text_test.dart +++ b/test/features/diets/presentation/widgets/expandable_text_test.dart @@ -1,9 +1,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/expandable_text.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -15,12 +14,7 @@ void main() { Widget wrap(Widget child, {Size size = const Size(360, 800)}) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: MediaQuery( data: MediaQueryData(size: size), diff --git a/test/features/diets/presentation/widgets/info_bouble_test.dart b/test/features/diets/presentation/widgets/info_bouble_test.dart index 928f528f..63afcd3e 100644 --- a/test/features/diets/presentation/widgets/info_bouble_test.dart +++ b/test/features/diets/presentation/widgets/info_bouble_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/info_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/diets/presentation/widgets/more_options_test.dart b/test/features/diets/presentation/widgets/more_options_test.dart index 01a608f5..8000df01 100644 --- a/test/features/diets/presentation/widgets/more_options_test.dart +++ b/test/features/diets/presentation/widgets/more_options_test.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/more_options.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -28,12 +27,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: Scaffold( diff --git a/test/features/diets/presentation/widgets/start_diet_bottom_sheet_test.dart b/test/features/diets/presentation/widgets/start_diet_bottom_sheet_test.dart index 3ca05ee3..aee6fc30 100644 --- a/test/features/diets/presentation/widgets/start_diet_bottom_sheet_test.dart +++ b/test/features/diets/presentation/widgets/start_diet_bottom_sheet_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/diets/presentation/cubit/about_diet_cubit.dart'; import 'package:eatvio_app/features/diets/presentation/widgets/start_diet_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -28,12 +27,7 @@ void main() { Widget createTestWidget(Widget child, AboutDietCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: BlocProvider( diff --git a/test/features/diets/presentation/widgets/type_badges_test.dart b/test/features/diets/presentation/widgets/type_badges_test.dart index a1a0eceb..5e9f7a5b 100644 --- a/test/features/diets/presentation/widgets/type_badges_test.dart +++ b/test/features/diets/presentation/widgets/type_badges_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/diets/presentation/widgets/type_badges.dart' import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_svg/svg.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -19,12 +18,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Portal(child: Scaffold(body: child)), ); diff --git a/test/features/diets/presentation/widgets/widgets_test.dart b/test/features/diets/presentation/widgets/widgets_test.dart index 5d57df51..d1f1d5f5 100644 --- a/test/features/diets/presentation/widgets/widgets_test.dart +++ b/test/features/diets/presentation/widgets/widgets_test.dart @@ -9,8 +9,7 @@ import 'package:eatvio_app/features/diets/presentation/widgets/type_badges.dart' import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -27,12 +26,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/feed/presentation/pages/feed_screen_smoke_test.dart b/test/features/feed/presentation/pages/feed_screen_smoke_test.dart index b986e350..3e5e6f2e 100644 --- a/test/features/feed/presentation/pages/feed_screen_smoke_test.dart +++ b/test/features/feed/presentation/pages/feed_screen_smoke_test.dart @@ -20,10 +20,9 @@ import 'package:eatvio_app/core/views/service/views_service.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -64,12 +63,7 @@ void main() { ], child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ), diff --git a/test/features/feed/presentation/widgets/basic_widget_test.dart b/test/features/feed/presentation/widgets/basic_widget_test.dart index b9d7a80b..9cba74e1 100644 --- a/test/features/feed/presentation/widgets/basic_widget_test.dart +++ b/test/features/feed/presentation/widgets/basic_widget_test.dart @@ -11,9 +11,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/blog_posts.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/chip_group.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -86,12 +85,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); @@ -131,12 +125,7 @@ void main() { return MaterialApp.router( theme: ThemeHelper().themeData(), routerConfig: router, - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], ); } @@ -235,12 +224,7 @@ void main() { MaterialApp.router( theme: ThemeHelper().themeData(), routerConfig: router, - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], ), ); diff --git a/test/features/feed/presentation/widgets/blog_post_media_content_test.dart b/test/features/feed/presentation/widgets/blog_post_media_content_test.dart index 17a19a8e..4716b496 100644 --- a/test/features/feed/presentation/widgets/blog_post_media_content_test.dart +++ b/test/features/feed/presentation/widgets/blog_post_media_content_test.dart @@ -1,7 +1,7 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/features/feed/models/post_feed_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_media_content.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; diff --git a/test/features/feed/presentation/widgets/blog_post_widget_test.dart b/test/features/feed/presentation/widgets/blog_post_widget_test.dart index ffc2b581..24c21935 100644 --- a/test/features/feed/presentation/widgets/blog_post_widget_test.dart +++ b/test/features/feed/presentation/widgets/blog_post_widget_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/blog_posts_test.dart b/test/features/feed/presentation/widgets/blog_posts_test.dart index 95ced332..0df2f2eb 100644 --- a/test/features/feed/presentation/widgets/blog_posts_test.dart +++ b/test/features/feed/presentation/widgets/blog_posts_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/blog_posts.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/chip_group_test.dart b/test/features/feed/presentation/widgets/chip_group_test.dart index 148dc8c6..19a8b8a8 100644 --- a/test/features/feed/presentation/widgets/chip_group_test.dart +++ b/test/features/feed/presentation/widgets/chip_group_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/chip_group.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/choice_chip_widget_test.dart b/test/features/feed/presentation/widgets/choice_chip_widget_test.dart index 971f97d2..75d19438 100644 --- a/test/features/feed/presentation/widgets/choice_chip_widget_test.dart +++ b/test/features/feed/presentation/widgets/choice_chip_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/choice_chip_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/comments_widget_test.dart b/test/features/feed/presentation/widgets/comments_widget_test.dart index 48974de6..3eebca97 100644 --- a/test/features/feed/presentation/widgets/comments_widget_test.dart +++ b/test/features/feed/presentation/widgets/comments_widget_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/features/feed/models/comment_model.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/comments_widget.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:get_it/get_it.dart'; import 'package:mocktail/mocktail.dart'; @@ -66,12 +65,7 @@ void main() { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: const Scaffold( body: CommentsWidget(id: '1', commentSourceType: CommentSourceType.blogPost, comment: commentModel), @@ -124,12 +118,7 @@ void main() { await mockNetworkImagesFor(() async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold( body: CommentsWidget(id: '1', commentSourceType: CommentSourceType.blogPost, comment: commentModel), diff --git a/test/features/feed/presentation/widgets/consultant_widget_test.dart b/test/features/feed/presentation/widgets/consultant_widget_test.dart index 8b84cafa..dac448fe 100644 --- a/test/features/feed/presentation/widgets/consultant_widget_test.dart +++ b/test/features/feed/presentation/widgets/consultant_widget_test.dart @@ -7,8 +7,7 @@ import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/consultant_widget.dart'; import 'package:eatvio_app/features/profile/models/badge_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -34,12 +33,7 @@ void main() { Widget createTestWidget(FeedConsultantModel consultant) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), routerConfig: GoRouter( diff --git a/test/features/feed/presentation/widgets/consultants_test.dart b/test/features/feed/presentation/widgets/consultants_test.dart index 81b65bb8..a9179477 100644 --- a/test/features/feed/presentation/widgets/consultants_test.dart +++ b/test/features/feed/presentation/widgets/consultants_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/consultants.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/diet_filter_bottom_sheet_test.dart b/test/features/feed/presentation/widgets/diet_filter_bottom_sheet_test.dart index edc18afd..d8fbe352 100644 --- a/test/features/feed/presentation/widgets/diet_filter_bottom_sheet_test.dart +++ b/test/features/feed/presentation/widgets/diet_filter_bottom_sheet_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/diet_filter_bottom import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.dart'; import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -20,12 +19,7 @@ void main() { Widget wrap(Widget child, DietsCubit? dietsCubit, MyDietsCubit? myDietsCubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: MultiBlocProvider( diff --git a/test/features/feed/presentation/widgets/diets_test.dart b/test/features/feed/presentation/widgets/diets_test.dart index c80df8eb..e92fa661 100644 --- a/test/features/feed/presentation/widgets/diets_test.dart +++ b/test/features/feed/presentation/widgets/diets_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/diets.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/duration_choice_filter_widget_test.dart b/test/features/feed/presentation/widgets/duration_choice_filter_widget_test.dart index ecc1028a..1d4b3394 100644 --- a/test/features/feed/presentation/widgets/duration_choice_filter_widget_test.dart +++ b/test/features/feed/presentation/widgets/duration_choice_filter_widget_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_cub import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/duration_choice_filter_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -18,12 +17,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/feed/presentation/widgets/filter_badge_test.dart b/test/features/feed/presentation/widgets/filter_badge_test.dart index 4bbbfc48..3bdfd828 100644 --- a/test/features/feed/presentation/widgets/filter_badge_test.dart +++ b/test/features/feed/presentation/widgets/filter_badge_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/filter_badge.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/plan_widget_test.dart b/test/features/feed/presentation/widgets/plan_widget_test.dart index d8112647..0ec492f4 100644 --- a/test/features/feed/presentation/widgets/plan_widget_test.dart +++ b/test/features/feed/presentation/widgets/plan_widget_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/plans_filter_bottom_sheet_test.dart b/test/features/feed/presentation/widgets/plans_filter_bottom_sheet_test.dart index fbc7cf65..798ad4f6 100644 --- a/test/features/feed/presentation/widgets/plans_filter_bottom_sheet_test.dart +++ b/test/features/feed/presentation/widgets/plans_filter_bottom_sheet_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/plans_filter_botto import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.dart'; import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -20,12 +19,7 @@ void main() { Widget wrap(Widget child, PlansCubit? plansCubit, MyPlansCubit? myPlansCubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: MultiBlocProvider( diff --git a/test/features/feed/presentation/widgets/plans_test.dart b/test/features/feed/presentation/widgets/plans_test.dart index d5c8ebb6..ba5d3c67 100644 --- a/test/features/feed/presentation/widgets/plans_test.dart +++ b/test/features/feed/presentation/widgets/plans_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/plans.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/price_choice_filter_widget_test.dart b/test/features/feed/presentation/widgets/price_choice_filter_widget_test.dart index a8bd07bb..c2c95af9 100644 --- a/test/features/feed/presentation/widgets/price_choice_filter_widget_test.dart +++ b/test/features/feed/presentation/widgets/price_choice_filter_widget_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/price_choice_filter_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/feed/presentation/widgets/recipes_test.dart b/test/features/feed/presentation/widgets/recipes_test.dart index 32e09164..06098ac4 100644 --- a/test/features/feed/presentation/widgets/recipes_test.dart +++ b/test/features/feed/presentation/widgets/recipes_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/recipes.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/recipes_widget_test.dart b/test/features/feed/presentation/widgets/recipes_widget_test.dart index ae2bbce9..2b57a1ed 100644 --- a/test/features/feed/presentation/widgets/recipes_widget_test.dart +++ b/test/features/feed/presentation/widgets/recipes_widget_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/recipes_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/feed/presentation/widgets/sorting_drop_down_filter_test.dart b/test/features/feed/presentation/widgets/sorting_drop_down_filter_test.dart index 60df9ad5..18117ef3 100644 --- a/test/features/feed/presentation/widgets/sorting_drop_down_filter_test.dart +++ b/test/features/feed/presentation/widgets/sorting_drop_down_filter_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/sorting_drop_down_ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.dart'; import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: Scaffold(body: child), diff --git a/test/features/feed/presentation/widgets/subscribe_button_widget_test.dart b/test/features/feed/presentation/widgets/subscribe_button_widget_test.dart index 1c0824d3..2793037d 100644 --- a/test/features/feed/presentation/widgets/subscribe_button_widget_test.dart +++ b/test/features/feed/presentation/widgets/subscribe_button_widget_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/subscribe_button_widget.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/feed/presentation/widgets/tags_modal_widget_test.dart b/test/features/feed/presentation/widgets/tags_modal_widget_test.dart index e448aa2e..95abadaa 100644 --- a/test/features/feed/presentation/widgets/tags_modal_widget_test.dart +++ b/test/features/feed/presentation/widgets/tags_modal_widget_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/features/create_recipe/models/recipe_tag_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/tags_modal_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/feed/presentation/widgets/type_choice_filter_widget_test.dart b/test/features/feed/presentation/widgets/type_choice_filter_widget_test.dart index 33224b2e..1279e00a 100644 --- a/test/features/feed/presentation/widgets/type_choice_filter_widget_test.dart +++ b/test/features/feed/presentation/widgets/type_choice_filter_widget_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_cub import 'package:eatvio_app/features/feed/presentation/bloc/diets_cubit/diets_state.dart'; import 'package:eatvio_app/features/feed/presentation/widgets/type_choice_filter_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -18,12 +17,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/finances_and_consultations_archive/presentation/consultant_finances_screen_smoke_test.dart b/test/features/finances_and_consultations_archive/presentation/consultant_finances_screen_smoke_test.dart index d62431ab..382ed394 100644 --- a/test/features/finances_and_consultations_archive/presentation/consultant_finances_screen_smoke_test.dart +++ b/test/features/finances_and_consultations_archive/presentation/consultant_finances_screen_smoke_test.dart @@ -7,9 +7,8 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/cubit/con import 'package:eatvio_app/features/finances_and_consultations_archive/models/consultant_finance_model.dart'; import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -44,12 +43,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/finances_and_consultations_archive/presentation/consultations_archive_screen_smoke_test.dart b/test/features/finances_and_consultations_archive/presentation/consultations_archive_screen_smoke_test.dart index a9e159f2..0f8ff4f0 100644 --- a/test/features/finances_and_consultations_archive/presentation/consultations_archive_screen_smoke_test.dart +++ b/test/features/finances_and_consultations_archive/presentation/consultations_archive_screen_smoke_test.dart @@ -9,9 +9,8 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/models/st import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultations_archive_screen.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -55,12 +54,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/finances_and_consultations_archive/presentation/user_purchases_screen_smoke_test.dart b/test/features/finances_and_consultations_archive/presentation/user_purchases_screen_smoke_test.dart index da71783a..499b09f0 100644 --- a/test/features/finances_and_consultations_archive/presentation/user_purchases_screen_smoke_test.dart +++ b/test/features/finances_and_consultations_archive/presentation/user_purchases_screen_smoke_test.dart @@ -8,9 +8,8 @@ import 'package:eatvio_app/features/finances_and_consultations_archive/models/us import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -44,12 +43,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/finances_and_consultations_archive/presentation/widgets/status_widget_test.dart b/test/features/finances_and_consultations_archive/presentation/widgets/status_widget_test.dart index af8b6c2f..685a5e7d 100644 --- a/test/features/finances_and_consultations_archive/presentation/widgets/status_widget_test.dart +++ b/test/features/finances_and_consultations_archive/presentation/widgets/status_widget_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/widgets/status_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/glossary/presentation/pages/glossary_screen_test.dart b/test/features/glossary/presentation/pages/glossary_screen_test.dart index a6e33666..a243583c 100644 --- a/test/features/glossary/presentation/pages/glossary_screen_test.dart +++ b/test/features/glossary/presentation/pages/glossary_screen_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/glossary/presentation/pages/glossary_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/test/features/insights/domain/insights_text_builder_test.dart b/test/features/insights/domain/insights_text_builder_test.dart new file mode 100644 index 00000000..78dfe39a --- /dev/null +++ b/test/features/insights/domain/insights_text_builder_test.dart @@ -0,0 +1,285 @@ +import 'package:eatvio_app/features/insights/domain/insights_text_builder.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/profile/models/weight_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +WeightModel _weight(double weight, {double? bmi, int day = 1}) { + final date = DateTime(2026, 11, day, 12); + return WeightModel( + id: day, + userId: 1, + weight: weight, + createdAt: date, + updatedAt: date, + bmi: bmi, + ); +} + +CircumferenceModel _circumference({ + double waist = 80, + double chest = 95, + double hips = 100, + int day = 1, +}) { + final date = DateTime(2026, 11, day, 12); + return CircumferenceModel( + id: day, + userId: 1, + chestCircumference: chest, + waistCircumference: waist, + hipCircumference: hips, + createdAt: date, + updatedAt: date, + ); +} + +void main() { + late InsightsTextBuilder builder; + + setUpAll(() async { + final s = await S.load(const Locale('ru')); + builder = InsightsTextBuilder(s); + }); + + group('форматирование', () { + test('formatNumber: один знак без хвостового нуля', () { + expect(builder.formatNumber(3), '3'); + expect(builder.formatNumber(3.5), '3.5'); + expect(builder.formatNumber(3.04), '3'); + expect(builder.formatNumber(3.26), '3.3'); + }); + + test('formatLabel: dd.MM', () { + expect(builder.formatLabel(DateTime(2026, 11, 9, 12)), '09.11'); + }); + + test('periodLabel: все периоды', () { + expect(builder.periodLabel(BodyPeriod.month), 'месяц'); + expect(builder.periodLabel(BodyPeriod.threeMonths), '3 месяца'); + expect(builder.periodLabel(BodyPeriod.sixMonths), '6 месяцев'); + expect(builder.periodLabel(BodyPeriod.year), 'год'); + expect(builder.periodLabel(BodyPeriod.all), 'всё время'); + }); + }); + + group('вес', () { + test('снижение', () { + final model = builder.buildWeight([ + _weight(74.5), + _weight(73.2, day: 9), + ], BodyPeriod.month); + + expect(model.deltaText, 'Снизили на 1.3 кг за месяц'); + expect(model.delta, -1.3); + expect(model.last, 73.2); + expect(model.headline, '73.2'); + expect(model.unit, 'кг'); + expect(model.labels, ['01.11', '09.11']); + expect(model.values, [74.5, 73.2]); + }); + + test('набор', () { + final model = builder.buildWeight([ + _weight(70), + _weight(72, day: 3), + ], BodyPeriod.threeMonths); + + expect(model.deltaText, 'Набрали 2 кг за 3 месяца'); + expect(model.delta, 2); + }); + + test('порог 0.05: меньше — не изменился', () { + final model = builder.buildWeight([ + _weight(70), + _weight(70.04, day: 3), + ], BodyPeriod.year); + + expect(model.deltaText, 'Вес не изменился за год'); + }); + + test('порог 0.05: ровно 0.25 — уже изменение', () { + final model = builder.buildWeight([ + _weight(70), + _weight(70.25, day: 3), + ], BodyPeriod.all); + + expect(model.deltaText, 'Набрали 0.3 кг за всё время'); + }); + + test('одна точка: недостаточно данных, но headline есть', () { + final model = builder.buildWeight([_weight(72)], BodyPeriod.month); + + expect(model.deltaText, 'Недостаточно данных'); + expect(model.delta, isNull); + expect(model.headline, '72.0'); + }); + + test('нет точек', () { + final model = builder.buildWeight([], BodyPeriod.month); + + expect(model.deltaText, 'Недостаточно данных'); + expect(model.last, isNull); + expect(model.headline, '—'); + expect(model.values, isEmpty); + }); + }); + + group('категории ИМТ (границы)', () { + final cases = { + 15.9: 'выраженный дефицит массы', + 16.0: 'недостаточная масса', + 18.4: 'недостаточная масса', + 18.5: 'норма', + 24.9: 'норма', + 25.0: 'избыточная масса', + 29.9: 'избыточная масса', + 30.0: 'ожирение I ст.', + 34.9: 'ожирение I ст.', + 35.0: 'ожирение II ст.', + 39.9: 'ожирение II ст.', + 40.0: 'ожирение III ст.', + 55.0: 'ожирение III ст.', + }; + + cases.forEach((bmi, expected) { + test('$bmi → $expected', () { + expect(builder.bmiCategory(bmi), expected); + }); + }); + }); + + group('ИМТ', () { + test('без роста: пусто и подсказка', () { + final model = builder.buildBmi( + [_weight(70, bmi: 22)], + BodyPeriod.month, + null, + ); + + expect(model.values, isEmpty); + expect(model.headline, '—'); + expect(model.hint, 'Укажите рост, чтобы посчитать ИМТ.'); + expect(model.deltaText, 'Укажите рост, чтобы посчитать ИМТ.'); + expect(model.category, isNull); + }); + + test('нулевой рост считается отсутствующим', () { + final model = builder.buildBmi( + [_weight(70, bmi: 22)], + BodyPeriod.month, + 0, + ); + + expect(model.values, isEmpty); + }); + + test('ИМТ ниже', () { + final model = builder.buildBmi( + [_weight(80, bmi: 26.5), _weight(75, bmi: 24.2, day: 5)], + BodyPeriod.threeMonths, + 176, + ); + + expect(model.deltaText, 'ИМТ ниже на 2.3 за 3 месяца · норма'); + expect(model.category, 'норма'); + expect(model.headline, '24.2'); + expect(model.last, 24.2); + expect(model.delta, -2.3); + expect(model.hint, contains('Считаем при росте 176 см.')); + }); + + test('ИМТ выше', () { + final model = builder.buildBmi( + [_weight(70, bmi: 24), _weight(80, bmi: 27, day: 5)], + BodyPeriod.month, + 170, + ); + + expect(model.deltaText, 'ИМТ выше на 3 за месяц · избыточная масса'); + }); + + test('ИМТ не изменился', () { + final model = builder.buildBmi( + [_weight(70, bmi: 22), _weight(70, bmi: 22.01, day: 5)], + BodyPeriod.year, + 170, + ); + + expect(model.deltaText, 'ИМТ не изменился за год · норма'); + }); + + test('точки с bmi = null пропускаются', () { + final model = builder.buildBmi( + [_weight(70, bmi: null), _weight(71, bmi: 22, day: 3)], + BodyPeriod.month, + 170, + ); + + expect(model.values, [22]); + expect(model.labels, ['03.11']); + expect(model.deltaText, 'Недостаточно данных'); + }); + + test('рост есть, точек нет', () { + final model = builder.buildBmi([], BodyPeriod.month, 170); + + expect(model.values, isEmpty); + expect(model.deltaText, 'Недостаточно данных'); + expect(model.hint, contains('170')); + }); + }); + + group('замеры', () { + test('по каждой части: меньше / больше / без изменений', () { + final model = builder.buildMeasure([ + _circumference(waist: 82, chest: 96, hips: 100), + _circumference(waist: 80.5, chest: 98, hips: 100, day: 9), + ], BodyPeriod.month); + + expect( + model.deltaText, + 'Талия меньше на 1.5 см, Грудь больше на 2 см, Бёдра без изменений за месяц', + ); + expect(model.headline, '81'); + expect(model.waist, [82, 80.5]); + expect(model.labels, ['01.11', '09.11']); + }); + + test('одна точка — недостаточно данных', () { + final model = builder.buildMeasure([_circumference()], BodyPeriod.month); + + expect(model.deltaText, 'Недостаточно данных'); + expect(model.headline, '80'); + }); + + test('нет точек', () { + final model = builder.buildMeasure([], BodyPeriod.month); + + expect(model.headline, '—'); + expect(model.deltaText, 'Недостаточно данных'); + }); + }); + + group('build', () { + test('сортирует по дате, daily/intra = null', () { + final payload = builder.build( + weights: [_weight(73, bmi: 23, day: 9), _weight(75, bmi: 24, day: 1)], + circumferences: [ + _circumference(waist: 79, day: 9), + _circumference(waist: 81), + ], + period: BodyPeriod.month, + heightCm: 175, + ); + + expect(payload.weight.values, [75, 73]); + expect(payload.bmi.values, [24, 23]); + expect(payload.measure.waist, [81, 79]); + expect(payload.daily, isNull); + expect(payload.intra, isNull); + }); + }); +} diff --git a/test/features/insights/models/insights_payload_model_test.dart b/test/features/insights/models/insights_payload_model_test.dart new file mode 100644 index 00000000..a8296799 --- /dev/null +++ b/test/features/insights/models/insights_payload_model_test.dart @@ -0,0 +1,75 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Map _fixture(String name) { + return jsonDecode(File('test/fixtures/insights/$name').readAsStringSync()) + as Map; +} + +void main() { + group('InsightsPayloadModel', () { + test('парсит полный payload (weight/bmi/measure/daily/intra)', () { + final model = InsightsPayloadModel.fromJson( + _fixture('insights_payload.json'), + ); + + expect(model.weight.values, [74.5, 73.9, 73.2]); + expect(model.weight.last, 73.2); + expect(model.weight.delta, -1.3); + expect(model.weight.unit, 'кг'); + + expect(model.measure.waist, [82.0, 80.5]); + expect(model.measure.chest, [96.0, 96.0]); + + expect(model.daily, isNotNull); + expect(model.daily!.kcal, [1850.0, 2010.0, 1930.0]); + expect(model.daily!.average, 1930); + + expect(model.intra, isNotNull); + expect(model.intra!.bars, hasLength(2)); + expect(model.intra!.bars.first.x, 8.5); + expect(model.intra!.bars.first.c, 240); + expect(model.intra!.satiety.last.y, 4); + expect(model.intra!.wake, 7.5); + expect(model.intra!.isToday, isTrue); + }); + + test('bmi.values пустой и last/delta/category = null', () { + final model = InsightsPayloadModel.fromJson( + _fixture('insights_payload.json'), + ); + + expect(model.bmi.values, isEmpty); + expect(model.bmi.last, isNull); + expect(model.bmi.delta, isNull); + expect(model.bmi.category, isNull); + expect(model.bmi.deltaText, contains('рост')); + }); + + test('пустой intra без wake/sleep; daily == null', () { + final model = InsightsPayloadModel.fromJson( + _fixture('insights_payload_minimal.json'), + ); + + expect(model.intra!.wake, isNull); + expect(model.intra!.sleep, isNull); + expect(model.intra!.bars, isEmpty); + expect(model.daily, isNull); + expect(model.weight.last, isNull); + }); + + test('daily и intra необязательны', () { + final json = _fixture('insights_payload_minimal.json') + ..remove('daily') + ..remove('intra'); + + final model = InsightsPayloadModel.fromJson(json); + + expect(model.daily, isNull); + expect(model.intra, isNull); + }); + }); +} diff --git a/test/features/insights/models/insights_response_model_test.dart b/test/features/insights/models/insights_response_model_test.dart new file mode 100644 index 00000000..9a3e3095 --- /dev/null +++ b/test/features/insights/models/insights_response_model_test.dart @@ -0,0 +1,154 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:eatvio_app/features/insights/models/insights_response_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Map _fixture(String name) => + jsonDecode(File('test/fixtures/insights/$name').readAsStringSync()) + as Map; + +/// Контракт `GET /api/profile/insights*` (eatvio/eatvio#3017). +void main() { + group('InsightsResponseModel', () { + test('полный ответ: data с weight/bmi/measure/daily/intra', () { + final data = InsightsResponseModel.fromJson( + _fixture('insights_response.json'), + ).data; + + expect(data.weight.headline, '73.2'); + expect(data.measure.waist, [82, 80.5]); + expect(data.daily!.kcal, hasLength(3)); + expect(data.intra!.bars, hasLength(2)); + }); + + test('daily.percent — изменение за период, а не процент от нормы', () { + final daily = InsightsResponseModel.fromJson( + _fixture('insights_response.json'), + ).data.daily!; + + expect(daily.percent, 5); + expect(daily.deltaText, 'Калораж вырос на 5% за период'); + }); + + test('нет КБЖУ за период: daily == null', () { + final data = InsightsResponseModel.fromJson( + _fixture('insights_response_empty.json'), + ).data; + + expect(data.daily, isNull); + }); + + test('пустые замеры: headline "—" и текст «Недостаточно данных»', () { + final measure = InsightsResponseModel.fromJson( + _fixture('insights_response_empty.json'), + ).data.measure; + + expect(measure.labels, isEmpty); + expect(measure.headline, '—'); + expect(measure.deltaText, 'Недостаточно данных'); + }); + + test('пустой день: intra приходит объектом с датами, без сна', () { + final intra = InsightsResponseModel.fromJson( + _fixture('insights_response_empty.json'), + ).data.intra!; + + expect(intra.bars, isEmpty); + expect(intra.satiety, isEmpty); + expect(intra.mood, isEmpty); + expect(intra.wake, isNull); + expect(intra.sleep, isNull); + expect(intra.date, '2026-11-09'); + expect(intra.maxDate, '2026-11-09'); + expect(intra.isToday, isTrue); + }); + + test( + 'сокращённый пример из описания бэка разбирается без подписей сна', + () { + final data = InsightsResponseModel.fromJson( + jsonDecode( + jsonEncode({ + 'data': { + 'weight': { + 'labels': ['30.10', '07.11'], + 'values': [80, 78], + 'last': 78, + 'delta': -2, + 'headline': '78', + 'unit': 'кг', + 'deltaText': 'Снизили на 2 кг за 3 месяца', + }, + 'bmi': {}, + 'measure': { + 'labels': [], + 'waist': [], + 'chest': [], + 'hips': [], + 'headline': '—', + 'deltaText': 'Недостаточно данных', + }, + 'daily': { + 'labels': ['09.11'], + 'kcal': [250], + 'proteins': [10], + 'fats': [5], + 'carbs': [30], + 'average': 250, + 'percent': 0, + 'headline': '250', + 'deltaText': 'Калораж не изменился за период', + }, + 'intra': { + 'bars': [ + {'x': 12.5, 'p': 40, 'f': 45, 'c': 120}, + ], + 'satiety': [ + {'x': 12.5, 'y': 4}, + ], + 'mood': [ + {'x': 12.5, 'y': 3}, + ], + 'wake': 7, + 'sleep': 23, + 'date': '2026-11-09', + 'maxDate': '2026-11-09', + 'dateLabel': 'Сегодня', + 'isToday': true, + }, + }, + }), + ) + as Map, + ).data; + + expect(data.weight.values, [80, 78]); + expect(data.daily!.percent, 0); + expect(data.intra!.wake, 7); + expect(data.intra!.wakeLabel, isNull); + expect(data.intra!.wakeText, isNull); + }, + ); + }); + + group('InsightsIntraResponseModel', () { + test('ответ /insights/intra: data.intra', () { + final intra = InsightsIntraResponseModel.fromJson( + _fixture('insights_intra_response.json'), + ).data.intra; + + expect(intra.date, '2026-11-09'); + expect(intra.bars, isNotEmpty); + }); + + test('прошедший день: isToday == false', () { + final intra = InsightsIntraResponseModel.fromJson( + _fixture('insights_intra_response_yesterday.json'), + ).data.intra; + + expect(intra.isToday, isFalse); + expect(intra.dateLabel, '8 ноября'); + }); + }); +} diff --git a/test/features/insights/presentation/charts/insights_chart_common_test.dart b/test/features/insights/presentation/charts/insights_chart_common_test.dart new file mode 100644 index 00000000..d3e0e435 --- /dev/null +++ b/test/features/insights/presentation/charts/insights_chart_common_test.dart @@ -0,0 +1,76 @@ +import 'package:eatvio_app/features/insights/presentation/charts/insights_chart_common.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +void main() { + test('insightsSplineType — monotonic, чтобы кривая не уходила ниже точек', () { + expect(insightsSplineType, SplineType.monotonic); + }); + + group('buildPoints', () { + test('сохраняет индекс и дату даже при повторяющихся labels', () { + final points = buildPoints( + ['05.07', '05.07', '06.07', '07.07'], + [10, 20, 30, 40], + ); + + expect(points.map((p) => p.index).toList(), [0, 1, 2, 3]); + expect(points.map((p) => p.label).toList(), [ + '05.07', + '05.07', + '06.07', + '07.07', + ]); + expect(points.map((p) => p.value).toList(), [10, 20, 30, 40]); + }); + + test('обрезает по короткому массиву', () { + expect(buildPoints(['a', 'b'], [1]), hasLength(1)); + }); + }); + + group('buildInsightsIndexAxis', () { + test('ось строится по числу точек, а не по уникальным строкам дат', () { + final labels = [ + '05.07', + '06.07', + '07.07', + '08.07', + '09.07', + '10.07', + '11.07', + ]; + final axis = buildInsightsIndexAxis(labels); + + expect(axis.minimum, 0); + expect(axis.maximum, 6); + expect(axis.interval, 1); + expect(axis.axisLabelFormatter, isNotNull); + }); + + test('для длинного периода ставит интервал больше 1', () { + final labels = List.generate(30, (i) => '${i + 1}.07'); + final axis = buildInsightsIndexAxis(labels); + + expect(axis.maximum, 29); + expect(axis.interval, greaterThan(1)); + }); + }); + + group('paddedRange', () { + test('даёт локальный диапазон вокруг данных', () { + final range = paddedRange([70, 72], minPadding: 1); + + expect(range.min, lessThan(70)); + expect(range.max, greaterThan(72)); + expect(range.min, greaterThan(0)); + }); + + test('clampZero не уводит минимум ниже нуля', () { + final range = paddedRange([2, 8], minPadding: 5, clampZero: true); + + expect(range.min, 0); + expect(range.max, greaterThan(8)); + }); + }); +} diff --git a/test/features/insights/presentation/cubit/insights_cubit_server_test.dart b/test/features/insights/presentation/cubit/insights_cubit_server_test.dart new file mode 100644 index 00000000..8382c534 --- /dev/null +++ b/test/features/insights/presentation/cubit/insights_cubit_server_test.dart @@ -0,0 +1,395 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_cubit.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../../fixtures/doubles/insights_doubles.dart'; + +/// Серверный режим (`kbjuEnabled: true`): `GET /api/profile/insights*`. +void main() { + late FakeInsightsRepository repository; + late IntraChartModel today; + late IntraChartModel yesterday; + + setUp(() { + repository = FakeInsightsRepository(); + today = repository.payload.intra!; + yesterday = today.copyWith( + date: '2026-11-08', + dateLabel: '8 ноября', + isToday: false, + ); + repository.intraByDate['2026-11-08'] = yesterday; + repository.intraByDate['2026-11-09'] = today; + }); + + InsightsCubit buildCubit({String? slug}) { + return InsightsCubit(repository: repository, slug: slug, kbjuEnabled: true); + } + + InsightsStateLoaded loaded(InsightsCubit cubit) => + cubit.state as InsightsStateLoaded; + + group('load', () { + test('запрашивает серверный payload с дефолтными периодами', () async { + final cubit = buildCubit(); + + await cubit.load(); + + expect(repository.serverRequests, [ + ( + slug: null, + bodyPeriod: BodyPeriod.threeMonths, + dailyPeriod: DailyPeriod.twoWeeks, + intraDate: null, + ), + ]); + expect(repository.insightsRequests, isEmpty); + expect(loaded(cubit).payload.daily, isNotNull); + expect(loaded(cubit).dailyPeriod, DailyPeriod.twoWeeks); + expect(loaded(cubit).intraDate, isNull); + await cubit.close(); + }); + + test('рост профиля не запрашивается: ИМТ считает сервер', () async { + repository.heightCm = null; + final cubit = buildCubit(slug: 'client'); + + await cubit.load(); + + expect(repository.serverRequests.single.slug, 'client'); + expect(loaded(cubit).payload.bmi, repository.payload.bmi); + await cubit.close(); + }); + + test('403 скрывает блок', () async { + repository.error = const InsightsForbidden(); + final cubit = buildCubit(slug: 'client'); + + await cubit.load(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + + test('ошибка сервера → error', () async { + repository.error = DioException(requestOptions: RequestOptions()); + final cubit = buildCubit(); + + await cubit.load(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + }); + + group('setDailyPeriod', () { + test('перезапрашивает все данные, сохраняя период тела и день', () async { + final cubit = buildCubit(); + await cubit.load(); + await cubit.setBodyPeriod(BodyPeriod.year); + await cubit.setIntraDate(DateTime(2026, 11, 8)); + repository.serverRequests.clear(); + + await cubit.setDailyPeriod(DailyPeriod.month); + + expect(repository.serverRequests, [ + ( + slug: null, + bodyPeriod: BodyPeriod.year, + dailyPeriod: DailyPeriod.month, + intraDate: '2026-11-08', + ), + ]); + expect(loaded(cubit).dailyPeriod, DailyPeriod.month); + expect(loaded(cubit).isRefreshing, isFalse); + await cubit.close(); + }); + + test('тот же период не перезапрашивается', () async { + final cubit = buildCubit(); + await cubit.load(); + repository.serverRequests.clear(); + + await cubit.setDailyPeriod(DailyPeriod.twoWeeks); + + expect(repository.serverRequests, isEmpty); + await cubit.close(); + }); + + test('ошибка оставляет выбранный период и старые данные', () async { + final cubit = buildCubit(); + await cubit.load(); + final before = loaded(cubit).payload; + repository.error = DioException(requestOptions: RequestOptions()); + + await cubit.setDailyPeriod(DailyPeriod.week); + + expect(loaded(cubit).dailyPeriod, DailyPeriod.week); + expect(loaded(cubit).payload, before); + expect(loaded(cubit).isRefreshing, isFalse); + await cubit.close(); + }); + + test('смена периода тела передаёт текущий период КБЖУ', () async { + final cubit = buildCubit(); + await cubit.load(); + await cubit.setDailyPeriod(DailyPeriod.week); + repository.serverRequests.clear(); + + await cubit.setBodyPeriod(BodyPeriod.month); + + expect(repository.serverRequests.single.dailyPeriod, DailyPeriod.week); + await cubit.close(); + }); + }); + + group('«В течение дня»', () { + test( + 'setIntraDate запрашивает только intra и подменяет её в payload', + () async { + final cubit = buildCubit(); + await cubit.load(); + repository.serverRequests.clear(); + + await cubit.setIntraDate(DateTime(2026, 11, 8)); + + expect(repository.serverRequests, isEmpty); + expect(repository.intraRequests, [(slug: null, date: '2026-11-08')]); + final state = loaded(cubit); + expect(state.payload.intra, yesterday); + expect(state.payload.weight, repository.payload.weight); + expect(state.intraDate, '2026-11-08'); + expect(state.isRefreshing, isFalse); + await cubit.close(); + }, + ); + + test('slug передаётся в запрос чужого дня', () async { + final cubit = buildCubit(slug: 'client'); + await cubit.load(); + + await cubit.setIntraDate(DateTime(2026, 11, 8)); + + expect(repository.intraRequests.single.slug, 'client'); + await cubit.close(); + }); + + test( + 'быстрые «назад» запрашивают разные дни (оптимистичная дата)', + () async { + repository.fetchIntraDelay = const Duration(milliseconds: 30); + repository.intraByDate['2026-11-07'] = yesterday.copyWith( + date: '2026-11-07', + dateLabel: '7 ноября', + ); + final cubit = buildCubit(); + await cubit.load(); + + final first = cubit.showPreviousDay(); + final second = cubit.showPreviousDay(); + await Future.wait([first, second]); + + expect(repository.intraRequests.map((e) => e.date).toList(), [ + '2026-11-08', + '2026-11-07', + ]); + expect(loaded(cubit).payload.intra!.date, '2026-11-07'); + await cubit.close(); + }, + ); + + test('полный ответ не затирает более свежий intra и UI-выбор', () async { + repository.fetchInsightsDelay = const Duration(milliseconds: 40); + final cubit = buildCubit(); + await cubit.load(); + repository.fetchInsightsDelay = const Duration(milliseconds: 80); + repository.serverRequests.clear(); + + final periodChange = cubit.setBodyPeriod(BodyPeriod.year); + await Future.delayed(const Duration(milliseconds: 10)); + cubit.setPanel(InsightsPanel.measures); + cubit.toggleExpanded(); + await cubit.setIntraDate(DateTime(2026, 11, 8)); + await periodChange; + + final state = loaded(cubit); + expect(state.bodyPeriod, BodyPeriod.year); + expect(state.payload.weight, repository.payload.weight); + expect(state.payload.intra, yesterday); + expect(state.intraDate, '2026-11-08'); + expect(state.panel, InsightsPanel.measures); + expect(state.isExpanded, isTrue); + expect(state.isRefreshing, isFalse); + await cubit.close(); + }); + + test('load с initialIntraDate запрашивает этот день', () async { + final cubit = buildCubit(); + + await cubit.load(intraDate: '2026-11-08'); + + expect(repository.serverRequests.single.intraDate, '2026-11-08'); + expect(loaded(cubit).intraDate, '2026-11-08'); + await cubit.close(); + }); + + test('showPreviousDay и showNextDay листают по дню', () async { + final cubit = buildCubit(); + await cubit.load(); + + await cubit.showPreviousDay(); + expect(repository.intraRequests.last.date, '2026-11-08'); + expect(loaded(cubit).payload.intra!.isToday, isFalse); + + await cubit.showNextDay(); + expect(repository.intraRequests.last.date, '2026-11-09'); + expect(loaded(cubit).payload.intra!.isToday, isTrue); + expect(loaded(cubit).intraDate, isNull); + await cubit.close(); + }); + + test('showPreviousDay переходит через границу месяца', () async { + repository.payload = repository.payload.copyWith( + intra: today.copyWith(date: '2026-11-01', isToday: false), + ); + final cubit = buildCubit(); + await cubit.load(); + + await cubit.showPreviousDay(); + + expect(repository.intraRequests.single.date, '2026-10-31'); + await cubit.close(); + }); + + test('showNextDay на сегодняшнем дне ничего не запрашивает', () async { + final cubit = buildCubit(); + await cubit.load(); + + await cubit.showNextDay(); + + expect(repository.intraRequests, isEmpty); + await cubit.close(); + }); + + test('сервер вернул другую дату (clamp) — берём её', () async { + repository.intraByDate['2026-11-20'] = today; + final cubit = buildCubit(); + await cubit.load(); + + await cubit.setIntraDate(DateTime(2026, 11, 20)); + + expect(loaded(cubit).intraDate, isNull); + expect(loaded(cubit).payload.intra!.date, '2026-11-09'); + await cubit.close(); + }); + + test('пустой день: intra с пустыми сериями остаётся объектом', () async { + final empty = today.copyWith( + date: '2026-11-07', + dateLabel: '7 ноября', + isToday: false, + bars: const [], + satiety: const [], + mood: const [], + wake: null, + sleep: null, + wakeText: null, + sleepText: null, + ); + repository.intraByDate['2026-11-07'] = empty; + final cubit = buildCubit(); + await cubit.load(); + + await cubit.setIntraDate(DateTime(2026, 11, 7)); + + expect(loaded(cubit).payload.intra, empty); + await cubit.close(); + }); + + test('ошибка запроса дня не стирает показанные данные', () async { + final cubit = buildCubit(); + await cubit.load(); + repository.intraError = DioException(requestOptions: RequestOptions()); + + await cubit.setIntraDate(DateTime(2026, 11, 8)); + + final state = loaded(cubit); + expect(state.payload.intra, today); + expect(state.intraDate, isNull); + expect(state.isRefreshing, isFalse); + await cubit.close(); + }); + + test('403 при листании скрывает блок', () async { + final cubit = buildCubit(slug: 'client'); + await cubit.load(); + repository.intraError = const InsightsForbidden(); + + await cubit.showPreviousDay(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + + test('refresh сохраняет выбранный день, вкладку и серии', () async { + final cubit = buildCubit(); + await cubit.load(); + cubit.toggleExpanded(); + cubit.setPanel(InsightsPanel.intra); + cubit.toggleSleep(); + await cubit.setIntraDate(DateTime(2026, 11, 8)); + repository.serverRequests.clear(); + + await cubit.refresh(); + + expect(repository.serverRequests.single.intraDate, '2026-11-08'); + final state = loaded(cubit); + expect(state.panel, InsightsPanel.intra); + expect(state.isExpanded, isTrue); + expect(state.showSleep, isFalse); + expect(state.intraDate, '2026-11-08'); + await cubit.close(); + }); + + test('refresh во время первой загрузки не дублирует запрос', () async { + final cubit = buildCubit(); + final loading = cubit.load(); + + await cubit.refresh(); + await loading; + + expect(repository.serverRequests, hasLength(1)); + await cubit.close(); + }); + + test('без флага навигация по дням игнорируется', () async { + final cubit = InsightsCubit(repository: repository, kbjuEnabled: false); + await cubit.load(); + + await cubit.showPreviousDay(); + await cubit.setDailyPeriod(DailyPeriod.week); + + expect(repository.intraRequests, isEmpty); + expect(repository.serverRequests, isEmpty); + await cubit.close(); + }); + }); + + test('после добавления веса данные обновляются с сервера', () async { + final cubit = buildCubit(); + await cubit.load(); + repository.serverRequests.clear(); + + final isSaved = await cubit.addWeight(weight: 72.5); + + expect(isSaved, isTrue); + expect(repository.addedWeights, [72.5]); + expect(repository.serverRequests, hasLength(1)); + await cubit.close(); + }); +} diff --git a/test/features/insights/presentation/cubit/insights_cubit_test.dart b/test/features/insights/presentation/cubit/insights_cubit_test.dart new file mode 100644 index 00000000..f23d9b0f --- /dev/null +++ b/test/features/insights/presentation/cubit/insights_cubit_test.dart @@ -0,0 +1,439 @@ +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_cubit.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_panel.dart'; +import 'package:eatvio_app/features/insights/presentation/cubit/insights_state.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockInsightsRepository extends Mock implements InsightsRepository {} + +const _payload = InsightsPayloadModel( + weight: WeightChartModel(values: [70, 71], headline: '71.0'), + bmi: BmiChartModel(), + measure: MeasureChartModel(), +); + +const _payload2 = InsightsPayloadModel( + weight: WeightChartModel(values: [72], headline: '72.0'), + bmi: BmiChartModel(), + measure: MeasureChartModel(), +); + +void main() { + late _MockInsightsRepository repository; + + setUpAll(() { + registerFallbackValue(BodyPeriod.month); + registerFallbackValue(DailyPeriod.week); + }); + + setUp(() { + repository = _MockInsightsRepository(); + when( + () => repository.getHeightCm(slug: any(named: 'slug')), + ).thenAnswer((_) async => 176); + when( + () => repository.getInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + heightCm: any(named: 'heightCm'), + ), + ).thenAnswer((_) async => _payload); + when( + () => repository.fetchInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + dailyPeriod: any(named: 'dailyPeriod'), + intraDate: any(named: 'intraDate'), + ), + ).thenAnswer((_) async => _payload); + }); + + InsightsCubit buildCubit({ + String? slug, + bool canAdd = false, + bool kbjuEnabled = false, + }) { + return InsightsCubit( + repository: repository, + slug: slug, + canAdd: canAdd, + kbjuEnabled: kbjuEnabled, + ); + } + + InsightsStateLoaded loaded(InsightsCubit cubit) => + cubit.state as InsightsStateLoaded; + + test('начальное состояние — initial', () { + expect(buildCubit().state, isA()); + }); + + group('load', () { + test('дефолты: период 3М, вкладка «Вес», блок свёрнут', () async { + final cubit = buildCubit(); + final states = []; + cubit.stream.listen(states.add); + + await cubit.load(); + await Future.delayed(Duration.zero); + + expect(states.first, isA()); + final state = loaded(cubit); + expect(state.bodyPeriod, BodyPeriod.threeMonths); + expect(state.panel, InsightsPanel.weight); + expect(state.isExpanded, isFalse); + expect(state.isRefreshing, isFalse); + expect(state.showSleep, isTrue); + expect(state.payload, _payload); + verify( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ), + ).called(1); + await cubit.close(); + }); + + test('пробрасывает slug владельца', () async { + final cubit = buildCubit(slug: 'client'); + + await cubit.load(); + + verify(() => repository.getHeightCm(slug: 'client')).called(1); + verify( + () => repository.getInsights( + slug: 'client', + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ), + ).called(1); + await cubit.close(); + }); + + test('403 → hidden', () async { + when( + () => repository.getHeightCm(slug: any(named: 'slug')), + ).thenThrow(const InsightsForbidden()); + final cubit = buildCubit(slug: 'client'); + + await cubit.load(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + + test('403 на запросе точек → hidden', () async { + when( + () => repository.getInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + heightCm: any(named: 'heightCm'), + ), + ).thenThrow(const InsightsForbidden()); + final cubit = buildCubit(slug: 'client'); + + await cubit.load(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + + test('другая ошибка → error', () async { + when( + () => repository.getInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + heightCm: any(named: 'heightCm'), + ), + ).thenThrow(Exception('boom')); + final cubit = buildCubit(); + + await cubit.load(); + + expect(cubit.state, isA()); + await cubit.close(); + }); + }); + + group('setBodyPeriod', () { + test( + 'смена периода → перезапрос; рост не запрашивается повторно', + () async { + final cubit = buildCubit(); + await cubit.load(); + when( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.year, + heightCm: 176, + ), + ).thenAnswer((_) async => _payload2); + + await cubit.setBodyPeriod(BodyPeriod.year); + + expect(loaded(cubit).bodyPeriod, BodyPeriod.year); + expect(loaded(cubit).payload, _payload2); + expect(loaded(cubit).isRefreshing, isFalse); + verify(() => repository.getHeightCm(slug: null)).called(1); + await cubit.close(); + }, + ); + + test('тот же период — без запроса', () async { + final cubit = buildCubit(); + await cubit.load(); + clearInteractions(repository); + + await cubit.setBodyPeriod(BodyPeriod.threeMonths); + + verifyNever( + () => repository.getInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + heightCm: any(named: 'heightCm'), + ), + ); + await cubit.close(); + }); + + test('ошибка перезапроса оставляет выбранный период и старые данные', () async { + final cubit = buildCubit(); + await cubit.load(); + when( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.all, + heightCm: 176, + ), + ).thenThrow(Exception('boom')); + + await cubit.setBodyPeriod(BodyPeriod.all); + + expect(loaded(cubit).bodyPeriod, BodyPeriod.all); + expect(loaded(cubit).payload, _payload); + expect(loaded(cubit).isRefreshing, isFalse); + await cubit.close(); + }); + + test('403 при перезапросе → hidden', () async { + final cubit = buildCubit(slug: 'c'); + await cubit.load(); + when( + () => repository.getInsights( + slug: 'c', + bodyPeriod: BodyPeriod.month, + heightCm: 176, + ), + ).thenThrow(const InsightsForbidden()); + + await cubit.setBodyPeriod(BodyPeriod.month); + + expect(cubit.state, isA()); + await cubit.close(); + }); + }); + + group('панели и серии', () { + test('toggleExpanded раскрывает и сворачивает', () async { + final cubit = buildCubit(); + await cubit.load(); + + cubit.toggleExpanded(); + expect(loaded(cubit).isExpanded, isTrue); + cubit.toggleExpanded(); + expect(loaded(cubit).isExpanded, isFalse); + await cubit.close(); + }); + + test('setPanel переключает вкладку', () async { + final cubit = buildCubit(); + await cubit.load(); + + cubit.setPanel(InsightsPanel.measures); + + expect(loaded(cubit).panel, InsightsPanel.measures); + await cubit.close(); + }); + + test('вкладки КБЖУ недоступны при выключенном флаге', () async { + final cubit = buildCubit(); + await cubit.load(); + + cubit.setPanel(InsightsPanel.daily); + + expect(loaded(cubit).panel, InsightsPanel.weight); + expect(cubit.panels, [ + InsightsPanel.weight, + InsightsPanel.bmi, + InsightsPanel.measures, + ]); + await cubit.close(); + }); + + test('вкладки КБЖУ доступны при включённом флаге', () async { + final cubit = buildCubit(kbjuEnabled: true); + await cubit.load(); + + cubit.setPanel(InsightsPanel.intra); + + expect(loaded(cubit).panel, InsightsPanel.intra); + expect(cubit.panels, InsightsPanel.values); + await cubit.close(); + }); + + test('toggleSeries переключает только выбранную серию', () async { + final cubit = buildCubit(); + await cubit.load(); + + cubit.toggleSeries(InsightsPanel.measures, 1); + expect(loaded(cubit).seriesVisibility.measure, [true, false, true]); + + cubit.toggleSeries(InsightsPanel.measures, 1); + expect(loaded(cubit).seriesVisibility.measure, [true, true, true]); + + cubit.toggleSeries(InsightsPanel.daily, 0); + expect(loaded(cubit).seriesVisibility.daily, [false, true, true, true]); + expect(loaded(cubit).seriesVisibility.measure, [true, true, true]); + await cubit.close(); + }); + + test( + 'toggleSeries игнорирует неверный индекс и вкладку без серий', + () async { + final cubit = buildCubit(); + await cubit.load(); + final before = loaded(cubit).seriesVisibility; + + cubit.toggleSeries(InsightsPanel.measures, 5); + cubit.toggleSeries(InsightsPanel.weight, 0); + + expect(loaded(cubit).seriesVisibility, before); + await cubit.close(); + }, + ); + + test('toggleSleep', () async { + final cubit = buildCubit(); + await cubit.load(); + + cubit.toggleSleep(); + + expect(loaded(cubit).showSleep, isFalse); + await cubit.close(); + }); + }); + + group('refresh и добавление записей', () { + test('refresh сохраняет вкладку, период, серии и раскрытие', () async { + final cubit = buildCubit(); + await cubit.load(); + cubit.toggleExpanded(); + cubit.setPanel(InsightsPanel.measures); + cubit.toggleSeries(InsightsPanel.measures, 0); + when( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ), + ).thenAnswer((_) async => _payload2); + + await cubit.refresh(); + + final state = loaded(cubit); + expect(state.payload, _payload2); + expect(state.panel, InsightsPanel.measures); + expect(state.isExpanded, isTrue); + expect(state.seriesVisibility.measure, [false, true, true]); + expect(state.isRefreshing, isFalse); + await cubit.close(); + }); + + test('addWeight сохраняет и обновляет данные', () async { + when( + () => repository.addWeight(weight: any(named: 'weight')), + ).thenAnswer((_) async {}); + final cubit = buildCubit(canAdd: true); + await cubit.load(); + when( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ), + ).thenAnswer((_) async => _payload2); + + final isSaved = await cubit.addWeight(weight: 72); + + expect(isSaved, isTrue); + verify(() => repository.addWeight(weight: 72)).called(1); + expect(loaded(cubit).payload, _payload2); + await cubit.close(); + }); + + test('addCircumference сохраняет и обновляет данные', () async { + when( + () => repository.addCircumference( + chestCircumference: any(named: 'chestCircumference'), + waistCircumference: any(named: 'waistCircumference'), + hipCircumference: any(named: 'hipCircumference'), + ), + ).thenAnswer((_) async {}); + final cubit = buildCubit(canAdd: true); + await cubit.load(); + when( + () => repository.getInsights( + slug: null, + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ), + ).thenAnswer((_) async => _payload2); + + final isSaved = await cubit.addCircumference( + chestCircumference: 95, + waistCircumference: 80, + hipCircumference: 100, + ); + + expect(isSaved, isTrue); + + verify( + () => repository.addCircumference( + chestCircumference: 95, + waistCircumference: 80, + hipCircumference: 100, + ), + ).called(1); + expect(loaded(cubit).payload, _payload2); + await cubit.close(); + }); + + test( + 'ошибка сохранения не перезагружает данные и возвращает false', + () async { + when( + () => repository.addWeight(weight: any(named: 'weight')), + ).thenThrow(Exception('boom')); + final cubit = buildCubit(canAdd: true); + await cubit.load(); + clearInteractions(repository); + + expect(await cubit.addWeight(weight: 72), isFalse); + + verifyNever( + () => repository.getInsights( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + heightCm: any(named: 'heightCm'), + ), + ); + expect(loaded(cubit).payload, _payload); + await cubit.close(); + }, + ); + }); +} diff --git a/test/features/insights/presentation/widgets/insights_card_test.dart b/test/features/insights/presentation/widgets/insights_card_test.dart new file mode 100644 index 00000000..2273995a --- /dev/null +++ b/test/features/insights/presentation/widgets/insights_card_test.dart @@ -0,0 +1,376 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/bmi_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/measure_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/weight_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../../../../fixtures/doubles/insights_doubles.dart'; + +void main() { + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: SingleChildScrollView(child: child)), + ); + } + + Future pumpCard( + WidgetTester tester, + FakeInsightsRepository repository, { + String? slug, + bool canAdd = false, + bool kbjuEnabled = false, + bool expand = true, + }) async { + tester.view.physicalSize = const Size(900, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + wrap( + InsightsCard( + slug: slug, + canAdd: canAdd, + repository: repository, + kbjuEnabled: kbjuEnabled, + ), + ), + ); + await tester.pumpAndSettle(); + if (expand && + find.byKey(const Key('insights_toggle')).evaluate().isNotEmpty) { + await tester.tap(find.byKey(const Key('insights_toggle'))); + await tester.pumpAndSettle(); + } + } + + group('свёрнутое состояние', () { + testWidgets('по умолчанию свёрнут: виден заголовок, графиков нет', ( + tester, + ) async { + await pumpCard(tester, FakeInsightsRepository(), expand: false); + + expect(find.text('Аналитика'), findsOneWidget); + expect(find.text('нажмите, чтобы посмотреть прогресс'), findsOneWidget); + expect(find.byType(WeightChart), findsNothing); + expect(find.byKey(const Key('insights_tab_weight')), findsNothing); + }); + + testWidgets('тап по заголовку раскрывает и сворачивает блок', ( + tester, + ) async { + await pumpCard(tester, FakeInsightsRepository(), expand: false); + + await tester.tap(find.byKey(const Key('insights_toggle'))); + await tester.pumpAndSettle(); + expect(find.byType(WeightChart), findsOneWidget); + expect(find.text('вес, замеры и питание'), findsOneWidget); + + await tester.tap(find.byKey(const Key('insights_toggle'))); + await tester.pumpAndSettle(); + expect(find.byType(WeightChart), findsNothing); + }); + }); + + group('вкладки', () { + testWidgets( + 'показаны Вес, ИМТ, Замеры; вкладки КБЖУ скрыты при выключенном флаге', + (tester) async { + await pumpCard(tester, FakeInsightsRepository()); + + expect(find.byKey(const Key('insights_tab_weight')), findsOneWidget); + expect(find.byKey(const Key('insights_tab_bmi')), findsOneWidget); + expect(find.byKey(const Key('insights_tab_measures')), findsOneWidget); + expect(find.byKey(const Key('insights_tab_daily')), findsNothing); + expect(find.byKey(const Key('insights_tab_intra')), findsNothing); + }, + ); + + testWidgets('вкладки переключают панели', (tester) async { + await pumpCard(tester, FakeInsightsRepository()); + + expect(find.byType(WeightChart), findsOneWidget); + expect(find.byKey(const Key('insights_headline')), findsOneWidget); + + await tester.tap(find.byKey(const Key('insights_tab_measures'))); + await tester.pumpAndSettle(); + expect(find.byType(MeasureChart), findsOneWidget); + expect(find.byType(WeightChart), findsNothing); + + await tester.tap(find.byKey(const Key('insights_tab_bmi'))); + await tester.pumpAndSettle(); + expect(find.byType(BmiChart), findsOneWidget); + expect(find.byType(MeasureChart), findsNothing); + + await tester.tap(find.byKey(const Key('insights_tab_weight'))); + await tester.pumpAndSettle(); + expect(find.byType(WeightChart), findsOneWidget); + }); + + testWidgets('вкладки КБЖУ видны при включённом флаге', (tester) async { + await pumpCard(tester, FakeInsightsRepository(), kbjuEnabled: true); + + expect(find.byKey(const Key('insights_tab_daily')), findsOneWidget); + expect(find.byKey(const Key('insights_tab_intra')), findsOneWidget); + }); + }); + + group('вес', () { + testWidgets('показывает крупное число и текст дельты из payload', ( + tester, + ) async { + await pumpCard(tester, FakeInsightsRepository()); + + expect(find.text('73.2'), findsOneWidget); + expect(find.text('кг'), findsWidgets); + expect(find.text('Снизили на 1.3 кг за период'), findsOneWidget); + }); + }); + + group('пилюли периодов', () { + testWidgets( + 'по умолчанию запрошены 3 месяца; смена периода перезапрашивает данные', + (tester) async { + final repository = FakeInsightsRepository(); + await pumpCard(tester, repository); + + expect( + repository.insightsRequests.single.period, + BodyPeriod.threeMonths, + ); + + await tester.tap(find.byKey(const Key('insights_period_12'))); + await tester.pumpAndSettle(); + + expect(repository.insightsRequests.map((e) => e.period), [ + BodyPeriod.threeMonths, + BodyPeriod.year, + ]); + + await tester.tap(find.byKey(const Key('insights_period_all'))); + await tester.pumpAndSettle(); + + expect(repository.insightsRequests.last.period, BodyPeriod.all); + }, + ); + + testWidgets('повторный тап по активной пилюле не делает запрос', ( + tester, + ) async { + final repository = FakeInsightsRepository(); + await pumpCard(tester, repository); + + await tester.tap(find.byKey(const Key('insights_period_3'))); + await tester.pumpAndSettle(); + + expect(repository.insightsRequests, hasLength(1)); + }); + + testWidgets('slug пробрасывается в запросы', (tester) async { + final repository = FakeInsightsRepository(); + await pumpCard(tester, repository, slug: 'client'); + + await tester.tap(find.byKey(const Key('insights_period_1'))); + await tester.pumpAndSettle(); + + expect(repository.insightsRequests.map((e) => e.slug), [ + 'client', + 'client', + ]); + }); + }); + + group('кнопка «+»', () { + testWidgets('нет при canAdd = false', (tester) async { + await pumpCard(tester, FakeInsightsRepository()); + + expect(find.byKey(const Key('insights_fab')), findsNothing); + }); + + testWidgets('есть на вкладках «Вес» и «Замеры», нет на «ИМТ»', ( + tester, + ) async { + await pumpCard(tester, FakeInsightsRepository(), canAdd: true); + + expect(find.byKey(const Key('insights_fab')), findsOneWidget); + + await tester.tap(find.byKey(const Key('insights_tab_bmi'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('insights_fab')), findsNothing); + + await tester.tap(find.byKey(const Key('insights_tab_measures'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('insights_fab')), findsOneWidget); + }); + + testWidgets('нет в свёрнутом состоянии', (tester) async { + await pumpCard( + tester, + FakeInsightsRepository(), + canAdd: true, + expand: false, + ); + + expect(find.byKey(const Key('insights_fab')), findsNothing); + }); + + testWidgets( + 'сохранение веса отправляет значение и перезапрашивает данные', + (tester) async { + final repository = FakeInsightsRepository(); + await pumpCard(tester, repository, canAdd: true); + + await tester.tap(find.byKey(const Key('insights_fab'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('add_weight_kilo_picker')), findsOneWidget); + + await tester.tap(find.byKey(const Key('add_sheet_save'))); + await tester.pumpAndSettle(); + + // Начальное значение шторки — последний вес из payload (73.2). + expect(repository.addedWeights, [73.2]); + expect(repository.insightsRequests, hasLength(2)); + }, + ); + + testWidgets( + 'сохранение замеров отправляет значения и перезапрашивает данные', + (tester) async { + final repository = FakeInsightsRepository(); + await pumpCard(tester, repository, canAdd: true); + + await tester.tap(find.byKey(const Key('insights_tab_measures'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('insights_fab'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('add_circumference_waist_picker')), + findsOneWidget, + ); + + await tester.tap(find.byKey(const Key('add_sheet_save'))); + await tester.pumpAndSettle(); + + // Последние значения из payload: грудь 96, талия 80.5 → 81 (округление), бёдра 100. + expect(repository.addedCircumferences, [ + (chest: 96, waist: 81, hip: 100), + ]); + expect(repository.insightsRequests, hasLength(2)); + }, + ); + }); + + group('серии замеров', () { + testWidgets('чипы переключают видимость серии', (tester) async { + await pumpCard(tester, FakeInsightsRepository()); + await tester.tap(find.byKey(const Key('insights_tab_measures'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('insights_series_0')), findsOneWidget); + expect(find.byKey(const Key('insights_series_1')), findsOneWidget); + expect(find.byKey(const Key('insights_series_2')), findsOneWidget); + expect( + tester + .widget( + find + .ancestor( + of: find.byKey(const Key('insights_series_1')), + matching: find.byType(Opacity), + ) + .first, + ) + .opacity, + 1, + ); + + await tester.tap(find.byKey(const Key('insights_series_1'))); + await tester.pumpAndSettle(); + + expect( + tester + .widget( + find + .ancestor( + of: find.byKey(const Key('insights_series_1')), + matching: find.byType(Opacity), + ) + .first, + ) + .opacity, + 0.45, + ); + }); + }); + + group('ИМТ', () { + testWidgets('без значений показывает только deltaText', (tester) async { + await pumpCard(tester, FakeInsightsRepository()); + + await tester.tap(find.byKey(const Key('insights_tab_bmi'))); + await tester.pumpAndSettle(); + + expect(find.text('Укажите рост, чтобы посчитать ИМТ.'), findsOneWidget); + expect(find.byKey(const Key('insights_bmi_chart')), findsNothing); + expect(find.byKey(const Key('insights_headline')), findsNothing); + }); + + testWidgets('со значениями рисует график и подсказку', (tester) async { + final payload = loadInsightsPayloadFixture().copyWith.bmi( + labels: ['01.11', '09.11'], + values: [26.1, 24.2], + last: 24.2, + delta: -1.9, + headline: '24.2', + category: 'норма', + deltaText: 'ИМТ ниже на 1.9 за 3 месяца · норма', + hint: 'Считаем при росте 176 см.', + ); + await pumpCard(tester, FakeInsightsRepository(payload: payload)); + + await tester.tap(find.byKey(const Key('insights_tab_bmi'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('insights_bmi_chart')), findsOneWidget); + expect(find.byKey(const Key('insights_bmi_hint')), findsOneWidget); + expect(find.text('ИМТ ниже на 1.9 за 3 месяца · норма'), findsOneWidget); + }); + }); + + group('скрытие и ошибки', () { + testWidgets('403 → блок скрыт целиком', (tester) async { + await pumpCard( + tester, + FakeInsightsRepository(error: const InsightsForbidden()), + slug: 'client', + expand: false, + ); + + expect(find.byKey(const Key('insights_card')), findsNothing); + expect(find.text('Аналитика'), findsNothing); + }); + + testWidgets( + 'ошибка загрузки показывает кнопку «Повторить», повтор грузит данные', + (tester) async { + final repository = FakeInsightsRepository(error: Exception('boom')); + await pumpCard(tester, repository, expand: false); + + expect(find.text('Не удалось загрузить аналитику'), findsOneWidget); + repository.error = null; + + await tester.tap(find.byKey(const Key('insights_retry'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('insights_toggle')), findsOneWidget); + expect(find.text('Не удалось загрузить аналитику'), findsNothing); + }, + ); + }); +} diff --git a/test/features/insights/presentation/widgets/insights_kbju_test.dart b/test/features/insights/presentation/widgets/insights_kbju_test.dart new file mode 100644 index 00000000..b1daffae --- /dev/null +++ b/test/features/insights/presentation/widgets/insights_kbju_test.dart @@ -0,0 +1,447 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/daily_kbju_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/charts/intra_day_chart.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/intra_date_nav.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/intra_legend.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; + +import '../../../../fixtures/doubles/insights_doubles.dart'; + +void main() { + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: SingleChildScrollView(child: child)), + ); + } + + Future pumpKbjuCard( + WidgetTester tester, + FakeInsightsRepository repository, + String tabKey, + ) async { + tester.view.physicalSize = const Size(900, 2600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + wrap(InsightsCard(repository: repository, kbjuEnabled: true)), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('insights_toggle'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(Key(tabKey))); + await tester.pumpAndSettle(); + } + + group('КБЖУ по дням', () { + testWidgets('рисует график, шапку со средним и 4 чипа серий', ( + tester, + ) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_daily', + ); + + expect(find.byType(DailyKbjuChart), findsOneWidget); + expect(find.text('1930'), findsOneWidget); + expect(find.text('ккал в среднем'), findsOneWidget); + expect(find.text('Калораж вырос на 5% за период'), findsOneWidget); + for (var i = 0; i < 4; i++) { + expect(find.byKey(Key('insights_series_$i')), findsOneWidget); + } + expect(find.byKey(const Key('insights_series_4')), findsNothing); + }); + + testWidgets('чипы скрывают серии', (tester) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_daily', + ); + + SfCartesianChart chart() => tester.widget( + find.byKey(const Key('insights_daily_chart')), + ); + expect(chart().series, hasLength(4)); + + await tester.tap(find.byKey(const Key('insights_series_1'))); + await tester.pumpAndSettle(); + + expect(chart().series, hasLength(3)); + }); + + testWidgets('пилюли периода активны и перезапрашивают данные', ( + tester, + ) async { + final repository = FakeInsightsRepository(); + await pumpKbjuCard(tester, repository, 'insights_tab_daily'); + repository.serverRequests.clear(); + + await tester.tap(find.byKey(const Key('insights_period_30'))); + await tester.pumpAndSettle(); + + expect(repository.serverRequests.single.dailyPeriod, DailyPeriod.month); + expect( + repository.serverRequests.single.bodyPeriod, + BodyPeriod.threeMonths, + ); + }); + + testWidgets('без daily показывает заглушку', (tester) async { + final payload = loadInsightsPayloadFixture().copyWith(daily: null); + await pumpKbjuCard( + tester, + FakeInsightsRepository(payload: payload), + 'insights_tab_daily', + ); + + expect(find.byType(DailyKbjuChart), findsNothing); + expect(find.text('Недостаточно данных'), findsOneWidget); + }); + + testWidgets('пустой daily показывает заглушку вместо графика', ( + tester, + ) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository( + payload: loadInsightsPayloadFixture('insights_payload_minimal.json'), + ), + 'insights_tab_daily', + ); + + expect(find.byKey(const Key('insights_daily_chart')), findsNothing); + expect(find.text('Недостаточно данных'), findsWidgets); + }); + }); + + group('В течение дня', () { + testWidgets('рисует график, навигацию по дням, легенду и подсказку', ( + tester, + ) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_intra', + ); + + expect(find.byType(IntraDayChart), findsOneWidget); + expect(find.byType(IntraDateNav), findsOneWidget); + expect(find.text('Сегодня'), findsOneWidget); + expect(find.text('Подъём в 07:30'), findsOneWidget); + expect(find.text('Отход ко сну в 23:00'), findsOneWidget); + expect(find.text('Затемнение — время сна'), findsOneWidget); + expect(find.byKey(const Key('insights_intra_hint')), findsOneWidget); + for (var i = 0; i < 6; i++) { + expect(find.byKey(Key('insights_series_$i')), findsOneWidget); + } + }); + + testWidgets( + 'на сегодняшнем дне «следующий день» отключён, «предыдущий» нет', + (tester) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_intra', + ); + + IconButton buttonIn(String key) => tester.widget( + find.descendant( + of: find.byKey(Key(key)), + matching: find.byType(IconButton), + ), + ); + + expect(buttonIn('insights_intra_next').onPressed, isNull); + expect(buttonIn('insights_intra_prev').onPressed, isNotNull); + }, + ); + + testWidgets('«предыдущий день» запрашивает только intra и меняет дату', ( + tester, + ) async { + final repository = FakeInsightsRepository(); + repository.intraByDate['2026-11-08'] = loadInsightsPayloadFixture().intra! + .copyWith(date: '2026-11-08', dateLabel: '8 ноября', isToday: false); + await pumpKbjuCard(tester, repository, 'insights_tab_intra'); + repository.serverRequests.clear(); + + await tester.tap(find.byKey(const Key('insights_intra_prev'))); + await tester.pumpAndSettle(); + + expect(repository.intraRequests, [(slug: null, date: '2026-11-08')]); + expect(repository.serverRequests, isEmpty); + expect(find.text('8 ноября'), findsOneWidget); + expect(find.text('Сегодня'), findsNothing); + }); + + testWidgets('с прошедшего дня можно вернуться «следующим днём»', ( + tester, + ) async { + final repository = FakeInsightsRepository(); + final today = loadInsightsPayloadFixture().intra!; + repository.intraByDate['2026-11-08'] = today.copyWith( + date: '2026-11-08', + dateLabel: '8 ноября', + isToday: false, + ); + repository.intraByDate['2026-11-09'] = today; + await pumpKbjuCard(tester, repository, 'insights_tab_intra'); + + await tester.tap(find.byKey(const Key('insights_intra_prev'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('insights_intra_next'))); + await tester.pumpAndSettle(); + + expect(repository.intraRequests.last.date, '2026-11-09'); + expect(find.text('Сегодня'), findsOneWidget); + }); + + testWidgets('чип «Сон и подъём» убирает затемнение и легенду не трогает', ( + tester, + ) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_intra', + ); + + NumericAxis xAxis() => + tester + .widget( + find.byKey(const Key('insights_intra_chart')), + ) + .primaryXAxis + as NumericAxis; + + // wake + sleep: две полосы затемнения и две линии. + expect(xAxis().plotBands, hasLength(4)); + + await tester.tap(find.byKey(const Key('insights_series_5'))); + await tester.pumpAndSettle(); + + expect(xAxis().plotBands, isEmpty); + expect(find.text('Затемнение — время сна'), findsOneWidget); + }); + + testWidgets('чипы сытости и настроения скрывают линии', (tester) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository(), + 'insights_tab_intra', + ); + + int seriesCount() => tester + .widget( + find.byKey(const Key('insights_intra_chart')), + ) + .series + .length; + + // 3 столбика + сытость + настроение. + expect(seriesCount(), 5); + + await tester.tap(find.byKey(const Key('insights_series_3'))); + await tester.pumpAndSettle(); + expect(seriesCount(), 4); + + await tester.tap(find.byKey(const Key('insights_series_4'))); + await tester.pumpAndSettle(); + expect(seriesCount(), 3); + }); + + testWidgets('пустые линии не создают серий (без экстраполяции)', ( + tester, + ) async { + final intra = loadInsightsPayloadFixture().intra!.copyWith( + satiety: const [], + mood: const [], + ); + final payload = loadInsightsPayloadFixture().copyWith(intra: intra); + await pumpKbjuCard( + tester, + FakeInsightsRepository(payload: payload), + 'insights_tab_intra', + ); + + final chart = tester.widget( + find.byKey(const Key('insights_intra_chart')), + ); + expect(chart.series, hasLength(3)); + }); + + testWidgets('без wake/sleep затемнения нет', (tester) async { + const intra = IntraChartModel( + bars: [IntraBarModel(x: 12, p: 100, f: 50, c: 200)], + date: '2026-11-09', + maxDate: '2026-11-09', + dateLabel: 'Сегодня', + isToday: true, + ); + final payload = loadInsightsPayloadFixture().copyWith(intra: intra); + await pumpKbjuCard( + tester, + FakeInsightsRepository(payload: payload), + 'insights_tab_intra', + ); + + final xAxis = + tester + .widget( + find.byKey(const Key('insights_intra_chart')), + ) + .primaryXAxis + as NumericAxis; + expect(xAxis.plotBands, isEmpty); + expect(find.byKey(const Key('insights_legend_wake')), findsNothing); + expect(find.byKey(const Key('insights_legend_sleep')), findsNothing); + expect(find.byType(IntraLegend), findsOneWidget); + }); + + testWidgets('день только со сном рисует затемнение, без заглушки', ( + tester, + ) async { + final intra = loadInsightsPayloadFixture().intra!.copyWith( + bars: const [], + satiety: const [], + mood: const [], + ); + await pumpKbjuCard( + tester, + FakeInsightsRepository( + payload: loadInsightsPayloadFixture().copyWith(intra: intra), + ), + 'insights_tab_intra', + ); + + expect(find.byKey(const Key('insights_intra_chart')), findsOneWidget); + expect(find.text('Недостаточно данных'), findsNothing); + final xAxis = + tester + .widget( + find.byKey(const Key('insights_intra_chart')), + ) + .primaryXAxis + as NumericAxis; + expect(xAxis.plotBands, isNotEmpty); + }); + + testWidgets('пустой день показывает заглушку', (tester) async { + await pumpKbjuCard( + tester, + FakeInsightsRepository( + payload: loadInsightsPayloadFixture('insights_payload_minimal.json'), + ), + 'insights_tab_intra', + ); + + expect(find.byKey(const Key('insights_intra_chart')), findsNothing); + expect(find.text('Недостаточно данных'), findsOneWidget); + }); + }); + + group('IntraDateNav', () { + const model = IntraChartModel( + date: '2026-11-08', + maxDate: '2026-11-09', + dateLabel: '8 ноября', + isToday: false, + ); + + testWidgets('вызывает колбэки предыдущего и следующего дня', ( + tester, + ) async { + var prev = 0; + var next = 0; + await tester.pumpWidget( + wrap( + IntraDateNav( + model: model, + onPreviousDay: () => prev++, + onNextDay: () => next++, + onDatePicked: (_) {}, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('insights_intra_prev'))); + await tester.tap(find.byKey(const Key('insights_intra_next'))); + + expect(prev, 1); + expect(next, 1); + expect(find.text('8 ноября'), findsOneWidget); + }); + + testWidgets('«следующий день» отключён, когда выбран сегодняшний день', ( + tester, + ) async { + var next = 0; + await tester.pumpWidget( + wrap( + IntraDateNav( + model: model.copyWith(isToday: true, dateLabel: 'Сегодня'), + onPreviousDay: () {}, + onNextDay: () => next++, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap( + find.byKey(const Key('insights_intra_next')), + warnIfMissed: false, + ); + + expect(next, 0); + }); + + testWidgets( + 'выбор даты: календарь ограничен maxDate и возвращает выбранный день', + (tester) async { + DateTime? picked; + await tester.pumpWidget( + wrap( + IntraDateNav( + model: model, + onPreviousDay: () {}, + onNextDay: () {}, + onDatePicked: (date) => picked = date, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('insights_intra_pick'))); + await tester.pumpAndSettle(); + + final dialog = tester.widget( + find.byType(CalendarDatePicker), + ); + expect(dialog.lastDate, DateTime(2026, 11, 9)); + expect(dialog.initialDate, DateTime(2026, 11, 8)); + + await tester.tap(find.text('5')); + await tester.tap( + find.text('OK').evaluate().isNotEmpty + ? find.text('OK') + : find.text('ОК'), + ); + await tester.pumpAndSettle(); + + expect(picked, DateTime(2026, 11, 5)); + }, + ); + }); +} diff --git a/test/features/insights/repositories/insights_repository_test.dart b/test/features/insights/repositories/insights_repository_test.dart new file mode 100644 index 00000000..3d0affea --- /dev/null +++ b/test/features/insights/repositories/insights_repository_test.dart @@ -0,0 +1,341 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/insights/domain/insights_text_builder.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/models/insights_response_model.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:eatvio_app/features/insights/services/insights_service.dart'; +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/models/weight_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../../fixtures/doubles/insights_doubles.dart'; + +class _MockProfileRepository extends Mock implements ProfileRepository {} + +class _MockInsightsService extends Mock implements InsightsService {} + +ProfileDetailsModel _details({int height = 176}) => ProfileDetailsModel( + firstName: 'A', + lastName: 'B', + birthdate: '1990-01-01', + gender: 'male', + country: 'RU', + city: 'Moscow', + lang: 'ru', + weight: 70, + height: height, + chestCircumference: 90, + waistCircumference: 80, + hipCircumference: 95, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: false, + isBedtimeFillable: false, + activityCoefficient: 1.2, +); + +DioException _dio(int status) => DioException( + requestOptions: RequestOptions(path: '/x'), + response: Response( + requestOptions: RequestOptions(path: '/x'), + statusCode: status, + ), +); + +void main() { + late _MockProfileRepository profileRepository; + late _MockInsightsService insightsService; + late InsightsRepository repository; + + final date1 = DateTime(2026, 11, 1, 12); + final date2 = DateTime(2026, 11, 9, 12); + + final weights = [ + WeightModel( + id: 1, + userId: 1, + weight: 75, + createdAt: date1, + updatedAt: date1, + bmi: 24, + ), + WeightModel( + id: 2, + userId: 1, + weight: 73.5, + createdAt: date2, + updatedAt: date2, + bmi: 23.5, + ), + ]; + final circumferences = [ + CircumferenceModel( + id: 1, + userId: 1, + chestCircumference: 95, + waistCircumference: 82, + hipCircumference: 100, + createdAt: date1, + updatedAt: date1, + ), + ]; + + setUp(() async { + final s = await S.load(const Locale('ru')); + profileRepository = _MockProfileRepository(); + insightsService = _MockInsightsService(); + repository = InsightsRepository( + profileRepository: profileRepository, + insightsService: insightsService, + textBuilderFactory: () => InsightsTextBuilder(s), + ); + }); + + group('getInsights', () { + test('собирает payload из веса и замеров; daily/intra == null', () async { + when( + () => profileRepository.getWeight(period: '3', slug: null), + ).thenAnswer((_) async => weights); + when( + () => profileRepository.getCircumferences(period: '3', slug: null), + ).thenAnswer((_) async => circumferences); + + final payload = await repository.getInsights( + bodyPeriod: BodyPeriod.threeMonths, + heightCm: 176, + ); + + expect(payload.weight.values, [75, 73.5]); + expect(payload.weight.deltaText, 'Снизили на 1.5 кг за 3 месяца'); + expect(payload.bmi.values, [24, 23.5]); + expect(payload.measure.waist, [82]); + expect(payload.daily, isNull); + expect(payload.intra, isNull); + }); + + test('пробрасывает slug и значение периода', () async { + when( + () => profileRepository.getWeight(period: 'all', slug: 'client'), + ).thenAnswer((_) async => weights); + when( + () => + profileRepository.getCircumferences(period: 'all', slug: 'client'), + ).thenAnswer((_) async => circumferences); + + await repository.getInsights(slug: 'client', bodyPeriod: BodyPeriod.all); + + verify( + () => profileRepository.getWeight(period: 'all', slug: 'client'), + ).called(1); + verify( + () => + profileRepository.getCircumferences(period: 'all', slug: 'client'), + ).called(1); + }); + + test('403 → InsightsForbidden', () async { + when( + () => profileRepository.getWeight(period: '3', slug: 'client'), + ).thenThrow(_dio(403)); + when( + () => profileRepository.getCircumferences(period: '3', slug: 'client'), + ).thenAnswer((_) async => circumferences); + + expect( + repository.getInsights( + slug: 'client', + bodyPeriod: BodyPeriod.threeMonths, + ), + throwsA(isA()), + ); + }); + + test('прочие ошибки пробрасываются как есть', () async { + when( + () => profileRepository.getWeight(period: '3', slug: null), + ).thenThrow(_dio(500)); + when( + () => profileRepository.getCircumferences(period: '3', slug: null), + ).thenAnswer((_) async => circumferences); + + expect( + repository.getInsights(bodyPeriod: BodyPeriod.threeMonths), + throwsA(isA()), + ); + }); + }); + + group('getHeightCm', () { + test('свой профиль', () async { + when( + () => profileRepository.getMyProfileDetails(), + ).thenAnswer((_) async => _details()); + + expect(await repository.getHeightCm(), 176); + }); + + test('профиль клиента по slug', () async { + when( + () => profileRepository.getProfileDetailsBySlug('client'), + ).thenAnswer((_) async => _details(height: 168)); + + expect(await repository.getHeightCm(slug: 'client'), 168); + }); + + test('нулевой рост → null', () async { + when( + () => profileRepository.getMyProfileDetails(), + ).thenAnswer((_) async => _details(height: 0)); + + expect(await repository.getHeightCm(), isNull); + }); + + test('ошибка не 403 → null', () async { + when(() => profileRepository.getMyProfileDetails()).thenThrow(_dio(500)); + + expect(await repository.getHeightCm(), isNull); + }); + + test('403 → InsightsForbidden', () async { + when( + () => profileRepository.getProfileDetailsBySlug('client'), + ).thenThrow(_dio(403)); + + expect( + repository.getHeightCm(slug: 'client'), + throwsA(isA()), + ); + }); + }); + + group('fetchInsights (сервер)', () { + final response = InsightsResponseModel(data: loadInsightsPayloadFixture()); + + test('свой профиль: /insights с периодами и датой', () async { + when( + () => insightsService.getInsights( + bodyPeriod: '6', + dailyPeriod: '30', + intraDate: '2026-11-08', + ), + ).thenAnswer((_) async => response); + + final payload = await repository.fetchInsights( + bodyPeriod: BodyPeriod.sixMonths, + dailyPeriod: DailyPeriod.month, + intraDate: '2026-11-08', + ); + + expect(payload, response.data); + verifyNever( + () => insightsService.getInsightsBySlug( + slug: any(named: 'slug'), + bodyPeriod: any(named: 'bodyPeriod'), + dailyPeriod: any(named: 'dailyPeriod'), + intraDate: any(named: 'intraDate'), + ), + ); + }); + + test('чужой профиль: /insights/{slug}', () async { + when( + () => insightsService.getInsightsBySlug( + slug: 'client', + bodyPeriod: 'all', + dailyPeriod: 'all', + intraDate: null, + ), + ).thenAnswer((_) async => response); + + final payload = await repository.fetchInsights( + slug: 'client', + bodyPeriod: BodyPeriod.all, + dailyPeriod: DailyPeriod.all, + ); + + expect(payload, response.data); + }); + + test('403 → InsightsForbidden', () { + when( + () => insightsService.getInsightsBySlug( + slug: 'client', + bodyPeriod: '3', + dailyPeriod: '14', + intraDate: null, + ), + ).thenThrow(_dio(403)); + + expect( + repository.fetchInsights( + slug: 'client', + bodyPeriod: BodyPeriod.threeMonths, + dailyPeriod: DailyPeriod.twoWeeks, + ), + throwsA(isA()), + ); + }); + + test('422 пробрасывается как DioException', () { + when( + () => insightsService.getInsights( + bodyPeriod: '3', + dailyPeriod: '14', + intraDate: null, + ), + ).thenThrow(_dio(422)); + + expect( + repository.fetchInsights( + bodyPeriod: BodyPeriod.threeMonths, + dailyPeriod: DailyPeriod.twoWeeks, + ), + throwsA(isA()), + ); + }); + }); + + group('fetchIntra (сервер)', () { + final intra = loadInsightsPayloadFixture().intra!; + final response = InsightsIntraResponseModel( + data: InsightsIntraDataModel(intra: intra), + ); + + test('свой профиль: /insights/intra', () async { + when( + () => insightsService.getIntra(intraDate: '2026-11-09'), + ).thenAnswer((_) async => response); + + expect(await repository.fetchIntra(intraDate: '2026-11-09'), intra); + }); + + test('чужой профиль: /insights/{slug}/intra', () async { + when( + () => insightsService.getIntraBySlug(slug: 'client', intraDate: null), + ).thenAnswer((_) async => response); + + expect(await repository.fetchIntra(slug: 'client'), intra); + }); + + test('403 → InsightsForbidden', () { + when( + () => insightsService.getIntra(intraDate: null), + ).thenThrow(_dio(403)); + + expect(repository.fetchIntra(), throwsA(isA())); + }); + }); +} diff --git a/test/features/menu/presentation/bloc/menu_cubit_test.dart b/test/features/menu/presentation/bloc/menu_cubit_test.dart index 9cdf18d3..e7dd9a9c 100644 --- a/test/features/menu/presentation/bloc/menu_cubit_test.dart +++ b/test/features/menu/presentation/bloc/menu_cubit_test.dart @@ -4,6 +4,8 @@ import 'package:eatvio_app/features/profile/repositories/profile_repository.dart import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; + +import '../../../../fixtures/doubles/session_doubles.dart'; import 'menu_cubit_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) @@ -25,12 +27,12 @@ void main() { }); test('начальное состояние - MenuState', () { - menuCubit = MenuCubit(mockProfileRepository); + menuCubit = MenuCubit(mockProfileRepository, FakeSessionLifecycleService()); expect(menuCubit!.state, isA()); }); test('makePassKey - успешно создает passKey', () async { - menuCubit = MenuCubit(mockProfileRepository); + menuCubit = MenuCubit(mockProfileRepository, FakeSessionLifecycleService()); const expectedPassKey = 'test-pass-key'; when(mockProfileRepository.getPassKey( @@ -48,7 +50,7 @@ void main() { }); test('makePassKey - возвращает null при ошибке', () async { - menuCubit = MenuCubit(mockProfileRepository); + menuCubit = MenuCubit(mockProfileRepository, FakeSessionLifecycleService()); when(mockProfileRepository.getPassKey( routeName: 'product_nutritional_value.index', diff --git a/test/features/menu/presentation/pages/blocked_users_screen_smoke_test.dart b/test/features/menu/presentation/pages/blocked_users_screen_smoke_test.dart index eb2fb68c..04cbb298 100644 --- a/test/features/menu/presentation/pages/blocked_users_screen_smoke_test.dart +++ b/test/features/menu/presentation/pages/blocked_users_screen_smoke_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart'; import 'package:eatvio_app/features/menu/presentation/pages/blocked_users_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -30,12 +29,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/menu/presentation/pages/menu_screen_smoke_test.dart b/test/features/menu/presentation/pages/menu_screen_smoke_test.dart index 1facf0bb..2dce3fe9 100644 --- a/test/features/menu/presentation/pages/menu_screen_smoke_test.dart +++ b/test/features/menu/presentation/pages/menu_screen_smoke_test.dart @@ -7,14 +7,14 @@ import 'package:eatvio_app/features/menu/presentation/pages/menu_screen.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import 'menu_screen_smoke_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) @@ -68,12 +68,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', @@ -106,6 +101,11 @@ void main() { name: 'myPlansScreen', builder: (context, state) => const Scaffold(body: Text('My Plans')), ), + GoRoute( + path: '/video-call-recordings-screen', + name: 'videoCallRecordingsScreen', + builder: (context, state) => const Scaffold(body: Text('My Consultations')), + ), GoRoute( path: '/consultant-finances-screen', name: 'consultantFinancesScreen', @@ -138,7 +138,7 @@ void main() { testWidgets('renders menu screen for user', (tester) async { final repository = MockProfileRepository(); - final cubit = MenuCubit(repository); + final cubit = MenuCubit(repository, FakeSessionLifecycleService()); when(repository.getPassKey(routeName: anyNamed('routeName'), routeParams: anyNamed('routeParams'))).thenAnswer((_) async => 'test-passkey'); when(repository.getMyProfile()).thenAnswer((_) async => mockUserProfile); @@ -151,11 +151,12 @@ void main() { expect(find.text('Меню'), findsOneWidget); expect(find.text('Настройки профиля'), findsOneWidget); + expect(find.text('Мои консультации'), findsOneWidget); }); testWidgets('renders menu screen for consultant', (tester) async { final repository = MockProfileRepository(); - final cubit = MenuCubit(repository); + final cubit = MenuCubit(repository, FakeSessionLifecycleService()); when(repository.getPassKey(routeName: anyNamed('routeName'), routeParams: anyNamed('routeParams'))).thenAnswer((_) async => 'test-passkey'); when(repository.getMyProfile()).thenAnswer((_) async => mockConsultantProfile); @@ -170,6 +171,7 @@ void main() { expect(find.text('Мои рецепты'), findsOneWidget); expect(find.text('Мои диеты'), findsOneWidget); expect(find.text('Мои планы'), findsOneWidget); + expect(find.text('Мои консультации'), findsOneWidget); }); }); } diff --git a/test/features/menu/presentation/pages/notifications_settings_screen_smoke_test.dart b/test/features/menu/presentation/pages/notifications_settings_screen_smoke_test.dart index 9ee07d14..0a8b70a8 100644 --- a/test/features/menu/presentation/pages/notifications_settings_screen_smoke_test.dart +++ b/test/features/menu/presentation/pages/notifications_settings_screen_smoke_test.dart @@ -8,10 +8,9 @@ import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings import 'package:eatvio_app/features/menu/presentation/pages/notifications_settings_screen.dart'; import 'package:eatvio_app/features/menu/repositories/notification_settings_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -45,12 +44,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/menu/presentation/widgets/blocked_user_widget_test.dart b/test/features/menu/presentation/widgets/blocked_user_widget_test.dart index a77fd0dd..c81d3235 100644 --- a/test/features/menu/presentation/widgets/blocked_user_widget_test.dart +++ b/test/features/menu/presentation/widgets/blocked_user_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart'; import 'package:eatvio_app/features/menu/presentation/widgets/blocked_user_widget.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/my_diets/presentation/my_diets_screen_smoke_test.dart b/test/features/my_diets/presentation/my_diets_screen_smoke_test.dart index 1a852e9e..ef005094 100644 --- a/test/features/my_diets/presentation/my_diets_screen_smoke_test.dart +++ b/test/features/my_diets/presentation/my_diets_screen_smoke_test.dart @@ -9,9 +9,8 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.d import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart'; import 'package:eatvio_app/features/my_diets/repositories/my_diets_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -39,12 +38,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/my_diets/presentation/widgets/basic_widget_test.dart b/test/features/my_diets/presentation/widgets/basic_widget_test.dart index 9afb6818..2afb1c1a 100644 --- a/test/features/my_diets/presentation/widgets/basic_widget_test.dart +++ b/test/features/my_diets/presentation/widgets/basic_widget_test.dart @@ -12,9 +12,8 @@ import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diet_widget import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diets_tab.dart'; import 'package:eatvio_app/features/my_diets/repositories/my_diets_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -73,12 +72,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); diff --git a/test/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet_test.dart b/test/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet_test.dart index f2c63d3f..afc461df 100644 --- a/test/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet_test.dart +++ b/test/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet_test.dart @@ -4,8 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/my_diets/presentation/widgets/diet_deleted_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -23,12 +22,7 @@ void main() { Widget createTestWidget(String title) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: DietDeletedBottomSheet(title: title), diff --git a/test/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet_test.dart b/test/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet_test.dart index f6489239..08dfc780 100644 --- a/test/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet_test.dart +++ b/test/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet_test.dart @@ -4,8 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/my_diets/presentation/widgets/diet_drafetd_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -23,12 +22,7 @@ void main() { Widget createTestWidget(String title) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: DietDraftedBottomSheet(title: title), diff --git a/test/features/my_diets/presentation/widgets/my_diet_widget_test.dart b/test/features/my_diets/presentation/widgets/my_diet_widget_test.dart index f6204cb5..47ccd46b 100644 --- a/test/features/my_diets/presentation/widgets/my_diet_widget_test.dart +++ b/test/features/my_diets/presentation/widgets/my_diet_widget_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.d import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.dart'; import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diet_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:go_router/go_router.dart'; @@ -63,12 +62,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/my_diets/presentation/widgets/my_diets_tab_test.dart b/test/features/my_diets/presentation/widgets/my_diets_tab_test.dart index 4efadd60..4abe0b2e 100644 --- a/test/features/my_diets/presentation/widgets/my_diets_tab_test.dart +++ b/test/features/my_diets/presentation/widgets/my_diets_tab_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.d import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_state.dart'; import 'package:eatvio_app/features/my_diets/presentation/widgets/my_diets_tab.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -18,12 +17,7 @@ void main() { Widget wrap(Widget child, MyDietsCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value(value: cubit, child: child), diff --git a/test/features/my_finance/presentation/pages/card_settings_smoke_test.dart b/test/features/my_finance/presentation/pages/card_settings_smoke_test.dart index f4329b18..f31ae131 100644 --- a/test/features/my_finance/presentation/pages/card_settings_smoke_test.dart +++ b/test/features/my_finance/presentation/pages/card_settings_smoke_test.dart @@ -8,10 +8,9 @@ import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cub import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_state.dart'; import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -37,12 +36,7 @@ void main() { Widget wrap(UserCardsCubit cubit, Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value(value: cubit, child: child), ); diff --git a/test/features/my_finance/presentation/pages/user_finance_screen_smoke_test.dart b/test/features/my_finance/presentation/pages/user_finance_screen_smoke_test.dart index 3cba81f7..3f7c75af 100644 --- a/test/features/my_finance/presentation/pages/user_finance_screen_smoke_test.dart +++ b/test/features/my_finance/presentation/pages/user_finance_screen_smoke_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/prof import 'package:eatvio_app/features/my_finance/presentation/pages/user_finance_screen.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -50,12 +49,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/my_finance/presentation/widgets/card_widget_test.dart b/test/features/my_finance/presentation/widgets/card_widget_test.dart index 0b3b8273..791e87bb 100644 --- a/test/features/my_finance/presentation/widgets/card_widget_test.dart +++ b/test/features/my_finance/presentation/widgets/card_widget_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cub import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_state.dart'; import 'package:eatvio_app/features/my_finance/presentation/widgets/card_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -30,12 +29,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: BlocProvider.value( diff --git a/test/features/my_plans/presentation/my_plans_screen_smoke_test.dart b/test/features/my_plans/presentation/my_plans_screen_smoke_test.dart index a8d95fcf..dbdcc37a 100644 --- a/test/features/my_plans/presentation/my_plans_screen_smoke_test.dart +++ b/test/features/my_plans/presentation/my_plans_screen_smoke_test.dart @@ -8,9 +8,8 @@ import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.d import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart'; import 'package:eatvio_app/features/my_plans/repositories/my_diets_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -38,12 +37,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/my_plans/presentation/widgets/basic_widget_test.dart b/test/features/my_plans/presentation/widgets/basic_widget_test.dart index 270088f2..b3238a0b 100644 --- a/test/features/my_plans/presentation/widgets/basic_widget_test.dart +++ b/test/features/my_plans/presentation/widgets/basic_widget_test.dart @@ -10,9 +10,8 @@ import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.d import 'package:eatvio_app/features/my_plans/presentation/widgets/my_plan_widget.dart'; import 'package:eatvio_app/features/my_plans/repositories/my_diets_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -71,12 +70,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); diff --git a/test/features/my_plans/presentation/widgets/my_plan_widget_test.dart b/test/features/my_plans/presentation/widgets/my_plan_widget_test.dart index 87ca2c65..317e2ba5 100644 --- a/test/features/my_plans/presentation/widgets/my_plan_widget_test.dart +++ b/test/features/my_plans/presentation/widgets/my_plan_widget_test.dart @@ -8,10 +8,9 @@ import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.d import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart'; import 'package:eatvio_app/features/my_plans/presentation/widgets/my_plan_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -39,12 +38,7 @@ void main() { Widget wrap(Widget child, MyPlansCubit? cubit) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( routes: [ diff --git a/test/features/notifications/models/notification_model_fromjson_bulk_test.dart b/test/features/notifications/models/notification_model_fromjson_bulk_test.dart index 8ee7fe97..771518c7 100644 --- a/test/features/notifications/models/notification_model_fromjson_bulk_test.dart +++ b/test/features/notifications/models/notification_model_fromjson_bulk_test.dart @@ -92,6 +92,7 @@ void main() { DiaryReminderForUsersNotification.fromJson(base, NotificationType.diaryReminderForUsers); DiaryReminderForUsersNotification.fromJson({'created_at': c, 'data': {}}, NotificationType.diaryReminderForUsers); PersonalDietIsDefinedToCustomerNotification.fromJson(base, NotificationType.personalDietIsDefinedToCustomer); + PersonalDietIsDefinedToAuthorNotification.fromJson(base, NotificationType.personalDietIsDefinedToAuthor); ConsultantEducationUpdatedNotification.fromJson(base, NotificationType.consultantEducationUpdated); ComplaintRegisteredNotification.fromJson(base, NotificationType.complaintRegistered); ContentUnpublishedNotification.fromJson(base, NotificationType.contentUnpublished); diff --git a/test/features/notifications/models/notification_model_test.dart b/test/features/notifications/models/notification_model_test.dart index d7f809e0..0c89e2fd 100644 --- a/test/features/notifications/models/notification_model_test.dart +++ b/test/features/notifications/models/notification_model_test.dart @@ -50,6 +50,7 @@ void main() { 'stay-on-track-to-customer': NotificationType.stayOnTrackToCustomer, 'diary-reminder-for-users': NotificationType.diaryReminderForUsers, 'personal-diet-is-defined-to-customer': NotificationType.personalDietIsDefinedToCustomer, + 'personal-diet-is-defined-to-author': NotificationType.personalDietIsDefinedToAuthor, }; cases.forEach((key, expected) { @@ -671,6 +672,34 @@ void main() { expect(notification.type, NotificationType.personalizedDietIsDefined); }); + test('PersonalDietIsDefinedToAuthorNotification.fromJson parses all fields', () { + final json = { + 'chosen_plan_id': 12, + 'diet_id': 34, + 'plan_name': 'Plan', + 'user_name': 'Client', + 'consultant_name': 'Consultant', + 'diet_name': 'Personal diet', + 'role': 'consultant', + 'peer_slug': 'client-slug', + 'peer_image_path': 'avatars/client.png', + 'created_at': '2024-01-30T12:00:00Z', + }; + + final notification = PersonalDietIsDefinedToAuthorNotification.fromJson( + json, + NotificationType.personalDietIsDefinedToAuthor, + isRead: false, + ); + + expect(notification.chosenPlanId, 12); + expect(notification.dietId, 34); + expect(notification.userName, 'Client'); + expect(notification.dietName, 'Personal diet'); + expect(notification.peerSlug, 'client-slug'); + expect(notification.type, NotificationType.personalDietIsDefinedToAuthor); + }); + test('ChosenPlanFinishedToClientNotification.fromJson parses all fields', () { final json = { 'plan_name': 'Finished Plan', diff --git a/test/features/notifications/presentation/notifications_screen_smoke_test.dart b/test/features/notifications/presentation/notifications_screen_smoke_test.dart index 0c6e63e4..333e9c61 100644 --- a/test/features/notifications/presentation/notifications_screen_smoke_test.dart +++ b/test/features/notifications/presentation/notifications_screen_smoke_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/notifications/presentation/notifications_cub import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_state.dart'; import 'package:eatvio_app/features/notifications/presentation/notifications_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -32,12 +31,7 @@ void main() { Widget wrap(NotificationsCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value(value: cubit, child: const NotificationsScreen()), ); diff --git a/test/features/notifications/presentation/widgets/notification_widget_test.dart b/test/features/notifications/presentation/widgets/notification_widget_test.dart index 2127155b..a109d9ed 100644 --- a/test/features/notifications/presentation/widgets/notification_widget_test.dart +++ b/test/features/notifications/presentation/widgets/notification_widget_test.dart @@ -1,1255 +1,1327 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; -import 'package:eatvio_app/features/notifications/models/notification_model.dart'; -import 'package:eatvio_app/features/notifications/presentation/widgets/notification_widget.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:go_router/go_router.dart'; - -void main() { - group('NotificationWidget', () { - final testDate = DateTime(2024, 1, 15, 10, 30); - - Widget createTestWidget(BaseNotificationModel notification) { - return MaterialApp( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru'), Locale('en')], - locale: const Locale('ru'), - theme: ThemeHelper().themeData(), - home: Scaffold(body: NotificationWidget(notification: notification)), - ); - } - - testWidgets('displays PlanSubscriptionStartedToAuthorNotification', ( - tester, - ) async { - final notification = PlanSubscriptionStartedToAuthorNotification( - type: NotificationType.planSubscriptionStartedToAuthor, - planName: 'Test Plan', - planId: 1, - customerName: 'Test Customer', - userId: 0, - userPhotoPath: '', - chatId: 'chat123', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PlanSubscriptionCanceledToAuthorNotification', ( - tester, - ) async { - final notification = PlanSubscriptionCanceledToAuthorNotification( - type: NotificationType.planSubscriptionCanceledToAuthor, - planName: 'Test Plan', - planId: 1, - customerName: 'Test Customer', - userId: 0, - userPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanStartedToClientNotification', ( - tester, - ) async { - final notification = ChosenPlanStartedToClientNotification( - type: NotificationType.chosenPlanStartedToClient, - planName: 'Test Plan', - planId: 1, - consultantName: 'Test Consultant', - peerProfileUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanTomorrowReminderToClientNotification', ( - tester, - ) async { - final notification = ChosenPlanTomorrowReminderToClientNotification( - type: NotificationType.chosenPlanTomorrowReminderToClient, - planName: 'Test Plan', - consultantName: '', - chatId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DiaryReminderNotification', (tester) async { - final notification = DiaryReminderNotification( - type: NotificationType.diaryReminderNotification, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantLeftCommentNotification', (tester) async { - final notification = ConsultantLeftCommentNotification( - type: NotificationType.consultantLeftComment, - chosenPlanId: 1, - diaryId: 0, - date: testDate, - planName: '', - userName: '', - consultantName: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PersonalizedDietIsDefinedNotification', ( - tester, - ) async { - final notification = PersonalizedDietIsDefinedNotification( - type: NotificationType.personalizedDietIsDefined, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanFinishedToClientNotification', ( - tester, - ) async { - final notification = ChosenPlanFinishedToClientNotification( - type: NotificationType.chosenPlanFinishedToClient, - planName: 'Test Plan', - chosenPlanId: 1, - consultantName: '', - consultantPhotoPath: '', - consultantProfileUrl: '', - consultantId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PlanSubscriptionCanceledToCustomerNotification', ( - tester, - ) async { - final notification = PlanSubscriptionCanceledToCustomerNotification( - type: NotificationType.planSubscriptionCanceledToCustomer, - planName: 'Test Plan', - planId: 1, - authorName: '', - authorId: 0, - authorPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanStartedToConsultantNotification', ( - tester, - ) async { - final notification = ChosenPlanStartedToConsultantNotification( - type: NotificationType.chosenPlanStartedToConsultant, - planName: 'Test Plan', - customerName: 'Test Customer', - planId: 1, - customerId: 1, - peerProfileUrl: '', - consultationUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanTomorrowReminderToConsultantNotification', ( - tester, - ) async { - final notification = ChosenPlanTomorrowReminderToConsultantNotification( - type: NotificationType.chosenPlanTomorrowReminderToConsultant, - planName: 'Test Plan', - customerName: 'Test Customer', - chatId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PlanSubscriptionPaidToAuthorNotification', ( - tester, - ) async { - final notification = PlanSubscriptionPaidToAuthorNotification( - type: NotificationType.planSubscriptionPaidToAuthor, - planName: 'Test Plan', - planId: 1, - customerName: 'Test Customer', - userId: 0, - userPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets( - 'displays ChosenPlanFinishedToConsultantNotification with button', - (tester) async { - final notification = ChosenPlanFinishedToConsultantNotification( - type: NotificationType.chosenPlanFinishedToConsultant, - planName: 'Test Plan', - customerName: 'Test Customer', - planId: 1, - chosenPlanId: 1, - clientPhotoPath: '', - clientId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - expect(find.text('Получить выплату'), findsOneWidget); - }, - ); - - testWidgets( - 'collect charge from finished notification uses chosenPlanId, not planId', - (tester) async { - int? capturedChosenPlanId; - final notification = ChosenPlanFinishedToConsultantNotification( - type: NotificationType.chosenPlanFinishedToConsultant, - planName: 'Test Plan', - customerName: 'Test Customer', - planId: 99, - chosenPlanId: 42, - clientPhotoPath: '', - clientId: 0, - isRead: false, - createdAt: testDate, - ); - - final router = GoRouter( - routes: [ - GoRoute( - path: '/', - builder: (context, state) => Scaffold( - body: NotificationWidget(notification: notification), - ), - ), - GoRoute( - path: CardSettingsScreen.path, - builder: (context, state) { - capturedChosenPlanId = state.extra as int?; - return const Scaffold(body: Text('card-settings')); - }, - ), - ], - ); - - await tester.pumpWidget( - MaterialApp.router( - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru'), Locale('en')], - locale: const Locale('ru'), - theme: ThemeHelper().themeData(), - routerConfig: router, - ), - ); - await tester.pumpAndSettle(); - - await tester.tap(find.text('Получить выплату')); - await tester.pumpAndSettle(); - - expect(find.text('card-settings'), findsOneWidget); - expect(capturedChosenPlanId, 42); - }, - ); - - testWidgets('displays ChosenPlanLastDayFinishedForUser', (tester) async { - final notification = ChosenPlanLastDayFinishedForUser( - type: NotificationType.chosenPlanLastDayFinishedForUser, - planName: 'Test Plan', - chosenPlanId: 1, - complaintUrl: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanConsultantLastDayStarted', (tester) async { - final notification = ChosenPlanConsultantLastDayStarted( - type: NotificationType.chosenPlanConsultantLastDayStarted, - planName: 'Test Plan', - planId: 1, - chatId: 'chat123', - chatUrl: 'chat_url', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ComplaintToModerationForUser', (tester) async { - final notification = ComplaintToModerationForUser( - type: NotificationType.complaintToModerationForUser, - message: 'Test message', - entityId: 1, - entityType: 'test', - entityName: 'Test Entity', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays CommentReplied', (tester) async { - final notification = CommentReplied( - type: NotificationType.commentReplied, - entityName: 'Test Entity', - commentedEntityId: 1, - commentedEntityType: CommentedEntityType.diet, - author: 'Test Author', - authorId: 1, - parentCommentId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ScoreAdded', (tester) async { - final notification = ScoreAdded( - type: NotificationType.scoreAdded, - scoreKey: 'test_key', - scorableId: 1, - scorableType: 'test', - scorableName: 'Test Name', - scorableSlug: 'test-slug', - scoreValue: 10, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays EntityCommented', (tester) async { - final notification = EntityCommented( - type: NotificationType.entityCommented, - entityName: 'Test Entity', - entityId: 1, - entityType: CommentedEntityType.diet, - entityTranslatedType: 'Test Type', - entityUrl: 'test_url', - authorName: 'Test Author', - authorId: 1, - authorSlug: 'test-author', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PlanSubscriptionExpiredNotification', (tester) async { - final notification = PlanSubscriptionExpiredNotification( - type: NotificationType.planSubscriptionExpired, - planName: 'Test Plan', - customerName: 'Test Customer', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PlanSubscriptionRenewedNotification', (tester) async { - final notification = PlanSubscriptionRenewedNotification( - type: NotificationType.planSubscriptionRenewed, - planName: 'Test Plan', - customerName: 'Test Customer', - renewalDate: '2024-02-01', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantAssignedNotification', (tester) async { - final notification = ConsultantAssignedNotification( - type: NotificationType.consultantAssigned, - consultantName: 'Test Consultant', - planName: 'Test Plan', - planId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantUnassignedNotification', (tester) async { - final notification = ConsultantUnassignedNotification( - type: NotificationType.consultantUnassigned, - consultantName: 'Test Consultant', - planName: 'Test Plan', - planId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PaymentFailedNotification', (tester) async { - final notification = PaymentFailedNotification( - type: NotificationType.paymentFailed, - planName: 'Test Plan', - errorMessage: 'Test error', - paymentMethod: 'card', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PaymentSuccessfulNotification', (tester) async { - final notification = PaymentSuccessfulNotification( - type: NotificationType.paymentSuccessful, - planName: 'Test Plan', - amount: 100.0, - currency: 'USD', - transactionId: 'trans123', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays GoalAchievedNotification', (tester) async { - final notification = GoalAchievedNotification( - type: NotificationType.goalAchieved, - goalName: 'Test Goal', - goalType: 'weight', - achievedValue: 50.0, - targetValue: 100.0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays WorkoutReminderNotification', (tester) async { - final notification = WorkoutReminderNotification( - type: NotificationType.workoutReminder, - workoutName: 'Test Workout', - workoutType: 'cardio', - duration: 30, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays MealReminderNotification', (tester) async { - final notification = MealReminderNotification( - type: NotificationType.mealReminder, - mealName: 'Test Meal', - mealType: 'breakfast', - calories: 500, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DietCancelledNotification', (tester) async { - final notification = DietCancelledNotification( - type: NotificationType.dietCancelled, - dietName: 'Test Diet', - dietId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DietStartedNotification', (tester) async { - final notification = DietStartedNotification( - type: NotificationType.dietStarted, - dietName: 'Test Diet', - dietId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DietExpiredNotification', (tester) async { - final notification = DietExpiredNotification( - type: NotificationType.dietExpired, - dietName: 'Test Diet', - dietId: 1, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DietWillStartedInNotification', (tester) async { - final notification = DietWillStartedInNotification( - type: NotificationType.dietWillStartedIn, - dietName: 'Test Diet', - dietId: 1, - startDate: '2024-02-01', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DietCanNotBeStartedNotification', (tester) async { - final notification = DietCanNotBeStartedNotification( - type: NotificationType.dietCanNotBeStarted, - dietName: 'Test Diet', - dietId: 1, - reason: 'Test reason', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PersonalDietCreationNeededNotification', ( - tester, - ) async { - final notification = PersonalDietCreationNeededNotification( - type: NotificationType.personalDietCreationNeeded, - userName: 'Test Client', - consultantName: '', - myDietsUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanClientLastDayFinishedNotification', ( - tester, - ) async { - final notification = ChosenPlanClientLastDayFinishedNotification( - type: NotificationType.chosenPlanClientLastDayFinished, - planName: 'Test Plan', - chosenPlanId: 1, - complaintUrl: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ChosenPlanClientLastDayStartedNotification', ( - tester, - ) async { - final notification = ChosenPlanClientLastDayStartedNotification( - type: NotificationType.chosenPlanClientLastDayStarted, - planName: 'Test Plan', - chosenPlanId: 1, - lastDayDiaryUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays StayOnTrackToAuthorNotification', (tester) async { - final notification = StayOnTrackToAuthorNotification( - type: NotificationType.stayOnTrackToAuthor, - planName: 'Test Plan', - userName: 'Test Client', - dayNum: 1, - diaryDayId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets( - 'displays ClientStartPlanSubscriptionToSubscriberNotification', - (tester) async { - final notification = - ClientStartPlanSubscriptionToSubscriberNotification( - type: NotificationType.clientStartPlanSubscriptionToSubscriber, - planName: 'Test Plan', - planId: 1, - authorName: '', - authorId: 0, - authorPhotoPath: '', - chatUrl: '', - chatId: '', - startDate: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }, - ); - - testWidgets( - 'displays ConsultantConfirmPlanSubscriptionToSubscriberNotification', - (tester) async { - final notification = - ConsultantConfirmPlanSubscriptionToSubscriberNotification( - type: NotificationType - .consultantConfirmPlanSubscriptionToSubscriber, - planName: 'Test Plan', - planId: 1, - consultantName: 'Test Consultant', - authorId: 0, - authorPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }, - ); - - testWidgets('displays ClientPaidPlanSubscriptionToAuthorNotification', ( - tester, - ) async { - final notification = ClientPaidPlanSubscriptionToAuthorNotification( - type: NotificationType.clientPaidPlanSubscriptionToAuthor, - planName: 'Test Plan', - planId: 1, - clientName: 'Test Client', - userId: 0, - userPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantLeftDiaryCommentNotification', ( - tester, - ) async { - final notification = ConsultantLeftDiaryCommentNotification( - type: NotificationType.consultantLeftDiaryComment, - chosenPlanId: 1, - diaryId: 0, - planName: 'Test Plan', - userName: '', - consultantName: 'Test Consultant', - diaryDate: testDate, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets( - 'displays ConsultantConfirmPlanSubscriptionToAuthorNotification', - (tester) async { - final notification = - ConsultantConfirmPlanSubscriptionToAuthorNotification( - type: NotificationType.consultantConfirmPlanSubscriptionToAuthor, - planName: 'Test Plan', - planId: 1, - clientName: 'Test Consultant', - userId: 0, - userPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }, - ); - - testWidgets('displays ClientPaidPlanSubscriptionToSubscriberNotification', ( - tester, - ) async { - final notification = ClientPaidPlanSubscriptionToSubscriberNotification( - type: NotificationType.clientPaidPlanSubscriptionToSubscriber, - planName: 'Test Plan', - planId: 1, - authorName: '', - authorId: 0, - authorPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ClientStartPlanSubscriptionToAuthorNotification', ( - tester, - ) async { - final notification = ClientStartPlanSubscriptionToAuthorNotification( - type: NotificationType.clientStartPlanSubscriptionToAuthor, - planName: 'Test Plan', - planId: 1, - clientName: 'Test Client', - userId: 0, - userPhotoPath: '', - chatId: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ClientCancelPlanSubscriptionToAuthorNotification', ( - tester, - ) async { - final notification = ClientCancelPlanSubscriptionToAuthorNotification( - type: NotificationType.clientCancelPlanSubscriptionToAuthor, - planName: 'Test Plan', - planId: 1, - clientName: 'Test Client', - userId: 0, - userPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets( - 'displays ClientCancelPlanSubscriptionToSubscriberNotification', - (tester) async { - final notification = - ClientCancelPlanSubscriptionToSubscriberNotification( - type: NotificationType.clientCancelPlanSubscriptionToSubscriber, - planName: 'Test Plan', - planId: 1, - authorName: '', - authorId: 0, - authorPhotoPath: '', - chatUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }, - ); - - testWidgets('displays UserDailyReportCompletedNotification', ( - tester, - ) async { - final notification = UserDailyReportCompletedNotification( - type: NotificationType.userDailyReportCompleted, - chosenPlanId: 1, - diaryId: 0, - planName: 'Test Plan', - clientName: 'Test Client', - consultantName: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays StayOnTrackToCustomerNotification', (tester) async { - final notification = StayOnTrackToCustomerNotification( - type: NotificationType.stayOnTrackToCustomer, - planName: 'Test Plan', - dayNum: 1, - diaryDayId: 0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PhoneChangedNotification', (tester) async { - final notification = PhoneChangedNotification( - type: NotificationType.phoneChanged, - oldPhone: '+1234567890', - newPhone: '+0987654321', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays SubscriptionNotification', (tester) async { - final notification = SubscriptionNotification( - type: NotificationType.subscription, - userName: '', - userPhotoPath: '', - userProfileUrl: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays BadgeAwardedNotification', (tester) async { - final notification = BadgeAwardedNotification( - type: NotificationType.badgeAwarded, - badgeTitle: 'Test Badge', - badgeType: '', - badgeImage: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays BadgeRevokedNotification', (tester) async { - final notification = BadgeRevokedNotification( - type: NotificationType.badgeRevoked, - badgeTitle: 'Test Badge', - badgeType: '', - badgeImage: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantRequestStartedNotification', ( - tester, - ) async { - final notification = ConsultantRequestStartedNotification( - type: NotificationType.consultantRequestStarted, - consultantName: 'Test Consultant', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ClientCloseComplaintSuccessNotification', ( - tester, - ) async { - final notification = ClientCloseComplaintSuccessNotification( - type: NotificationType.clientCloseComplaintSuccess, - planName: 'Test Plan', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ClientRefundSuccessNotification', (tester) async { - final notification = ClientRefundSuccessNotification( - type: NotificationType.clientRefundSuccess, - planName: 'Test Plan', - amount: 100.0, - reason: 'Test reason', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantRefundSuccessNotification', (tester) async { - final notification = ConsultantRefundSuccessNotification( - type: NotificationType.consultantRefundSuccess, - planName: 'Test Plan', - clientName: 'Test Client', - amount: 100.0, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ClientRejectSuccessNotification', (tester) async { - final notification = ClientRejectSuccessNotification( - type: NotificationType.clientRejectSuccess, - planName: 'Test Plan', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ConsultantRejectSuccessNotification', (tester) async { - final notification = ConsultantRejectSuccessNotification( - type: NotificationType.consultantRejectSuccess, - planName: 'Test Plan', - clientName: 'Test Client', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ScoreSubstractedNotification', (tester) async { - final notification = ScoreSubstractedNotification( - type: NotificationType.scoreSubstracted, - scoreKey: 'test_key', - scorableId: 1, - scorableType: 'test', - scorableName: 'Test Name', - scorableSlug: 'test-slug', - scoreValue: 10, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays ProductStatusUpdatedForAuthorNotification', ( - tester, - ) async { - final notification = ProductStatusUpdatedForAuthorNotification( - type: NotificationType.productStatusUpdatedForAuthor, - productName: 'Test Product', - productId: 1, - author: '', - authorId: 0, - status: 'approved', - subject: '', - messageLine: '', - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays DiaryReminderForUsersNotification', (tester) async { - final notification = DiaryReminderForUsersNotification( - type: NotificationType.diaryReminderForUsers, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays PersonalDietIsDefinedToCustomerNotification', ( - tester, - ) async { - final notification = PersonalDietIsDefinedToCustomerNotification( - type: NotificationType.personalDietIsDefinedToCustomer, - isRead: false, - createdAt: testDate, - chosenPlanId: 1, - dietId: 1, - planName: '', - userName: '', - consultantName: '', - dietName: 'Test Diet', - role: '', - peerSlug: '', - peerImagePath: '', - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('displays UnknownNotification', (tester) async { - final notification = UnknownNotification( - type: NotificationType.unknown, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - - testWidgets('shows unread indicator when isRead is false', (tester) async { - final notification = DiaryReminderNotification( - type: NotificationType.diaryReminderNotification, - isRead: false, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - // Check for unread indicator (blue circle) - expect(find.byType(Container), findsWidgets); - }); - - testWidgets('hides unread indicator when isRead is true', (tester) async { - final notification = DiaryReminderNotification( - type: NotificationType.diaryReminderNotification, - isRead: true, - createdAt: testDate, - ); - - await tester.pumpWidget(createTestWidget(notification)); - await tester.pumpAndSettle(); - - expect(find.byType(NotificationWidget), findsOneWidget); - }); - }); -} +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart'; +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; +import 'package:eatvio_app/features/notifications/presentation/widgets/notification_widget.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +void main() { + group('NotificationWidget', () { + final testDate = DateTime(2024, 1, 15, 10, 30); + + Widget createTestWidget(BaseNotificationModel notification) { + return MaterialApp( + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru'), Locale('en')], + locale: const Locale('ru'), + theme: ThemeHelper().themeData(), + home: Scaffold(body: NotificationWidget(notification: notification)), + ); + } + + testWidgets('displays PlanSubscriptionStartedToAuthorNotification', ( + tester, + ) async { + final notification = PlanSubscriptionStartedToAuthorNotification( + type: NotificationType.planSubscriptionStartedToAuthor, + planName: 'Test Plan', + planId: 1, + customerName: 'Test Customer', + userId: 0, + userPhotoPath: '', + chatId: 'chat123', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PlanSubscriptionCanceledToAuthorNotification', ( + tester, + ) async { + final notification = PlanSubscriptionCanceledToAuthorNotification( + type: NotificationType.planSubscriptionCanceledToAuthor, + planName: 'Test Plan', + planId: 1, + customerName: 'Test Customer', + userId: 0, + userPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanStartedToClientNotification', ( + tester, + ) async { + final notification = ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClient, + planName: 'Test Plan', + planId: 1, + consultantName: 'Test Consultant', + peerProfileUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanTomorrowReminderToClientNotification', ( + tester, + ) async { + final notification = ChosenPlanTomorrowReminderToClientNotification( + type: NotificationType.chosenPlanTomorrowReminderToClient, + planName: 'Test Plan', + consultantName: '', + chatId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DiaryReminderNotification', (tester) async { + final notification = DiaryReminderNotification( + type: NotificationType.diaryReminderNotification, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantLeftCommentNotification', (tester) async { + final notification = ConsultantLeftCommentNotification( + type: NotificationType.consultantLeftComment, + chosenPlanId: 1, + diaryId: 0, + date: testDate, + planName: '', + userName: '', + consultantName: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PersonalizedDietIsDefinedNotification', ( + tester, + ) async { + final notification = PersonalizedDietIsDefinedNotification( + type: NotificationType.personalizedDietIsDefined, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanFinishedToClientNotification', ( + tester, + ) async { + final notification = ChosenPlanFinishedToClientNotification( + type: NotificationType.chosenPlanFinishedToClient, + planName: 'Test Plan', + chosenPlanId: 1, + consultantName: '', + consultantPhotoPath: '', + consultantProfileUrl: '', + consultantId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PlanSubscriptionCanceledToCustomerNotification', ( + tester, + ) async { + final notification = PlanSubscriptionCanceledToCustomerNotification( + type: NotificationType.planSubscriptionCanceledToCustomer, + planName: 'Test Plan', + planId: 1, + authorName: '', + authorId: 0, + authorPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanStartedToConsultantNotification', ( + tester, + ) async { + final notification = ChosenPlanStartedToConsultantNotification( + type: NotificationType.chosenPlanStartedToConsultant, + planName: 'Test Plan', + customerName: 'Test Customer', + planId: 1, + customerId: 1, + peerProfileUrl: '', + consultationUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanTomorrowReminderToConsultantNotification', ( + tester, + ) async { + final notification = ChosenPlanTomorrowReminderToConsultantNotification( + type: NotificationType.chosenPlanTomorrowReminderToConsultant, + planName: 'Test Plan', + customerName: 'Test Customer', + chatId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PlanSubscriptionPaidToAuthorNotification', ( + tester, + ) async { + final notification = PlanSubscriptionPaidToAuthorNotification( + type: NotificationType.planSubscriptionPaidToAuthor, + planName: 'Test Plan', + planId: 1, + customerName: 'Test Customer', + userId: 0, + userPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets( + 'displays ChosenPlanFinishedToConsultantNotification with button', + (tester) async { + final notification = ChosenPlanFinishedToConsultantNotification( + type: NotificationType.chosenPlanFinishedToConsultant, + planName: 'Test Plan', + customerName: 'Test Customer', + planId: 1, + chosenPlanId: 1, + clientPhotoPath: '', + clientId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + expect(find.text('Получить выплату'), findsOneWidget); + }, + ); + + testWidgets( + 'collect charge from finished notification uses chosenPlanId, not planId', + (tester) async { + int? capturedChosenPlanId; + final notification = ChosenPlanFinishedToConsultantNotification( + type: NotificationType.chosenPlanFinishedToConsultant, + planName: 'Test Plan', + customerName: 'Test Customer', + planId: 99, + chosenPlanId: 42, + clientPhotoPath: '', + clientId: 0, + isRead: false, + createdAt: testDate, + ); + + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: NotificationWidget(notification: notification), + ), + ), + GoRoute( + path: CardSettingsScreen.path, + builder: (context, state) { + capturedChosenPlanId = state.extra as int?; + return const Scaffold(body: Text('card-settings')); + }, + ), + ], + ); + + await tester.pumpWidget( + MaterialApp.router( + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru'), Locale('en')], + locale: const Locale('ru'), + theme: ThemeHelper().themeData(), + routerConfig: router, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Получить выплату')); + await tester.pumpAndSettle(); + + expect(find.text('card-settings'), findsOneWidget); + expect(capturedChosenPlanId, 42); + }, + ); + + testWidgets('displays ChosenPlanLastDayFinishedForUser', (tester) async { + final notification = ChosenPlanLastDayFinishedForUser( + type: NotificationType.chosenPlanLastDayFinishedForUser, + planName: 'Test Plan', + chosenPlanId: 1, + complaintUrl: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanConsultantLastDayStarted', (tester) async { + final notification = ChosenPlanConsultantLastDayStarted( + type: NotificationType.chosenPlanConsultantLastDayStarted, + planName: 'Test Plan', + planId: 1, + chatId: 'chat123', + chatUrl: 'chat_url', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ComplaintToModerationForUser', (tester) async { + final notification = ComplaintToModerationForUser( + type: NotificationType.complaintToModerationForUser, + message: 'Test message', + entityId: 1, + entityType: 'test', + entityName: 'Test Entity', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays CommentReplied', (tester) async { + final notification = CommentReplied( + type: NotificationType.commentReplied, + entityName: 'Test Entity', + commentedEntityId: 1, + commentedEntityType: CommentedEntityType.diet, + author: 'Test Author', + authorId: 1, + parentCommentId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ScoreAdded', (tester) async { + final notification = ScoreAdded( + type: NotificationType.scoreAdded, + scoreKey: 'test_key', + scorableId: 1, + scorableType: 'test', + scorableName: 'Test Name', + scorableSlug: 'test-slug', + scoreValue: 10, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays EntityCommented', (tester) async { + final notification = EntityCommented( + type: NotificationType.entityCommented, + entityName: 'Test Entity', + entityId: 1, + entityType: CommentedEntityType.diet, + entityTranslatedType: 'Test Type', + entityUrl: 'test_url', + authorName: 'Test Author', + authorId: 1, + authorSlug: 'test-author', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PlanSubscriptionExpiredNotification', (tester) async { + final notification = PlanSubscriptionExpiredNotification( + type: NotificationType.planSubscriptionExpired, + planName: 'Test Plan', + customerName: 'Test Customer', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PlanSubscriptionRenewedNotification', (tester) async { + final notification = PlanSubscriptionRenewedNotification( + type: NotificationType.planSubscriptionRenewed, + planName: 'Test Plan', + customerName: 'Test Customer', + renewalDate: '2024-02-01', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantAssignedNotification', (tester) async { + final notification = ConsultantAssignedNotification( + type: NotificationType.consultantAssigned, + consultantName: 'Test Consultant', + planName: 'Test Plan', + planId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantUnassignedNotification', (tester) async { + final notification = ConsultantUnassignedNotification( + type: NotificationType.consultantUnassigned, + consultantName: 'Test Consultant', + planName: 'Test Plan', + planId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PaymentFailedNotification', (tester) async { + final notification = PaymentFailedNotification( + type: NotificationType.paymentFailed, + planName: 'Test Plan', + errorMessage: 'Test error', + paymentMethod: 'card', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PaymentSuccessfulNotification', (tester) async { + final notification = PaymentSuccessfulNotification( + type: NotificationType.paymentSuccessful, + planName: 'Test Plan', + amount: 100.0, + currency: 'USD', + transactionId: 'trans123', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays GoalAchievedNotification', (tester) async { + final notification = GoalAchievedNotification( + type: NotificationType.goalAchieved, + goalName: 'Test Goal', + goalType: 'weight', + achievedValue: 50.0, + targetValue: 100.0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays WorkoutReminderNotification', (tester) async { + final notification = WorkoutReminderNotification( + type: NotificationType.workoutReminder, + workoutName: 'Test Workout', + workoutType: 'cardio', + duration: 30, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays MealReminderNotification', (tester) async { + final notification = MealReminderNotification( + type: NotificationType.mealReminder, + mealName: 'Test Meal', + mealType: 'breakfast', + calories: 500, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DietCancelledNotification', (tester) async { + final notification = DietCancelledNotification( + type: NotificationType.dietCancelled, + dietName: 'Test Diet', + dietId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DietStartedNotification', (tester) async { + final notification = DietStartedNotification( + type: NotificationType.dietStarted, + dietName: 'Test Diet', + dietId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DietExpiredNotification', (tester) async { + final notification = DietExpiredNotification( + type: NotificationType.dietExpired, + dietName: 'Test Diet', + dietId: 1, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DietWillStartedInNotification', (tester) async { + final notification = DietWillStartedInNotification( + type: NotificationType.dietWillStartedIn, + dietName: 'Test Diet', + dietId: 1, + startDate: '2024-02-01', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DietCanNotBeStartedNotification', (tester) async { + final notification = DietCanNotBeStartedNotification( + type: NotificationType.dietCanNotBeStarted, + dietName: 'Test Diet', + dietId: 1, + reason: 'Test reason', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PersonalDietCreationNeededNotification', ( + tester, + ) async { + final notification = PersonalDietCreationNeededNotification( + type: NotificationType.personalDietCreationNeeded, + userName: 'Test Client', + consultantName: '', + myDietsUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanClientLastDayFinishedNotification', ( + tester, + ) async { + final notification = ChosenPlanClientLastDayFinishedNotification( + type: NotificationType.chosenPlanClientLastDayFinished, + planName: 'Test Plan', + chosenPlanId: 1, + complaintUrl: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ChosenPlanClientLastDayStartedNotification', ( + tester, + ) async { + final notification = ChosenPlanClientLastDayStartedNotification( + type: NotificationType.chosenPlanClientLastDayStarted, + planName: 'Test Plan', + chosenPlanId: 1, + lastDayDiaryUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays StayOnTrackToAuthorNotification', (tester) async { + final notification = StayOnTrackToAuthorNotification( + type: NotificationType.stayOnTrackToAuthor, + planName: 'Test Plan', + userName: 'Test Client', + dayNum: 1, + diaryDayId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets( + 'displays ClientStartPlanSubscriptionToSubscriberNotification', + (tester) async { + final notification = + ClientStartPlanSubscriptionToSubscriberNotification( + type: NotificationType.clientStartPlanSubscriptionToSubscriber, + planName: 'Test Plan', + planId: 1, + authorName: '', + authorId: 0, + authorPhotoPath: '', + chatUrl: '', + chatId: '', + startDate: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }, + ); + + testWidgets( + 'displays ConsultantConfirmPlanSubscriptionToSubscriberNotification', + (tester) async { + final notification = + ConsultantConfirmPlanSubscriptionToSubscriberNotification( + type: NotificationType + .consultantConfirmPlanSubscriptionToSubscriber, + planName: 'Test Plan', + planId: 1, + consultantName: 'Test Consultant', + authorId: 0, + authorPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }, + ); + + testWidgets('displays ClientPaidPlanSubscriptionToAuthorNotification', ( + tester, + ) async { + final notification = ClientPaidPlanSubscriptionToAuthorNotification( + type: NotificationType.clientPaidPlanSubscriptionToAuthor, + planName: 'Test Plan', + planId: 1, + clientName: 'Test Client', + userId: 0, + userPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantLeftDiaryCommentNotification', ( + tester, + ) async { + final notification = ConsultantLeftDiaryCommentNotification( + type: NotificationType.consultantLeftDiaryComment, + chosenPlanId: 1, + diaryId: 0, + planName: 'Test Plan', + userName: '', + consultantName: 'Test Consultant', + diaryDate: testDate, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets( + 'displays ConsultantConfirmPlanSubscriptionToAuthorNotification', + (tester) async { + final notification = + ConsultantConfirmPlanSubscriptionToAuthorNotification( + type: NotificationType.consultantConfirmPlanSubscriptionToAuthor, + planName: 'Test Plan', + planId: 1, + clientName: 'Test Consultant', + userId: 0, + userPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }, + ); + + testWidgets('displays ClientPaidPlanSubscriptionToSubscriberNotification', ( + tester, + ) async { + final notification = ClientPaidPlanSubscriptionToSubscriberNotification( + type: NotificationType.clientPaidPlanSubscriptionToSubscriber, + planName: 'Test Plan', + planId: 1, + authorName: '', + authorId: 0, + authorPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ClientStartPlanSubscriptionToAuthorNotification', ( + tester, + ) async { + final notification = ClientStartPlanSubscriptionToAuthorNotification( + type: NotificationType.clientStartPlanSubscriptionToAuthor, + planName: 'Test Plan', + planId: 1, + clientName: 'Test Client', + userId: 0, + userPhotoPath: '', + chatId: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ClientCancelPlanSubscriptionToAuthorNotification', ( + tester, + ) async { + final notification = ClientCancelPlanSubscriptionToAuthorNotification( + type: NotificationType.clientCancelPlanSubscriptionToAuthor, + planName: 'Test Plan', + planId: 1, + clientName: 'Test Client', + userId: 0, + userPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets( + 'displays ClientCancelPlanSubscriptionToSubscriberNotification', + (tester) async { + final notification = + ClientCancelPlanSubscriptionToSubscriberNotification( + type: NotificationType.clientCancelPlanSubscriptionToSubscriber, + planName: 'Test Plan', + planId: 1, + authorName: '', + authorId: 0, + authorPhotoPath: '', + chatUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }, + ); + + testWidgets('displays UserDailyReportCompletedNotification', ( + tester, + ) async { + final notification = UserDailyReportCompletedNotification( + type: NotificationType.userDailyReportCompleted, + chosenPlanId: 1, + diaryId: 0, + planName: 'Test Plan', + clientName: 'Test Client', + consultantName: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays StayOnTrackToCustomerNotification', (tester) async { + final notification = StayOnTrackToCustomerNotification( + type: NotificationType.stayOnTrackToCustomer, + planName: 'Test Plan', + dayNum: 1, + diaryDayId: 0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PhoneChangedNotification', (tester) async { + final notification = PhoneChangedNotification( + type: NotificationType.phoneChanged, + oldPhone: '+1234567890', + newPhone: '+0987654321', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays SubscriptionNotification', (tester) async { + final notification = SubscriptionNotification( + type: NotificationType.subscription, + userName: '', + userPhotoPath: '', + userProfileUrl: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays BadgeAwardedNotification', (tester) async { + final notification = BadgeAwardedNotification( + type: NotificationType.badgeAwarded, + badgeTitle: 'Test Badge', + badgeType: '', + badgeImage: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays BadgeRevokedNotification', (tester) async { + final notification = BadgeRevokedNotification( + type: NotificationType.badgeRevoked, + badgeTitle: 'Test Badge', + badgeType: '', + badgeImage: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantRequestStartedNotification', ( + tester, + ) async { + final notification = ConsultantRequestStartedNotification( + type: NotificationType.consultantRequestStarted, + consultantName: 'Test Consultant', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ClientCloseComplaintSuccessNotification', ( + tester, + ) async { + final notification = ClientCloseComplaintSuccessNotification( + type: NotificationType.clientCloseComplaintSuccess, + planName: 'Test Plan', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ClientRefundSuccessNotification', (tester) async { + final notification = ClientRefundSuccessNotification( + type: NotificationType.clientRefundSuccess, + planName: 'Test Plan', + amount: 100.0, + reason: 'Test reason', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantRefundSuccessNotification', (tester) async { + final notification = ConsultantRefundSuccessNotification( + type: NotificationType.consultantRefundSuccess, + planName: 'Test Plan', + clientName: 'Test Client', + amount: 100.0, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ClientRejectSuccessNotification', (tester) async { + final notification = ClientRejectSuccessNotification( + type: NotificationType.clientRejectSuccess, + planName: 'Test Plan', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ConsultantRejectSuccessNotification', (tester) async { + final notification = ConsultantRejectSuccessNotification( + type: NotificationType.consultantRejectSuccess, + planName: 'Test Plan', + clientName: 'Test Client', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ScoreSubstractedNotification', (tester) async { + final notification = ScoreSubstractedNotification( + type: NotificationType.scoreSubstracted, + scoreKey: 'test_key', + scorableId: 1, + scorableType: 'test', + scorableName: 'Test Name', + scorableSlug: 'test-slug', + scoreValue: 10, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays ProductStatusUpdatedForAuthorNotification', ( + tester, + ) async { + final notification = ProductStatusUpdatedForAuthorNotification( + type: NotificationType.productStatusUpdatedForAuthor, + productName: 'Test Product', + productId: 1, + author: '', + authorId: 0, + status: 'approved', + subject: '', + messageLine: '', + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays DiaryReminderForUsersNotification', (tester) async { + final notification = DiaryReminderForUsersNotification( + type: NotificationType.diaryReminderForUsers, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PersonalDietIsDefinedToCustomerNotification', ( + tester, + ) async { + final notification = PersonalDietIsDefinedToCustomerNotification( + type: NotificationType.personalDietIsDefinedToCustomer, + isRead: false, + createdAt: testDate, + chosenPlanId: 1, + dietId: 1, + planName: '', + userName: '', + consultantName: '', + dietName: 'Test Diet', + role: '', + peerSlug: '', + peerImagePath: '', + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('displays PersonalDietIsDefinedToAuthorNotification', ( + tester, + ) async { + final notification = PersonalDietIsDefinedToAuthorNotification( + type: NotificationType.personalDietIsDefinedToAuthor, + isRead: false, + createdAt: testDate, + chosenPlanId: 1, + dietId: 1, + planName: 'Plan', + userName: 'Client', + consultantName: 'Consultant', + dietName: 'Test Diet', + role: 'consultant', + peerSlug: 'client-slug', + peerImagePath: '', + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect( + find.text('Вы предложили персональную диету пользователю Client, выбранная диета: «Test Diet»'), + findsOneWidget, + ); + }); + + testWidgets( + 'displays PersonalDietIsDefinedToAuthorNotification with fallback user name', + (tester) async { + final notification = PersonalDietIsDefinedToAuthorNotification( + type: NotificationType.personalDietIsDefinedToAuthor, + isRead: false, + createdAt: testDate, + chosenPlanId: 1, + dietId: 1, + planName: 'Plan', + userName: '', + consultantName: 'Consultant', + dietName: 'Test Diet', + role: 'consultant', + peerSlug: 'client-slug', + peerImagePath: '', + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect( + find.text('Вы предложили персональную диету пользователю Пользователь, выбранная диета: «Test Diet»'), + findsOneWidget, + ); + }, + ); + + testWidgets( + 'displays PersonalDietIsDefinedToAuthorNotification without diet name', + (tester) async { + final notification = PersonalDietIsDefinedToAuthorNotification( + type: NotificationType.personalDietIsDefinedToAuthor, + isRead: false, + createdAt: testDate, + chosenPlanId: 1, + dietId: 1, + planName: 'Plan', + userName: 'Client', + consultantName: 'Consultant', + dietName: '', + role: 'consultant', + peerSlug: 'client-slug', + peerImagePath: '', + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect( + find.text('Вы предложили персональную диету пользователю Client'), + findsOneWidget, + ); + }, + ); + + testWidgets('displays UnknownNotification', (tester) async { + final notification = UnknownNotification( + type: NotificationType.unknown, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + + testWidgets('shows unread indicator when isRead is false', (tester) async { + final notification = DiaryReminderNotification( + type: NotificationType.diaryReminderNotification, + isRead: false, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + // Check for unread indicator (blue circle) + expect(find.byType(Container), findsWidgets); + }); + + testWidgets('hides unread indicator when isRead is true', (tester) async { + final notification = DiaryReminderNotification( + type: NotificationType.diaryReminderNotification, + isRead: true, + createdAt: testDate, + ); + + await tester.pumpWidget(createTestWidget(notification)); + await tester.pumpAndSettle(); + + expect(find.byType(NotificationWidget), findsOneWidget); + }); + }); +} diff --git a/test/features/notifications/service/notifications_service_test.dart b/test/features/notifications/service/notifications_service_test.dart index 5c2b62ab..4effb8f3 100644 --- a/test/features/notifications/service/notifications_service_test.dart +++ b/test/features/notifications/service/notifications_service_test.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; import 'package:eatvio_app/features/notifications/service/notifications_service.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -1454,6 +1455,42 @@ void main() { expect(result, isNotNull); expect(result!['notifications'], isA()); expect(result['notifications'].length, 1); + expect(result['notifications'].first, isA()); + }); + + test('getNotifications - обрабатывает PersonalDietIsDefinedToAuthor', () async { + const page = 1; + final response = Response( + data: { + 'data': [ + { + 'type': 'personal-diet-is-defined-to-author', + 'data': { + 'diet_name': 'Test Diet', + 'diet_id': 1, + 'user_name': 'Client', + }, + 'read_at': null, + 'created_at': '2024-01-01T12:00:00Z', + }, + ], + 'current_page': 1, + 'last_page': 1, + 'per_page': 10, + 'total': 1, + }, + statusCode: 200, + requestOptions: RequestOptions(path: '/api/profile/notifications'), + ); + + when(mockDio.get(any)).thenAnswer((_) async => response); + + final result = await notificationsService.getNotifications(page: page); + + expect(result, isNotNull); + expect(result!['notifications'], isA()); + expect(result['notifications'].length, 1); + expect(result['notifications'].first, isA()); }); test('getNotifications - обрабатывает UserDailyReportCompleted', () async { diff --git a/test/features/order_info/presentation/info_by_order_screen_smoke_test.dart b/test/features/order_info/presentation/info_by_order_screen_smoke_test.dart index 1a8b5be4..522735d1 100644 --- a/test/features/order_info/presentation/info_by_order_screen_smoke_test.dart +++ b/test/features/order_info/presentation/info_by_order_screen_smoke_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; import 'package:eatvio_app/features/order_info/cubit/order_info_state.dart'; import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -48,12 +47,7 @@ void main() { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); diff --git a/test/features/order_info/presentation/info_by_order_screen_test.dart b/test/features/order_info/presentation/info_by_order_screen_test.dart index ea426152..cb8f062d 100644 --- a/test/features/order_info/presentation/info_by_order_screen_test.dart +++ b/test/features/order_info/presentation/info_by_order_screen_test.dart @@ -13,9 +13,8 @@ import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -63,12 +62,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: InfoByOrderScreen( planId: planId, @@ -243,12 +237,12 @@ void main() { expect(find.byType(InfoByOrderScreen), findsOneWidget); }); - ChosenPlanModel donePlan() { + ChosenPlanModel donePlan({ChosenPlanStateEnum state = ChosenPlanStateEnum.stateDone}) { return ChosenPlanModel( id: 1, optionType: 'options1', startDate: DateTime(2024, 1, 1), - chosenPlanState: ChosenPlanStateEnum.stateDone, + chosenPlanState: state, chatId: 'chat-1', consultantId: 1, plan: const PlanModel( @@ -320,6 +314,7 @@ void main() { expect(find.byType(CollectChargeBanner), findsOneWidget); expect(find.text('Получить выплату'), findsOneWidget); + expect(find.text('Отменить консультацию'), findsNothing); }, ); @@ -337,6 +332,22 @@ void main() { expect(find.byType(CollectChargeBanner), findsNothing); expect(find.text('Получить выплату'), findsNothing); + expect(find.text('Отменить консультацию'), findsNothing); + }); + + testWidgets('shows cancel action for cancellable post-paid plan', ( + WidgetTester tester, + ) async { + when( + mockChatRepository.getChosenPlan(id: anyNamed('id')), + ).thenAnswer((_) async => donePlan(state: ChosenPlanStateEnum.stateStarted)); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createTestWidget(planId: 1)); + await tester.pumpAndSettle(); + }); + + expect(find.text('Отменить консультацию'), findsOneWidget); }); }); } diff --git a/test/features/order_info/presentation/widgets/collect_charge_banner_test.dart b/test/features/order_info/presentation/widgets/collect_charge_banner_test.dart index 28610415..4d9186b4 100644 --- a/test/features/order_info/presentation/widgets/collect_charge_banner_test.dart +++ b/test/features/order_info/presentation/widgets/collect_charge_banner_test.dart @@ -11,8 +11,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart' import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart' show Author; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -35,12 +34,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( routes: [ diff --git a/test/features/order_info/presentation/widgets/payment_banner_test.dart b/test/features/order_info/presentation/widgets/payment_banner_test.dart index 0b032179..aa1ddf6a 100644 --- a/test/features/order_info/presentation/widgets/payment_banner_test.dart +++ b/test/features/order_info/presentation/widgets/payment_banner_test.dart @@ -5,9 +5,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/payment_banner.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -28,12 +27,7 @@ void main() { Widget createTestWidget(Widget child, OrderInfoCubit cubit) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( routes: [ diff --git a/test/features/order_info/presentation/widgets/plan_info_test.dart b/test/features/order_info/presentation/widgets/plan_info_test.dart index 89687935..6d6652f1 100644 --- a/test/features/order_info/presentation/widgets/plan_info_test.dart +++ b/test/features/order_info/presentation/widgets/plan_info_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_info.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/test/features/order_info/presentation/widgets/plan_props_test.dart b/test/features/order_info/presentation/widgets/plan_props_test.dart index 8d85e220..1370671e 100644 --- a/test/features/order_info/presentation/widgets/plan_props_test.dart +++ b/test/features/order_info/presentation/widgets/plan_props_test.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_props.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_status_box.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -22,12 +21,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/order_info/presentation/widgets/plan_state_test.dart b/test/features/order_info/presentation/widgets/plan_state_test.dart index 68862e25..c3115ced 100644 --- a/test/features/order_info/presentation/widgets/plan_state_test.dart +++ b/test/features/order_info/presentation/widgets/plan_state_test.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_state.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -22,12 +21,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/order_info/presentation/widgets/plan_status_box_test.dart b/test/features/order_info/presentation/widgets/plan_status_box_test.dart index ec53a9cf..90104eb7 100644 --- a/test/features/order_info/presentation/widgets/plan_status_box_test.dart +++ b/test/features/order_info/presentation/widgets/plan_status_box_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/order_info/presentation/widgets/plan_status_box.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,12 +9,7 @@ void main() { Widget createTestWidget(PlanStatusValues status) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: PlanStatusBox(status: status), diff --git a/test/features/payment/consultation_payment_flow_test.dart b/test/features/payment/consultation_payment_flow_test.dart index 8b532853..b2ab503f 100644 --- a/test/features/payment/consultation_payment_flow_test.dart +++ b/test/features/payment/consultation_payment_flow_test.dart @@ -4,8 +4,7 @@ import 'package:eatvio_app/features/payment/models/promo_validate_response.dart' import 'package:eatvio_app/features/payment/presentation/payment_flow.dart'; import 'package:eatvio_app/features/payment/presentation/widgets/promo_code_modal.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -13,12 +12,7 @@ void main() { Widget createTestApp() { return const MaterialApp( - localizationsDelegates: [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: [Locale('ru')], home: Scaffold(body: SizedBox()), ); @@ -73,7 +67,7 @@ void main() { return formResult; } - Future mockSbp(BuildContext context, {required int planId}) async { + Future mockSbp(BuildContext context, {required int planId, double? amount}) async { sbpCalled = true; sbpPlanId = planId; } diff --git a/test/features/payment/presentation/widgets/promo_code_gate_bottom_sheet_test.dart b/test/features/payment/presentation/widgets/promo_code_gate_bottom_sheet_test.dart index 48cf3859..4709faaa 100644 --- a/test/features/payment/presentation/widgets/promo_code_gate_bottom_sheet_test.dart +++ b/test/features/payment/presentation/widgets/promo_code_gate_bottom_sheet_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart'; import 'package:eatvio_app/features/payment/presentation/widgets/promo_code_gate_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -13,12 +12,7 @@ void main() { Widget createTestWidget({required ValueChanged onResult}) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: PromoCodeGateBottomSheet(onResult: onResult), diff --git a/test/features/payment/presentation/widgets/promo_code_modal_test.dart b/test/features/payment/presentation/widgets/promo_code_modal_test.dart index 56d10633..38199b8b 100644 --- a/test/features/payment/presentation/widgets/promo_code_modal_test.dart +++ b/test/features/payment/presentation/widgets/promo_code_modal_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/payment/models/promo_code_model.dart'; import 'package:eatvio_app/features/payment/presentation/widgets/promo_code_modal.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -17,12 +16,7 @@ void main() { }) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Builder( builder: (context) => ElevatedButton( diff --git a/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart b/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart index 773a1d74..627105ac 100644 --- a/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart +++ b/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart @@ -1,18 +1,25 @@ import 'dart:async'; +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/chat/models/payment_model.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart'; import 'package:eatvio_app/features/payment/presentation/widgets/sbp_banks_bottom_sheet.dart'; +import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart'; import 'package:eatvio_app/features/payment/repositories/payment_repository.dart'; import 'package:eatvio_app/features/payment/repositories/sbp_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:get_it/get_it.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:qr_flutter/qr_flutter.dart'; import 'package:sbp/models/c2bmembers_model.dart'; import '../../../../fixtures/fixture_reader.dart'; @@ -21,9 +28,21 @@ import 'sbp_banks_bottom_sheet_test.mocks.dart'; @GenerateNiceMocks([ MockSpec(), MockSpec(), + MockSpec(), ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); + // AppConfig в конструкторе читает EnvConfig (dotenv) — инициализируем. + setUpAll(() async { + await dotenv.load( + fileName: 'test.env', + isOptional: true, + mergeWith: const { + 'BASE_URL': 'https://eatvio.ru', + 'DEV_BASE_URL': 'https://dev2.eatvio.com', + }, + ); + }); group('SbpBanksBottomSheet', () { late MockPaymentRepository mockPaymentRepository; @@ -58,12 +77,7 @@ void main() { Widget createTestWidget({required int planId}) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: SbpBanksBottomSheet( @@ -183,5 +197,66 @@ void main() { expect(find.byType(Loader), findsNothing); expect(find.text('Нет установленных банков'), findsOneWidget); }); + + testWidgets('QR-кнопка доступна до загрузки списка банков', (tester) async { + const planId = 12; + final banksCompleter = Completer>(); + + when( + mockPaymentRepository.startPaymentProcess(planId: planId), + ).thenAnswer((_) async => alfaPayment); + when(mockSbpRepository.getInstalledBanks()).thenAnswer((_) => banksCompleter.future); + sl.registerLazySingleton( + () => AppConfig(buildType: AppBuildType.tests), + ); + sl.registerLazySingleton(() => MockChatRepository()); + + await tester.pumpWidget(createTestWidget(planId: planId)); + await tester.pump(); + await tester.pump(); + + // Банки ещё грузятся (Loader), а QR-кнопка уже доступна. + expect(find.byType(Loader), findsOneWidget); + expect(find.text('Оплатить по QR-коду'), findsOneWidget); + + banksCompleter.complete([installedBank]); + await tester.pumpAndSettle(); + expect(find.byType(Loader), findsNothing); + expect(find.text('Сбербанк'), findsOneWidget); + expect(find.text('Оплатить по QR-коду'), findsOneWidget); + + await GetIt.I.reset(); + }); + + testWidgets('после старта оплаты показывает кнопку QR и открывает QR-шит', (tester) async { + const planId = 12; + + when( + mockPaymentRepository.startPaymentProcess(planId: planId), + ).thenAnswer((_) async => alfaPayment); + when(mockSbpRepository.getInstalledBanks()).thenAnswer((_) async => [installedBank]); + sl.registerLazySingleton( + () => AppConfig(buildType: AppBuildType.tests), + ); + sl.registerLazySingleton(() => MockChatRepository()); + + await tester.pumpWidget(createTestWidget(planId: planId)); + await tester.pumpAndSettle(); + + expect(find.text('Оплатить по QR-коду'), findsOneWidget); + + await tester.tap(find.text('Оплатить по QR-коду')); + await tester.pump(); + await tester.pump(); + expect(find.byType(SbpQrBottomSheet), findsOneWidget); + expect(find.byType(QrImageView), findsOneWidget); + + // Закрываем QR-шит (останавливает polling-таймер). + tester.state(find.byType(Navigator).first).pop(); + await tester.pump(); + await tester.pump(); + + await GetIt.I.reset(); + }); }); } diff --git a/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart b/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart new file mode 100644 index 00000000..1d09ec3f --- /dev/null +++ b/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart @@ -0,0 +1,250 @@ +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart'; +import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart'; +import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart'; +import 'package:eatvio_app/features/payment/repositories/payment_repository.dart'; +import 'package:eatvio_app/features/payment/repositories/sbp_repository.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:get_it/get_it.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:qr_flutter/qr_flutter.dart'; + +import 'sbp_qr_bottom_sheet_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const planId = 12; + const checkoutUrl = 'https://qr.nspk.ru/AD10106TB0BVFTBG9DQ96NKJEIVVTKIO'; + + group('SbpQrBottomSheet', () { + late MockPaymentRepository mockPaymentRepository; + late MockSbpRepository mockSbpRepository; + late MockChatRepository mockChatRepository; + late MockChosenPlanModel mockPlan; + late ConsultationPaymentCubit cubit; + late Future? sheetResult; + + setUp(() async { + await GetIt.I.reset(); + // AppConfig в конструкторе читает EnvConfig (dotenv) — инициализируем. + await dotenv.load( + fileName: 'test.env', + isOptional: true, + mergeWith: const { + 'BASE_URL': 'https://eatvio.ru', + 'DEV_BASE_URL': 'https://dev2.eatvio.com', + }, + ); + sl.registerLazySingleton( + () => AppConfig(buildType: AppBuildType.tests), + ); + sl.registerLazySingleton(() => mockChatRepository); + + mockPaymentRepository = MockPaymentRepository(); + mockSbpRepository = MockSbpRepository(); + mockChatRepository = MockChatRepository(); + mockPlan = MockChosenPlanModel(); + cubit = ConsultationPaymentCubit( + paymentRepository: mockPaymentRepository, + sbpRepository: mockSbpRepository, + ); + cubit.emit( + ConsultationPaymentState( + isLoading: false, + checkoutUrl: checkoutUrl, + ), + ); + sheetResult = null; + }); + + tearDown(() async { + await GetIt.I.reset(); + await cubit.close(); + }); + + Future pumpApp(WidgetTester tester, {double? amount}) { + return tester.pumpWidget( + MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold( + body: Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () => sheetResult = showSbpQrBottomSheet( + context, + planId: planId, + cubit: cubit, + amount: amount, + ), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + } + + Future openSheet(WidgetTester tester, {double? amount}) async { + await pumpApp(tester, amount: amount); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(); + } + + /// Закрывает шит, чтобы остановить polling-таймер в конце теста. + Future closeSheet(WidgetTester tester) async { + final navigator = tester.state( + find.byType(Navigator).first, + ); + navigator.pop(); + await tester.pump(); + await tester.pump(); + } + + void stubPlanState(ChosenPlanStateEnum state) { + when(mockChatRepository.getChosenPlan(id: planId)) + .thenAnswer((_) async => mockPlan); + when(mockPlan.chosenPlanState).thenReturn(state); + } + + /// Перерегистрирует DI с AppConfig, смотрящим на конкретный base URL. + Future useApiBaseUrl(String baseUrl) async { + await GetIt.I.reset(); + sl.registerLazySingleton( + () => AppConfig(buildType: AppBuildType.tests)..setBaseUrl(baseUrl), + ); + sl.registerLazySingleton(() => mockChatRepository); + } + + testWidgets('рендерит QR-код из checkout_url и инструкцию', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + + await openSheet(tester); + + expect(find.byKey(const ValueKey('sbp_qr_code')), findsOneWidget); + expect(find.byType(QrImageView), findsOneWidget); + expect(find.text('Оплата по QR-коду'), findsOneWidget); + expect(find.text('Ожидание оплаты…'), findsOneWidget); + + await closeSheet(tester); + }); + + testWidgets('показывает сумму, если передана', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + + await openSheet(tester, amount: 1200); + + expect(find.text('Сумма к оплате'), findsOneWidget); + expect(find.text('1200 ₽'), findsOneWidget); + + await closeSheet(tester); + }); + + testWidgets('не показывает сумму, если не передана', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + + await openSheet(tester); + + expect(find.text('Сумма к оплате'), findsNothing); + + await closeSheet(tester); + }); + + testWidgets('показывает тестовую кнопку на stage-стенде (dev2)', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + await useApiBaseUrl('https://dev2.eatvio.com'); + + await openSheet(tester); + + expect(find.text('Открыть тестовую оплату'), findsOneWidget); + + await closeSheet(tester); + }); + + testWidgets('показывает тестовую кнопку на стенде-поддомене прод-хоста', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + // Поддомен eatvio.ru — стенд (например, hasan), а не прод. + await useApiBaseUrl('https://ubooquiequ7ohz9ias3aik4a-hasan.eatvio.ru'); + + await openSheet(tester); + + expect(find.text('Открыть тестовую оплату'), findsOneWidget); + + await closeSheet(tester); + }); + + testWidgets('скрывает тестовую кнопку на продуктовом API', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + await useApiBaseUrl('https://eatvio.ru'); + + await openSheet(tester); + + expect(find.text('Открыть тестовую оплату'), findsNothing); + // Сам QR при этом работает. + expect(find.byType(QrImageView), findsOneWidget); + + await closeSheet(tester); + }); + + testWidgets('скрывает тестовую кнопку на продуктовом API (eatvio.com)', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + await useApiBaseUrl('https://eatvio.com'); + + await openSheet(tester); + + expect(find.text('Открыть тестовую оплату'), findsNothing); + + await closeSheet(tester); + }); + + testWidgets('при оплате (statePaid) показывает успех и закрывает шит', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePaid); + + await openSheet(tester); + + // Первый poll выполняется сразу в initState. + await tester.pump(); + expect(find.text('Оплата прошла успешно!'), findsOneWidget); + + // Автозакрытие через 2 секунды. + await tester.pump(const Duration(seconds: 2)); + await tester.pump(); + expect(find.byType(SbpQrBottomSheet), findsNothing); + expect(await sheetResult, isTrue); + }); + + testWidgets('до оплаты продолжает ждать', (tester) async { + stubPlanState(ChosenPlanStateEnum.statePendingPayment); + + await openSheet(tester); + + await tester.pump(const Duration(seconds: 3)); + await tester.pump(); + + expect(find.text('Оплата прошла успешно!'), findsNothing); + expect(find.text('Ожидание оплаты…'), findsOneWidget); + + await closeSheet(tester); + }); + }); +} diff --git a/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart index 82df287b..c30b99f3 100644 --- a/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart +++ b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart @@ -34,6 +34,7 @@ void main() { expect(cubit.state.consultationsWithDiet, isEmpty); expect(cubit.state.consultationsWithoutDiet, isEmpty); expect(cubit.state.dietName, isEmpty); + expect(cubit.state.dietDuration, 0); expect(cubit.state.isLoading, isFalse); expect(cubit.state.error, isNull); }); @@ -71,6 +72,7 @@ void main() { await cubit.setDietName(dietId); expect(cubit.state.dietName, equals(dietName)); + expect(cubit.state.dietDuration, 30); expect(cubit.state.isLoading, isFalse); verify(mockDietRepository.getDiet(dietId)).called(1); }); @@ -161,6 +163,7 @@ void main() { await cubit.getConsultationWithPersonalDiets(dietId); expect(cubit.state.dietName, equals(dietName)); + expect(cubit.state.dietDuration, 30); expect(cubit.state.consultationsWithDiet.length, 1); expect(cubit.state.consultationsWithoutDiet.length, 1); expect(cubit.state.isLoading, isFalse); @@ -216,6 +219,8 @@ void main() { consultationId: consultationId, dietId: dietId, )).called(1); + verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2); + verify(mockDietRepository.getDiet(dietId)).called(2); }); test('reattachDietToConsultation - успешное переприкрепление диеты', () async { @@ -265,6 +270,8 @@ void main() { consultationId: consultationId, dietId: dietId, )).called(1); + verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2); + verify(mockDietRepository.getDiet(dietId)).called(2); }); }); } diff --git a/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state_test.dart b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state_test.dart index 256bb75b..23be2f78 100644 --- a/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state_test.dart +++ b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state_test.dart @@ -9,6 +9,7 @@ void main() { expect(state.consultationsWithDiet, isEmpty); expect(state.consultationsWithoutDiet, isEmpty); expect(state.dietName, ''); + expect(state.dietDuration, 0); expect(state.isLoading, isFalse); expect(state.error, isNull); }); @@ -16,6 +17,7 @@ void main() { test('creates instance with custom values', () { final state = PersonalDietSuggestionState( dietName: 'Test Diet', + dietDuration: 14, isLoading: true, error: 'Test error', ); @@ -23,6 +25,7 @@ void main() { expect(state.consultationsWithDiet, isEmpty); expect(state.consultationsWithoutDiet, isEmpty); expect(state.dietName, 'Test Diet'); + expect(state.dietDuration, 14); expect(state.isLoading, isTrue); expect(state.error, 'Test error'); }); @@ -31,14 +34,15 @@ void main() { final original = PersonalDietSuggestionState(); final updated = original.copyWith( dietName: 'New Diet', + dietDuration: 7, isLoading: true, ); expect(updated.dietName, 'New Diet'); + expect(updated.dietDuration, 7); expect(updated.isLoading, isTrue); expect(updated.consultationsWithDiet, original.consultationsWithDiet); expect(updated.error, original.error); }); }); } - diff --git a/test/features/personal_diet_suggestion/presentation/consultation_widget_test.dart b/test/features/personal_diet_suggestion/presentation/consultation_widget_test.dart index 55b184b1..9b5c8d47 100644 --- a/test/features/personal_diet_suggestion/presentation/consultation_widget_test.dart +++ b/test/features/personal_diet_suggestion/presentation/consultation_widget_test.dart @@ -2,16 +2,16 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/localization_utils.dart'; import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/presentation/consultation_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -34,6 +34,7 @@ void main() { final mockConsultation = ConsultationModel( id: 1, + chatId: 'chat-1', chosenPlanState: ChosenPlanStateEnum.stateInProgress, planTitle: 'Test Plan', userName: 'Test User', @@ -53,12 +54,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', @@ -68,6 +64,32 @@ void main() { path: '/personal-diet-suggestion', builder: (context, state) => const Scaffold(body: Text('Personal Diet')), ), + GoRoute( + path: '/chat-select-screen', + name: 'chatSelectScreen', + builder: (context, state) => const Scaffold(body: Text('Chats')), + ), + GoRoute( + path: '/chat-screen', + name: 'chatScreen', + builder: (context, state) { + final uuid = state.uri.queryParameters['uuid']; + return Scaffold( + appBar: AppBar( + leading: BackButton( + onPressed: () { + if (context.canPop()) { + GoRouter.of(context).pop(); + return; + } + GoRouter.of(context).go('/chat-select-screen'); + }, + ), + ), + body: Text('Chat $uuid'), + ); + }, + ), ], ), ); @@ -201,7 +223,7 @@ void main() { }); }); - testWidgets('shows success bottom sheet after successful diet attachment', (tester) async { + testWidgets('opens chat after successful diet attachment', (tester) async { await mockNetworkImagesFor(() async { final cubit = MockPersonalDietSuggestionCubit(); @@ -226,7 +248,99 @@ void main() { await tester.tap(offerButton); await tester.pumpAndSettle(); - expect(find.text('«Test Diet» предложена пользователю Test User'), findsOneWidget); + expect(find.text('Chat chat-1'), findsOneWidget); + verify(cubit.attachDietToConsultation(consultationId: 1)).called(1); + + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + + expect(find.text('Chats'), findsOneWidget); + }); + }); + + testWidgets('opens chat after successful diet reattachment', (tester) async { + await mockNetworkImagesFor(() async { + final cubit = MockPersonalDietSuggestionCubit(); + final consultationWithDiet = ConsultationModel( + id: 1, + chatId: 'chat-2', + chosenPlanState: ChosenPlanStateEnum.stateInProgress, + planTitle: 'Test Plan', + userName: 'Test User', + userSlug: 'test-user', + consultantPayment: 1000.0, + duration: 7, + currentDiaryDay: 3, + userProfilePhotoUrl: '/avatar.jpg', + consultationOptionPrice: 500, + startDate: DateTime(2025, 1, 1), + endDate: DateTime(2025, 1, 8), + consultantId: 1, + diaries: [], + personalDietId: 1, + ); + + when(cubit.state).thenReturn(PersonalDietSuggestionState()); + when(cubit.stream).thenAnswer((_) => const Stream.empty()); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.reattachDietToConsultation(consultationId: 1)).thenAnswer((_) async => true); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(ConsultationWidget(consultationModel: consultationWithDiet, dietName: 'Test Diet')), + ), + ); + await tester.pumpAndSettle(); + + final changeButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).changeDiet); + await tester.tap(changeButton); + await tester.pumpAndSettle(); + + final offerButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).toOffer); + await tester.tap(offerButton); + await tester.pumpAndSettle(); + + expect(find.text('Chat chat-2'), findsOneWidget); + verify(cubit.reattachDietToConsultation(consultationId: 1)).called(1); + verifyNever(cubit.attachDietToConsultation(consultationId: 1)); + + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + + expect(find.text('Chats'), findsOneWidget); + }); + }); + + testWidgets('stays on screen when chat id is missing after success', (tester) async { + await mockNetworkImagesFor(() async { + final cubit = MockPersonalDietSuggestionCubit(); + + when(cubit.state).thenReturn(PersonalDietSuggestionState()); + when(cubit.stream).thenAnswer((_) => const Stream.empty()); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.attachDietToConsultation(consultationId: 1)).thenAnswer((_) async => true); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap( + ConsultationWidget( + consultationModel: mockConsultation.copyWith(chatId: null), + dietName: 'Test Diet', + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Предложить диету')); + await tester.pumpAndSettle(); + await tester.tap(find.text(S.of(tester.element(find.byType(ConsultationWidget))).toOffer)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Chat '), findsNothing); + expect(find.text('Test User'), findsOneWidget); verify(cubit.attachDietToConsultation(consultationId: 1)).called(1); }); }); @@ -279,7 +393,7 @@ void main() { expect(find.text('Test User'), findsOneWidget); expect(find.text('Test Plan'), findsOneWidget); - expect(find.text('Старт: Test User'), findsOneWidget); + expect(find.text('Старт: 01.01.2025'), findsOneWidget); }); }); @@ -318,7 +432,71 @@ void main() { expect(find.text('Test User'), findsOneWidget); expect(find.text('Test Plan'), findsOneWidget); - expect(find.text('Старт: Test User'), findsNothing); + expect(find.text('Старт: 01.01.2025'), findsNothing); + }); + }); + + testWidgets('disables CTA when plan duration differs from diet duration', (tester) async { + await mockNetworkImagesFor(() async { + final cubit = MockPersonalDietSuggestionCubit(); + final consultation = ConsultationModel( + id: 1, + chosenPlanState: ChosenPlanStateEnum.stateInProgress, + planTitle: 'Test Plan', + userName: 'Test User', + userSlug: 'test-user', + consultantPayment: 1000.0, + duration: 14, + currentDiaryDay: 3, + userProfilePhotoUrl: '/avatar.jpg', + consultationOptionPrice: 500, + startDate: DateTime(2025, 1, 1), + endDate: DateTime(2025, 1, 15), + consultantId: 1, + diaries: [], + personalDietId: null, + ); + + when(cubit.state).thenReturn(PersonalDietSuggestionState()); + when(cubit.stream).thenAnswer((_) => const Stream.empty()); + when(cubit.close()).thenAnswer((_) async => Future.value()); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap( + ConsultationWidget( + consultationModel: consultation, + dietName: 'Test Diet', + dietDuration: 7, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final s = S.of(tester.element(find.byType(ConsultationWidget))); + expect( + find.text( + s.personal_diet_duration_mismatch( + 7, + getDayForm(7, s), + 14, + getDayForm(14, s), + ), + ), + findsOneWidget, + ); + final button = tester.widget(find.byType(OutlinedButton)); + expect(button.onPressed, isNull); + expect( + button.style?.backgroundColor?.resolve({WidgetState.disabled}), + appTheme.dividerColor, + ); + expect( + tester.widget(find.text(s.suggestDiet)).style?.color, + appTheme.gray, + ); }); }); }); diff --git a/test/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen_smoke_test.dart b/test/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen_smoke_test.dart index b74938ae..deb93c8f 100644 --- a/test/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen_smoke_test.dart +++ b/test/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen_smoke_test.dart @@ -2,14 +2,14 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/localization_utils.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart'; import 'package:eatvio_app/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +31,7 @@ void main() { Widget wrap(Widget child, PersonalDietSuggestionCubit cubit) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value( @@ -84,5 +79,31 @@ void main() { expect(find.textContaining('Test Diet Name'), findsOneWidget); }); + + testWidgets('shows diet duration hint and empty state', (tester) async { + final cubit = MockPersonalDietSuggestionCubit(); + const dietDuration = 7; + final state = PersonalDietSuggestionState( + isLoading: false, + dietName: 'Test Diet', + dietDuration: dietDuration, + consultationsWithDiet: [], + consultationsWithoutDiet: [], + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + + await tester.pumpWidget(wrap(const PersonalDietSuggestionScreenContent(), cubit)); + await tester.pump(); + + final s = S.of(tester.element(find.byType(PersonalDietSuggestionScreenContent))); + expect( + find.text(s.personal_diet_duration_hint(dietDuration, getDayForm(dietDuration, s))), + findsOneWidget, + ); + expect(find.text(s.no_active_personal_diet_consultations), findsOneWidget); + }); }); } diff --git a/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart b/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart index 76b292aa..7d5e26ec 100644 --- a/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart +++ b/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart @@ -68,41 +68,33 @@ void main() { test('attachPersonalDiet - успешное прикрепление диеты', () async { const consultationId = 1; const dietId = 2; + final body = {'diet_id': dietId}; - when(mockService.attachPersonalDiet( - consultationId: consultationId, - dietId: dietId, - )).thenAnswer((_) async => {}); + when(mockService.attachPersonalDiet(consultationId, body)) + .thenAnswer((_) async => {}); await repository.attachPersonalDiet( consultationId: consultationId, dietId: dietId, ); - verify(mockService.attachPersonalDiet( - consultationId: consultationId, - dietId: dietId, - )).called(1); + verify(mockService.attachPersonalDiet(consultationId, body)).called(1); }); test('reattachPersonalDiet - успешное переприкрепление диеты', () async { const consultationId = 1; const dietId = 2; + final body = {'diet_id': dietId}; - when(mockService.reattachPersonalDiet( - consultationId: consultationId, - dietId: dietId, - )).thenAnswer((_) async => {}); + when(mockService.reattachPersonalDiet(consultationId, body)) + .thenAnswer((_) async => {}); await repository.reattachPersonalDiet( consultationId: consultationId, dietId: dietId, ); - verify(mockService.reattachPersonalDiet( - consultationId: consultationId, - dietId: dietId, - )).called(1); + verify(mockService.reattachPersonalDiet(consultationId, body)).called(1); }); }); } diff --git a/test/features/personal_diet_suggestion/services/personal_diet_suggestion_service_test.dart b/test/features/personal_diet_suggestion/services/personal_diet_suggestion_service_test.dart index ef33e11f..b18fde38 100644 --- a/test/features/personal_diet_suggestion/services/personal_diet_suggestion_service_test.dart +++ b/test/features/personal_diet_suggestion/services/personal_diet_suggestion_service_test.dart @@ -15,55 +15,48 @@ void main() { setUp(() { mockDio = MockDio(); + when(mockDio.options).thenReturn(BaseOptions(baseUrl: 'http://localhost')); service = PersonalDietSuggestionService(mockDio); }); test('getConsultationWithPersonalDiets - успешное получение консультаций', () async { final mockData = { 'data': [], - 'links': {}, - 'meta': { - 'current_page': 1, - 'last_page': 1, - 'total': 0, - 'per_page': 10, - }, }; + late RequestOptions capturedRequest; - when(mockDio.get( - '/api/consultations', - queryParameters: anyNamed('queryParameters'), - )).thenAnswer((_) async => Response( - requestOptions: RequestOptions(path: '/api/consultations'), - statusCode: 200, - data: mockData, - )); + when(mockDio.fetch>(any)).thenAnswer((invocation) async { + capturedRequest = invocation.positionalArguments.first as RequestOptions; + return Response>( + requestOptions: capturedRequest, + statusCode: 200, + data: mockData, + ); + }); final result = await service.getConsultationWithPersonalDiets(); expect(result, isA()); - verify(mockDio.get( - '/api/consultations', - queryParameters: { - 'filters[plan][has_personal_diet][\$personal_diet]': '1', - 'filters[last_state][\$notIn][]': [ - 'done', - 'charge_was_collected', - 'complained', - 'last_day_finished', - 'canceled_by_the_initiator', - 'inited' - ], - 'sort[]': 'start_date:desc', - }, - )).called(1); + expect(capturedRequest.path, '/api/consultations'); + expect(capturedRequest.method, 'GET'); + expect(capturedRequest.queryParameters, { + r'filters[plan][has_personal_diet][$personal_diet]': '1', + r'filters[last_state][$notIn][]': [ + 'done', + 'charge_was_collected', + 'complained', + 'last_day_finished', + 'last_day_started', + 'canceled_by_the_initiator', + 'inited', + ], + r'sort[]': ['start_date:desc'], + }); + verify(mockDio.fetch>(any)).called(1); }); test('getConsultationWithPersonalDiets - пробрасывает ошибку', () async { - when(mockDio.get( - any, - queryParameters: anyNamed('queryParameters'), - )).thenThrow(DioException( + when(mockDio.fetch>(any)).thenThrow(DioException( requestOptions: RequestOptions(path: '/api/consultations'), )); @@ -75,74 +68,70 @@ void main() { test('attachPersonalDiet - успешное прикрепление диеты', () async { const consultationId = 1; - const dietId = 2; + final body = {'diet_id': 2}; + late RequestOptions capturedRequest; - when(mockDio.post( - '/api/chosen_plans/$consultationId/attach_diet', - data: anyNamed('data'), - )).thenAnswer((_) async => Response( - requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'), - statusCode: 200, - )); + when(mockDio.fetch(any)).thenAnswer((invocation) async { + capturedRequest = invocation.positionalArguments.first as RequestOptions; + return Response( + requestOptions: capturedRequest, + statusCode: 200, + ); + }); - await service.attachPersonalDiet(consultationId: consultationId, dietId: dietId); + await service.attachPersonalDiet(consultationId, body); - verify(mockDio.post( - '/api/chosen_plans/$consultationId/attach_diet', - data: {'diet_id': dietId}, - )).called(1); + expect(capturedRequest.path, '/api/chosen_plans/$consultationId/attach_diet'); + expect(capturedRequest.method, 'POST'); + expect(capturedRequest.data, body); + verify(mockDio.fetch(any)).called(1); }); test('attachPersonalDiet - пробрасывает ошибку', () async { const consultationId = 1; - const dietId = 2; + final body = {'diet_id': 2}; - when(mockDio.post( - any, - data: anyNamed('data'), - )).thenThrow(DioException( + when(mockDio.fetch(any)).thenThrow(DioException( requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'), )); expect( - () => service.attachPersonalDiet(consultationId: consultationId, dietId: dietId), + () => service.attachPersonalDiet(consultationId, body), throwsA(isA()), ); }); test('reattachPersonalDiet - успешное повторное прикрепление диеты', () async { const consultationId = 1; - const dietId = 3; + final body = {'diet_id': 3}; + late RequestOptions capturedRequest; - when(mockDio.post( - '/api/chosen_plans/$consultationId/re_attach_diet', - data: anyNamed('data'), - )).thenAnswer((_) async => Response( - requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'), - statusCode: 200, - )); + when(mockDio.fetch(any)).thenAnswer((invocation) async { + capturedRequest = invocation.positionalArguments.first as RequestOptions; + return Response( + requestOptions: capturedRequest, + statusCode: 200, + ); + }); - await service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId); + await service.reattachPersonalDiet(consultationId, body); - verify(mockDio.post( - '/api/chosen_plans/$consultationId/re_attach_diet', - data: {'diet_id': dietId}, - )).called(1); + expect(capturedRequest.path, '/api/chosen_plans/$consultationId/re_attach_diet'); + expect(capturedRequest.method, 'POST'); + expect(capturedRequest.data, body); + verify(mockDio.fetch(any)).called(1); }); test('reattachPersonalDiet - пробрасывает ошибку', () async { const consultationId = 1; - const dietId = 3; + final body = {'diet_id': 3}; - when(mockDio.post( - any, - data: anyNamed('data'), - )).thenThrow(DioException( + when(mockDio.fetch(any)).thenThrow(DioException( requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'), )); expect( - () => service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId), + () => service.reattachPersonalDiet(consultationId, body), throwsA(isA()), ); }); diff --git a/test/features/plans/enums/chosen_plan_state_enum_test.dart b/test/features/plans/enums/chosen_plan_state_enum_test.dart index 3c963836..a82ef455 100644 --- a/test/features/plans/enums/chosen_plan_state_enum_test.dart +++ b/test/features/plans/enums/chosen_plan_state_enum_test.dart @@ -61,6 +61,47 @@ void main() { expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(), isTrue); }); + test('canShowCancelAction returns true for cancellable states', () { + expect(ChosenPlanStateEnum.stateInited.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.stateInCoordination.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.statePendingPayment.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.statePaid.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.stateStarted.canShowCancelAction, isTrue); + expect(ChosenPlanStateEnum.stateInProgress.canShowCancelAction, isTrue); + }); + + test('canShowCancelAction returns false for non-cancellable states', () { + expect(ChosenPlanStateEnum.personalDietSet.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateComplained.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateDone.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction, isFalse); + expect(ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction, isFalse); + }); + + test('isCancelAfterPaidState returns true only for post-paid cancellable states', () { + expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue); + expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue); + expect(ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState, isTrue); + expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState, isFalse); + expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isCancelAfterPaidState, isFalse); + }); + test('getActiveStates returns correct states', () { final activeStates = ChosenPlanStateEnum.getActiveStates(); diff --git a/test/features/plans/models/chosen_plan_model_test.dart b/test/features/plans/models/chosen_plan_model_test.dart index a3100298..8dfee56b 100644 --- a/test/features/plans/models/chosen_plan_model_test.dart +++ b/test/features/plans/models/chosen_plan_model_test.dart @@ -60,6 +60,7 @@ void main() { 'last_state': 'initied', 'chat_id': 'chat-1', 'consultant_id': 1, + 'personal_diet_name': 'Индивидуальный план питания', 'plan': { 'id': 1, 'slug': 'test-plan', @@ -94,6 +95,7 @@ void main() { expect(chosenPlan.optionType, 'options1'); expect(chosenPlan.chosenPlanState, ChosenPlanStateEnum.stateInited); expect(chosenPlan.chatId, 'chat-1'); + expect(chosenPlan.personalDietName, 'Индивидуальный план питания'); }); test('toJson serializes ChosenPlanModel correctly', () { @@ -198,6 +200,66 @@ void main() { }); }); + group('chosenOption', () { + const plan = PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: 'https://example.com/image.jpg', + duration: 7, + state: 'active', + type: PlanType(fit: true, slim: false, behavior: false, wellness: false), + details: 'Test details', + packetsCount: 3, + packet1Options: PacketOptions(items: ['one'], price: 100, short: 'packet-1', hasPersonalDiet: false), + packet2Options: PacketOptions(items: ['two'], price: 200, short: 'packet-2', hasPersonalDiet: true), + packet3Options: PacketOptions(items: ['three'], price: 300, short: 'packet-3', hasPersonalDiet: false), + author: Author( + authorSlug: 'author', + authorName: 'Author Name', + authorProfileIcon: 'https://example.com/icon.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + totalLikes: 10, + totalViews: 100, + totalComments: 5, + isFavorite: false, + minPriceOfOptions: 100, + maxPriceOfOptions: 300, + wasLikedByMe: false, + ); + + ChosenPlanModel modelWith(String optionType) => ChosenPlanModel( + id: 1, + optionType: optionType, + startDate: DateTime(2024, 1, 1), + chosenPlanState: ChosenPlanStateEnum.stateInited, + chatId: 'chat-1', + consultantId: 1, + plan: plan, + ); + + test('возвращает первую опцию для options1', () { + expect(modelWith('options1').chosenOption?.short, 'packet-1'); + }); + + test('возвращает вторую опцию для options2', () { + expect(modelWith('options2').chosenOption?.short, 'packet-2'); + }); + + test('возвращает третью опцию для options3', () { + expect(modelWith('options3').chosenOption?.short, 'packet-3'); + }); + + test('возвращает null для неизвестного значения', () { + expect(modelWith('unknown').chosenOption, isNull); + expect(modelWith('1').chosenOption, isNull); + expect(modelWith('').chosenOption, isNull); + }); + }); + group('parseChosenPlan', () { test('parseChosenPlan создает ChosenPlanModel из Map', () { final json = { @@ -207,6 +269,7 @@ void main() { 'last_state': 'initied', 'chat_id': 'chat-1', 'consultant_id': 1, + 'personal_diet_name': 'Индивидуальный план питания', 'plan': { 'id': 1, 'slug': 'test-plan', diff --git a/test/features/plans/presentation/pages/about_plan_screen_smoke_test.dart b/test/features/plans/presentation/pages/about_plan_screen_smoke_test.dart index b47e1d2b..2dad6dbe 100644 --- a/test/features/plans/presentation/pages/about_plan_screen_smoke_test.dart +++ b/test/features/plans/presentation/pages/about_plan_screen_smoke_test.dart @@ -14,10 +14,9 @@ import 'package:eatvio_app/features/plans/presentation/pages/about_plan_screen.d import 'package:eatvio_app/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart'; import 'package:eatvio_app/features/profile/models/chosen_diets_pagination_model.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; @@ -95,12 +94,7 @@ void main() { return Portal( child: MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ), @@ -240,7 +234,8 @@ void main() { await tester.tap(find.byType(BackButton)); await tester.pump(); - expect(find.byType(AboutPlanScreen), findsOneWidget); + expect(tester.takeException(), isNull); + expect(find.byType(AboutPlanScreen), findsNothing); }); testWidgets('loaded state bookmark tap calls addToFavorite when not favorite', (tester) async { diff --git a/test/features/plans/presentation/widgets/basic_widget_test.dart b/test/features/plans/presentation/widgets/basic_widget_test.dart index da6eecde..49098275 100644 --- a/test/features/plans/presentation/widgets/basic_widget_test.dart +++ b/test/features/plans/presentation/widgets/basic_widget_test.dart @@ -11,9 +11,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -78,12 +77,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); @@ -92,12 +86,7 @@ void main() { Widget createPlansTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet_test.dart b/test/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet_test.dart index 44e358c1..fceb15a2 100644 --- a/test/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet_test.dart +++ b/test/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet_test.dart @@ -2,8 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/features/plans/presentation/widgets/confirm_start_plan_bottom_sheet.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -11,12 +10,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/plans/presentation/widgets/options_tab_test.dart b/test/features/plans/presentation/widgets/options_tab_test.dart index c820442b..f2851ebd 100644 --- a/test/features/plans/presentation/widgets/options_tab_test.dart +++ b/test/features/plans/presentation/widgets/options_tab_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_cubit.dart'; import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart'; import 'package:eatvio_app/features/plans/presentation/widgets/options_tab.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/plans/presentation/widgets/widgets_test.dart b/test/features/plans/presentation/widgets/widgets_test.dart index aaecf30a..d2ed824e 100644 --- a/test/features/plans/presentation/widgets/widgets_test.dart +++ b/test/features/plans/presentation/widgets/widgets_test.dart @@ -10,9 +10,8 @@ import 'package:eatvio_app/features/plans/presentation/widgets/options_tab.dart' import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -52,12 +51,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/profile/models/weight_model_test.dart b/test/features/profile/models/weight_model_test.dart index 2fa157b1..66c09398 100644 --- a/test/features/profile/models/weight_model_test.dart +++ b/test/features/profile/models/weight_model_test.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; import 'package:eatvio_app/features/profile/models/weight_model.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -42,6 +43,51 @@ void main() { expect(json['created_at'], isA()); expect(json['updated_at'], isA()); }); + + Map json({Object? weight = 72.3, Object? bmi = 22.4}) => { + 'id': 1, + 'user_id': 2, + 'weight': weight, + 'created_at': '2026-11-01T10:00:00.000000Z', + 'updated_at': '2026-11-01T10:00:00.000000Z', + 'bmi': bmi, + }; + + test('парсит дробный weight', () { + final model = WeightModel.fromJson(json()); + + expect(model.weight, 72.3); + expect(model.bmi, 22.4); + }); + + test('парсит целый weight как double', () { + final model = WeightModel.fromJson(json(weight: 72)); + + expect(model.weight, 72.0); + }); + + test('допускает bmi: null (рост не указан)', () { + final model = WeightModel.fromJson(json(bmi: null)); + + expect(model.bmi, isNull); + }); + }); + + group('CircumferenceModel', () { + test('парсит целые и дробные значения (прореженные средние)', () { + final model = CircumferenceModel.fromJson({ + 'id': 1, + 'user_id': 2, + 'chest_circumference': 95, + 'waist_circumference': 80.5, + 'hip_circumference': 100, + 'created_at': '2026-11-01T10:00:00.000000Z', + 'updated_at': '2026-11-01T10:00:00.000000Z', + }); + + expect(model.chestCircumference, 95.0); + expect(model.waistCircumference, 80.5); + expect(model.hipCircumference, 100.0); + }); }); } - diff --git a/test/features/profile/presentation/basic_widget_test.dart b/test/features/profile/presentation/basic_widget_test.dart index e92f2906..0d06f807 100644 --- a/test/features/profile/presentation/basic_widget_test.dart +++ b/test/features/profile/presentation/basic_widget_test.dart @@ -1,7 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/profile/presentation/pages/profile_screen_smoke_test.dart b/test/features/profile/presentation/pages/profile_screen_smoke_test.dart index 4ecef522..23d2eb53 100644 --- a/test/features/profile/presentation/pages/profile_screen_smoke_test.dart +++ b/test/features/profile/presentation/pages/profile_screen_smoke_test.dart @@ -4,26 +4,32 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/insights/presentation/widgets/insights_card.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' as profile_plans; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' + as profile_plans; import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:network_image_mock/network_image_mock.dart'; +import '../../../../fixtures/doubles/insights_doubles.dart'; import 'profile_screen_smoke_test.mocks.dart'; -@GenerateNiceMocks([MockSpec(), MockSpec(), MockSpec(), MockSpec()]) +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) void main() { group('ProfileScreen smoke', () { late MockProfileRepository profileRepository; @@ -32,12 +38,18 @@ void main() { late MockPlansRepository plansRepository; setUpAll(() async { - dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); + dotenv.loadFromString( + envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost', + ); }); setUp(() async { await sl.reset(); - sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + sl.registerLazySingleton( + () => + AppConfig(buildType: AppBuildType.tests) + ..setBaseUrl('http://localhost'), + ); profileRepository = MockProfileRepository(); chatRepository = MockChatRepository(); @@ -45,23 +57,31 @@ void main() { plansRepository = MockPlansRepository(); sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton( + () => FakeInsightsRepository(), + ); sl.registerLazySingleton(() => chatRepository); - sl.registerLazySingleton(() => consultantRepository); + sl.registerLazySingleton( + () => consultantRepository, + ); sl.registerLazySingleton(() => plansRepository); - sl.registerFactory(() => ProfileCubit(profileRepository: sl(), chatRepository: sl(), consultantRepository: sl())); - sl.registerFactory(() => profile_plans.PlansCubit(plansRepository: sl())); + sl.registerFactory( + () => ProfileCubit( + profileRepository: sl(), + chatRepository: sl(), + consultantRepository: sl(), + ), + ); + sl.registerFactory( + () => profile_plans.PlansCubit(plansRepository: sl()), + ); }); Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); @@ -115,10 +135,12 @@ void main() { ); when(profileRepository.getMyProfile()).thenAnswer((_) async => profile); - when(profileRepository.getMyProfileDetails()).thenAnswer((_) async => profileDetails); - when(profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug'))).thenAnswer((_) async => []); - when(profileRepository.getWeight(period: anyNamed('period'))).thenAnswer((_) async => []); - when(profileRepository.getCircumferences(period: anyNamed('period'))).thenAnswer((_) async => []); + when( + profileRepository.getMyProfileDetails(), + ).thenAnswer((_) async => profileDetails); + when( + profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')), + ).thenAnswer((_) async => []); await mockNetworkImagesFor(() async { await tester.pumpWidget(wrap(const ProfileScreen())); @@ -129,8 +151,12 @@ void main() { }); testWidgets('renders error state', (tester) async { - when(profileRepository.getMyProfile()).thenThrow(Exception('Error loading profile')); - when(profileRepository.getMyProfileDetails()).thenThrow(Exception('Error')); + when( + profileRepository.getMyProfile(), + ).thenThrow(Exception('Error loading profile')); + when( + profileRepository.getMyProfileDetails(), + ).thenThrow(Exception('Error')); await tester.pumpWidget(wrap(const ProfileScreen())); await tester.pumpAndSettle(); @@ -185,13 +211,19 @@ void main() { activityCoefficient: 1.5, ); - when(profileRepository.getProfileBySlug(any)).thenAnswer((_) async => profile); + when( + profileRepository.getProfileBySlug(any), + ).thenAnswer((_) async => profile); when(profileRepository.getMyProfile()).thenAnswer((_) async => profile); - when(profileRepository.getMyProfileDetails()).thenAnswer((_) async => profileDetails); - when(profileRepository.getProfileDetailsBySlug(any)).thenAnswer((_) async => profileDetails); - when(profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug'))).thenAnswer((_) async => []); - when(profileRepository.getWeight(period: anyNamed('period'))).thenAnswer((_) async => []); - when(profileRepository.getCircumferences(period: anyNamed('period'))).thenAnswer((_) async => []); + when( + profileRepository.getMyProfileDetails(), + ).thenAnswer((_) async => profileDetails); + when( + profileRepository.getProfileDetailsBySlug(any), + ).thenAnswer((_) async => profileDetails); + when( + profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')), + ).thenAnswer((_) async => []); await mockNetworkImagesFor(() async { await tester.pumpWidget(wrap(const ProfileScreen(slug: 'test-user'))); @@ -199,7 +231,159 @@ void main() { }); expect(find.byType(ProfileScreen), findsOneWidget); - expect(find.text('Пользователь ограничил доступ к своей странице'), findsOneWidget); + expect( + find.text('Пользователь ограничил доступ к своей странице'), + findsOneWidget, + ); + }); + group('аналитика (InsightsCard)', () { + ProfileModel profileOf( + String slug, { + bool blockedByMe = false, + bool blockedByAuthor = false, + }) => ProfileModel( + id: 1, + name: 'Test User', + email: 'test@example.com', + phoneConfirmationState: 'confirmed', + slug: slug, + isPublicProfile: true, + isBlockedByMe: blockedByMe, + isBlockedByAuthor: blockedByAuthor, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: '', + roles: const [], + badges: const [], + subscriptions: const [], + subscribers: const [], + ); + + const details = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, + ); + + Future pumpProfile( + WidgetTester tester, { + required ProfileModel viewed, + String? slug, + Object? insightsError, + }) async { + final insights = FakeInsightsRepository(error: insightsError); + sl.unregister(); + sl.registerLazySingleton(() => insights); + when( + profileRepository.getProfileBySlug(any), + ).thenAnswer((_) async => viewed); + when( + profileRepository.getMyProfile(), + ).thenAnswer((_) async => profileOf('me')); + when( + profileRepository.getMyProfileDetails(), + ).thenAnswer((_) async => details); + when( + profileRepository.getProfileDetailsBySlug(any), + ).thenAnswer((_) async => details); + when( + profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')), + ).thenAnswer((_) async => []); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget(wrap(ProfileScreen(slug: slug))); + await tester.pumpAndSettle(); + }); + return insights; + } + + testWidgets('собственный профиль: свои данные и кнопка добавления', ( + tester, + ) async { + final insights = await pumpProfile(tester, viewed: profileOf('me')); + + final card = tester.widget(find.byType(InsightsCard)); + expect(card.slug, isNull); + expect(card.canAdd, isTrue); + expect(insights.serverRequests.single.slug, isNull); + }); + + testWidgets( + 'чужой профиль (консультант → клиент): данные по slug без кнопки добавления', + (tester) async { + final insights = await pumpProfile( + tester, + viewed: profileOf('client'), + slug: 'client', + ); + + final card = tester.widget(find.byType(InsightsCard)); + expect(card.slug, 'client'); + expect(card.canAdd, isFalse); + expect(insights.serverRequests.single.slug, 'client'); + expect(find.byKey(const Key('insights_card')), findsOneWidget); + }, + ); + + testWidgets('чужой профиль: 403 скрывает блок', (tester) async { + await pumpProfile( + tester, + viewed: profileOf('client'), + slug: 'client', + insightsError: const InsightsForbidden(), + ); + + expect(find.byKey(const Key('insights_card')), findsNothing); + }); + + testWidgets( + 'профиль, заблокированный мной, не показывает аналитику и не запрашивает её', + (tester) async { + final insights = await pumpProfile( + tester, + viewed: profileOf('client', blockedByMe: true), + slug: 'client', + ); + + expect(find.byType(InsightsCard), findsNothing); + expect(insights.serverRequests, isEmpty); + }, + ); + + testWidgets('профиль, ограничивший доступ, не показывает аналитику', ( + tester, + ) async { + final insights = await pumpProfile( + tester, + viewed: profileOf('client', blockedByAuthor: true), + slug: 'client', + ); + + expect(find.byType(InsightsCard), findsNothing); + expect(insights.serverRequests, isEmpty); + }); }); }); } diff --git a/test/features/profile/presentation/pages/subs_screen_smoke_test.dart b/test/features/profile/presentation/pages/subs_screen_smoke_test.dart index 70797652..7ef370bb 100644 --- a/test/features/profile/presentation/pages/subs_screen_smoke_test.dart +++ b/test/features/profile/presentation/pages/subs_screen_smoke_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/profile/models/sub_model.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/pages/subs_screen.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/profile/presentation/pages/subs_screen_test.dart b/test/features/profile/presentation/pages/subs_screen_test.dart index f1cd34a5..1ab78869 100644 --- a/test/features/profile/presentation/pages/subs_screen_test.dart +++ b/test/features/profile/presentation/pages/subs_screen_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/pages/subs_screen.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/profile/presentation/widgets/circumference_chart_widget_test.dart b/test/features/profile/presentation/widgets/circumference_chart_widget_test.dart deleted file mode 100644 index 1c68a19f..00000000 --- a/test/features/profile/presentation/widgets/circumference_chart_widget_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:intl/date_symbol_data_local.dart'; - -void main() { - group('CircumferenceChartWidget smoke', () { - setUpAll(() async { - await initializeDateFormatting('ru', null); - }); - Widget wrap(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - home: Scaffold(body: child), - ); - } - - testWidgets('renders circumference chart widget with empty points', (tester) async { - await tester.pumpWidget(wrap(const CircumferenceChartWidget(circumferencePoints: []))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.byType(CircumferenceChartWidget), findsOneWidget); - }); - - testWidgets('renders circumference chart widget with points', (tester) async { - final points = [ - CircumferenceModel( - id: 1, - userId: 1, - chestCircumference: 90, - waistCircumference: 80, - hipCircumference: 95, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - ), - ]; - await tester.pumpWidget(wrap(CircumferenceChartWidget(circumferencePoints: points))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.byType(CircumferenceChartWidget), findsOneWidget); - }); - }); -} diff --git a/test/features/profile/presentation/widgets/expandable_page_view_test.dart b/test/features/profile/presentation/widgets/expandable_page_view_test.dart index 057e1de4..b213fbc3 100644 --- a/test/features/profile/presentation/widgets/expandable_page_view_test.dart +++ b/test/features/profile/presentation/widgets/expandable_page_view_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/profile/presentation/widgets/expandable_page_view.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/profile/presentation/widgets/imt_chart_widget_test.dart b/test/features/profile/presentation/widgets/imt_chart_widget_test.dart deleted file mode 100644 index 59eb1da3..00000000 --- a/test/features/profile/presentation/widgets/imt_chart_widget_test.dart +++ /dev/null @@ -1,132 +0,0 @@ -import 'package:eatvio_app/core/app_config.dart'; -import 'package:eatvio_app/core/app_initializer.dart'; -import 'package:eatvio_app/core/locator_service.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/imt_chart_widget.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_portal/flutter_portal.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:intl/date_symbol_data_local.dart'; - -void main() { - group('ImtChartWidget', () { - setUp(() async { - await sl.reset(); - await initializeDateFormatting('ru', null); - dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); - sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); - }); - - Widget createTestWidget(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - home: Portal( - child: Scaffold(body: SingleChildScrollView(child: child)), - ), - ); - } - - testWidgets('should display chart with empty weight points', (WidgetTester tester) async { - // Arrange - const widget = ImtChartWidget(weightPoints: []); - - // Act - await tester.pumpWidget(createTestWidget(widget)); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - // Assert - expect(find.byType(ImtChartWidget), findsOneWidget); - }); - - testWidgets('should display chart with single weight point', (WidgetTester tester) async { - // Arrange - final weightPoints = [ - WeightModel( - id: 1, - userId: 1, - weight: 70, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - bmi: 23.5, - ), - ]; - final widget = ImtChartWidget(weightPoints: weightPoints); - - // Act - await tester.pumpWidget(createTestWidget(widget)); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - // Assert - expect(find.byType(ImtChartWidget), findsOneWidget); - }); - - testWidgets('should display chart with multiple weight points and show increase arrow', (WidgetTester tester) async { - // Arrange - final now = DateTime.now(); - final weightPoints = [ - WeightModel( - id: 1, - userId: 1, - weight: 70, - createdAt: now.subtract(const Duration(days: 7)), - updatedAt: now.subtract(const Duration(days: 7)), - bmi: 23.0, - ), - WeightModel( - id: 2, - userId: 1, - weight: 72, - createdAt: now, - updatedAt: now, - bmi: 24.0, - ), - ]; - final widget = ImtChartWidget(weightPoints: weightPoints); - - // Act - await tester.pumpWidget(createTestWidget(widget)); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - // Assert - expect(find.byType(ImtChartWidget), findsOneWidget); - }); - - testWidgets('should display chart with multiple weight points and show decrease arrow', (WidgetTester tester) async { - // Arrange - final now = DateTime.now(); - final weightPoints = [ - WeightModel( - id: 1, - userId: 1, - weight: 72, - createdAt: now.subtract(const Duration(days: 7)), - updatedAt: now.subtract(const Duration(days: 7)), - bmi: 24.0, - ), - WeightModel( - id: 2, - userId: 1, - weight: 70, - createdAt: now, - updatedAt: now, - bmi: 23.0, - ), - ]; - final widget = ImtChartWidget(weightPoints: weightPoints); - - // Act - await tester.pumpWidget(createTestWidget(widget)); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - // Assert - expect(find.byType(ImtChartWidget), findsOneWidget); - }); - }); -} - diff --git a/test/features/profile/presentation/widgets/profile_blog_post_widget_smoke_test.dart b/test/features/profile/presentation/widgets/profile_blog_post_widget_smoke_test.dart index e1a5411f..cda2960f 100644 --- a/test/features/profile/presentation/widgets/profile_blog_post_widget_smoke_test.dart +++ b/test/features/profile/presentation/widgets/profile_blog_post_widget_smoke_test.dart @@ -11,9 +11,8 @@ import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/prof import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/profile_blog_post_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -218,12 +217,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: MediaQuery( @@ -341,12 +335,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: MediaQuery( diff --git a/test/features/profile/presentation/widgets/profile_charts_smoke_test.dart b/test/features/profile/presentation/widgets/profile_charts_smoke_test.dart deleted file mode 100644 index df88a7b5..00000000 --- a/test/features/profile/presentation/widgets/profile_charts_smoke_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/circumference_chart_widget.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:intl/date_symbol_data_local.dart'; -import 'package:intl/intl.dart'; - -void main() { - group('Profile chart widgets smoke', () { - setUpAll(() async { - Intl.defaultLocale = 'ru'; - await initializeDateFormatting('ru'); - }); - - Widget wrap(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - home: Scaffold(body: SingleChildScrollView(child: child)), - ); - } - - testWidgets('WeightChartWidget renders empty state', (tester) async { - await tester.pumpWidget(wrap(const WeightChartWidget(weightPoints: []))); - await tester.pumpAndSettle(const Duration(milliseconds: 200)); - expect(find.text('Добавьте Ваш вес'), findsOneWidget); - }); - - testWidgets('WeightChartWidget renders with one point', (tester) async { - final points = [WeightModel(id: 1, userId: 1, weight: 70, createdAt: DateTime(2025, 1, 1), updatedAt: DateTime(2025, 1, 1), bmi: 22.0)]; - await tester.pumpWidget(wrap(WeightChartWidget(weightPoints: points))); - await tester.pumpAndSettle(const Duration(milliseconds: 200)); - expect(find.textContaining('кг'), findsWidgets); - }); - - testWidgets('CircumferenceChartWidget renders empty state', (tester) async { - await tester.pumpWidget(wrap(const CircumferenceChartWidget(circumferencePoints: []))); - await tester.pumpAndSettle(const Duration(milliseconds: 200)); - expect(find.text('Добавьте Ваши замеры'), findsOneWidget); - }); - - testWidgets('CircumferenceChartWidget renders with one point', (tester) async { - final points = [ - CircumferenceModel( - id: 1, - userId: 1, - chestCircumference: 100, - waistCircumference: 80, - hipCircumference: 90, - createdAt: DateTime(2025, 1, 1), - updatedAt: DateTime(2025, 1, 1), - ), - ]; - await tester.pumpWidget(wrap(CircumferenceChartWidget(circumferencePoints: points))); - await tester.pumpAndSettle(const Duration(milliseconds: 200)); - - expect(find.text('100'), findsOneWidget); - expect(find.text('80'), findsOneWidget); - expect(find.text('90'), findsOneWidget); - }); - }); -} diff --git a/test/features/profile/presentation/widgets/sub_action_button_widget_test.dart b/test/features/profile/presentation/widgets/sub_action_button_widget_test.dart index 9d61437e..7b4c3571 100644 --- a/test/features/profile/presentation/widgets/sub_action_button_widget_test.dart +++ b/test/features/profile/presentation/widgets/sub_action_button_widget_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/prof import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_state.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/sub_action_button_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/profile/presentation/widgets/sub_widget_test.dart b/test/features/profile/presentation/widgets/sub_widget_test.dart index 40967be0..d38e09d4 100644 --- a/test/features/profile/presentation/widgets/sub_widget_test.dart +++ b/test/features/profile/presentation/widgets/sub_widget_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/models/sub_model.dart'; import 'package:eatvio_app/features/profile/presentation/widgets/sub_widget.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; diff --git a/test/features/profile/presentation/widgets/weight_chart_widget_test.dart b/test/features/profile/presentation/widgets/weight_chart_widget_test.dart deleted file mode 100644 index f16d5322..00000000 --- a/test/features/profile/presentation/widgets/weight_chart_widget_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; -import 'package:eatvio_app/features/profile/presentation/widgets/weight_chart_widget.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:intl/date_symbol_data_local.dart'; - -void main() { - group('WeightChartWidget smoke', () { - setUpAll(() async { - await initializeDateFormatting('ru', null); - }); - Widget wrap(Widget child) { - return MaterialApp( - theme: ThemeHelper().themeData(), - home: Scaffold(body: child), - ); - } - - testWidgets('renders weight chart widget with empty points', (tester) async { - await tester.pumpWidget(wrap(const WeightChartWidget(weightPoints: []))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.byType(WeightChartWidget), findsOneWidget); - }); - - testWidgets('renders weight chart widget with points', (tester) async { - final points = [WeightModel(id: 1, userId: 1, weight: 70, bmi: 22.5, createdAt: DateTime.now(), updatedAt: DateTime.now())]; - await tester.pumpWidget(wrap(WeightChartWidget(weightPoints: points))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - expect(find.byType(WeightChartWidget), findsOneWidget); - }); - }); -} diff --git a/test/features/recipe/presentation/pages/about_recipe_screen_smoke_test.dart b/test/features/recipe/presentation/pages/about_recipe_screen_smoke_test.dart index 5b1eb97a..5a939542 100644 --- a/test/features/recipe/presentation/pages/about_recipe_screen_smoke_test.dart +++ b/test/features/recipe/presentation/pages/about_recipe_screen_smoke_test.dart @@ -11,10 +11,9 @@ import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_state.dart'; import 'package:eatvio_app/features/recipe/presentation/pages/about_recipe_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -102,12 +101,7 @@ void main() { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: router, ); @@ -248,7 +242,8 @@ void main() { await tester.tap(find.byType(BackButton)); await tester.pump(); - expect(find.byType(AboutRecipeScreen), findsOneWidget); + expect(tester.takeException(), isNull); + expect(find.byType(AboutRecipeScreen), findsNothing); }); testWidgets('renders with navigateToComments true', (tester) async { diff --git a/test/features/recipe/presentation/pages/my_recipes_screen_smoke_test.dart b/test/features/recipe/presentation/pages/my_recipes_screen_smoke_test.dart index ebd26e01..430e017c 100644 --- a/test/features/recipe/presentation/pages/my_recipes_screen_smoke_test.dart +++ b/test/features/recipe/presentation/pages/my_recipes_screen_smoke_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/m import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/my_recipes_state.dart'; import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -30,12 +29,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: child, ); diff --git a/test/features/recipe/presentation/widgets/ingredients_widget_test.dart b/test/features/recipe/presentation/widgets/ingredients_widget_test.dart index ccc46e3c..9bb9136a 100644 --- a/test/features/recipe/presentation/widgets/ingredients_widget_test.dart +++ b/test/features/recipe/presentation/widgets/ingredients_widget_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/ingredients_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -63,12 +62,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/recipe/presentation/widgets/my_recipe_widget_test.dart b/test/features/recipe/presentation/widgets/my_recipe_widget_test.dart index caa91380..2e37fb48 100644 --- a/test/features/recipe/presentation/widgets/my_recipe_widget_test.dart +++ b/test/features/recipe/presentation/widgets/my_recipe_widget_test.dart @@ -9,10 +9,9 @@ import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/m import 'package:eatvio_app/features/recipe/presentation/cubit/my_recipes_cubit/my_recipes_state.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/my_recipe_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -52,12 +51,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/recipe/presentation/widgets/my_recipes_tab_test.dart b/test/features/recipe/presentation/widgets/my_recipes_tab_test.dart index 58d21ef1..4a688bf1 100644 --- a/test/features/recipe/presentation/widgets/my_recipes_tab_test.dart +++ b/test/features/recipe/presentation/widgets/my_recipes_tab_test.dart @@ -1,8 +1,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/my_recipes_tab.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,12 +9,7 @@ void main() { Widget wrap() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Material( child: MyRecipesTab( diff --git a/test/features/recipes/presentation/widgets/basic_widget_test.dart b/test/features/recipes/presentation/widgets/basic_widget_test.dart index d71601c9..621b9c00 100644 --- a/test/features/recipes/presentation/widgets/basic_widget_test.dart +++ b/test/features/recipes/presentation/widgets/basic_widget_test.dart @@ -12,9 +12,8 @@ import 'package:eatvio_app/features/feed/presentation/widgets/recipes_widget.dar import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/recipe/repositories/about_recipe_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -87,12 +86,7 @@ void main() { ); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: widget, ); @@ -101,12 +95,7 @@ void main() { Widget createRecipesTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold( diff --git a/test/features/recipes/presentation/widgets/widgets_test.dart b/test/features/recipes/presentation/widgets/widgets_test.dart index 0bb74dd4..d9f7f1e7 100644 --- a/test/features/recipes/presentation/widgets/widgets_test.dart +++ b/test/features/recipes/presentation/widgets/widgets_test.dart @@ -7,8 +7,7 @@ import 'package:eatvio_app/features/feed/models/recipes_model.dart' as recipes; import 'package:eatvio_app/features/recipe/presentation/widgets/ingredients_widget.dart'; import 'package:eatvio_app/features/recipe/presentation/widgets/steps_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -25,12 +24,7 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Portal( child: Scaffold(body: SingleChildScrollView(child: child)), diff --git a/test/features/registration/basic_widget_test.dart b/test/features/registration/basic_widget_test.dart index 16995a82..cc2fde41 100644 --- a/test/features/registration/basic_widget_test.dart +++ b/test/features/registration/basic_widget_test.dart @@ -4,11 +4,12 @@ import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; +import '../../fixtures/doubles/session_doubles.dart'; import 'basic_widget_test.mocks.dart'; @GenerateMocks([RegistrationRepository, Prefs]) @@ -19,7 +20,7 @@ void main() { setUp(() { mockRegistrationRepository = MockRegistrationRepository(); - registrationCubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs()); + registrationCubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs(), sessionLifecycleService: FakeSessionLifecycleService()); }); tearDown(() { @@ -38,7 +39,7 @@ void main() { testWidgets('should create RegistrationCubit successfully', (WidgetTester tester) async { // Arrange & Act - final cubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs()); + final cubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs(), sessionLifecycleService: FakeSessionLifecycleService()); // Assert expect(cubit, isA()); diff --git a/test/features/registration/integration_widget_test.dart b/test/features/registration/integration_widget_test.dart index e5559a80..c03692f6 100644 --- a/test/features/registration/integration_widget_test.dart +++ b/test/features/registration/integration_widget_test.dart @@ -2,11 +2,12 @@ import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; +import '../../fixtures/doubles/session_doubles.dart'; import 'integration_widget_test.mocks.dart'; @GenerateMocks([RegistrationRepository, Prefs]) @@ -17,7 +18,7 @@ void main() { setUp(() { mockRegistrationRepository = MockRegistrationRepository(); - registrationCubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs()); + registrationCubit = RegistrationCubit(registrationRepository: mockRegistrationRepository, prefs: MockPrefs(), sessionLifecycleService: FakeSessionLifecycleService()); }); tearDown(() { diff --git a/test/features/registration/presentation/bloc/registration_cubit/registration_cubit_test.dart b/test/features/registration/presentation/bloc/registration_cubit/registration_cubit_test.dart index 11bfe5d6..3f108a79 100644 --- a/test/features/registration/presentation/bloc/registration_cubit/registration_cubit_test.dart +++ b/test/features/registration/presentation/bloc/registration_cubit/registration_cubit_test.dart @@ -7,6 +7,8 @@ import 'package:eatvio_app/features/registration/repositories/registration_repos import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; +import '../../../../../fixtures/doubles/session_doubles.dart'; + class MockRegistrationRepository extends Mock implements RegistrationRepository {} class MockPrefs extends Mock implements Prefs {} @@ -26,7 +28,7 @@ void main() { setUp(() { mockRepository = MockRegistrationRepository(); mockPrefs = MockPrefs(); - cubit = RegistrationCubit(registrationRepository: mockRepository, prefs: mockPrefs); + cubit = RegistrationCubit(registrationRepository: mockRepository, prefs: mockPrefs, sessionLifecycleService: FakeSessionLifecycleService()); }); tearDown(() { diff --git a/test/features/registration/presentation/pages/additional_information_screen_test.dart b/test/features/registration/presentation/pages/additional_information_screen_test.dart index d1f1e0d5..d696e050 100644 --- a/test/features/registration/presentation/pages/additional_information_screen_test.dart +++ b/test/features/registration/presentation/pages/additional_information_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/additional_information_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/registration/presentation/pages/allergies_screen_test.dart b/test/features/registration/presentation/pages/allergies_screen_test.dart index aed4d2b2..c42b81f1 100644 --- a/test/features/registration/presentation/pages/allergies_screen_test.dart +++ b/test/features/registration/presentation/pages/allergies_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/allergies_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/blood_pressure_screen_test.dart b/test/features/registration/presentation/pages/blood_pressure_screen_test.dart index bec7200f..3c1ffc8f 100644 --- a/test/features/registration/presentation/pages/blood_pressure_screen_test.dart +++ b/test/features/registration/presentation/pages/blood_pressure_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/blood_pressure_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/body_circumferences_screen_test.dart b/test/features/registration/presentation/pages/body_circumferences_screen_test.dart index 6295ffb8..6efaf48a 100644 --- a/test/features/registration/presentation/pages/body_circumferences_screen_test.dart +++ b/test/features/registration/presentation/pages/body_circumferences_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/body_circumferences_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/city_of_living_screen_test.dart b/test/features/registration/presentation/pages/city_of_living_screen_test.dart index 3d63647f..eee380ac 100644 --- a/test/features/registration/presentation/pages/city_of_living_screen_test.dart +++ b/test/features/registration/presentation/pages/city_of_living_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/registration/presentation/pages/credentials_screen_test.dart b/test/features/registration/presentation/pages/credentials_screen_test.dart index 8547f2c3..490dc60c 100644 --- a/test/features/registration/presentation/pages/credentials_screen_test.dart +++ b/test/features/registration/presentation/pages/credentials_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/credentials_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/date_of_birth_screen_test.dart b/test/features/registration/presentation/pages/date_of_birth_screen_test.dart index 9256e053..bd68a0f1 100644 --- a/test/features/registration/presentation/pages/date_of_birth_screen_test.dart +++ b/test/features/registration/presentation/pages/date_of_birth_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/date_of_birth_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/favorite_foods_screen_test.dart b/test/features/registration/presentation/pages/favorite_foods_screen_test.dart index e51fbbd5..6e60f4f7 100644 --- a/test/features/registration/presentation/pages/favorite_foods_screen_test.dart +++ b/test/features/registration/presentation/pages/favorite_foods_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/favorite_sports_screen_test.dart b/test/features/registration/presentation/pages/favorite_sports_screen_test.dart index 5caa1e3b..e83020aa 100644 --- a/test/features/registration/presentation/pages/favorite_sports_screen_test.dart +++ b/test/features/registration/presentation/pages/favorite_sports_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/favorite_sports_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/gender_screen_test.dart b/test/features/registration/presentation/pages/gender_screen_test.dart index f202bbb4..f625352f 100644 --- a/test/features/registration/presentation/pages/gender_screen_test.dart +++ b/test/features/registration/presentation/pages/gender_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/gender_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/registration/presentation/pages/height_screen_test.dart b/test/features/registration/presentation/pages/height_screen_test.dart index 4972969e..45953341 100644 --- a/test/features/registration/presentation/pages/height_screen_test.dart +++ b/test/features/registration/presentation/pages/height_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/language_select_screen_test.dart b/test/features/registration/presentation/pages/language_select_screen_test.dart index 769fed02..fd6c9558 100644 --- a/test/features/registration/presentation/pages/language_select_screen_test.dart +++ b/test/features/registration/presentation/pages/language_select_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/language_select_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/medicine_intake_screen_test.dart b/test/features/registration/presentation/pages/medicine_intake_screen_test.dart index ab89404a..59ec8e80 100644 --- a/test/features/registration/presentation/pages/medicine_intake_screen_test.dart +++ b/test/features/registration/presentation/pages/medicine_intake_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/medicine_intake_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/name_screen_test.dart b/test/features/registration/presentation/pages/name_screen_test.dart index a6481ade..0db39790 100644 --- a/test/features/registration/presentation/pages/name_screen_test.dart +++ b/test/features/registration/presentation/pages/name_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/pages/phone_screen_test.dart b/test/features/registration/presentation/pages/phone_screen_test.dart index 4bbf9fd8..dc42e9b8 100644 --- a/test/features/registration/presentation/pages/phone_screen_test.dart +++ b/test/features/registration/presentation/pages/phone_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/registration/models/user_registration_model. import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/phone_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/registration/presentation/pages/registration_screen_smoke_test.dart b/test/features/registration/presentation/pages/registration_screen_smoke_test.dart index d3b60f15..88cc7cfd 100644 --- a/test/features/registration/presentation/pages/registration_screen_smoke_test.dart +++ b/test/features/registration/presentation/pages/registration_screen_smoke_test.dart @@ -7,12 +7,12 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/pages/registration_screen.dart'; import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import 'registration_screen_smoke_test.mocks.dart'; @GenerateNiceMocks([MockSpec(), MockSpec()]) @@ -30,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); @@ -44,7 +39,7 @@ void main() { testWidgets('renders registration screen with initial step', (tester) async { final repository = MockRegistrationRepository(); final prefs = MockPrefs(); - final cubit = RegistrationCubit(registrationRepository: repository, prefs: prefs); + final cubit = RegistrationCubit(registrationRepository: repository, prefs: prefs, sessionLifecycleService: FakeSessionLifecycleService()); sl.registerLazySingleton(() => repository); sl.registerLazySingleton(() => prefs); @@ -59,7 +54,7 @@ void main() { testWidgets('renders phone screen as first step', (tester) async { final repository = MockRegistrationRepository(); final prefs = MockPrefs(); - final cubit = RegistrationCubit(registrationRepository: repository, prefs: prefs); + final cubit = RegistrationCubit(registrationRepository: repository, prefs: prefs, sessionLifecycleService: FakeSessionLifecycleService()); sl.registerLazySingleton(() => repository); sl.registerLazySingleton(() => prefs); diff --git a/test/features/registration/presentation/pages/verify_email_screen_test.dart b/test/features/registration/presentation/pages/verify_email_screen_test.dart index e65f4b5f..01b8ad29 100644 --- a/test/features/registration/presentation/pages/verify_email_screen_test.dart +++ b/test/features/registration/presentation/pages/verify_email_screen_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_ import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/verify_email_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -35,12 +34,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/registration/presentation/pages/verify_screen_test.dart b/test/features/registration/presentation/pages/verify_screen_test.dart index 4ec33bb1..3ce5bb3a 100644 --- a/test/features/registration/presentation/pages/verify_screen_test.dart +++ b/test/features/registration/presentation/pages/verify_screen_test.dart @@ -2,7 +2,7 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/registration/presentation/pages/verify_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/test/features/registration/presentation/pages/weight_screen_test.dart b/test/features/registration/presentation/pages/weight_screen_test.dart index 1f670ea7..1423f9e8 100644 --- a/test/features/registration/presentation/pages/weight_screen_test.dart +++ b/test/features/registration/presentation/pages/weight_screen_test.dart @@ -7,10 +7,9 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/pages/weight_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -61,12 +60,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: Scaffold(body: child), ); diff --git a/test/features/registration/presentation/widgets/change_email_dialog_test.dart b/test/features/registration/presentation/widgets/change_email_dialog_test.dart index 8ab87af3..337c0460 100644 --- a/test/features/registration/presentation/widgets/change_email_dialog_test.dart +++ b/test/features/registration/presentation/widgets/change_email_dialog_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_state.dart'; import 'package:eatvio_app/features/registration/presentation/widgets/change_email_dialog.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/registration/presentation/widgets/code_not_received_dialog_test.dart b/test/features/registration/presentation/widgets/code_not_received_dialog_test.dart index d770afa5..6b682fef 100644 --- a/test/features/registration/presentation/widgets/code_not_received_dialog_test.dart +++ b/test/features/registration/presentation/widgets/code_not_received_dialog_test.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/verify_email_cubit/verify_email_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/widgets/code_not_received_dialog.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/registration_v2/cubit/registration_cubit_v2_test.dart b/test/features/registration_v2/cubit/registration_cubit_v2_test.dart index cec3aa9a..98f4ac25 100644 --- a/test/features/registration_v2/cubit/registration_cubit_v2_test.dart +++ b/test/features/registration_v2/cubit/registration_cubit_v2_test.dart @@ -1,4 +1,6 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/firebase_api.dart'; +import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; import 'package:flutter/services.dart'; @@ -7,45 +9,66 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../../../fixtures/doubles/session_doubles.dart'; import 'registration_cubit_v2_test.mocks.dart'; +class _RecordingFirebaseApi extends Fake implements FirebaseApi { + int registerPushTokenCalls = 0; + bool hadAuthToken = false; + + @override + Future registerPushToken() async { + registerPushTokenCalls++; + hadAuthToken = await TokenStorage.haveTokenInStorage(); + } +} + @GenerateMocks([RegistrationRepositoryV2]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); - + group('RegistrationCubitV2', () { late RegistrationCubitV2 cubit; late MockRegistrationRepositoryV2 mockRepository; - const MethodChannel passwordGeneratorChannel = MethodChannel('flutter_password_generator'); + late _RecordingFirebaseApi firebaseApi; + late FakeSessionLifecycleService fakeSession; + const MethodChannel passwordGeneratorChannel = MethodChannel( + 'flutter_password_generator', + ); setUp(() { mockRepository = MockRegistrationRepositoryV2(); - cubit = RegistrationCubitV2(registrationRepository: mockRepository); - + firebaseApi = _RecordingFirebaseApi(); + fakeSession = FakeSessionLifecycleService(); + cubit = RegistrationCubitV2( + registrationRepository: mockRepository, + firebaseApi: firebaseApi, + sessionLifecycleService: fakeSession, + ); + // Инициализируем SharedPreferences для тестов SharedPreferences.setMockInitialValues({}); - + // Мокируем MethodChannel для flutter_password_generator - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( - passwordGeneratorChannel, - (MethodCall methodCall) async { - if (methodCall.method == 'generateSecureRandomData') { - // Возвращаем Uint8List для генерации пароля - // MethodChannel автоматически преобразует Uint8List в List - return Uint8List.fromList(List.generate(32, (i) => i % 256)); - } - return null; - }, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(passwordGeneratorChannel, ( + MethodCall methodCall, + ) async { + if (methodCall.method == 'generateSecureRandomData') { + // Возвращаем Uint8List для генерации пароля + // MethodChannel автоматически преобразует Uint8List в List + return Uint8List.fromList(List.generate(32, (i) => i % 256)); + } + return null; + }); }); tearDown(() { + TokenStorage.clearCache(); cubit.close(); // Очищаем моки - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( - passwordGeneratorChannel, - null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(passwordGeneratorChannel, null); }); test('начальное состояние', () { @@ -182,14 +205,23 @@ void main() { cubit.setBirthday(DateTime(1990, 1, 1)); const token = 'test-token'; - when(mockRepository.register(registrationModel: anyNamed('registrationModel'))) - .thenAnswer((_) async => token); + when( + mockRepository.register( + registrationModel: anyNamed('registrationModel'), + ), + ).thenAnswer((_) async => token); final result = await cubit.register(); expect(result.$1, isTrue); expect(result.$2, isFalse); - verify(mockRepository.register(registrationModel: anyNamed('registrationModel'))).called(1); + expect(await TokenStorage.getTokenFromStorage(), token); + expect(fakeSession.onAuthenticatedCalls, 1); + verify( + mockRepository.register( + registrationModel: anyNamed('registrationModel'), + ), + ).called(1); }); test('register - возвращает false при невалидных полях', () async { @@ -199,7 +231,11 @@ void main() { expect(result.$1, isFalse); expect(result.$2, isTrue); - verifyNever(mockRepository.register(registrationModel: anyNamed('registrationModel'))); + verifyNever( + mockRepository.register( + registrationModel: anyNamed('registrationModel'), + ), + ); }); test('register - обработка ошибки валидации email', () async { @@ -226,16 +262,21 @@ void main() { ), ); - when(mockRepository.register(registrationModel: anyNamed('registrationModel'))) - .thenThrow(dioException); + when( + mockRepository.register( + registrationModel: anyNamed('registrationModel'), + ), + ).thenThrow(dioException); final result = await cubit.register(); expect(result.$1, isFalse); expect(result.$2, isTrue); expect(cubit.state.isEmailValid, isFalse); - expect(cubit.state.emailDisplayError, equals('Некорректный формат email')); + expect( + cubit.state.emailDisplayError, + equals('Некорректный формат email'), + ); }); }); } - diff --git a/test/features/registration_v2/presentation/pages/registration_v2_page_smoke_test.dart b/test/features/registration_v2/presentation/pages/registration_v2_page_smoke_test.dart index d3a0905b..0802e84b 100644 --- a/test/features/registration_v2/presentation/pages/registration_v2_page_smoke_test.dart +++ b/test/features/registration_v2/presentation/pages/registration_v2_page_smoke_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/pages/registration_v2_page.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -32,12 +31,7 @@ void main() { sl.registerLazySingleton(() => cubit); return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold( body: BlocProvider.value( diff --git a/test/features/registration_v2/presentation/widgets/first_step_content_test.dart b/test/features/registration_v2/presentation/widgets/first_step_content_test.dart index cfb23b2d..6ec7db51 100644 --- a/test/features/registration_v2/presentation/widgets/first_step_content_test.dart +++ b/test/features/registration_v2/presentation/widgets/first_step_content_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/first_step_content.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration_v2/presentation/widgets/password_field_test.dart b/test/features/registration_v2/presentation/widgets/password_field_test.dart index 575a6a2b..edae714f 100644 --- a/test/features/registration_v2/presentation/widgets/password_field_test.dart +++ b/test/features/registration_v2/presentation/widgets/password_field_test.dart @@ -1,83 +1,77 @@ -import 'package:eatvio_app/core/app_config.dart'; -import 'package:eatvio_app/core/app_initializer.dart'; -import 'package:eatvio_app/core/locator_service.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; -import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; -import 'package:eatvio_app/features/registration_v2/presentation/widgets/password_field.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_portal/flutter_portal.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'password_field_test.mocks.dart'; - -@GenerateNiceMocks([MockSpec()]) -void main() { - group('PasswordField', () { - setUp(() async { - await sl.reset(); - dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); - sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); - }); - - Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru')], - home: Portal( - child: BlocProvider( - create: (_) => cubit, - child: Scaffold(body: child), - ), - ), - ); - } - - testWidgets('should display password field with password from state', (WidgetTester tester) async { - // Arrange - final mockCubit = MockRegistrationCubitV2(); - const testPassword = 'testPassword123'; - when(mockCubit.state).thenReturn( - const RegistrationStateV2(password: testPassword), - ); - final widget = PasswordField(cubit: mockCubit); - - // Act - await tester.pumpWidget(createTestWidget(widget, mockCubit)); - await tester.pump(); - - // Assert - expect(find.byType(PasswordField), findsOneWidget); - expect(find.text(testPassword), findsOneWidget); - }); - - testWidgets('should show copy icon initially', (WidgetTester tester) async { - // Arrange - final mockCubit = MockRegistrationCubitV2(); - when(mockCubit.state).thenReturn( - const RegistrationStateV2(password: 'test'), - ); - final widget = PasswordField(cubit: mockCubit); - - // Act - await tester.pumpWidget(createTestWidget(widget, mockCubit)); - await tester.pump(); - - // Assert - expect(find.byType(PasswordField), findsOneWidget); - }); - }); -} - +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; +import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; +import 'package:eatvio_app/features/registration_v2/presentation/widgets/password_field.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_portal/flutter_portal.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'password_field_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('PasswordField', () { + setUp(() async { + await sl.reset(); + dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); + sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + }); + + Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Portal( + child: BlocProvider( + create: (_) => cubit, + child: Scaffold(body: child), + ), + ), + ); + } + + testWidgets('should display password field with password from state', (WidgetTester tester) async { + // Arrange + final mockCubit = MockRegistrationCubitV2(); + const testPassword = 'testPassword123'; + when(mockCubit.state).thenReturn( + const RegistrationStateV2(password: testPassword), + ); + final widget = PasswordField(cubit: mockCubit); + + // Act + await tester.pumpWidget(createTestWidget(widget, mockCubit)); + await tester.pump(); + + // Assert + expect(find.byType(PasswordField), findsOneWidget); + expect(find.text(testPassword), findsOneWidget); + }); + + testWidgets('should show copy icon initially', (WidgetTester tester) async { + // Arrange + final mockCubit = MockRegistrationCubitV2(); + when(mockCubit.state).thenReturn( + const RegistrationStateV2(password: 'test'), + ); + final widget = PasswordField(cubit: mockCubit); + + // Act + await tester.pumpWidget(createTestWidget(widget, mockCubit)); + await tester.pump(); + + // Assert + expect(find.byType(PasswordField), findsOneWidget); + }); + }); +} + diff --git a/test/features/registration_v2/presentation/widgets/phisical_activity_test.dart b/test/features/registration_v2/presentation/widgets/phisical_activity_test.dart index cedace03..fa37c175 100644 --- a/test/features/registration_v2/presentation/widgets/phisical_activity_test.dart +++ b/test/features/registration_v2/presentation/widgets/phisical_activity_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/phisical_activity.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; @@ -22,12 +21,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: BlocProvider.value( diff --git a/test/features/registration_v2/presentation/widgets/second_step_content_test.dart b/test/features/registration_v2/presentation/widgets/second_step_content_test.dart index 9ea40583..6a22ea43 100644 --- a/test/features/registration_v2/presentation/widgets/second_step_content_test.dart +++ b/test/features/registration_v2/presentation/widgets/second_step_content_test.dart @@ -6,10 +6,9 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/second_step_content.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,12 +30,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/registration_v2/presentation/widgets/sex_widget_test.dart b/test/features/registration_v2/presentation/widgets/sex_widget_test.dart index 0c85cc60..c6ce0e13 100644 --- a/test/features/registration_v2/presentation/widgets/sex_widget_test.dart +++ b/test/features/registration_v2/presentation/widgets/sex_widget_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/sex_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -24,12 +23,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: BlocProvider.value( value: mockCubit, diff --git a/test/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet_test.dart b/test/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet_test.dart index e55692f5..e9c29630 100644 --- a/test/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet_test.dart +++ b/test/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet_test.dart @@ -1,120 +1,109 @@ -import 'package:eatvio_app/core/app_config.dart'; -import 'package:eatvio_app/core/app_initializer.dart'; -import 'package:eatvio_app/core/locator_service.dart'; -import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; -import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; -import 'package:eatvio_app/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart'; -import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_portal/flutter_portal.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'show_successful_registration_bottom_sheet_test.mocks.dart'; - -@GenerateNiceMocks([MockSpec()]) -void main() { - group('ShowSuccessfulRegistrationBottomSheet', () { - setUp(() async { - await sl.reset(); - dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); - sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); - }); - - Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru')], - home: Portal( - child: BlocProvider( - create: (_) => cubit, - child: Scaffold( - body: Builder( - builder: (context) => ElevatedButton( - onPressed: () { - showRegistrationBottomSheet(context, cubit, true); - }, - child: const Text('Show Bottom Sheet'), - ), - ), - ), - ), - ), - ); - } - - testWidgets('should display success bottom sheet when isSuccess is true', (WidgetTester tester) async { - // Arrange - final mockCubit = MockRegistrationCubitV2(); - when(mockCubit.state).thenReturn( - const RegistrationStateV2(password: 'testPassword'), - ); - - // Act - await tester.pumpWidget(createTestWidget(const SizedBox(), mockCubit)); - await tester.pump(); - await tester.tap(find.text('Show Bottom Sheet')); - await tester.pumpAndSettle(); - - // Assert - expect(find.byType(RegistrationBottomSheet), findsOneWidget); - }); - - testWidgets('should display error bottom sheet when isSuccess is false', (WidgetTester tester) async { - // Arrange - final mockCubit = MockRegistrationCubitV2(); - when(mockCubit.state).thenReturn( - const RegistrationStateV2(), - ); - - Widget createTestWidgetError(Widget child, RegistrationCubitV2 cubit) { - return MaterialApp( - theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [Locale('ru')], - home: Portal( - child: BlocProvider( - create: (_) => cubit, - child: Scaffold( - body: Builder( - builder: (context) => ElevatedButton( - onPressed: () { - showRegistrationBottomSheet(context, cubit, false); - }, - child: const Text('Show Bottom Sheet'), - ), - ), - ), - ), - ), - ); - } - - // Act - await tester.pumpWidget(createTestWidgetError(const SizedBox(), mockCubit)); - await tester.pump(); - await tester.tap(find.text('Show Bottom Sheet')); - await tester.pumpAndSettle(); - - // Assert - expect(find.byType(RegistrationBottomSheet), findsOneWidget); - }); - }); -} - +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; +import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; +import 'package:eatvio_app/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_portal/flutter_portal.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'show_successful_registration_bottom_sheet_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('ShowSuccessfulRegistrationBottomSheet', () { + setUp(() async { + await sl.reset(); + dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); + sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + }); + + Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Portal( + child: BlocProvider( + create: (_) => cubit, + child: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () { + showRegistrationBottomSheet(context, cubit, true); + }, + child: const Text('Show Bottom Sheet'), + ), + ), + ), + ), + ), + ); + } + + testWidgets('should display success bottom sheet when isSuccess is true', (WidgetTester tester) async { + // Arrange + final mockCubit = MockRegistrationCubitV2(); + when(mockCubit.state).thenReturn( + const RegistrationStateV2(password: 'testPassword'), + ); + + // Act + await tester.pumpWidget(createTestWidget(const SizedBox(), mockCubit)); + await tester.pump(); + await tester.tap(find.text('Show Bottom Sheet')); + await tester.pumpAndSettle(); + + // Assert + expect(find.byType(RegistrationBottomSheet), findsOneWidget); + }); + + testWidgets('should display error bottom sheet when isSuccess is false', (WidgetTester tester) async { + // Arrange + final mockCubit = MockRegistrationCubitV2(); + when(mockCubit.state).thenReturn( + const RegistrationStateV2(), + ); + + Widget createTestWidgetError(Widget child, RegistrationCubitV2 cubit) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Portal( + child: BlocProvider( + create: (_) => cubit, + child: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () { + showRegistrationBottomSheet(context, cubit, false); + }, + child: const Text('Show Bottom Sheet'), + ), + ), + ), + ), + ), + ); + } + + // Act + await tester.pumpWidget(createTestWidgetError(const SizedBox(), mockCubit)); + await tester.pump(); + await tester.tap(find.text('Show Bottom Sheet')); + await tester.pumpAndSettle(); + + // Assert + expect(find.byType(RegistrationBottomSheet), findsOneWidget); + }); + }); +} + diff --git a/test/features/registration_v2/presentation/widgets/step_progress_test.dart b/test/features/registration_v2/presentation/widgets/step_progress_test.dart index 4fbfdc38..89aa2edc 100644 --- a/test/features/registration_v2/presentation/widgets/step_progress_test.dart +++ b/test/features/registration_v2/presentation/widgets/step_progress_test.dart @@ -5,7 +5,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/step_progress.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/registration_v2/presentation/widgets/step_widget_test.dart b/test/features/registration_v2/presentation/widgets/step_widget_test.dart index 9d923ff0..a7b2689f 100644 --- a/test/features/registration_v2/presentation/widgets/step_widget_test.dart +++ b/test/features/registration_v2/presentation/widgets/step_widget_test.dart @@ -3,9 +3,8 @@ import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dar import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/step_widget.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -24,12 +23,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru'), Locale('en')], locale: const Locale('ru'), home: BlocProvider.value( diff --git a/test/features/settings/presentation/bloc/settings_cubit_test.dart b/test/features/settings/presentation/bloc/settings_cubit_test.dart index 2733bd07..674492c4 100644 --- a/test/features/settings/presentation/bloc/settings_cubit_test.dart +++ b/test/features/settings/presentation/bloc/settings_cubit_test.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; @@ -7,6 +8,7 @@ import 'package:eatvio_app/features/settings/repositories/service_repository.dar import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import '../../../../fixtures/settings_fixtures.dart'; import 'settings_cubit_test.mocks.dart'; @@ -23,6 +25,7 @@ void main() { late MockSettingsRepository mockSettingsRepository; late MockConsultantRepository mockConsultantRepository; late MockConsultationsRepository mockConsultationsRepository; + late FakeSessionLifecycleService fakeSession; setUp(() { @@ -30,6 +33,7 @@ void main() { mockSettingsRepository = MockSettingsRepository(); mockConsultantRepository = MockConsultantRepository(); mockConsultationsRepository = MockConsultationsRepository(); + fakeSession = FakeSessionLifecycleService(); }); tearDown(() async { @@ -46,6 +50,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); expect(settingsCubit!.state, const SettingsState.loading()); }); @@ -56,6 +61,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.getMyProfile()) @@ -86,6 +92,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); // Ошибка происходит при загрузке настроек профиля (внутри try-catch блока) @@ -114,6 +121,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.getMyProfile()) @@ -145,6 +153,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.getMyProfile()) @@ -176,6 +185,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.deleteAccount()) @@ -184,6 +194,8 @@ void main() { final result = await settingsCubit!.deleteAccount(); expect(result, true); + expect(fakeSession.endSessionCalls, 1); + expect(fakeSession.lastEndReason, SessionEndReason.accountDeleted); verify(mockProfileRepository.deleteAccount()).called(1); }); @@ -193,6 +205,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.deleteAccount()) @@ -209,6 +222,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.getMyProfile()) @@ -244,6 +258,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, ); when(mockProfileRepository.getMyProfile()) diff --git a/test/features/settings/presentation/pages/change_email_screen_test.dart b/test/features/settings/presentation/pages/change_email_screen_test.dart index addc8e4e..cecbbba1 100644 --- a/test/features/settings/presentation/pages/change_email_screen_test.dart +++ b/test/features/settings/presentation/pages/change_email_screen_test.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/features/settings/models/profile_settings_model.dart' import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/pages/change_email_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:mockito/annotations.dart'; diff --git a/test/features/settings/presentation/pages/change_password_screen_test.dart b/test/features/settings/presentation/pages/change_password_screen_test.dart index fe576e3b..0069ff77 100644 --- a/test/features/settings/presentation/pages/change_password_screen_test.dart +++ b/test/features/settings/presentation/pages/change_password_screen_test.dart @@ -3,9 +3,9 @@ import 'package:eatvio_app/features/settings/presentation/pages/change_password_ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import '../../../../fixtures/settings_fixtures.dart'; import '../bloc/settings_cubit_test.mocks.dart'; @@ -27,6 +27,7 @@ void main() { settingsRepository: mockSettingsRepository, consultantRepository: mockConsultantRepository, consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: FakeSessionLifecycleService(), ); }); @@ -44,12 +45,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: ChangePasswordScreen(settingsEntity: settingsEntity), ), @@ -71,12 +67,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: ChangePasswordScreen(settingsEntity: settingsEntity), ), diff --git a/test/features/settings/presentation/pages/general_info_screen_test.dart b/test/features/settings/presentation/pages/general_info_screen_test.dart index 2f0fa437..1d302215 100644 --- a/test/features/settings/presentation/pages/general_info_screen_test.dart +++ b/test/features/settings/presentation/pages/general_info_screen_test.dart @@ -12,10 +12,9 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/general_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -92,12 +91,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/settings/presentation/pages/other_info_screen_test.dart b/test/features/settings/presentation/pages/other_info_screen_test.dart index ce6a1406..ee437678 100644 --- a/test/features/settings/presentation/pages/other_info_screen_test.dart +++ b/test/features/settings/presentation/pages/other_info_screen_test.dart @@ -9,10 +9,9 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/other_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -89,12 +88,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/settings/presentation/pages/physical_activity_screen_test.dart b/test/features/settings/presentation/pages/physical_activity_screen_test.dart index 36b06b96..10d4a46b 100644 --- a/test/features/settings/presentation/pages/physical_activity_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_activity_screen_test.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/features/settings/models/profile_settings_model.dart' import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/physical_activity_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/settings/presentation/pages/physical_form_screen_test.dart b/test/features/settings/presentation/pages/physical_form_screen_test.dart index d0fb6cfd..bc86fdda 100644 --- a/test/features/settings/presentation/pages/physical_form_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_form_screen_test.dart @@ -9,10 +9,9 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/physical_form_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -89,12 +88,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/settings/presentation/pages/pressure_screen_test.dart b/test/features/settings/presentation/pages/pressure_screen_test.dart index d83ded4a..309597f9 100644 --- a/test/features/settings/presentation/pages/pressure_screen_test.dart +++ b/test/features/settings/presentation/pages/pressure_screen_test.dart @@ -9,10 +9,9 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/pressure_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -89,12 +88,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/settings/presentation/pages/settings_additional_info_screens_smoke_test.dart b/test/features/settings/presentation/pages/settings_additional_info_screens_smoke_test.dart index 24b6c8dd..58f7cc4f 100644 --- a/test/features/settings/presentation/pages/settings_additional_info_screens_smoke_test.dart +++ b/test/features/settings/presentation/pages/settings_additional_info_screens_smoke_test.dart @@ -13,9 +13,8 @@ import 'package:eatvio_app/features/settings/presentation/pages/physical_activit import 'package:eatvio_app/features/settings/presentation/pages/physical_form_screen.dart'; import 'package:eatvio_app/features/settings/presentation/pages/pressure_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -140,12 +139,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: Scaffold(body: child), ); diff --git a/test/features/settings/presentation/pages/settings_screen_smoke_test.dart b/test/features/settings/presentation/pages/settings_screen_smoke_test.dart index 92cb508a..63a94707 100644 --- a/test/features/settings/presentation/pages/settings_screen_smoke_test.dart +++ b/test/features/settings/presentation/pages/settings_screen_smoke_test.dart @@ -11,13 +11,13 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/settings_screen.dart'; import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import '../../../../fixtures/doubles/session_doubles.dart'; import 'settings_screen_smoke_test.mocks.dart'; @GenerateNiceMocks([ @@ -57,6 +57,7 @@ void main() { settingsRepository: sl(), consultantRepository: sl(), consultationsRepository: sl(), + sessionLifecycleService: FakeSessionLifecycleService(), ), ); }); @@ -64,12 +65,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ); diff --git a/test/features/settings/presentation/pages/settings_screen_test.dart b/test/features/settings/presentation/pages/settings_screen_test.dart index 256e9f7c..d530be0d 100644 --- a/test/features/settings/presentation/pages/settings_screen_test.dart +++ b/test/features/settings/presentation/pages/settings_screen_test.dart @@ -6,9 +6,8 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/settings_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -36,12 +35,7 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', diff --git a/test/features/support/presentation/pages/support_screen_test.dart b/test/features/support/presentation/pages/support_screen_test.dart index ba6a44d3..50ea4eb6 100644 --- a/test/features/support/presentation/pages/support_screen_test.dart +++ b/test/features/support/presentation/pages/support_screen_test.dart @@ -4,9 +4,8 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/support/presentation/pages/support_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -20,12 +19,7 @@ void main() { Widget createTestWidget() { return MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: const SupportScreen(), ); diff --git a/test/features/update_screen/presentation/update_screen_smoke_test.dart b/test/features/update_screen/presentation/update_screen_smoke_test.dart index 4ba0bbb0..17fd8aa2 100644 --- a/test/features/update_screen/presentation/update_screen_smoke_test.dart +++ b/test/features/update_screen/presentation/update_screen_smoke_test.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/update_screen/presentation/update_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/test/features/user_details/presentation/cubit/user_details_cubit_test.dart b/test/features/user_details/presentation/cubit/user_details_cubit_test.dart index e12fa8f2..afad3f91 100644 --- a/test/features/user_details/presentation/cubit/user_details_cubit_test.dart +++ b/test/features/user_details/presentation/cubit/user_details_cubit_test.dart @@ -1,6 +1,4 @@ -import 'package:eatvio_app/features/profile/models/circumference_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; -import 'package:eatvio_app/features/profile/models/weight_model.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -28,8 +26,6 @@ void main() { expect(cubit.state.isLoading, isFalse); expect(cubit.state.error, isNull); expect(cubit.state.profileDetails, isNull); - expect(cubit.state.weightPoints, isNull); - expect(cubit.state.circumferencePoints, isNull); }); test('getUserDetails - успешная загрузка деталей пользователя', () async { @@ -62,37 +58,8 @@ void main() { activityCoefficient: 1.5, ); - final weightPoints = [ - WeightModel( - id: 1, - userId: 1, - weight: 70, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - bmi: 22.9, - ), - ]; - - final circumferencePoints = [ - CircumferenceModel( - id: 1, - userId: 1, - chestCircumference: 100, - waistCircumference: 80, - hipCircumference: 90, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - ), - ]; - when(mockProfileRepository.getProfileDetailsBySlug(slug)) .thenAnswer((_) async => profileDetails); - - when(mockProfileRepository.getWeight(period: '1', slug: slug)) - .thenAnswer((_) async => weightPoints); - - when(mockProfileRepository.getCircumferences(period: '1', slug: slug)) - .thenAnswer((_) async => circumferencePoints); cubit.getUserDetails(slug); @@ -119,75 +86,6 @@ void main() { expect(cubit.state.error, equals(error.toString())); expect(cubit.state.isLoading, isFalse); }); - - test('getChartData - успешная загрузка данных графика', () async { - const slug = 'test-user'; - const period = '1'; - - final weightPoints = [ - WeightModel( - id: 1, - userId: 1, - weight: 70, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - bmi: 22.9, - ), - WeightModel( - id: 2, - userId: 1, - weight: 71, - createdAt: DateTime.now().add(const Duration(days: 1)), - updatedAt: DateTime.now().add(const Duration(days: 1)), - bmi: 23.2, - ), - ]; - - final circumferencePoints = [ - CircumferenceModel( - id: 1, - userId: 1, - chestCircumference: 100, - waistCircumference: 80, - hipCircumference: 90, - createdAt: DateTime.now(), - updatedAt: DateTime.now(), - ), - ]; - - when(mockProfileRepository.getWeight(period: period, slug: slug)) - .thenAnswer((_) async => weightPoints); - - when(mockProfileRepository.getCircumferences(period: period, slug: slug)) - .thenAnswer((_) async => circumferencePoints); - - cubit.getChartData(period: period, slug: slug); - - // Ждем завершения асинхронных операций - await Future.delayed(const Duration(milliseconds: 100)); - - expect(cubit.state.weightPoints, equals(weightPoints)); - expect(cubit.state.circumferencePoints, equals(circumferencePoints)); - verify(mockProfileRepository.getWeight(period: period, slug: slug)).called(1); - verify(mockProfileRepository.getCircumferences(period: period, slug: slug)).called(1); - }); - - test('getChartData - обработка ошибки', () async { - const slug = 'test-user'; - const period = '1'; - final error = Exception('Ошибка загрузки'); - - when(mockProfileRepository.getWeight(period: period, slug: slug)) - .thenThrow(error); - - cubit.getChartData(period: period, slug: slug); - - // Ждем завершения асинхронных операций - await Future.delayed(const Duration(milliseconds: 100)); - - expect(cubit.state.error, equals(error.toString())); - expect(cubit.state.isLoading, isFalse); - }); }); } diff --git a/test/features/user_details/presentation/user_details_screen_smoke_test.dart b/test/features/user_details/presentation/user_details_screen_smoke_test.dart index 6b8a2996..f86e6397 100644 --- a/test/features/user_details/presentation/user_details_screen_smoke_test.dart +++ b/test/features/user_details/presentation/user_details_screen_smoke_test.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; import 'package:eatvio_app/features/profile/models/circumference_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/profile/models/weight_model.dart'; @@ -9,14 +10,14 @@ import 'package:eatvio_app/features/profile/repositories/profile_repository.dart import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import '../../../fixtures/doubles/insights_doubles.dart'; import 'user_details_screen_smoke_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) @@ -80,12 +81,7 @@ void main() { return Portal( child: MaterialApp( theme: ThemeHelper().themeData(), - localizationsDelegates: const [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: const [Locale('ru')], home: child, ), @@ -97,10 +93,11 @@ void main() { final cubit = UserDetailsCubit(profileRepository: profileRepository); when(profileRepository.getProfileDetailsBySlug('test-slug')).thenAnswer((_) async => mockProfileDetails); - when(profileRepository.getWeight(period: '1', slug: 'test-slug')).thenAnswer((_) async => mockWeightPoints); - when(profileRepository.getCircumferences(period: '1', slug: 'test-slug')).thenAnswer((_) async => mockCircumferencePoints); + when(profileRepository.getWeight(period: '3', slug: 'test-slug')).thenAnswer((_) async => mockWeightPoints); + when(profileRepository.getCircumferences(period: '3', slug: 'test-slug')).thenAnswer((_) async => mockCircumferencePoints); sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton(() => FakeInsightsRepository()); sl.registerLazySingleton(() => cubit); await tester.pumpWidget(wrap(const UserDetailsScreen(slug: 'test-slug'))); @@ -117,10 +114,11 @@ void main() { final cubit = UserDetailsCubit(profileRepository: profileRepository); when(profileRepository.getProfileDetailsBySlug('test-slug')).thenAnswer((_) async => mockProfileDetails); - when(profileRepository.getWeight(period: '1', slug: 'test-slug')).thenAnswer((_) async => mockWeightPoints); - when(profileRepository.getCircumferences(period: '1', slug: 'test-slug')).thenAnswer((_) async => mockCircumferencePoints); + when(profileRepository.getWeight(period: '3', slug: 'test-slug')).thenAnswer((_) async => mockWeightPoints); + when(profileRepository.getCircumferences(period: '3', slug: 'test-slug')).thenAnswer((_) async => mockCircumferencePoints); sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton(() => FakeInsightsRepository()); sl.registerLazySingleton(() => cubit); await tester.pumpWidget(wrap(const UserDetailsScreen(slug: 'test-slug'))); @@ -136,6 +134,7 @@ void main() { when(profileRepository.getProfileDetailsBySlug('test-slug')).thenThrow(Exception('Error loading profile')); sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton(() => FakeInsightsRepository()); sl.registerLazySingleton(() => cubit); await tester.pumpWidget(wrap(const UserDetailsScreen(slug: 'test-slug'))); diff --git a/test/features/user_details/presentation/widgets/expandable_bouble_test.dart b/test/features/user_details/presentation/widgets/expandable_bouble_test.dart index 5c3cd24c..257795c9 100644 --- a/test/features/user_details/presentation/widgets/expandable_bouble_test.dart +++ b/test/features/user_details/presentation/widgets/expandable_bouble_test.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/user_details/presentation/widgets/expandable_bouble.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/video_calls/recordings/models/video_call_recording_model_test.dart b/test/features/video_calls/recordings/models/video_call_recording_model_test.dart new file mode 100644 index 00000000..03f7892d --- /dev/null +++ b/test/features/video_calls/recordings/models/video_call_recording_model_test.dart @@ -0,0 +1,47 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:eatvio_app/features/video_calls/recordings/models/recording_duration_formatter.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('VideoCallRecordingsPagination', () { + test('parses fixture with ready and in_progress items', () { + final json = jsonDecode( + File('test/fixtures/video_call_recordings/recordings_page.json').readAsStringSync(), + ) as Map; + + final page = VideoCallRecordingsPagination.fromJson(json); + + expect(page.data, hasLength(2)); + expect(page.meta.currentPage, 1); + expect(page.meta.lastPage, 1); + expect(page.meta.perPage, 20); + + final ready = page.data.first; + expect(ready.id, 123); + expect(ready.isReady, isTrue); + expect(ready.durationSeconds, 187); + expect(ready.fileUrl, isNotNull); + expect(ready.counterpart?.name, 'Иван Петров'); + expect(ready.counterpart?.slug, 'ivan-petrov'); + + final processing = page.data.last; + expect(processing.isInProgress, isTrue); + expect(processing.durationSeconds, isNull); + expect(processing.fileUrl, isNull); + expect(processing.counterpart, isNull); + expect(processing.previewUrl, contains('placeholder')); + }); + }); + + group('formatRecordingDuration', () { + test('formats seconds and hours', () { + expect(formatRecordingDuration(null), ''); + expect(formatRecordingDuration(5), '00:05'); + expect(formatRecordingDuration(187), '03:07'); + expect(formatRecordingDuration(3661), '1:01:01'); + }); + }); +} diff --git a/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart b/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart new file mode 100644 index 00000000..62337ff2 --- /dev/null +++ b/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart @@ -0,0 +1,215 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_status.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/video_call_recording_file_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockRecordingsRepository extends Mock implements VideoCallRecordingsRepository {} + +void main() { + setUpAll(() { + registerFallbackValue((int _, int _) {}); + }); + + late _MockRecordingsRepository repository; + late VideoCallRecordingsCubit cubit; + + VideoCallRecordingsPagination page({ + required int currentPage, + required int lastPage, + required List data, + }) { + return VideoCallRecordingsPagination( + data: data, + links: const Links( + first: 'https://example.com?page=1', + last: 'https://example.com?page=2', + prev: null, + next: null, + ), + meta: Meta( + currentPage: currentPage, + from: 1, + lastPage: lastPage, + links: const [], + perPage: 20, + to: data.length, + total: data.length, + ), + ); + } + + VideoCallRecordingModel recording(int id) { + return VideoCallRecordingModel( + id: id, + status: RecordingStatus.ready, + createdAt: DateTime.utc(2026, 9, 21, 10), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/api/video-call/recordings/$id/file', + ); + } + + setUp(() { + repository = _MockRecordingsRepository(); + cubit = VideoCallRecordingsCubit(repository: repository); + }); + + tearDown(() async { + await cubit.close(); + }); + + test('load fills recordings', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 1, data: [recording(1)]), + ); + + await cubit.load(); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.recordings, hasLength(1)); + expect(cubit.state.error, isNull); + }); + + test('setPeriod resets to page 1 and reloads', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]), + ); + when( + () => repository.getRecordings(page: 1, period: RecordingPeriod.week), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 1, data: [recording(2)]), + ); + + await cubit.load(); + await cubit.setPeriod(RecordingPeriod.week); + + expect(cubit.state.period, RecordingPeriod.week); + expect(cubit.state.currentPage, 1); + expect(cubit.state.recordings.single.id, 2); + verify(() => repository.getRecordings(page: 1, period: RecordingPeriod.week)).called(1); + }); + + test('loadNextPage appends recordings', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]), + ); + when( + () => repository.getRecordings(page: 2, period: null), + ).thenAnswer( + (_) async => page(currentPage: 2, lastPage: 2, data: [recording(2)]), + ); + + await cubit.load(); + await cubit.loadNextPage(); + + expect(cubit.state.recordings.map((e) => e.id), [1, 2]); + expect(cubit.state.currentPage, 2); + }); + + test('ignores a stale page after the period changes', () async { + final first = Completer(); + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer((_) => first.future); + when( + () => repository.getRecordings(page: 1, period: RecordingPeriod.week), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 1, data: [recording(2)]), + ); + + final pending = cubit.load(); + await cubit.setPeriod(RecordingPeriod.week); + first.complete(page(currentPage: 1, lastPage: 1, data: [recording(1)])); + await pending; + + expect(cubit.state.period, RecordingPeriod.week); + expect(cubit.state.recordings.single.id, 2); + expect(cubit.state.error, isNull); + }); + + test('downloadRecording exposes progress then clears it', () async { + when( + () => repository.downloadRecordingFile( + fileUrl: any(named: 'fileUrl'), + recordingId: any(named: 'recordingId'), + onProgress: any(named: 'onProgress'), + ), + ).thenAnswer((invocation) async { + final onProgress = + invocation.namedArguments[#onProgress] as RecordingDownloadProgress?; + onProgress?.call(25, 100); + await Future.delayed(Duration.zero); + onProgress?.call(100, 100); + await Future.delayed(Duration.zero); + return '/storage/emulated/0/Download/recording_7.mp4'; + }); + + final progressValues = []; + final sub = cubit.stream.listen((state) { + if (state.downloadingRecordingId != null || state.downloadProgress != null) { + progressValues.add(state.downloadProgress); + } + }); + + final saved = await cubit.downloadRecording( + recordingId: 7, + fileUrl: 'https://example.com/file', + ); + await Future.delayed(Duration.zero); + await sub.cancel(); + + expect(saved, isA()); + expect( + (saved as RecordingDownloadSaved).path, + '/storage/emulated/0/Download/recording_7.mp4', + ); + expect(progressValues, containsAll([0.0, 0.25, 1.0])); + expect(cubit.state.downloadingRecordingId, isNull); + expect(cubit.state.downloadProgress, isNull); + }); + + test('second download while one is running is not a failure', () async { + final gate = Completer(); + when( + () => repository.downloadRecordingFile( + fileUrl: any(named: 'fileUrl'), + recordingId: any(named: 'recordingId'), + onProgress: any(named: 'onProgress'), + ), + ).thenAnswer((_) => gate.future); + + final first = cubit.downloadRecording( + recordingId: 7, + fileUrl: 'https://example.com/file', + ); + final second = await cubit.downloadRecording( + recordingId: 8, + fileUrl: 'https://example.com/other', + ); + + expect(second, isA()); + expect(cubit.state.downloadError, isNull); + + gate.complete('/storage/emulated/0/Download/recording_7.mp4'); + expect(await first, isA()); + verify( + () => repository.downloadRecordingFile( + fileUrl: any(named: 'fileUrl'), + recordingId: any(named: 'recordingId'), + onProgress: any(named: 'onProgress'), + ), + ).called(1); + }); +} diff --git a/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart b/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart new file mode 100644 index 00000000..b672d460 --- /dev/null +++ b/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart @@ -0,0 +1,86 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_status.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +void main() { + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: child), + ); + } + + testWidgets('ready card shows download and play', (tester) async { + await mockNetworkImagesFor(() async { + final recording = VideoCallRecordingModel( + id: 1, + status: RecordingStatus.ready, + durationSeconds: 125, + createdAt: DateTime.utc(2026, 5, 12, 14), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/file', + counterpart: const VideoCallRecordingCounterpartModel(name: 'Сидни', slug: 'sydney', profilePhotoUrl: 'https://example.com/a.jpg'), + ); + + var played = false; + var downloaded = false; + + await tester.pumpWidget(wrap(RecordingCard(recording: recording, onPlay: () => played = true, onDownload: () => downloaded = true))); + await tester.pumpAndSettle(); + + expect(find.text('Скачать'), findsOneWidget); + expect(find.text('02:05'), findsOneWidget); + expect(find.textContaining('обрабатывается'), findsNothing); + + await tester.tap(find.byIcon(Icons.play_arrow)); + await tester.tap(find.text('Скачать')); + expect(played, isTrue); + expect(downloaded, isTrue); + }); + }); + + testWidgets('ready card shows download percent progress', (tester) async { + await mockNetworkImagesFor(() async { + final recording = VideoCallRecordingModel( + id: 1, + status: RecordingStatus.ready, + durationSeconds: 125, + createdAt: DateTime.utc(2026, 5, 12, 14), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/file', + ); + + await tester.pumpWidget(wrap(RecordingCard(recording: recording, isDownloading: true, downloadProgress: 0.42, onPlay: () {}, onDownload: () {}))); + await tester.pump(); + + expect(find.text('Скачать'), findsNothing); + expect(find.textContaining('42%'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + }); + }); + + testWidgets('in_progress card hides download and play', (tester) async { + await mockNetworkImagesFor(() async { + final recording = VideoCallRecordingModel( + id: 2, + status: RecordingStatus.inProgress, + createdAt: DateTime.utc(2026, 5, 12, 14), + previewUrl: 'https://example.com/placeholder.png', + ); + + await tester.pumpWidget(wrap(RecordingCard(recording: recording, onPlay: () {}, onDownload: () {}))); + await tester.pump(); + + expect(find.textContaining('обрабатывается'), findsOneWidget); + expect(find.text('Скачать'), findsNothing); + expect(find.byIcon(Icons.play_arrow), findsNothing); + }); + }); +} diff --git a/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart b/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart new file mode 100644 index 00000000..b06c68d4 --- /dev/null +++ b/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart @@ -0,0 +1,54 @@ +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/video_call_recording_file_service.dart'; +import 'package:eatvio_app/features/video_calls/services/video_call_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockVideoCallService extends Mock implements VideoCallService {} + +class _MockFileService extends Mock implements VideoCallRecordingFileService {} + +void main() { + late _MockVideoCallService videoCallService; + late _MockFileService fileService; + late VideoCallRecordingsRepository repository; + + setUpAll(() { + registerFallbackValue((int _, int _) {}); + }); + + setUp(() { + videoCallService = _MockVideoCallService(); + fileService = _MockFileService(); + repository = VideoCallRecordingsRepository( + videoCallService: videoCallService, + fileService: fileService, + ); + }); + + test('downloadRecordingFile delegates to file service with progress', () async { + RecordingDownloadProgress? captured; + + when( + () => fileService.downloadRecordingFile( + fileUrl: any(named: 'fileUrl'), + recordingId: any(named: 'recordingId'), + onProgress: any(named: 'onProgress'), + ), + ).thenAnswer((invocation) async { + captured = invocation.namedArguments[#onProgress] as RecordingDownloadProgress?; + captured?.call(10, 20); + return '/storage/emulated/0/Download/recording_1.mp4'; + }); + + final progress = <(int, int)>[]; + final result = await repository.downloadRecordingFile( + fileUrl: 'https://example.com/file', + recordingId: 1, + onProgress: (received, total) => progress.add((received, total)), + ); + + expect(result, '/storage/emulated/0/Download/recording_1.mp4'); + expect(progress, [(10, 20)]); + }); +} diff --git a/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart b/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart new file mode 100644 index 00000000..760f1cee --- /dev/null +++ b/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart @@ -0,0 +1,163 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_not_ready_exception.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/public_downloads_saver.dart'; +import 'package:eatvio_app/features/video_calls/recordings/services/video_call_recording_file_service.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockDio extends Mock implements Dio {} + +class _FakeDownloadsSaver extends Fake implements PublicDownloadsSaver { + String? lastSourcePath; + String? lastFileName; + + @override + Future saveToDownloads({ + required String sourcePath, + required String fileName, + String mimeType = 'video/mp4', + String subfolder = PublicDownloadsSaver.appFolderName, + }) async { + lastSourcePath = sourcePath; + lastFileName = fileName; + return 'content://downloads/Itvio/$fileName'; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() { + registerFallbackValue(''); + registerFallbackValue(Options()); + + const MethodChannel pathProviderChannel = + MethodChannel('plugins.flutter.io/path_provider'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(pathProviderChannel, (call) async { + switch (call.method) { + case 'getTemporaryDirectory': + case 'getApplicationDocumentsDirectory': + return '/tmp'; + default: + return null; + } + }); + }); + + late _MockDio dio; + late _FakeDownloadsSaver downloadsSaver; + late VideoCallRecordingFileService service; + + setUp(() { + dio = _MockDio(); + downloadsSaver = _FakeDownloadsSaver(); + service = VideoCallRecordingFileService( + dio: dio, + downloadsSaver: downloadsSaver, + ); + }); + + test('maps 409 to RecordingNotReadyException before save', () async { + when( + () => dio.download( + any(), + any(), + cancelToken: any(named: 'cancelToken'), + onReceiveProgress: any(named: 'onReceiveProgress'), + options: any(named: 'options'), + ), + ).thenThrow( + DioException( + requestOptions: RequestOptions(path: '/file'), + response: Response( + requestOptions: RequestOptions(path: '/file'), + statusCode: 409, + data: { + 'message': 'Not ready', + 'code': RecordingNotReadyException.code, + }, + ), + type: DioExceptionType.badResponse, + ), + ); + + await expectLater( + service.downloadRecordingFile( + fileUrl: 'https://example.com/api/video-call/recordings/1/file', + recordingId: 1, + ), + throwsA(isA()), + ); + }); + + test('maps a 409 byte body to RecordingNotReadyException', () async { + when( + () => dio.download( + any(), + any(), + cancelToken: any(named: 'cancelToken'), + onReceiveProgress: any(named: 'onReceiveProgress'), + options: any(named: 'options'), + ), + ).thenThrow( + DioException( + requestOptions: RequestOptions(path: '/file'), + response: Response( + requestOptions: RequestOptions(path: '/file'), + statusCode: 409, + data: utf8.encode( + '{"message":"Not ready","code":"${RecordingNotReadyException.code}"}', + ), + ), + type: DioExceptionType.badResponse, + ), + ); + + await expectLater( + service.downloadRecordingFile( + fileUrl: 'https://example.com/api/video-call/recordings/1/file', + recordingId: 1, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Not ready', + ), + ), + ); + }); + + test('saves downloaded file via downloads saver', () async { + when( + () => dio.download( + any(), + any(), + cancelToken: any(named: 'cancelToken'), + onReceiveProgress: any(named: 'onReceiveProgress'), + options: any(named: 'options'), + ), + ).thenAnswer((invocation) async { + final path = invocation.positionalArguments[1] as String; + await File(path).writeAsBytes([1, 2, 3]); + return Response( + requestOptions: RequestOptions(path: '/file'), + statusCode: 200, + ); + }); + + final saved = await service.downloadRecordingFile( + fileUrl: 'https://example.com/api/video-call/recordings/1/file', + recordingId: 1, + ); + + expect(downloadsSaver.lastFileName, 'recording_1.mp4'); + expect(saved, contains('Itvio')); + expect(File(downloadsSaver.lastSourcePath!).existsSync(), isFalse); + }); +} diff --git a/test/features/video_calls/widgets/video_call_controls_test.dart b/test/features/video_calls/widgets/video_call_controls_test.dart index b3317b3c..07850395 100644 --- a/test/features/video_calls/widgets/video_call_controls_test.dart +++ b/test/features/video_calls/widgets/video_call_controls_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_controls.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/video_calls/widgets/video_call_name_label_test.dart b/test/features/video_calls/widgets/video_call_name_label_test.dart index 6332785e..8562ea52 100644 --- a/test/features/video_calls/widgets/video_call_name_label_test.dart +++ b/test/features/video_calls/widgets/video_call_name_label_test.dart @@ -1,7 +1,6 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_name_chips.dart'; import 'package:eatvio_app/generated/l10n.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -9,11 +8,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Scaffold( - body: Stack( - children: [ - VideoCallParticipantNameLabel(name: 'Alex'), - ], - ), + body: Stack(children: [VideoCallParticipantNameLabel(name: 'Alex')]), ), ), ); @@ -24,21 +19,10 @@ void main() { testWidgets('VideoCallParticipantNameLabel renders consultant role above name', (tester) async { await tester.pumpWidget( MaterialApp( - localizationsDelegates: const [ - S.delegate, - ...GlobalMaterialLocalizations.delegates, - GlobalWidgetsLocalizations.delegate, - ], + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: const Scaffold( - body: Stack( - children: [ - VideoCallParticipantNameLabel( - name: 'Alex', - isConsultant: true, - ), - ], - ), + body: Stack(children: [VideoCallParticipantNameLabel(name: 'Alex', isConsultant: true)]), ), ), ); diff --git a/test/features/video_calls/widgets/video_call_no_video_background_test.dart b/test/features/video_calls/widgets/video_call_no_video_background_test.dart index bdb5a3d6..a387b2f6 100644 --- a/test/features/video_calls/widgets/video_call_no_video_background_test.dart +++ b/test/features/video_calls/widgets/video_call_no_video_background_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_no_video_background.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { diff --git a/test/features/video_calls/widgets/video_call_remote_video_stage_test.dart b/test/features/video_calls/widgets/video_call_remote_video_stage_test.dart index c34840f9..e2617226 100644 --- a/test/features/video_calls/widgets/video_call_remote_video_stage_test.dart +++ b/test/features/video_calls/widgets/video_call_remote_video_stage_test.dart @@ -1,7 +1,7 @@ import 'dart:collection'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_remote_video_stage.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:livekit_client/livekit_client.dart' as lk; import 'package:mockito/annotations.dart'; diff --git a/test/features/video_calls/widgets/video_call_stage_layout_test.dart b/test/features/video_calls/widgets/video_call_stage_layout_test.dart index ba3afd89..aa543e73 100644 --- a/test/features/video_calls/widgets/video_call_stage_layout_test.dart +++ b/test/features/video_calls/widgets/video_call_stage_layout_test.dart @@ -1,7 +1,7 @@ import 'dart:collection'; import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_stage_layout.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:livekit_client/livekit_client.dart' as lk; import 'package:mockito/annotations.dart'; diff --git a/test/features/video_calls/widgets/video_call_top_overlay_test.dart b/test/features/video_calls/widgets/video_call_top_overlay_test.dart index f6dc791a..80de255c 100644 --- a/test/features/video_calls/widgets/video_call_top_overlay_test.dart +++ b/test/features/video_calls/widgets/video_call_top_overlay_test.dart @@ -1,5 +1,5 @@ import 'package:eatvio_app/features/video_calls/presentation/widgets/video_call_top_overlay.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_svg/flutter_svg.dart'; diff --git a/test/features/welcome/presentation/pages/welcome_screen_test.dart b/test/features/welcome/presentation/pages/welcome_screen_test.dart index 406d7c2b..6bc7670c 100644 --- a/test/features/welcome/presentation/pages/welcome_screen_test.dart +++ b/test/features/welcome/presentation/pages/welcome_screen_test.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/core/prefs.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:eatvio_app/features/welcome/presentation/pages/welcome_screen.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; diff --git a/test/fixtures/doubles/insights_doubles.dart b/test/fixtures/doubles/insights_doubles.dart new file mode 100644 index 00000000..5e07a3a8 --- /dev/null +++ b/test/fixtures/doubles/insights_doubles.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:eatvio_app/features/insights/models/insights_payload_model.dart'; +import 'package:eatvio_app/features/insights/models/insights_period.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; + +InsightsPayloadModel loadInsightsPayloadFixture([ + String name = 'insights_payload.json', +]) { + final json = + jsonDecode(File('test/fixtures/insights/$name').readAsStringSync()) + as Map; + return InsightsPayloadModel.fromJson(json); +} + +/// Подмена [InsightsRepository] для виджет-тестов: без сети, с журналом вызовов. +class FakeInsightsRepository extends Fake implements InsightsRepository { + FakeInsightsRepository({ + InsightsPayloadModel? payload, + this.error, + this.heightCm = 176, + }) : payload = payload ?? loadInsightsPayloadFixture(); + + InsightsPayloadModel payload; + + /// Ответ [fetchIntra] по запрошенной дате (`YYYY-MM-DD`); для остальных дат + /// берётся `payload.intra`. + final Map intraByDate = {}; + + /// Если задан — выбрасывается из [fetchIntra]. + Object? intraError; + + /// Если задан — выбрасывается из [getInsights] (например, [InsightsForbidden]). + Object? error; + int? heightCm; + + /// Задержка ответа [fetchInsights] (для тестов гонок). + Duration? fetchInsightsDelay; + + /// Задержка ответа [fetchIntra] (для тестов гонок). + Duration? fetchIntraDelay; + + final List<({String? slug, BodyPeriod period})> insightsRequests = []; + final List< + ({ + String? slug, + BodyPeriod bodyPeriod, + DailyPeriod dailyPeriod, + String? intraDate, + }) + > + serverRequests = []; + final List<({String? slug, String? date})> intraRequests = []; + final List addedWeights = []; + final List<({int chest, int waist, int hip})> addedCircumferences = []; + + @override + Future getHeightCm({String? slug}) async => heightCm; + + @override + Future getInsights({ + String? slug, + required BodyPeriod bodyPeriod, + int? heightCm, + }) async { + insightsRequests.add((slug: slug, period: bodyPeriod)); + final failure = error; + if (failure != null) { + throw failure; + } + return payload; + } + + @override + Future fetchInsights({ + String? slug, + required BodyPeriod bodyPeriod, + required DailyPeriod dailyPeriod, + String? intraDate, + }) async { + serverRequests.add(( + slug: slug, + bodyPeriod: bodyPeriod, + dailyPeriod: dailyPeriod, + intraDate: intraDate, + )); + final delay = fetchInsightsDelay; + if (delay != null) { + await Future.delayed(delay); + } + final failure = error; + if (failure != null) { + throw failure; + } + return payload; + } + + @override + Future fetchIntra({String? slug, String? intraDate}) async { + intraRequests.add((slug: slug, date: intraDate)); + final delay = fetchIntraDelay; + if (delay != null) { + await Future.delayed(delay); + } + final failure = intraError ?? error; + if (failure != null) { + throw failure; + } + return intraByDate[intraDate] ?? payload.intra!; + } + + @override + Future addWeight({required double weight}) async { + addedWeights.add(weight); + } + + @override + Future addCircumference({ + required int chestCircumference, + required int waistCircumference, + required int hipCircumference, + }) async { + addedCircumferences.add(( + chest: chestCircumference, + waist: waistCircumference, + hip: hipCircumference, + )); + } +} diff --git a/test/fixtures/doubles/profile_doubles.dart b/test/fixtures/doubles/profile_doubles.dart index dfc8e935..0522fc1d 100644 --- a/test/fixtures/doubles/profile_doubles.dart +++ b/test/fixtures/doubles/profile_doubles.dart @@ -69,7 +69,7 @@ class FixtureChatRepository extends ChatRepository { : super(chatService: _NoopChatService()); @override - Future getChatByUserSlug(String slug) async { + Future getChatByUserSlug(String slug) async { return 'chat-uuid-123'; } } diff --git a/test/fixtures/doubles/session_doubles.dart b/test/fixtures/doubles/session_doubles.dart new file mode 100644 index 00000000..09b07b83 --- /dev/null +++ b/test/fixtures/doubles/session_doubles.dart @@ -0,0 +1,24 @@ +import 'package:eatvio_app/core/session/session_lifecycle_service.dart'; + +class FakeSessionLifecycleService implements SessionLifecycleService { + int onAuthenticatedCalls = 0; + int endSessionCalls = 0; + int logoutCalls = 0; + SessionEndReason? lastEndReason; + + @override + Future onAuthenticated() async { + onAuthenticatedCalls++; + } + + @override + Future endSession({required SessionEndReason reason}) async { + endSessionCalls++; + lastEndReason = reason; + } + + @override + Future logout() async { + logoutCalls++; + } +} diff --git a/test/fixtures/insights/insights_intra_response.json b/test/fixtures/insights/insights_intra_response.json new file mode 100644 index 00000000..efb10df4 --- /dev/null +++ b/test/fixtures/insights/insights_intra_response.json @@ -0,0 +1,46 @@ +{ + "data": { + "intra": { + "bars": [ + { + "x": 8.5, + "p": 120, + "f": 90, + "c": 240 + }, + { + "x": 13, + "p": 160, + "f": 130, + "c": 300 + } + ], + "satiety": [ + { + "x": 8.5, + "y": 3 + }, + { + "x": 13, + "y": 4 + } + ], + "mood": [ + { + "x": 8.5, + "y": 4 + } + ], + "wake": 7.5, + "sleep": 23, + "wakeLabel": "07:30", + "sleepLabel": "23:00", + "wakeText": "Подъём в 07:30", + "sleepText": "Отход ко сну в 23:00", + "date": "2026-11-09", + "maxDate": "2026-11-09", + "dateLabel": "Сегодня", + "isToday": true + } + } +} diff --git a/test/fixtures/insights/insights_intra_response_yesterday.json b/test/fixtures/insights/insights_intra_response_yesterday.json new file mode 100644 index 00000000..21bb45ae --- /dev/null +++ b/test/fixtures/insights/insights_intra_response_yesterday.json @@ -0,0 +1,46 @@ +{ + "data": { + "intra": { + "bars": [ + { + "x": 8.5, + "p": 120, + "f": 90, + "c": 240 + }, + { + "x": 13, + "p": 160, + "f": 130, + "c": 300 + } + ], + "satiety": [ + { + "x": 8.5, + "y": 3 + }, + { + "x": 13, + "y": 4 + } + ], + "mood": [ + { + "x": 8.5, + "y": 4 + } + ], + "wake": 7.5, + "sleep": 23, + "wakeLabel": "07:30", + "sleepLabel": "23:00", + "wakeText": "Подъём в 07:30", + "sleepText": "Отход ко сну в 23:00", + "date": "2026-11-08", + "maxDate": "2026-11-09", + "dateLabel": "8 ноября", + "isToday": false + } + } +} diff --git a/test/fixtures/insights/insights_payload.json b/test/fixtures/insights/insights_payload.json new file mode 100644 index 00000000..98bc004f --- /dev/null +++ b/test/fixtures/insights/insights_payload.json @@ -0,0 +1,122 @@ +{ + "weight": { + "labels": [ + "01.11", + "05.11", + "09.11" + ], + "values": [ + 74.5, + 73.9, + 73.2 + ], + "last": 73.2, + "delta": -1.3, + "headline": "73.2", + "unit": "кг", + "deltaText": "Снизили на 1.3 кг за период" + }, + "bmi": { + "labels": [], + "values": [], + "last": null, + "delta": null, + "headline": "—", + "category": null, + "deltaText": "Укажите рост, чтобы посчитать ИМТ.", + "hint": "" + }, + "measure": { + "labels": [ + "01.11", + "09.11" + ], + "waist": [ + 82, + 80.5 + ], + "chest": [ + 96, + 96 + ], + "hips": [ + 101, + 100 + ], + "headline": "81", + "deltaText": "Талия меньше на 1.5 см за период" + }, + "daily": { + "labels": [ + "03.11", + "04.11", + "05.11" + ], + "kcal": [ + 1850, + 2010, + 1930 + ], + "proteins": [ + 92, + 101, + 96 + ], + "fats": [ + 60, + 66, + 63 + ], + "carbs": [ + 210, + 222, + 215 + ], + "average": 1930, + "percent": 5, + "headline": "1930", + "deltaText": "Калораж вырос на 5% за период" + }, + "intra": { + "bars": [ + { + "x": 8.5, + "p": 120, + "f": 90, + "c": 240 + }, + { + "x": 13, + "p": 160, + "f": 130, + "c": 300 + } + ], + "satiety": [ + { + "x": 8.5, + "y": 3 + }, + { + "x": 13, + "y": 4 + } + ], + "mood": [ + { + "x": 8.5, + "y": 4 + } + ], + "wake": 7.5, + "sleep": 23, + "wakeLabel": "07:30", + "sleepLabel": "23:00", + "wakeText": "Подъём в 07:30", + "sleepText": "Отход ко сну в 23:00", + "date": "2026-11-09", + "maxDate": "2026-11-09", + "dateLabel": "Сегодня", + "isToday": true + } +} diff --git a/test/fixtures/insights/insights_payload_minimal.json b/test/fixtures/insights/insights_payload_minimal.json new file mode 100644 index 00000000..c9b596bf --- /dev/null +++ b/test/fixtures/insights/insights_payload_minimal.json @@ -0,0 +1,38 @@ +{ + "weight": { + "labels": [], + "values": [], + "last": null, + "delta": null, + "headline": "—", + "unit": "кг", + "deltaText": "Недостаточно данных" + }, + "bmi": { + "labels": [], + "values": [], + "headline": "—", + "deltaText": "Укажите рост, чтобы посчитать ИМТ.", + "hint": "" + }, + "measure": { + "labels": [], + "waist": [], + "chest": [], + "hips": [], + "headline": "—", + "deltaText": "Недостаточно данных" + }, + "daily": null, + "intra": { + "bars": [], + "satiety": [], + "mood": [], + "wake": null, + "sleep": null, + "date": "2026-11-09", + "maxDate": "2026-11-09", + "dateLabel": "Сегодня", + "isToday": true + } +} diff --git a/test/fixtures/insights/insights_response.json b/test/fixtures/insights/insights_response.json new file mode 100644 index 00000000..7a562d58 --- /dev/null +++ b/test/fixtures/insights/insights_response.json @@ -0,0 +1,124 @@ +{ + "data": { + "weight": { + "labels": [ + "01.11", + "05.11", + "09.11" + ], + "values": [ + 74.5, + 73.9, + 73.2 + ], + "last": 73.2, + "delta": -1.3, + "headline": "73.2", + "unit": "кг", + "deltaText": "Снизили на 1.3 кг за период" + }, + "bmi": { + "labels": [], + "values": [], + "last": null, + "delta": null, + "headline": "—", + "category": null, + "deltaText": "Укажите рост, чтобы посчитать ИМТ.", + "hint": "" + }, + "measure": { + "labels": [ + "01.11", + "09.11" + ], + "waist": [ + 82, + 80.5 + ], + "chest": [ + 96, + 96 + ], + "hips": [ + 101, + 100 + ], + "headline": "81", + "deltaText": "Талия меньше на 1.5 см за период" + }, + "daily": { + "labels": [ + "03.11", + "04.11", + "05.11" + ], + "kcal": [ + 1850, + 2010, + 1930 + ], + "proteins": [ + 92, + 101, + 96 + ], + "fats": [ + 60, + 66, + 63 + ], + "carbs": [ + 210, + 222, + 215 + ], + "average": 1930, + "percent": 5, + "headline": "1930", + "deltaText": "Калораж вырос на 5% за период" + }, + "intra": { + "bars": [ + { + "x": 8.5, + "p": 120, + "f": 90, + "c": 240 + }, + { + "x": 13, + "p": 160, + "f": 130, + "c": 300 + } + ], + "satiety": [ + { + "x": 8.5, + "y": 3 + }, + { + "x": 13, + "y": 4 + } + ], + "mood": [ + { + "x": 8.5, + "y": 4 + } + ], + "wake": 7.5, + "sleep": 23, + "wakeLabel": "07:30", + "sleepLabel": "23:00", + "wakeText": "Подъём в 07:30", + "sleepText": "Отход ко сну в 23:00", + "date": "2026-11-09", + "maxDate": "2026-11-09", + "dateLabel": "Сегодня", + "isToday": true + } + } +} diff --git a/test/fixtures/insights/insights_response_empty.json b/test/fixtures/insights/insights_response_empty.json new file mode 100644 index 00000000..ae96e9c1 --- /dev/null +++ b/test/fixtures/insights/insights_response_empty.json @@ -0,0 +1,40 @@ +{ + "data": { + "weight": { + "labels": [], + "values": [], + "last": null, + "delta": null, + "headline": "—", + "unit": "кг", + "deltaText": "Недостаточно данных" + }, + "bmi": { + "labels": [], + "values": [], + "headline": "—", + "deltaText": "Укажите рост, чтобы посчитать ИМТ.", + "hint": "" + }, + "measure": { + "labels": [], + "waist": [], + "chest": [], + "hips": [], + "headline": "—", + "deltaText": "Недостаточно данных" + }, + "daily": null, + "intra": { + "bars": [], + "satiety": [], + "mood": [], + "wake": null, + "sleep": null, + "date": "2026-11-09", + "maxDate": "2026-11-09", + "dateLabel": "Сегодня", + "isToday": true + } + } +} diff --git a/test/fixtures/video_call_recordings/recordings_page.json b/test/fixtures/video_call_recordings/recordings_page.json new file mode 100644 index 00000000..b2ed19e2 --- /dev/null +++ b/test/fixtures/video_call_recordings/recordings_page.json @@ -0,0 +1,44 @@ +{ + "data": [ + { + "id": 123, + "status": "ready", + "duration_seconds": 187, + "size_bytes": 15728640, + "created_at": "2026-09-21T10:00:00.000000Z", + "preview_url": "https://example.com/storage/recordings/123/preview.jpg", + "file_url": "https://example.com/api/video-call/recordings/123/file", + "counterpart": { + "name": "Иван Петров", + "slug": "ivan-petrov", + "profile_photo_url": "https://example.com/storage/users/ivan.jpg" + } + }, + { + "id": 122, + "status": "in_progress", + "duration_seconds": null, + "size_bytes": null, + "created_at": "2026-09-21T09:00:00.000000Z", + "preview_url": "https://example.com/images/element-image-placeholder.png", + "file_url": null, + "counterpart": null + } + ], + "links": { + "first": "https://example.com/api/video-call/recordings?page=1", + "last": "https://example.com/api/video-call/recordings?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [], + "path": "https://example.com/api/video-call/recordings", + "per_page": 20, + "to": 2, + "total": 2 + } +} diff --git a/test/helpers/webview_test_helper.dart b/test/helpers/webview_test_helper.dart index ef55f6c2..f466b10d 100644 --- a/test/helpers/webview_test_helper.dart +++ b/test/helpers/webview_test_helper.dart @@ -1,4 +1,4 @@ -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; /// Helper class to set up WebViewPlatform for testing