From 20f383dd62fb663083c04fccea621860b210fdc9 Mon Sep 17 00:00:00 2001 From: bastien Date: Sun, 28 Jun 2026 12:29:06 +0200 Subject: [PATCH 1/7] initial commit --- .gitignore | 39 ++ .metadata | 33 + README.md | 117 +++- analysis_options.yaml | 6 + android/.gitignore | 14 + android/app/build.gradle.kts | 45 ++ android/app/src/debug/AndroidManifest.xml | 4 + android/app/src/main/AndroidManifest.xml | 45 ++ .../fr/laverie/laverie_mobile/MainActivity.kt | 5 + .../res/drawable-v21/launch_background.xml | 12 + .../main/res/drawable/launch_background.xml | 12 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 544 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 442 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 721 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 1031 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 1443 bytes .../app/src/main/res/values-night/styles.xml | 18 + android/app/src/main/res/values/styles.xml | 18 + android/app/src/profile/AndroidManifest.xml | 7 + android/build.gradle.kts | 24 + android/gradle.properties | 6 + .../gradle/wrapper/gradle-wrapper.properties | 5 + android/settings.gradle.kts | 26 + ios/.gitignore | 34 + ios/Flutter/AppFrameworkInfo.plist | 24 + ios/Flutter/Debug.xcconfig | 1 + ios/Flutter/Release.xcconfig | 1 + ios/Runner.xcodeproj/project.pbxproj | 644 ++++++++++++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../xcshareddata/xcschemes/Runner.xcscheme | 119 ++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + ios/Runner/AppDelegate.swift | 16 + .../AppIcon.appiconset/Contents.json | 122 ++++ .../Icon-App-1024x1024@1x.png | Bin 0 -> 10932 bytes .../AppIcon.appiconset/Icon-App-20x20@1x.png | Bin 0 -> 295 bytes .../AppIcon.appiconset/Icon-App-20x20@2x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-20x20@3x.png | Bin 0 -> 450 bytes .../AppIcon.appiconset/Icon-App-29x29@1x.png | Bin 0 -> 282 bytes .../AppIcon.appiconset/Icon-App-29x29@2x.png | Bin 0 -> 462 bytes .../AppIcon.appiconset/Icon-App-29x29@3x.png | Bin 0 -> 704 bytes .../AppIcon.appiconset/Icon-App-40x40@1x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-40x40@2x.png | Bin 0 -> 586 bytes .../AppIcon.appiconset/Icon-App-40x40@3x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@2x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@3x.png | Bin 0 -> 1674 bytes .../AppIcon.appiconset/Icon-App-76x76@1x.png | Bin 0 -> 762 bytes .../AppIcon.appiconset/Icon-App-76x76@2x.png | Bin 0 -> 1226 bytes .../Icon-App-83.5x83.5@2x.png | Bin 0 -> 1418 bytes .../LaunchImage.imageset/Contents.json | 23 + .../LaunchImage.imageset/LaunchImage.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@2x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@3x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/README.md | 5 + ios/Runner/Base.lproj/LaunchScreen.storyboard | 37 + ios/Runner/Base.lproj/Main.storyboard | 26 + ios/Runner/Info.plist | 70 ++ ios/Runner/Runner-Bridging-Header.h | 1 + ios/Runner/SceneDelegate.swift | 6 + ios/RunnerTests/RunnerTests.swift | 12 + lib/core/api/api_client.dart | 99 +++ lib/core/api/api_endpoints.dart | 32 + lib/core/auth/auth_provider.dart | 158 +++++ lib/core/auth/auth_repository.dart | 125 ++++ lib/core/config/app_config.dart | 40 ++ lib/core/config/secure_storage_config.dart | 14 + lib/core/platform/app_platform.dart | 39 ++ lib/core/router/app_router.dart | 96 +++ lib/core/theme/app_theme.dart | 46 ++ lib/features/auth/domain/auth_user.dart | 53 ++ .../auth/presentation/login_screen.dart | 131 ++++ .../auth/presentation/register_screen.dart | 127 ++++ lib/features/booking/domain/booking.dart | 38 ++ .../booking/presentation/bookings_screen.dart | 87 +++ .../data/establishment_repository.dart | 58 ++ .../establishments/domain/establishment.dart | 110 +++ .../establishment_detail_screen.dart | 113 +++ .../home/presentation/home_screen.dart | 106 +++ .../profile/presentation/profile_screen.dart | 82 +++ .../wallet/data/wallet_repository.dart | 58 ++ lib/features/wallet/domain/wallet.dart | 49 ++ .../wallet/presentation/wallet_screen.dart | 116 ++++ lib/features/wash/domain/wash.dart | 41 ++ .../wash/presentation/wash_screen.dart | 104 +++ lib/main.dart | 43 ++ pubspec.lock | 551 +++++++++++++++ pubspec.yaml | 30 + scripts/bootstrap_platforms.ps1 | 36 + scripts/bootstrap_platforms.sh | 35 + test/widget_test.dart | 30 + 93 files changed, 4269 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 .metadata create mode 100644 analysis_options.yaml create mode 100644 android/.gitignore create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/src/debug/AndroidManifest.xml create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/kotlin/fr/laverie/laverie_mobile/MainActivity.kt create mode 100644 android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 android/app/src/main/res/drawable/launch_background.xml create mode 100644 android/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/values-night/styles.xml create mode 100644 android/app/src/main/res/values/styles.xml create mode 100644 android/app/src/profile/AndroidManifest.xml create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100644 android/settings.gradle.kts create mode 100644 ios/.gitignore create mode 100644 ios/Flutter/AppFrameworkInfo.plist create mode 100644 ios/Flutter/Debug.xcconfig create mode 100644 ios/Flutter/Release.xcconfig create mode 100644 ios/Runner.xcodeproj/project.pbxproj create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme create mode 100644 ios/Runner.xcworkspace/contents.xcworkspacedata create mode 100644 ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 ios/Runner/AppDelegate.swift create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md create mode 100644 ios/Runner/Base.lproj/LaunchScreen.storyboard create mode 100644 ios/Runner/Base.lproj/Main.storyboard create mode 100644 ios/Runner/Info.plist create mode 100644 ios/Runner/Runner-Bridging-Header.h create mode 100644 ios/Runner/SceneDelegate.swift create mode 100644 ios/RunnerTests/RunnerTests.swift create mode 100644 lib/core/api/api_client.dart create mode 100644 lib/core/api/api_endpoints.dart create mode 100644 lib/core/auth/auth_provider.dart create mode 100644 lib/core/auth/auth_repository.dart create mode 100644 lib/core/config/app_config.dart create mode 100644 lib/core/config/secure_storage_config.dart create mode 100644 lib/core/platform/app_platform.dart create mode 100644 lib/core/router/app_router.dart create mode 100644 lib/core/theme/app_theme.dart create mode 100644 lib/features/auth/domain/auth_user.dart create mode 100644 lib/features/auth/presentation/login_screen.dart create mode 100644 lib/features/auth/presentation/register_screen.dart create mode 100644 lib/features/booking/domain/booking.dart create mode 100644 lib/features/booking/presentation/bookings_screen.dart create mode 100644 lib/features/establishments/data/establishment_repository.dart create mode 100644 lib/features/establishments/domain/establishment.dart create mode 100644 lib/features/establishments/presentation/establishment_detail_screen.dart create mode 100644 lib/features/home/presentation/home_screen.dart create mode 100644 lib/features/profile/presentation/profile_screen.dart create mode 100644 lib/features/wallet/data/wallet_repository.dart create mode 100644 lib/features/wallet/domain/wallet.dart create mode 100644 lib/features/wallet/presentation/wallet_screen.dart create mode 100644 lib/features/wash/domain/wash.dart create mode 100644 lib/features/wash/presentation/wash_screen.dart create mode 100644 lib/main.dart create mode 100644 pubspec.lock create mode 100644 pubspec.yaml create mode 100644 scripts/bootstrap_platforms.ps1 create mode 100644 scripts/bootstrap_platforms.sh create mode 100644 test/widget_test.dart diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c612c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +# Application mobile Laverie — Android + iOS uniquement (pas de web Flutter). + +# Plateformes générées par Flutter (ne pas versionner entièrement si préféré) +/android/.gradle/ +/android/app/debug/ +/android/app/profile/ +/android/app/release/ +/android/local.properties +/android/**/GeneratedPluginRegistrant.java +/android/**/GeneratedPluginRegistrant.kt + +/ios/Pods/ +/ios/.symlinks/ +/ios/Flutter/Flutter.framework +/ios/Flutter/Flutter.podspec +/ios/Flutter/Generated.xcconfig +/ios/Flutter/ephemeral/ +/ios/Runner/GeneratedPluginRegistrant.* + +# Build +/build/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +*.iml + +# IDE +.idea/ +.vscode/ +*.swp + +# macOS (non ciblé) +/macos/ +/web/ +/linux/ +/windows/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..954d671 --- /dev/null +++ b/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "ad70ec4617166f1c38e5d2bfd388af71fda14f06" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + base_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + - platform: android + create_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + base_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + - platform: ios + create_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + base_revision: ad70ec4617166f1c38e5d2bfd388af71fda14f06 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md index 83cc4a8..15dd283 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,117 @@ -# mobile +# Laverie Mobile +Application **native** Android et iOS pour Laverie Connectée — consultation des laveries, portefeuille, réservations et lavages. + +> **Pas de cible web Flutter.** Le back-office web est géré séparément (Laravel + Inertia). Cette app est mobile-first : **Android en priorité**, **iOS prévu** dès le départ (même codebase). + +## Prérequis + +| Outil | Android | iOS (plus tard) | +|-------|---------|-----------------| +| Flutter SDK 3.2+ | Oui | Oui (sur macOS) | +| Android Studio + SDK | Oui | — | +| Xcode | — | Oui (macOS uniquement) | +| Backend API | [../README.md](../README.md) | idem | + +## Installation (première fois) + +Le dépôt contient le code Dart (`lib/`) mais pas les dossiers natifs. Générez **Android + iOS uniquement** : + +### Windows (PowerShell) + +```powershell +cd mobile +.\scripts\bootstrap_platforms.ps1 +``` + +### macOS / Linux + +```bash +cd mobile +chmod +x scripts/bootstrap_platforms.sh +./scripts/bootstrap_platforms.sh +``` + +Équivalent manuel : + +```bash +flutter create . --org fr.laverie --project-name laverie_mobile --platforms=android,ios +flutter pub get +``` + +Ne pas ajouter `--platforms web` : le web Flutter est hors périmètre. + +## Lancement Android (priorité) + +```bash +# Émulateur Android (API par défaut : 10.0.2.2 = localhost hôte) +flutter run -d android + +# Appareil physique — remplacer par l'IP de votre PC +flutter run -d android --dart-define=API_BASE_URL=http://192.168.1.10:8000/api/v1 +``` + +### HTTP en développement + +L'émulateur Android autorise le trafic HTTP clair vers `10.0.2.2` via la config réseau de debug. En production, l'API doit être en **HTTPS**. + +## iOS (préparation) + +Le même projet inclut le dossier `ios/` pour une future build App Store. Nécessite **macOS + Xcode**. + +```bash +# Simulateur iOS (localhost) +flutter run -d ios + +# Appareil physique +flutter run -d ios --dart-define=API_BASE_URL=http://192.168.1.10:8000/api/v1 +``` + +Points déjà prévus côté Dart : + +- `flutter_secure_storage` avec options Keychain iOS +- URL API par défaut `127.0.0.1` sur iOS simulateur +- Détection plateforme dans `lib/core/platform/app_platform.dart` + +## Configuration API + +| Contexte | URL API | +|----------|---------| +| Android émulateur | `http://10.0.2.2:8000/api/v1` (défaut) | +| iOS simulateur | `http://127.0.0.1:8000/api/v1` (défaut) | +| Appareil physique | `--dart-define=API_BASE_URL=http://IP:8000/api/v1` | + +## Compte de démonstration + +| Email | Mot de passe | +|-------|--------------| +| marie.dupont@demo.local | password | + +## Architecture + +``` +lib/ +├── main.dart # Garde anti-web / anti-desktop +├── core/ +│ ├── platform/ # Android / iOS uniquement +│ ├── config/ # API URL, secure storage +│ ├── api/ +│ ├── auth/ +│ ├── router/ +│ └── theme/ +└── features/ + ├── auth/ + ├── home/ + ├── establishments/ + ├── wallet/ + ├── booking/ + ├── wash/ + └── profile/ +``` + +## Prochaines étapes (Android) + +1. Scan QR machine (`mobile_scanner`) → `POST /washes/start` +2. Rechargement wallet simulé +3. Notifications push (FCM Android, APNs iOS plus tard) +4. Tests `integration_test` sur émulateur Android diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..fbd24ec --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,6 @@ +include: package:flutter_lints/flutter.yaml + +linter: + rules: + prefer_const_constructors: true + prefer_const_declarations: true diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..58d3f82 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "fr.laverie.laverie_mobile" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "fr.laverie.laverie_mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..3a94c91 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e47ed2c --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/fr/laverie/laverie_mobile/MainActivity.kt b/android/app/src/main/kotlin/fr/laverie/laverie_mobile/MainActivity.kt new file mode 100644 index 0000000..77a072f --- /dev/null +++ b/android/app/src/main/kotlin/fr/laverie/laverie_mobile/MainActivity.kt @@ -0,0 +1,5 @@ +package fr.laverie.laverie_mobile + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 GIT binary patch literal 544 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY3?!3`olAj~WQl7;NpOBzNqJ&XDuZK6ep0G} zXKrG8YEWuoN@d~6R2!h8bpbvhu0Wd6uZuB!w&u2PAxD2eNXD>P5D~Wn-+_Wa#27Xc zC?Zj|6r#X(-D3u$NCt}(Ms06KgJ4FxJVv{GM)!I~&n8Bnc94O7-Hd)cjDZswgC;Qs zO=b+9!WcT8F?0rF7!Uys2bs@gozCP?z~o%U|N3vA*22NaGQG zlg@K`O_XuxvZ&Ks^m&R!`&1=spLvfx7oGDKDwpwW`#iqdw@AL`7MR}m`rwr|mZgU`8P7SBkL78fFf!WnuYWm$5Z0 zNXhDbCv&49sM544K|?c)WrFfiZvCi9h0O)B3Pgg&ebxsLQ05GG~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be GIT binary patch literal 442 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA3?vioaBc-sk|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*D5Xx&nMcT!A!W`0S9QKQy;}1Cl^CgaH=;G9cpY;r$Q>i*pfB zP2drbID<_#qf;rPZx^FqH)F_D#*k@@q03KywUtLX8Ua?`H+NMzkczFPK3lFz@i_kW%1NOn0|D2I9n9wzH8m|-tHjsw|9>@K=iMBhxvkv6m8Y-l zytQ?X=U+MF$@3 zt`~i=@j|6y)RWMK--}M|=T`o&^Ni>IoWKHEbBXz7?A@mgWoL>!*SXo`SZH-*HSdS+ yn*9;$7;m`l>wYBC5bq;=U}IMqLzqbYCidGC!)_gkIk_C@Uy!y&wkt5C($~2D>~)O*cj@FGjOCM)M>_ixfudOh)?xMu#Fs z#}Y=@YDTwOM)x{K_j*Q;dPdJ?Mz0n|pLRx{4n|)f>SXlmV)XB04CrSJn#dS5nK2lM zrZ9#~WelCp7&e13Y$jvaEXHskn$2V!!DN-nWS__6T*l;H&Fopn?A6HZ-6WRLFP=R` zqG+CE#d4|IbyAI+rJJ`&x9*T`+a=p|0O(+s{UBcyZdkhj=yS1>AirP+0R;mf2uMgM zC}@~JfByORAh4SyRgi&!(cja>F(l*O+nd+@4m$|6K6KDn_&uvCpV23&>G9HJp{xgg zoq1^2_p9@|WEo z*X_Uko@K)qYYv~>43eQGMdbiGbo>E~Q& zrYBH{QP^@Sti!`2)uG{irBBq@y*$B zi#&(U-*=fp74j)RyIw49+0MRPMRU)+a2r*PJ$L5roHt2$UjExCTZSbq%V!HeS7J$N zdG@vOZB4v_lF7Plrx+hxo7(fCV&}fHq)$ literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^6F``Q8Ax83A=Cw=BuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFa`(sgt!6~Yi|1%a`XoT0ojZ}lNrNjb9xjc(B0U1_% zz5^97Xt*%oq$rQy4?0GKNfJ44uvxI)gC`h-NZ|&0-7(qS@?b!5r36oQ}zyZrNO3 zMO=Or+<~>+A&uN&E!^Sl+>xE!QC-|oJv`ApDhqC^EWD|@=#J`=d#Xzxs4ah}w&Jnc z$|q_opQ^2TrnVZ0o~wh<3t%W&flvYGe#$xqda2bR_R zvPYgMcHgjZ5nSA^lJr%;<&0do;O^tDDh~=pIxA#coaCY>&N%M2^tq^U%3DB@ynvKo}b?yu-bFc-u0JHzced$sg7S3zqI(2 z#Km{dPr7I=pQ5>FuK#)QwK?Y`E`B?nP+}U)I#c1+FM*1kNvWG|a(TpksZQ3B@sD~b zpQ2)*V*TdwjFOtHvV|;OsiDqHi=6%)o4b!)x$)%9pGTsE z-JL={-Ffv+T87W(Xpooq<`r*VzWQcgBN$$`u}f>-ZQI1BB8ykN*=e4rIsJx9>z}*o zo~|9I;xof literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 GIT binary patch literal 1443 zcmb`G{WsKk6vsdJTdFg%tJav9_E4vzrOaqkWF|A724Nly!y+?N9`YV6wZ}5(X(D_N(?!*n3`|_r0Hc?=PQw&*vnU?QTFY zB_MsH|!j$PP;I}?dppoE_gA(4uc!jV&0!l7_;&p2^pxNo>PEcNJv za5_RT$o2Mf!<+r?&EbHH6nMoTsDOa;mN(wv8RNsHpG)`^ymG-S5By8=l9iVXzN_eG%Xg2@Xeq76tTZ*dGh~Lo9vl;Zfs+W#BydUw zCkZ$o1LqWQO$FC9aKlLl*7x9^0q%0}$OMlp@Kk_jHXOjofdePND+j!A{q!8~Jn+s3 z?~~w@4?egS02}8NuulUA=L~QQfm;MzCGd)XhiftT;+zFO&JVyp2mBww?;QByS_1w! zrQlx%{^cMj0|Bo1FjwY@Q8?Hx0cIPF*@-ZRFpPc#bBw{5@tD(5%sClzIfl8WU~V#u zm5Q;_F!wa$BSpqhN>W@2De?TKWR*!ujY;Yylk_X5#~V!L*Gw~;$%4Q8~Mad z@`-kG?yb$a9cHIApZDVZ^U6Xkp<*4rU82O7%}0jjHlK{id@?-wpN*fCHXyXh(bLt* zPc}H-x0e4E&nQ>y%B-(EL=9}RyC%MyX=upHuFhAk&MLbsF0LP-q`XnH78@fT+pKPW zu72MW`|?8ht^tz$iC}ZwLp4tB;Q49K!QCF3@!iB1qOI=?w z7In!}F~ij(18UYUjnbmC!qKhPo%24?8U1x{7o(+?^Zu0Hx81|FuS?bJ0jgBhEMzf< zCgUq7r2OCB(`XkKcN-TL>u5y#dD6D!)5W?`O5)V^>jb)P)GBdy%t$uUMpf$SNV31$ zb||OojAbvMP?T@$h_ZiFLFVHDmbyMhJF|-_)HX3%m=CDI+ID$0^C>kzxprBW)hw(v zr!Gmda);ICoQyhV_oP5+C%?jcG8v+D@9f?Dk*!BxY}dazmrT@64UrP3hlslANK)bq z$67n83eh}OeW&SV@HG95P|bjfqJ7gw$e+`Hxo!4cx`jdK1bJ>YDSpGKLPZ^1cv$ek zIB?0S<#tX?SJCLWdMd{-ME?$hc7A$zBOdIJ)4!KcAwb=VMov)nK;9z>x~rfT1>dS+ zZ6#`2v@`jgbqq)P22H)Tx2CpmM^o1$B+xT6`(v%5xJ(?j#>Q$+rx_R|7TzDZe{J6q zG1*EcU%tE?!kO%^M;3aM6JN*LAKUVb^xz8-Pxo#jR5(-KBeLJvA@-gxNHx0M-ZJLl z;#JwQoh~9V?`UVo#}{6ka@II>++D@%KqGpMdlQ}?9E*wFcf5(#XQnP$Dk5~%iX^>f z%$y;?M0BLp{O3a(-4A?ewryHrrD%cx#Q^%KY1H zNre$ve+vceSLZcNY4U(RBX&)oZn*Py()h)XkE?PL$!bNb{N5FVI2Y%LKEm%yvpyTP z(1P?z~7YxD~Rf<(a@_y` literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2d428bf --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..c21f0c5 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.0.1" apply false + id("org.jetbrains.kotlin.android") version "2.3.20" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..86860e7 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,644 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = fr.laverie.laverieMobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* 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/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c3fedb2 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..dc9ada4725e9b0ddb1deab583e5b5102493aa332 GIT binary patch literal 10932 zcmeHN2~<R zh`|8`A_PQ1nSu(UMFx?8j8PC!!VDphaL#`F42fd#7Vlc`zIE4n%Y~eiz4y1j|NDpi z?<@|pSJ-HM`qifhf@m%MamgwK83`XpBA<+azdF#2QsT{X@z0A9Bq>~TVErigKH1~P zRX-!h-f0NJ4Mh++{D}J+K>~~rq}d%o%+4dogzXp7RxX4C>Km5XEI|PAFDmo;DFm6G zzjVoB`@qW98Yl0Kvc-9w09^PrsobmG*Eju^=3f?0o-t$U)TL1B3;sZ^!++3&bGZ!o-*6w?;oOhf z=A+Qb$scV5!RbG+&2S}BQ6YH!FKb0``VVX~T$dzzeSZ$&9=X$3)_7Z{SspSYJ!lGE z7yig_41zpQ)%5dr4ff0rh$@ky3-JLRk&DK)NEIHecf9c*?Z1bUB4%pZjQ7hD!A0r-@NF(^WKdr(LXj|=UE7?gBYGgGQV zidf2`ZT@pzXf7}!NH4q(0IMcxsUGDih(0{kRSez&z?CFA0RVXsVFw3^u=^KMtt95q z43q$b*6#uQDLoiCAF_{RFc{!H^moH_cmll#Fc^KXi{9GDl{>%+3qyfOE5;Zq|6#Hb zp^#1G+z^AXfRKaa9HK;%b3Ux~U@q?xg<2DXP%6k!3E)PA<#4$ui8eDy5|9hA5&{?v z(-;*1%(1~-NTQ`Is1_MGdQ{+i*ccd96ab$R$T3=% zw_KuNF@vI!A>>Y_2pl9L{9h1-C6H8<)J4gKI6{WzGBi<@u3P6hNsXG=bRq5c+z;Gc3VUCe;LIIFDmQAGy+=mRyF++u=drBWV8-^>0yE9N&*05XHZpPlE zxu@?8(ZNy7rm?|<+UNe0Vs6&o?l`Pt>P&WaL~M&#Eh%`rg@Mbb)J&@DA-wheQ>hRV z<(XhigZAT z>=M;URcdCaiO3d^?H<^EiEMDV+7HsTiOhoaMX%P65E<(5xMPJKxf!0u>U~uVqnPN7T!X!o@_gs3Ct1 zlZ_$5QXP4{Aj645wG_SNT&6m|O6~Tsl$q?nK*)(`{J4b=(yb^nOATtF1_aS978$x3 zx>Q@s4i3~IT*+l{@dx~Hst21fR*+5}S1@cf>&8*uLw-0^zK(+OpW?cS-YG1QBZ5q! zgTAgivzoF#`cSz&HL>Ti!!v#?36I1*l^mkrx7Y|K6L#n!-~5=d3;K<;Zqi|gpNUn_ z_^GaQDEQ*jfzh;`j&KXb66fWEk1K7vxQIMQ_#Wu_%3 z4Oeb7FJ`8I>Px;^S?)}2+4D_83gHEq>8qSQY0PVP?o)zAv3K~;R$fnwTmI-=ZLK`= zTm+0h*e+Yfr(IlH3i7gUclNH^!MU>id$Jw>O?2i0Cila#v|twub21@e{S2v}8Z13( zNDrTXZVgris|qYm<0NU(tAPouG!QF4ZNpZPkX~{tVf8xY690JqY1NVdiTtW+NqyRP zZ&;T0ikb8V{wxmFhlLTQ&?OP7 z;(z*<+?J2~z*6asSe7h`$8~Se(@t(#%?BGLVs$p``;CyvcT?7Y!{tIPva$LxCQ&4W z6v#F*);|RXvI%qnoOY&i4S*EL&h%hP3O zLsrFZhv&Hu5tF$Lx!8(hs&?!Kx5&L(fdu}UI5d*wn~A`nPUhG&Rv z2#ixiJdhSF-K2tpVL=)5UkXRuPAFrEW}7mW=uAmtVQ&pGE-&az6@#-(Te^n*lrH^m@X-ftVcwO_#7{WI)5v(?>uC9GG{lcGXYJ~Q8q zbMFl7;t+kV;|;KkBW2!P_o%Czhw&Q(nXlxK9ak&6r5t_KH8#1Mr-*0}2h8R9XNkr zto5-b7P_auqTJb(TJlmJ9xreA=6d=d)CVbYP-r4$hDn5|TIhB>SReMfh&OVLkMk-T zYf%$taLF0OqYF?V{+6Xkn>iX@TuqQ?&cN6UjC9YF&%q{Ut3zv{U2)~$>-3;Dp)*(? zg*$mu8^i=-e#acaj*T$pNowo{xiGEk$%DusaQiS!KjJH96XZ-hXv+jk%ard#fu=@Q z$AM)YWvE^{%tDfK%nD49=PI|wYu}lYVbB#a7wtN^Nml@CE@{Gv7+jo{_V?I*jkdLD zJE|jfdrmVbkfS>rN*+`#l%ZUi5_bMS<>=MBDNlpiSb_tAF|Zy`K7kcp@|d?yaTmB^ zo?(vg;B$vxS|SszusORgDg-*Uitzdi{dUV+glA~R8V(?`3GZIl^egW{a919!j#>f` znL1o_^-b`}xnU0+~KIFLQ)$Q6#ym%)(GYC`^XM*{g zv3AM5$+TtDRs%`2TyR^$(hqE7Y1b&`Jd6dS6B#hDVbJlUXcG3y*439D8MrK!2D~6gn>UD4Imctb z+IvAt0iaW73Iq$K?4}H`7wq6YkTMm`tcktXgK0lKPmh=>h+l}Y+pDtvHnG>uqBA)l zAH6BV4F}v$(o$8Gfo*PB>IuaY1*^*`OTx4|hM8jZ?B6HY;F6p4{`OcZZ(us-RVwDx zUzJrCQlp@mz1ZFiSZ*$yX3c_#h9J;yBE$2g%xjmGF4ca z&yL`nGVs!Zxsh^j6i%$a*I3ZD2SoNT`{D%mU=LKaEwbN(_J5%i-6Va?@*>=3(dQy` zOv%$_9lcy9+(t>qohkuU4r_P=R^6ME+wFu&LA9tw9RA?azGhjrVJKy&8=*qZT5Dr8g--d+S8zAyJ$1HlW3Olryt`yE zFIph~Z6oF&o64rw{>lgZISC6p^CBer9C5G6yq%?8tC+)7*d+ib^?fU!JRFxynRLEZ zj;?PwtS}Ao#9whV@KEmwQgM0TVP{hs>dg(1*DiMUOKHdQGIqa0`yZnHk9mtbPfoLx zo;^V6pKUJ!5#n`w2D&381#5#_t}AlTGEgDz$^;u;-vxDN?^#5!zN9ngytY@oTv!nc zp1Xn8uR$1Z;7vY`-<*?DfPHB;x|GUi_fI9@I9SVRv1)qETbNU_8{5U|(>Du84qP#7 z*l9Y$SgA&wGbj>R1YeT9vYjZuC@|{rajTL0f%N@>3$DFU=`lSPl=Iv;EjuGjBa$Gw zHD-;%YOE@<-!7-Mn`0WuO3oWuL6tB2cpPw~Nvuj|KM@))ixuDK`9;jGMe2d)7gHin zS<>k@!x;!TJEc#HdL#RF(`|4W+H88d4V%zlh(7#{q2d0OQX9*FW^`^_<3r$kabWAB z$9BONo5}*(%kx zOXi-yM_cmB3>inPpI~)duvZykJ@^^aWzQ=eQ&STUa}2uT@lV&WoRzkUoE`rR0)`=l zFT%f|LA9fCw>`enm$p7W^E@U7RNBtsh{_-7vVz3DtB*y#*~(L9+x9*wn8VjWw|Q~q zKFsj1Yl>;}%MG3=PY`$g$_mnyhuV&~O~u~)968$0b2!Jkd;2MtAP#ZDYw9hmK_+M$ zb3pxyYC&|CuAbtiG8HZjj?MZJBFbt`ryf+c1dXFuC z0*ZQhBzNBd*}s6K_G}(|Z_9NDV162#y%WSNe|FTDDhx)K!c(mMJh@h87@8(^YdK$&d*^WQe8Z53 z(|@MRJ$Lk-&ii74MPIs80WsOFZ(NX23oR-?As+*aq6b?~62@fSVmM-_*cb1RzZ)`5$agEiL`-E9s7{GM2?(KNPgK1(+c*|-FKoy}X(D_b#etO|YR z(BGZ)0Ntfv-7R4GHoXp?l5g#*={S1{u-QzxCGng*oWr~@X-5f~RA14b8~B+pLKvr4 zfgL|7I>jlak9>D4=(i(cqYf7#318!OSR=^`xxvI!bBlS??`xxWeg?+|>MxaIdH1U~#1tHu zB{QMR?EGRmQ_l4p6YXJ{o(hh-7Tdm>TAX380TZZZyVkqHNzjUn*_|cb?T? zt;d2s-?B#Mc>T-gvBmQZx(y_cfkXZO~{N zT6rP7SD6g~n9QJ)8F*8uHxTLCAZ{l1Y&?6v)BOJZ)=R-pY=Y=&1}jE7fQ>USS}xP#exo57uND0i*rEk@$;nLvRB@u~s^dwRf?G?_enN@$t* zbL%JO=rV(3Ju8#GqUpeE3l_Wu1lN9Y{D4uaUe`g>zlj$1ER$6S6@{m1!~V|bYkhZA z%CvrDRTkHuajMU8;&RZ&itnC~iYLW4DVkP<$}>#&(`UO>!n)Po;Mt(SY8Yb`AS9lt znbX^i?Oe9r_o=?})IHKHoQGKXsps_SE{hwrg?6dMI|^+$CeC&z@*LuF+P`7LfZ*yr+KN8B4{Nzv<`A(wyR@!|gw{zB6Ha ziwPAYh)oJ(nlqSknu(8g9N&1hu0$vFK$W#mp%>X~AU1ay+EKWcFdif{% z#4!4aoVVJ;ULmkQf!ke2}3hqxLK>eq|-d7Ly7-J9zMpT`?dxo6HdfJA|t)?qPEVBDv z{y_b?4^|YA4%WW0VZd8C(ZgQzRI5(I^)=Ub`Y#MHc@nv0w-DaJAqsbEHDWG8Ia6ju zo-iyr*sq((gEwCC&^TYBWt4_@|81?=B-?#P6NMff(*^re zYqvDuO`K@`mjm_Jd;mW_tP`3$cS?R$jR1ZN09$YO%_iBqh5ftzSpMQQtxKFU=FYmP zeY^jph+g<4>YO;U^O>-NFLn~-RqlHvnZl2yd2A{Yc1G@Ga$d+Q&(f^tnPf+Z7serIU};17+2DU_f4Z z@GaPFut27d?!YiD+QP@)T=77cR9~MK@bd~pY%X(h%L={{OIb8IQmf-!xmZkm8A0Ga zQSWONI17_ru5wpHg3jI@i9D+_Y|pCqVuHJNdHUauTD=R$JcD2K_liQisqG$(sm=k9;L* z!L?*4B~ql7uioSX$zWJ?;q-SWXRFhz2Jt4%fOHA=Bwf|RzhwqdXGr78y$J)LR7&3T zE1WWz*>GPWKZ0%|@%6=fyx)5rzUpI;bCj>3RKzNG_1w$fIFCZ&UR0(7S?g}`&Pg$M zf`SLsz8wK82Vyj7;RyKmY{a8G{2BHG%w!^T|Njr!h9TO2LaP^_f22Q1=l$QiU84ao zHe_#{S6;qrC6w~7{y(hs-?-j?lbOfgH^E=XcSgnwW*eEz{_Z<_xN#0001NP)t-s|Ns9~ z#rXRE|M&d=0au&!`~QyF`q}dRnBDt}*!qXo`c{v z{Djr|@Adh0(D_%#_&mM$D6{kE_x{oE{l@J5@%H*?%=t~i_`ufYOPkAEn!pfkr2$fs z652Tz0001XNklqeeKN4RM4i{jKqmiC$?+xN>3Apn^ z0QfuZLym_5b<*QdmkHjHlj811{If)dl(Z2K0A+ekGtrFJb?g|wt#k#pV-#A~bK=OT ts8>{%cPtyC${m|1#B1A6#u!Q;umknL1chzTM$P~L002ovPDHLkV1lTfnu!1a literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..797d452e458972bab9d994556c8305db4c827017 GIT binary patch literal 406 zcmV;H0crk;P))>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed2d933e1120817fe9182483a228007b18ab6ae GIT binary patch literal 450 zcmV;z0X_bSP)iGWQ_5NJQ_~rNh*z)}eT%KUb z`7gNk0#AwF^#0T0?hIa^`~Ck;!}#m+_uT050aTR(J!bU#|IzRL%^UsMS#KsYnTF*!YeDOytlP4VhV?b} z%rz_<=#CPc)tU1MZTq~*2=8~iZ!lSa<{9b@2Jl;?IEV8)=fG217*|@)CCYgFze-x? zIFODUIA>nWKpE+bn~n7;-89sa>#DR>TSlqWk*!2hSN6D~Qb#VqbP~4Fk&m`@1$JGr zXPIdeRE&b2Thd#{MtDK$px*d3-Wx``>!oimf%|A-&-q*6KAH)e$3|6JV%HX{Hig)k suLT-RhftRq8b9;(V=235Wa|I=027H2wCDra;{X5v07*qoM6N<$f;9x^2LJ#7 literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd7b0099ca80c806f8fe495613e8d6c69460d76 GIT binary patch literal 282 zcmV+#0p(^bcu7P-R4C8Q z&e;xxFbF_Vrezo%_kH*OKhshZ6BFpG-Y1e10`QXJKbND7AMQ&cMj60B5TNObaZxYybcN07*qoM6N<$g3m;S%K!iX literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..fe730945a01f64a61e2235dbe3f45b08f7729182 GIT binary patch literal 462 zcmV;<0WtoGP)-}iV`2<;=$?g5M=KQbZ{F&YRNy7Nn@%_*5{gvDM0aKI4?ESmw z{NnZg)A0R`+4?NF_RZexyVB&^^ZvN!{I28tr{Vje;QNTz`dG&Jz0~Ek&f2;*Z7>B|cg}xYpxEFY+0YrKLF;^Q+-HreN0P{&i zK~zY`?b7ECf-n?@;d<&orQ*Q7KoR%4|C>{W^h6@&01>0SKS`dn{Q}GT%Qj_{PLZ_& zs`MFI#j-(>?bvdZ!8^xTwlY{qA)T4QLbY@j(!YJ7aXJervHy6HaG_2SB`6CC{He}f zHVw(fJWApwPq!6VY7r1w-Fs)@ox~N+q|w~e;JI~C4Vf^@d>Wvj=fl`^u9x9wd9 zR%3*Q+)t%S!MU_`id^@&Y{y7-r98lZX0?YrHlfmwb?#}^1b{8g&KzmkE(L>Z&)179 zp<)v6Y}pRl100G2FL_t(o!|l{-Q-VMg#&MKg7c{O0 z2wJImOS3Gy*Z2Qifdv~JYOp;v+U)a|nLoc7hNH;I$;lzDt$}rkaFw1mYK5_0Q(Sut zvbEloxON7$+HSOgC9Z8ltuC&0OSF!-mXv5caV>#bc3@hBPX@I$58-z}(ZZE!t-aOG zpjNkbau@>yEzH(5Yj4kZiMH32XI!4~gVXNnjAvRx;Sdg^`>2DpUEwoMhTs_st8pKG z(%SHyHdU&v%f36~uERh!bd`!T2dw;z6PrOTQ7Vt*#9F2uHlUVnb#ev_o^fh}Dzmq} zWtlk35}k=?xj28uO|5>>$yXadTUE@@IPpgH`gJ~Ro4>jd1IF|(+IX>8M4Ps{PNvmI zNj4D+XgN83gPt_Gm}`Ybv{;+&yu-C(Grdiahmo~BjG-l&mWM+{e5M1sm&=xduwgM9 z`8OEh`=F3r`^E{n_;%9weN{cf2%7=VzC@cYj+lg>+3|D|_1C@{hcU(DyQG_BvBWe? zvTv``=%b1zrol#=R`JB)>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..502f463a9bc882b461c96aadf492d1729e49e725 GIT binary patch literal 586 zcmV-Q0=4~#P)+}#`wDE{8-2Mebf5<{{PqV{TgVcv*r8?UZ3{-|G?_}T*&y;@cqf{ z{Q*~+qr%%p!1pS*_Uicl#q9lc(D`!D`LN62sNwq{oYw(Wmhk)k<@f$!$@ng~_5)Ru z0Z)trIA5^j{DIW^c+vT2%lW+2<(RtE2wR;4O@)Tm`Xr*?A(qYoM}7i5Yxw>D(&6ou zxz!_Xr~yNF+waPe00049Nkl*;a!v6h%{rlvIH#gW3s8p;bFr=l}mRqpW2h zw=OA%hdyL~z+UHOzl0eKhEr$YYOL-c-%Y<)=j?(bzDweB7{b+%_ypvm_cG{SvM=DK zhv{K@m>#Bw>2W$eUI#iU)Wdgs8Y3U+A$Gd&{+j)d)BmGKx+43U_!tik_YlN)>$7G! zhkE!s;%oku3;IwG3U^2kw?z+HM)jB{@zFhK8P#KMSytSthr+4!c(5c%+^UBn`0X*2 zy3(k600_CSZj?O$Qu%&$;|TGUJrptR(HzyIx>5E(2r{eA(<6t3e3I0B)7d6s7?Z5J zZ!rtKvA{MiEBm&KFtoifx>5P^Z=vl)95XJn()aS5%ad(s?4-=Tkis9IGu{`Fy8r+H07*qoM6N<$f20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0ec303439225b78712f49115768196d8d76f6790 GIT binary patch literal 862 zcmV-k1EKthP)20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..e9f5fea27c705180eb716271f41b582e76dcbd90 GIT binary patch literal 1674 zcmV;526g#~P){YQnis^a@{&-nmRmq)<&%Mztj67_#M}W?l>kYSliK<%xAp;0j{!}J0!o7b zE>q9${Lb$D&h7k=+4=!ek^n+`0zq>LL1O?lVyea53S5x`Nqqo2YyeuIrQrJj9XjOp z{;T5qbj3}&1vg1VK~#9!?b~^C5-}JC@Pyrv-6dSEqJqT}#j9#dJ@GzT@B8}x zU&J@bBI>f6w6en+CeI)3^kC*U?}X%OD8$Fd$H&LV$H&LV$H&LV#|K5~mLYf|VqzOc zkc7qL~0sOYuM{tG`rYEDV{DWY`Z8&)kW*hc2VkBuY+^Yx&92j&StN}Wp=LD zxoGxXw6f&8sB^u})h@b@z0RBeD`K7RMR9deyL(ZJu#39Z>rT)^>v}Khq8U-IbIvT> z?4pV9qGj=2)TNH3d)=De<+^w;>S7m_eFKTvzeaBeir45xY!^m!FmxnljbSS_3o=g( z->^wC9%qkR{kbGnW8MfFew_o9h3(r55Is`L$8KI@d+*%{=Nx+FXJ98L0PjFIu;rGnnfY zn1R5Qnp<{Jq0M1vX=X&F8gtLmcWv$1*M@4ZfF^9``()#hGTeKeP`1!iED ztNE(TN}M5}3Bbc*d=FIv`DNv&@|C6yYj{sSqUj5oo$#*0$7pu|Dd2TLI>t5%I zIa4Dvr(iayb+5x=j*Vum9&irk)xV1`t509lnPO0%skL8_1c#Xbamh(2@f?4yUI zhhuT5<#8RJhGz4%b$`PJwKPAudsm|at?u;*hGgnA zU1;9gnxVBC)wA(BsB`AW54N{|qmikJR*%x0c`{LGsSfa|NK61pYH(r-UQ4_JXd!Rsz)=k zL{GMc5{h138)fF5CzHEDM>+FqY)$pdN3}Ml+riTgJOLN0F*Vh?{9ESR{SVVg>*>=# zix;VJHPtvFFCRY$Ks*F;VX~%*r9F)W`PmPE9F!(&s#x07n2<}?S{(ygpXgX-&B&OM zONY&BRQ(#%0%jeQs?oJ4P!p*R98>qCy5p8w>_gpuh39NcOlp)(wOoz0sY-Qz55eB~ z7OC-fKBaD1sE3$l-6QgBJO!n?QOTza`!S_YK z_v-lm^7{VO^8Q@M_^8F)09Ki6%=s?2_5eupee(w1FB%aqSweusQ-T+CH0Xt{` zFjMvW{@C&TB)k25()nh~_yJ9coBRL(0oO@HK~z}7?bm5j;y@69;bvlHb2tf!$ReA~x{22wTq550 z?f?Hnw(;m3ip30;QzdV~7pi!wyMYhDtXW#cO7T>|f=bdFhu+F!zMZ2UFj;GUKX7tI z;hv3{q~!*pMj75WP_c}>6)IWvg5_yyg<9Op()eD1hWC19M@?_9_MHec{Z8n3FaF{8 z;u`Mw0ly(uE>*CgQYv{be6ab2LWhlaH1^iLIM{olnag$78^Fd}%dR7;JECQ+hmk|o z!u2&!3MqPfP5ChDSkFSH8F2WVOEf0(E_M(JL17G}Y+fg0_IuW%WQ zG(mG&u?|->YSdk0;8rc{yw2@2Z&GA}z{Wb91Ooz9VhA{b2DYE7RmG zjL}?eq#iX%3#k;JWMx_{^2nNax`xPhByFiDX+a7uTGU|otOvIAUy|dEKkXOm-`aWS z27pUzD{a)Ct<6p{{3)+lq@i`t@%>-wT4r?*S}k)58e09WZYP0{{R3FC5Sl00039P)t-s|Ns9~ z#rP?<_5oL$Q^olD{r_0T`27C={r>*`|Nj71npVa5OTzc(_WfbW_({R{p56NV{r*M2 z_xt?)2V0#0NsfV0u>{42ctGP(8vQj-Btk1n|O0ZD=YLwd&R{Ko41Gr9H= zY@z@@bOAMB5Ltl$E>bJJ{>JP30ZxkmI%?eW{k`b?Wy<&gOo;dS`~CR$Vwb@XWtR|N zi~t=w02?-0&j0TD{>bb6sNwsK*!p?V`RMQUl(*DVjk-9Cx+-z1KXab|Ka2oXhX5f% z`$|e!000AhNklrxs)5QTeTVRiEmz~MKK1WAjCw(c-JK6eox;2O)?`? zTG`AHia671e^vgmp!llKp|=5sVHk#C7=~epA~VAf-~%aPC=%Qw01h8mnSZ|p?hz91 z7p83F3%LVu9;S$tSI$C^%^yud1dfTM_6p2|+5Ejp$bd`GDvbR|xit>i!ZD&F>@CJrPmu*UjD&?DfZs=$@e3FQA(vNiU+$A*%a} z?`XcG2jDxJ_ZQ#Md`H{4Lpf6QBDp81_KWZ6Tk#yCy1)32zO#3<7>b`eT7UyYH1eGz z;O(rH$=QR*L%%ZcBpc=eGua?N55nD^K(8<#gl2+pN_j~b2MHs4#mcLmv%DkspS-3< zpI1F=^9siI0s-;IN_IrA;5xm~3?3!StX}pUv0vkxMaqm+zxrg7X7(I&*N~&dEd0kD z-FRV|g=|QuUsuh>-xCI}vD2imzYIOIdcCVV=$Bz@*u0+Bs<|L^)32nN*=wu3n%Ynw z@1|eLG>!8ruU1pFXUfb`j>(=Gy~?Rn4QJ-c3%3T|(Frd!bI`9u&zAnyFYTqlG#&J7 zAkD(jpw|oZLNiA>;>hgp1KX7-wxC~31II47gc zHcehD6Uxlf%+M^^uN5Wc*G%^;>D5qT{>=uxUhX%WJu^Z*(_Wq9y}npFO{Hhb>s6<9 zNi0pHXWFaVZnb)1+RS&F)xOv6&aeILcI)`k#0YE+?e)5&#r7J#c`3Z7x!LpTc01dx zrdC3{Z;joZ^KN&))zB_i)I9fWedoN>Zl-6_Iz+^G&*ak2jpF07*qoM6N<$f;w%0(f|Me literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0467bf12aa4d28f374bb26596605a46dcbb3e7c8 GIT binary patch literal 1418 zcmV;51$Fv~P)q zKfU)WzW*n(@|xWGCA9ScMt*e9`2kdxPQ&&>|-UCa7_51w+ zLUsW@ZzZSW0y$)Hp~e9%PvP|a03ks1`~K?q{u;6NC8*{AOqIUq{CL&;p56Lf$oQGq z^={4hPQv)y=I|4n+?>7Fim=dxt1 z2H+Dm+1+fh+IF>G0SjJMkQQre1x4|G*Z==(Ot&kCnUrL4I(rf(ucITwmuHf^hXiJT zkdTm&kdTm&kdTm&kdP`esgWG0BcWCVkVZ&2dUwN`cgM8QJb`Z7Z~e<&Yj2(}>Tmf` zm1{eLgw!b{bXkjWbF%dTkTZEJWyWOb##Lfw4EK2}<0d6%>AGS{po>WCOy&f$Tay_> z?NBlkpo@s-O;0V%Y_Xa-G#_O08q5LR*~F%&)}{}r&L%Sbs8AS4t7Y0NEx*{soY=0MZExqA5XHQkqi#4gW3 zqODM^iyZl;dvf)-bOXtOru(s)Uc7~BFx{w-FK;2{`VA?(g&@3z&bfLFyctOH!cVsF z7IL=fo-qBndRUm;kAdXR4e6>k-z|21AaN%ubeVrHl*<|s&Ax@W-t?LR(P-24A5=>a z*R9#QvjzF8n%@1Nw@?CG@6(%>+-0ASK~jEmCV|&a*7-GKT72W<(TbSjf)&Eme6nGE z>Gkj4Sq&2e+-G%|+NM8OOm5zVl9{Z8Dd8A5z3y8mZ=4Bv4%>as_{9cN#bm~;h>62( zdqY93Zy}v&c4n($Vv!UybR8ocs7#zbfX1IY-*w~)p}XyZ-SFC~4w>BvMVr`dFbelV{lLL0bx7@*ZZdebr3`sP;? zVImji)kG)(6Juv0lz@q`F!k1FE;CQ(D0iG$wchPbKZQELlsZ#~rt8#90Y_Xh&3U-< z{s<&cCV_1`^TD^ia9!*mQDq& zn2{r`j};V|uV%_wsP!zB?m%;FeaRe+X47K0e+KE!8C{gAWF8)lCd1u1%~|M!XNRvw zvtqy3iz0WSpWdhn6$hP8PaRBmp)q`#PCA`Vd#Tc$@f1tAcM>f_I@bC)hkI9|o(Iqv zo}Piadq!j76}004RBio<`)70k^`K1NK)q>w?p^C6J2ZC!+UppiK6&y3Kmbv&O!oYF z34$0Z;QO!JOY#!`qyGH<3Pd}Pt@q*A0V=3SVtWKRR8d8Z&@)3qLPA19LPA19LPEUC YUoZo%k(ykuW&i*H07*qoM6N<$f+CH{y8r+H literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..b6c147e --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Laverie Mobile + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + laverie_mobile + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/core/api/api_client.dart b/lib/core/api/api_client.dart new file mode 100644 index 0000000..6e5fd6e --- /dev/null +++ b/lib/core/api/api_client.dart @@ -0,0 +1,99 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../config/app_config.dart'; +import '../auth/auth_provider.dart'; + +/// Client HTTP Dio configuré pour l'API Laverie. +class ApiClient { + ApiClient({ + required this.baseUrl, + this.getAccessToken, + this.onUnauthorized, + }) : _dio = Dio( + BaseOptions( + baseUrl: baseUrl, + connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(seconds: 30), + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ), + ) { + _dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) async { + final token = await getAccessToken?.call(); + if (token != null && token.isNotEmpty) { + options.headers['Authorization'] = 'Bearer $token'; + } + handler.next(options); + }, + onError: (error, handler) async { + if (error.response?.statusCode == 401) { + await onUnauthorized?.call(); + } + handler.next(error); + }, + ), + ); + } + + final String baseUrl; + final Future Function()? getAccessToken; + final Future Function()? onUnauthorized; + final Dio _dio; + + Dio get dio => _dio; + + Future> get( + String path, { + Map? queryParameters, + }) { + return _dio.get(path, queryParameters: queryParameters); + } + + Future> post( + String path, { + dynamic data, + Map? queryParameters, + }) { + return _dio.post(path, data: data, queryParameters: queryParameters); + } + + Future> patch( + String path, { + dynamic data, + Map? queryParameters, + }) { + return _dio.patch(path, data: data, queryParameters: queryParameters); + } + + Future> put( + String path, { + dynamic data, + Map? queryParameters, + }) { + return _dio.put(path, data: data, queryParameters: queryParameters); + } + + Future> delete( + String path, { + dynamic data, + Map? queryParameters, + }) { + return _dio.delete(path, data: data, queryParameters: queryParameters); + } +} + +/// Fournisseur Riverpod du client API (injecte le token depuis l'état auth). +final apiClientProvider = Provider((ref) { + final authNotifier = ref.read(authProvider.notifier); + + return ApiClient( + baseUrl: kApiBaseUrl, + getAccessToken: () async => ref.read(authProvider).accessToken, + onUnauthorized: () async => authNotifier.logout(), + ); +}); diff --git a/lib/core/api/api_endpoints.dart b/lib/core/api/api_endpoints.dart new file mode 100644 index 0000000..a8d9655 --- /dev/null +++ b/lib/core/api/api_endpoints.dart @@ -0,0 +1,32 @@ +/// Chemins des endpoints REST de l'API Laverie v1. +abstract final class ApiEndpoints { + // Authentification utilisateur + static const authRegister = '/auth/register'; + static const authLogin = '/auth/login'; + static const authRefresh = '/auth/refresh'; + static const authLogout = '/auth/logout'; + static const authMe = '/auth/me'; + + // Portefeuille + static const wallet = '/wallet'; + static const walletTransactions = '/wallet/transactions'; + static const walletTopUpInitiate = '/wallet/top-up/initiate'; + static const walletTopUpConfirm = '/wallet/top-up/confirm'; + + // Établissements & machines + static const establishments = '/establishments'; + static String establishment(String uuid) => '/establishments/$uuid'; + static String machine(String uuid) => '/machines/$uuid'; + static String machineAvailability(String uuid) => '/machines/$uuid/availability'; + static String machinePricing(String uuid) => '/machines/$uuid/pricing'; + + // Réservations + static const bookings = '/bookings'; + static String booking(String uuid) => '/bookings/$uuid'; + static String bookingCancel(String uuid) => '/bookings/$uuid/cancel'; + + // Lavages + static const washes = '/washes'; + static const washesStart = '/washes/start'; + static String wash(String uuid) => '/washes/$uuid'; +} diff --git a/lib/core/auth/auth_provider.dart b/lib/core/auth/auth_provider.dart new file mode 100644 index 0000000..c8b53dc --- /dev/null +++ b/lib/core/auth/auth_provider.dart @@ -0,0 +1,158 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../api/api_client.dart'; +import '../config/app_config.dart'; +import '../../features/auth/domain/auth_user.dart'; +import 'auth_repository.dart'; + +/// État d'authentification de l'application. +class AuthState { + const AuthState({ + this.user, + this.accessToken, + this.refreshToken, + this.isLoading = false, + this.error, + }); + + final AuthUser? user; + final String? accessToken; + final String? refreshToken; + final bool isLoading; + final String? error; + + bool get isAuthenticated => accessToken != null && accessToken!.isNotEmpty; + + AuthState copyWith({ + AuthUser? user, + String? accessToken, + String? refreshToken, + bool? isLoading, + String? error, + bool clearError = false, + bool clearUser = false, + }) { + return AuthState( + user: clearUser ? null : (user ?? this.user), + accessToken: accessToken ?? this.accessToken, + refreshToken: refreshToken ?? this.refreshToken, + isLoading: isLoading ?? this.isLoading, + error: clearError ? null : (error ?? this.error), + ); + } +} + +/// Gestionnaire d'état Riverpod pour l'authentification. +class AuthNotifier extends StateNotifier { + AuthNotifier(this._repository) : super(const AuthState()) { + _restoreSession(); + } + + final AuthRepository _repository; + + Future _restoreSession() async { + state = state.copyWith(isLoading: true, clearError: true); + + try { + final stored = await _repository.loadStoredTokens(); + if (stored == null) { + state = state.copyWith(isLoading: false); + return; + } + + state = state.copyWith( + accessToken: stored.accessToken, + refreshToken: stored.refreshToken, + ); + + final user = await _repository.fetchCurrentUser(); + state = state.copyWith(user: user, isLoading: false); + } catch (_) { + final refreshed = await _repository.refresh(); + if (refreshed != null) { + final user = await _repository.fetchCurrentUser(); + state = state.copyWith( + accessToken: refreshed.accessToken, + refreshToken: refreshed.refreshToken, + user: user, + isLoading: false, + ); + } else { + await _repository.clearStoredTokens(); + state = const AuthState(isLoading: false); + } + } + } + + Future login(String email, String password) async { + state = state.copyWith(isLoading: true, clearError: true); + + try { + final tokens = await _repository.login(email: email, password: password); + final user = tokens.user ?? await _repository.fetchCurrentUser(); + + state = state.copyWith( + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken, + user: user, + isLoading: false, + ); + return true; + } catch (e) { + state = state.copyWith( + isLoading: false, + error: 'Connexion impossible. Vérifiez vos identifiants.', + ); + return false; + } + } + + Future register({ + required String firstName, + required String lastName, + required String email, + required String password, + String? phone, + }) async { + state = state.copyWith(isLoading: true, clearError: true); + + try { + final tokens = await _repository.register( + firstName: firstName, + lastName: lastName, + email: email, + password: password, + phone: phone, + ); + final user = tokens.user ?? await _repository.fetchCurrentUser(); + + state = state.copyWith( + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken, + user: user, + isLoading: false, + ); + return true; + } catch (e) { + state = state.copyWith( + isLoading: false, + error: 'Inscription impossible. L\'email est peut-être déjà utilisé.', + ); + return false; + } + } + + Future logout() async { + await _repository.logout(); + state = const AuthState(); + } +} + +final authRepositoryProvider = Provider((ref) { + // Client dédié à l'auth pour éviter une dépendance circulaire avec apiClientProvider. + return AuthRepository(apiClient: ApiClient(baseUrl: kApiBaseUrl)); +}); + +final authProvider = StateNotifierProvider((ref) { + return AuthNotifier(ref.watch(authRepositoryProvider)); +}); diff --git a/lib/core/auth/auth_repository.dart b/lib/core/auth/auth_repository.dart new file mode 100644 index 0000000..74f332c --- /dev/null +++ b/lib/core/auth/auth_repository.dart @@ -0,0 +1,125 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +import '../api/api_client.dart'; +import '../api/api_endpoints.dart'; +import '../config/app_config.dart'; +import '../config/secure_storage_config.dart'; +import '../../features/auth/domain/auth_user.dart'; + +/// Dépôt d'authentification — login, inscription, refresh et logout. +class AuthRepository { + AuthRepository({ + required ApiClient apiClient, + FlutterSecureStorage? secureStorage, + }) : _apiClient = apiClient, + _secureStorage = secureStorage ?? laverieSecureStorage; + + final ApiClient _apiClient; + final FlutterSecureStorage _secureStorage; + + Future login({ + required String email, + required String password, + }) async { + final response = await _apiClient.post( + ApiEndpoints.authLogin, + data: { + 'email': email, + 'password': password, + }, + ); + + final tokens = AuthTokens.fromJson(response.data as Map); + await _persistTokens(tokens); + return tokens; + } + + Future register({ + required String firstName, + required String lastName, + required String email, + required String password, + String? phone, + }) async { + final response = await _apiClient.post( + ApiEndpoints.authRegister, + data: { + 'first_name': firstName, + 'last_name': lastName, + 'email': email, + 'password': password, + if (phone != null) 'phone': phone, + }, + ); + + final tokens = AuthTokens.fromJson(response.data as Map); + await _persistTokens(tokens); + return tokens; + } + + Future refresh() async { + final refreshToken = await _secureStorage.read(key: AuthStorageKeys.refreshToken); + if (refreshToken == null || refreshToken.isEmpty) { + return null; + } + + final response = await _apiClient.post( + ApiEndpoints.authRefresh, + data: {'refresh_token': refreshToken}, + ); + + final tokens = AuthTokens.fromJson(response.data as Map); + await _persistTokens(tokens); + return tokens; + } + + Future fetchCurrentUser() async { + final response = await _apiClient.get(ApiEndpoints.authMe); + final data = response.data; + + if (data is Map) { + if (data.containsKey('data')) { + return AuthUser.fromJson(data['data'] as Map); + } + return AuthUser.fromJson(data); + } + + return null; + } + + Future logout() async { + try { + await _apiClient.post(ApiEndpoints.authLogout); + } catch (_) { + // Déconnexion locale même si l'API est injoignable. + } + await clearStoredTokens(); + } + + Future loadStoredTokens() async { + final accessToken = await _secureStorage.read(key: AuthStorageKeys.accessToken); + final refreshToken = await _secureStorage.read(key: AuthStorageKeys.refreshToken); + + if (accessToken == null || refreshToken == null) { + return null; + } + + return AuthTokens(accessToken: accessToken, refreshToken: refreshToken); + } + + Future clearStoredTokens() async { + await _secureStorage.delete(key: AuthStorageKeys.accessToken); + await _secureStorage.delete(key: AuthStorageKeys.refreshToken); + } + + Future _persistTokens(AuthTokens tokens) async { + await _secureStorage.write( + key: AuthStorageKeys.accessToken, + value: tokens.accessToken, + ); + await _secureStorage.write( + key: AuthStorageKeys.refreshToken, + value: tokens.refreshToken, + ); + } +} diff --git a/lib/core/config/app_config.dart b/lib/core/config/app_config.dart new file mode 100644 index 0000000..c6da9b7 --- /dev/null +++ b/lib/core/config/app_config.dart @@ -0,0 +1,40 @@ +import 'dart:io' show Platform; + +import 'package:flutter/foundation.dart'; + +/// Surcharge explicite via `--dart-define=API_BASE_URL=...` +const String _envApiBaseUrl = String.fromEnvironment('API_BASE_URL'); + +/// URL de base de l'API Laverie. +/// +/// Priorité : +/// 1. `API_BASE_URL` passé en `--dart-define` +/// 2. Valeur par défaut selon la plateforme : +/// - Android émulateur : `10.0.2.2` (localhost de l'hôte) +/// - iOS simulateur : `127.0.0.1` +/// 3. Appareil physique : toujours passer `--dart-define=API_BASE_URL=http://IP:8000/api/v1` +String get kApiBaseUrl { + if (_envApiBaseUrl.isNotEmpty) { + return _envApiBaseUrl; + } + + if (kIsWeb) { + throw UnsupportedError('Le web Flutter n\'est pas supporté.'); + } + + if (Platform.isAndroid) { + return 'http://10.0.2.2:8000/api/v1'; + } + + if (Platform.isIOS) { + return 'http://127.0.0.1:8000/api/v1'; + } + + throw UnsupportedError('Plateforme non supportée.'); +} + +/// Clés de stockage sécurisé pour les jetons d'authentification. +abstract final class AuthStorageKeys { + static const accessToken = 'laverie_access_token'; + static const refreshToken = 'laverie_refresh_token'; +} diff --git a/lib/core/config/secure_storage_config.dart b/lib/core/config/secure_storage_config.dart new file mode 100644 index 0000000..b46ef1f --- /dev/null +++ b/lib/core/config/secure_storage_config.dart @@ -0,0 +1,14 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +/// Configuration du stockage sécurisé adaptée Android / iOS. +/// +/// Android : SharedPreferences chiffrées (Keystore). +/// iOS : Keychain avec accessibilité au premier déverrouillage. +const FlutterSecureStorage laverieSecureStorage = FlutterSecureStorage( + aOptions: AndroidOptions( + encryptedSharedPreferences: true, + ), + iOptions: IOSOptions( + accessibility: KeychainAccessibility.first_unlock, + ), +); diff --git a/lib/core/platform/app_platform.dart b/lib/core/platform/app_platform.dart new file mode 100644 index 0000000..88728cc --- /dev/null +++ b/lib/core/platform/app_platform.dart @@ -0,0 +1,39 @@ +import 'dart:io' show Platform; + +import 'package:flutter/foundation.dart'; + +/// Plateformes supportées par l'application (mobile natif uniquement, pas de web). +enum AppPlatform { + android, + ios, +} + +/// Indique si la plateforme courante est supportée (Android ou iOS). +bool get isMobilePlatformSupported { + if (kIsWeb) { + return false; + } + return Platform.isAndroid || Platform.isIOS; +} + +/// Plateforme courante. Lance une exception si web ou desktop. +AppPlatform get currentAppPlatform { + if (kIsWeb) { + throw UnsupportedError( + 'Laverie Mobile ne cible pas le web. Utilisez Android ou iOS.', + ); + } + if (Platform.isAndroid) { + return AppPlatform.android; + } + if (Platform.isIOS) { + return AppPlatform.ios; + } + throw UnsupportedError( + 'Plateforme non supportée. Cible : Android (prioritaire) et iOS.', + ); +} + +bool get isAndroid => !kIsWeb && Platform.isAndroid; + +bool get isIos => !kIsWeb && Platform.isIOS; diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart new file mode 100644 index 0000000..0f62cd7 --- /dev/null +++ b/lib/core/router/app_router.dart @@ -0,0 +1,96 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../auth/auth_provider.dart'; +import '../../features/auth/presentation/login_screen.dart'; +import '../../features/auth/presentation/register_screen.dart'; +import '../../features/home/presentation/home_screen.dart'; +import '../../features/establishments/presentation/establishment_detail_screen.dart'; +import '../../features/wallet/presentation/wallet_screen.dart'; +import '../../features/booking/presentation/bookings_screen.dart'; +import '../../features/wash/presentation/wash_screen.dart'; +import '../../features/profile/presentation/profile_screen.dart'; + +/// Routes nommées de l'application. +abstract final class AppRoutes { + static const login = '/login'; + static const register = '/register'; + static const home = '/'; + static const wallet = '/wallet'; + static const bookings = '/bookings'; + static const washes = '/washes'; + static const profile = '/profile'; + static const establishment = '/establishments/:uuid'; +} + +/// Configuration GoRouter avec redirection selon l'état d'authentification. +final appRouterProvider = Provider((ref) { + final authState = ref.watch(authProvider); + + return GoRouter( + initialLocation: AppRoutes.home, + refreshListenable: GoRouterRefreshStream(ref), + redirect: (context, state) { + final isAuthenticated = authState.isAuthenticated; + final isAuthRoute = state.matchedLocation == AppRoutes.login || + state.matchedLocation == AppRoutes.register; + + if (!isAuthenticated && !isAuthRoute) { + return AppRoutes.login; + } + + if (isAuthenticated && isAuthRoute) { + return AppRoutes.home; + } + + return null; + }, + routes: [ + GoRoute( + path: AppRoutes.login, + builder: (context, state) => const LoginScreen(), + ), + GoRoute( + path: AppRoutes.register, + builder: (context, state) => const RegisterScreen(), + ), + GoRoute( + path: AppRoutes.home, + builder: (context, state) => const HomeScreen(), + ), + GoRoute( + path: AppRoutes.establishment, + builder: (context, state) { + final uuid = state.pathParameters['uuid']!; + return EstablishmentDetailScreen(establishmentUuid: uuid); + }, + ), + GoRoute( + path: AppRoutes.wallet, + builder: (context, state) => const WalletScreen(), + ), + GoRoute( + path: AppRoutes.bookings, + builder: (context, state) => const BookingsScreen(), + ), + GoRoute( + path: AppRoutes.washes, + builder: (context, state) => const WashScreen(), + ), + GoRoute( + path: AppRoutes.profile, + builder: (context, state) => const ProfileScreen(), + ), + ], + ); +}); + +/// Écoute les changements Riverpod pour rafraîchir les redirections GoRouter. +class GoRouterRefreshStream extends ChangeNotifier { + GoRouterRefreshStream(this._ref) { + _ref.listen(authProvider, (_, __) => notifyListeners()); + } + + final Ref _ref; +} diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..58ff41a --- /dev/null +++ b/lib/core/theme/app_theme.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +/// Thème visuel de l'application Laverie. +class AppTheme { + AppTheme._(); + + static const Color _primary = Color(0xFF1565C0); + static const Color _secondary = Color(0xFF26A69A); + + static ThemeData get light { + final colorScheme = ColorScheme.fromSeed( + seedColor: _primary, + secondary: _secondary, + brightness: Brightness.light, + ); + + return ThemeData( + useMaterial3: true, + colorScheme: colorScheme, + appBarTheme: AppBarTheme( + centerTitle: true, + backgroundColor: colorScheme.primary, + foregroundColor: colorScheme.onPrimary, + elevation: 0, + ), + cardTheme: CardThemeData( + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + inputDecorationTheme: InputDecorationTheme( + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + minimumSize: const Size.fromHeight(48), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + backgroundColor: colorScheme.secondary, + foregroundColor: colorScheme.onSecondary, + ), + ); + } +} diff --git a/lib/features/auth/domain/auth_user.dart b/lib/features/auth/domain/auth_user.dart new file mode 100644 index 0000000..39c5f5a --- /dev/null +++ b/lib/features/auth/domain/auth_user.dart @@ -0,0 +1,53 @@ +/// Modèle utilisateur authentifié. +class AuthUser { + const AuthUser({ + required this.uuid, + required this.firstName, + required this.lastName, + required this.email, + this.phone, + this.locale = 'fr', + }); + + final String uuid; + final String firstName; + final String lastName; + final String email; + final String? phone; + final String locale; + + String get fullName => '$firstName $lastName'.trim(); + + factory AuthUser.fromJson(Map json) { + return AuthUser( + uuid: json['uuid'] as String, + firstName: json['first_name'] as String? ?? '', + lastName: json['last_name'] as String? ?? '', + email: json['email'] as String, + phone: json['phone'] as String?, + locale: json['locale'] as String? ?? 'fr', + ); + } +} + +/// Réponse d'authentification (login / register / refresh). +class AuthTokens { + const AuthTokens({ + required this.accessToken, + required this.refreshToken, + this.user, + }); + + final String accessToken; + final String refreshToken; + final AuthUser? user; + + factory AuthTokens.fromJson(Map json) { + final userJson = json['user'] as Map?; + return AuthTokens( + accessToken: json['access_token'] as String? ?? json['token'] as String, + refreshToken: json['refresh_token'] as String, + user: userJson != null ? AuthUser.fromJson(userJson) : null, + ); + } +} diff --git a/lib/features/auth/presentation/login_screen.dart b/lib/features/auth/presentation/login_screen.dart new file mode 100644 index 0000000..c5f0805 --- /dev/null +++ b/lib/features/auth/presentation/login_screen.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/auth/auth_provider.dart'; +import '../../../core/router/app_router.dart'; + +/// Écran de connexion utilisateur. +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final _formKey = GlobalKey(); + final _emailController = TextEditingController(text: 'marie.dupont@demo.local'); + final _passwordController = TextEditingController(text: 'password'); + + @override + void dispose() { + _emailController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + Future _submit() async { + if (!_formKey.currentState!.validate()) return; + + final success = await ref.read(authProvider.notifier).login( + _emailController.text.trim(), + _passwordController.text, + ); + + if (success && mounted) { + context.go(AppRoutes.home); + } + } + + @override + Widget build(BuildContext context) { + final authState = ref.watch(authProvider); + + return Scaffold( + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Icon(Icons.local_laundry_service, size: 72, color: Theme.of(context).colorScheme.primary), + const SizedBox(height: 16), + Text( + 'Laverie Connectée', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 8), + Text( + 'Connectez-vous pour réserver et laver', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 32), + TextFormField( + controller: _emailController, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Email requis'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: _passwordController, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Mot de passe', + prefixIcon: Icon(Icons.lock_outline), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Mot de passe requis'; + } + return null; + }, + ), + if (authState.error != null) ...[ + const SizedBox(height: 12), + Text( + authState.error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + textAlign: TextAlign.center, + ), + ], + const SizedBox(height: 24), + ElevatedButton( + onPressed: authState.isLoading ? null : _submit, + child: authState.isLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('Se connecter'), + ), + const SizedBox(height: 12), + TextButton( + onPressed: () => context.push(AppRoutes.register), + child: const Text('Créer un compte'), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/auth/presentation/register_screen.dart b/lib/features/auth/presentation/register_screen.dart new file mode 100644 index 0000000..c711f17 --- /dev/null +++ b/lib/features/auth/presentation/register_screen.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/auth/auth_provider.dart'; +import '../../../core/router/app_router.dart'; + +/// Écran d'inscription utilisateur. +class RegisterScreen extends ConsumerStatefulWidget { + const RegisterScreen({super.key}); + + @override + ConsumerState createState() => _RegisterScreenState(); +} + +class _RegisterScreenState extends ConsumerState { + final _formKey = GlobalKey(); + final _firstNameController = TextEditingController(); + final _lastNameController = TextEditingController(); + final _emailController = TextEditingController(); + final _phoneController = TextEditingController(); + final _passwordController = TextEditingController(); + + @override + void dispose() { + _firstNameController.dispose(); + _lastNameController.dispose(); + _emailController.dispose(); + _phoneController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + Future _submit() async { + if (!_formKey.currentState!.validate()) return; + + final success = await ref.read(authProvider.notifier).register( + firstName: _firstNameController.text.trim(), + lastName: _lastNameController.text.trim(), + email: _emailController.text.trim(), + password: _passwordController.text, + phone: _phoneController.text.trim().isEmpty + ? null + : _phoneController.text.trim(), + ); + + if (success && mounted) { + context.go(AppRoutes.home); + } + } + + @override + Widget build(BuildContext context) { + final authState = ref.watch(authProvider); + + return Scaffold( + appBar: AppBar(title: const Text('Inscription')), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextFormField( + controller: _firstNameController, + decoration: const InputDecoration(labelText: 'Prénom'), + validator: (v) => v == null || v.isEmpty ? 'Prénom requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _lastNameController, + decoration: const InputDecoration(labelText: 'Nom'), + validator: (v) => v == null || v.isEmpty ? 'Nom requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _emailController, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration(labelText: 'Email'), + validator: (v) => v == null || v.isEmpty ? 'Email requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _phoneController, + keyboardType: TextInputType.phone, + decoration: const InputDecoration(labelText: 'Téléphone (optionnel)'), + ), + const SizedBox(height: 12), + TextFormField( + controller: _passwordController, + obscureText: true, + decoration: const InputDecoration(labelText: 'Mot de passe'), + validator: (v) { + if (v == null || v.length < 8) { + return 'Minimum 8 caractères'; + } + return null; + }, + ), + if (authState.error != null) ...[ + const SizedBox(height: 12), + Text( + authState.error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + const SizedBox(height: 24), + ElevatedButton( + onPressed: authState.isLoading ? null : _submit, + child: authState.isLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('S\'inscrire'), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/booking/domain/booking.dart b/lib/features/booking/domain/booking.dart new file mode 100644 index 0000000..ce2b7cd --- /dev/null +++ b/lib/features/booking/domain/booking.dart @@ -0,0 +1,38 @@ +/// Modèle réservation de créneau machine. +class Booking { + const Booking({ + required this.uuid, + required this.machineUuid, + required this.machineName, + required this.slotStart, + required this.slotEnd, + required this.status, + this.bookingFee = 0, + }); + + final String uuid; + final String machineUuid; + final String machineName; + final DateTime? slotStart; + final DateTime? slotEnd; + final String status; + final double bookingFee; + + factory Booking.fromJson(Map json) { + final machine = json['machine'] as Map?; + + return Booking( + uuid: json['uuid'] as String, + machineUuid: machine?['uuid'] as String? ?? json['machine_uuid'] as String? ?? '', + machineName: machine?['name'] as String? ?? 'Machine', + slotStart: json['slot_start'] != null + ? DateTime.tryParse(json['slot_start'] as String) + : null, + slotEnd: json['slot_end'] != null + ? DateTime.tryParse(json['slot_end'] as String) + : null, + status: json['status'] as String? ?? 'pending', + bookingFee: (json['booking_fee'] as num?)?.toDouble() ?? 0, + ); + } +} diff --git a/lib/features/booking/presentation/bookings_screen.dart b/lib/features/booking/presentation/bookings_screen.dart new file mode 100644 index 0000000..3c796c0 --- /dev/null +++ b/lib/features/booking/presentation/bookings_screen.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../domain/booking.dart'; + +/// Fournisseur des réservations de l'utilisateur connecté. +final bookingsProvider = FutureProvider>((ref) async { + final response = await ref.watch(apiClientProvider).get(ApiEndpoints.bookings); + final data = response.data; + + List list; + if (data is List) { + list = data; + } else if (data is Map && data['data'] is List) { + list = data['data'] as List; + } else { + list = []; + } + + return list + .map((json) => Booking.fromJson(json as Map)) + .toList(); +}); + +/// Écran listant les réservations de l'utilisateur. +class BookingsScreen extends ConsumerWidget { + const BookingsScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final bookingsAsync = ref.watch(bookingsProvider); + + return Scaffold( + appBar: AppBar(title: const Text('Mes réservations')), + body: bookingsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Erreur : $error'), + const SizedBox(height: 12), + ElevatedButton( + onPressed: () => ref.invalidate(bookingsProvider), + child: const Text('Réessayer'), + ), + ], + ), + ), + data: (bookings) { + if (bookings.isEmpty) { + return const Center( + child: Text('Aucune réservation.\nRéservez un créneau depuis une laverie.'), + ); + } + + return RefreshIndicator( + onRefresh: () async => ref.invalidate(bookingsProvider), + child: ListView.separated( + padding: const EdgeInsets.all(16), + itemCount: bookings.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final booking = bookings[index]; + return Card( + child: ListTile( + leading: const Icon(Icons.event), + title: Text(booking.machineName), + subtitle: Text( + booking.slotStart != null + ? DateFormat('dd/MM/yyyy HH:mm').format(booking.slotStart!) + : 'Créneau à confirmer', + ), + trailing: Chip(label: Text(booking.status)), + ), + ); + }, + ), + ); + }, + ), + ); + } +} diff --git a/lib/features/establishments/data/establishment_repository.dart b/lib/features/establishments/data/establishment_repository.dart new file mode 100644 index 0000000..682c14f --- /dev/null +++ b/lib/features/establishments/data/establishment_repository.dart @@ -0,0 +1,58 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../domain/establishment.dart'; + +/// Dépôt de données pour les établissements et machines. +class EstablishmentRepository { + EstablishmentRepository(this._apiClient); + + final ApiClient _apiClient; + + Future> fetchEstablishments() async { + final response = await _apiClient.get(ApiEndpoints.establishments); + final data = _extractList(response.data); + + return data + .map((json) => Establishment.fromJson(json as Map)) + .toList(); + } + + Future fetchEstablishment(String uuid) async { + final response = await _apiClient.get(ApiEndpoints.establishment(uuid)); + final json = _extractObject(response.data); + return Establishment.fromJson(json); + } + + List _extractList(dynamic data) { + if (data is List) return data; + if (data is Map && data['data'] is List) { + return data['data'] as List; + } + return []; + } + + Map _extractObject(dynamic data) { + if (data is Map) { + if (data['data'] is Map) { + return data['data'] as Map; + } + return data; + } + throw StateError('Réponse API inattendue'); + } +} + +final establishmentRepositoryProvider = Provider((ref) { + return EstablishmentRepository(ref.watch(apiClientProvider)); +}); + +final establishmentsProvider = FutureProvider>((ref) async { + return ref.watch(establishmentRepositoryProvider).fetchEstablishments(); +}); + +final establishmentDetailProvider = + FutureProvider.family((ref, uuid) async { + return ref.watch(establishmentRepositoryProvider).fetchEstablishment(uuid); +}); diff --git a/lib/features/establishments/domain/establishment.dart b/lib/features/establishments/domain/establishment.dart new file mode 100644 index 0000000..da0db53 --- /dev/null +++ b/lib/features/establishments/domain/establishment.dart @@ -0,0 +1,110 @@ +/// Modèle établissement (laverie). +class Establishment { + const Establishment({ + required this.uuid, + required this.name, + required this.address, + this.city, + this.zipCode, + this.latitude, + this.longitude, + this.isActive = true, + this.machines = const [], + }); + + final String uuid; + final String name; + final String address; + final String? city; + final String? zipCode; + final double? latitude; + final double? longitude; + final bool isActive; + final List machines; + + String get fullAddress { + final parts = [address, zipCode, city].where((p) => p != null && p.isNotEmpty); + return parts.join(', '); + } + + factory Establishment.fromJson(Map json) { + final machinesJson = json['machines'] as List? ?? []; + + return Establishment( + uuid: json['uuid'] as String, + name: json['name'] as String, + address: json['address'] as String? ?? '', + city: json['city'] as String?, + zipCode: json['zip_code'] as String?, + latitude: (json['latitude'] as num?)?.toDouble(), + longitude: (json['longitude'] as num?)?.toDouble(), + isActive: json['is_active'] as bool? ?? true, + machines: machinesJson + .map((m) => Machine.fromJson(m as Map)) + .toList(), + ); + } +} + +/// Modèle machine (lave-linge / sèche-linge). +class Machine { + const Machine({ + required this.uuid, + required this.name, + required this.type, + required this.status, + this.qrCode, + }); + + final String uuid; + final String name; + final String type; + final String status; + final String? qrCode; + + bool get isAvailable => status == 'available'; + + String get typeLabel { + switch (type) { + case 'washer_small': + return 'Lave-linge petit'; + case 'washer_large': + return 'Lave-linge grand'; + case 'dryer_small': + return 'Sèche-linge petit'; + case 'dryer_large': + return 'Sèche-linge grand'; + default: + return type; + } + } + + String get statusLabel { + switch (status) { + case 'available': + return 'Disponible'; + case 'reserved': + return 'Réservée'; + case 'running': + return 'En cours'; + case 'maintenance': + return 'Maintenance'; + case 'offline': + return 'Hors ligne'; + case 'error': + return 'Erreur'; + default: + return status; + } + } + + factory Machine.fromJson(Map json) { + return Machine( + uuid: json['uuid'] as String, + name: json['name'] as String, + type: json['type'] as String, + status: json['status'] as String, + qrCode: json['qr_code'] as String?, + ); + } +} diff --git a/lib/features/establishments/presentation/establishment_detail_screen.dart b/lib/features/establishments/presentation/establishment_detail_screen.dart new file mode 100644 index 0000000..2cbcd83 --- /dev/null +++ b/lib/features/establishments/presentation/establishment_detail_screen.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../establishments/data/establishment_repository.dart'; +import '../../establishments/domain/establishment.dart'; + +/// Écran de détail d'un établissement avec liste des machines. +class EstablishmentDetailScreen extends ConsumerWidget { + const EstablishmentDetailScreen({ + super.key, + required this.establishmentUuid, + }); + + final String establishmentUuid; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final establishmentAsync = + ref.watch(establishmentDetailProvider(establishmentUuid)); + + return Scaffold( + appBar: AppBar(title: const Text('Détail laverie')), + body: establishmentAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Erreur : $error'), + const SizedBox(height: 12), + ElevatedButton( + onPressed: () => + ref.invalidate(establishmentDetailProvider(establishmentUuid)), + child: const Text('Réessayer'), + ), + ], + ), + ), + data: (establishment) => _EstablishmentBody(establishment: establishment), + ), + ); + } +} + +class _EstablishmentBody extends StatelessWidget { + const _EstablishmentBody({required this.establishment}); + + final Establishment establishment; + + @override + Widget build(BuildContext context) { + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Text( + establishment.name, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 4), + Text(establishment.fullAddress), + const SizedBox(height: 24), + Text( + 'Machines (${establishment.machines.length})', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + if (establishment.machines.isEmpty) + const Text('Aucune machine disponible') + else + ...establishment.machines.map((machine) => _MachineTile(machine: machine)), + ], + ); + } +} + +class _MachineTile extends StatelessWidget { + const _MachineTile({required this.machine}); + + final Machine machine; + + Color _statusColor(BuildContext context) { + switch (machine.status) { + case 'available': + return Colors.green; + case 'running': + return Colors.blue; + case 'reserved': + return Colors.orange; + case 'maintenance': + case 'offline': + return Colors.red; + default: + return Colors.grey; + } + } + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: Icon( + machine.type.startsWith('washer') ? Icons.water_drop : Icons.air, + color: _statusColor(context), + ), + title: Text(machine.name), + subtitle: Text('${machine.typeLabel} — ${machine.statusLabel}'), + trailing: machine.isAvailable + ? const Chip(label: Text('Libre')) + : null, + ), + ); + } +} diff --git a/lib/features/home/presentation/home_screen.dart b/lib/features/home/presentation/home_screen.dart new file mode 100644 index 0000000..2b6c9d4 --- /dev/null +++ b/lib/features/home/presentation/home_screen.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/router/app_router.dart'; +import '../../establishments/data/establishment_repository.dart'; + +/// Écran d'accueil — liste des laveries à proximité. +class HomeScreen extends ConsumerWidget { + const HomeScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final establishmentsAsync = ref.watch(establishmentsProvider); + + return Scaffold( + appBar: AppBar( + title: const Text('Laveries'), + actions: [ + IconButton( + icon: const Icon(Icons.account_balance_wallet_outlined), + onPressed: () => context.push(AppRoutes.wallet), + ), + IconButton( + icon: const Icon(Icons.person_outline), + onPressed: () => context.push(AppRoutes.profile), + ), + ], + ), + body: establishmentsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.cloud_off, size: 48), + const SizedBox(height: 12), + Text( + 'Impossible de charger les laveries.\nVérifiez que l\'API est démarrée.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () => ref.invalidate(establishmentsProvider), + child: const Text('Réessayer'), + ), + ], + ), + ), + ), + data: (establishments) { + if (establishments.isEmpty) { + return const Center(child: Text('Aucune laverie disponible')); + } + + return RefreshIndicator( + onRefresh: () async => ref.invalidate(establishmentsProvider), + child: ListView.separated( + padding: const EdgeInsets.all(16), + itemCount: establishments.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final establishment = establishments[index]; + return Card( + child: ListTile( + leading: CircleAvatar( + child: Text(establishment.name.substring(0, 1)), + ), + title: Text(establishment.name), + subtitle: Text(establishment.fullAddress), + trailing: const Icon(Icons.chevron_right), + onTap: () => context.push('/establishments/${establishment.uuid}'), + ), + ); + }, + ), + ); + }, + ), + bottomNavigationBar: NavigationBar( + selectedIndex: 0, + onDestinationSelected: (index) { + switch (index) { + case 0: + context.go(AppRoutes.home); + case 1: + context.push(AppRoutes.bookings); + case 2: + context.push(AppRoutes.washes); + case 3: + context.push(AppRoutes.wallet); + } + }, + destinations: const [ + NavigationDestination(icon: Icon(Icons.store), label: 'Laveries'), + NavigationDestination(icon: Icon(Icons.event), label: 'Réservations'), + NavigationDestination(icon: Icon(Icons.local_laundry_service), label: 'Lavages'), + NavigationDestination(icon: Icon(Icons.wallet), label: 'Wallet'), + ], + ), + ); + } +} diff --git a/lib/features/profile/presentation/profile_screen.dart b/lib/features/profile/presentation/profile_screen.dart new file mode 100644 index 0000000..9b8f41e --- /dev/null +++ b/lib/features/profile/presentation/profile_screen.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/auth/auth_provider.dart'; +import '../../../core/router/app_router.dart'; + +/// Écran profil utilisateur et déconnexion. +class ProfileScreen extends ConsumerWidget { + const ProfileScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final authState = ref.watch(authProvider); + final user = authState.user; + + return Scaffold( + appBar: AppBar(title: const Text('Mon profil')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + CircleAvatar( + radius: 40, + child: Text( + user != null && user.firstName.isNotEmpty + ? user.firstName.substring(0, 1).toUpperCase() + : '?', + style: const TextStyle(fontSize: 32), + ), + ), + const SizedBox(height: 16), + Text( + user?.fullName ?? 'Utilisateur', + style: Theme.of(context).textTheme.titleLarge, + ), + if (user?.email != null) ...[ + const SizedBox(height: 4), + Text(user!.email), + ], + ], + ), + ), + ), + const SizedBox(height: 16), + ListTile( + leading: const Icon(Icons.language), + title: const Text('Langue'), + subtitle: Text(user?.locale ?? 'fr'), + ), + ListTile( + leading: const Icon(Icons.notifications_outlined), + title: const Text('Notifications'), + onTap: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Préférences — à implémenter')), + ); + }, + ), + const Divider(), + ListTile( + leading: Icon(Icons.logout, color: Theme.of(context).colorScheme.error), + title: Text( + 'Se déconnecter', + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + onTap: () async { + await ref.read(authProvider.notifier).logout(); + if (context.mounted) { + context.go(AppRoutes.login); + } + }, + ), + ], + ), + ); + } +} diff --git a/lib/features/wallet/data/wallet_repository.dart b/lib/features/wallet/data/wallet_repository.dart new file mode 100644 index 0000000..58d29d8 --- /dev/null +++ b/lib/features/wallet/data/wallet_repository.dart @@ -0,0 +1,58 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../domain/wallet.dart'; + +/// Dépôt de données pour le portefeuille électronique. +class WalletRepository { + WalletRepository(this._apiClient); + + final ApiClient _apiClient; + + Future fetchWallet() async { + final response = await _apiClient.get(ApiEndpoints.wallet); + final json = _extractObject(response.data); + return Wallet.fromJson(json); + } + + Future> fetchTransactions() async { + final response = await _apiClient.get(ApiEndpoints.walletTransactions); + final list = _extractList(response.data); + + return list + .map((json) => WalletTransaction.fromJson(json as Map)) + .toList(); + } + + List _extractList(dynamic data) { + if (data is List) return data; + if (data is Map && data['data'] is List) { + return data['data'] as List; + } + return []; + } + + Map _extractObject(dynamic data) { + if (data is Map) { + if (data['data'] is Map) { + return data['data'] as Map; + } + return data; + } + throw StateError('Réponse API inattendue'); + } +} + +final walletRepositoryProvider = Provider((ref) { + return WalletRepository(ref.watch(apiClientProvider)); +}); + +final walletProvider = FutureProvider((ref) async { + return ref.watch(walletRepositoryProvider).fetchWallet(); +}); + +final walletTransactionsProvider = + FutureProvider>((ref) async { + return ref.watch(walletRepositoryProvider).fetchTransactions(); +}); diff --git a/lib/features/wallet/domain/wallet.dart b/lib/features/wallet/domain/wallet.dart new file mode 100644 index 0000000..1eaa580 --- /dev/null +++ b/lib/features/wallet/domain/wallet.dart @@ -0,0 +1,49 @@ +/// Modèle portefeuille électronique. +class Wallet { + const Wallet({ + required this.currency, + required this.currentBalance, + this.status = 'active', + }); + + final String currency; + final double currentBalance; + final String status; + + factory Wallet.fromJson(Map json) { + return Wallet( + currency: json['currency'] as String? ?? 'EUR', + currentBalance: (json['current_balance'] as num?)?.toDouble() ?? 0, + status: json['status'] as String? ?? 'active', + ); + } +} + +/// Mouvement sur le portefeuille. +class WalletTransaction { + const WalletTransaction({ + required this.uuid, + required this.type, + required this.amount, + required this.balanceAfter, + required this.createdAt, + }); + + final String uuid; + final String type; + final double amount; + final double balanceAfter; + final DateTime? createdAt; + + factory WalletTransaction.fromJson(Map json) { + return WalletTransaction( + uuid: json['uuid'] as String, + type: json['type'] as String, + amount: (json['amount'] as num?)?.toDouble() ?? 0, + balanceAfter: (json['balance_after'] as num?)?.toDouble() ?? 0, + createdAt: json['created_at'] != null + ? DateTime.tryParse(json['created_at'] as String) + : null, + ); + } +} diff --git a/lib/features/wallet/presentation/wallet_screen.dart b/lib/features/wallet/presentation/wallet_screen.dart new file mode 100644 index 0000000..ed8c754 --- /dev/null +++ b/lib/features/wallet/presentation/wallet_screen.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; + +import '../data/wallet_repository.dart'; + +/// Écran du portefeuille électronique — solde et historique. +class WalletScreen extends ConsumerWidget { + const WalletScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final walletAsync = ref.watch(walletProvider); + final transactionsAsync = ref.watch(walletTransactionsProvider); + final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return Scaffold( + appBar: AppBar(title: const Text('Mon portefeuille')), + body: RefreshIndicator( + onRefresh: () async { + ref.invalidate(walletProvider); + ref.invalidate(walletTransactionsProvider); + }, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + walletAsync.when( + loading: () => const Card( + child: Padding( + padding: EdgeInsets.all(24), + child: Center(child: CircularProgressIndicator()), + ), + ), + error: (error, _) => Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Text('Erreur solde : $error'), + ), + ), + data: (wallet) => Card( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + Text( + 'Solde disponible', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + Text( + currencyFormat.format(wallet.currentBalance), + style: Theme.of(context).textTheme.displaySmall?.copyWith( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + ), + const SizedBox(height: 24), + Text( + 'Historique', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + transactionsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Text('Erreur historique : $error'), + data: (transactions) { + if (transactions.isEmpty) { + return const Text('Aucune transaction pour le moment'); + } + + return Column( + children: transactions.map((tx) { + final isCredit = tx.type == 'credit' || tx.type == 'refund'; + return Card( + child: ListTile( + leading: Icon( + isCredit ? Icons.add_circle_outline : Icons.remove_circle_outline, + color: isCredit ? Colors.green : Colors.red, + ), + title: Text(tx.type), + subtitle: tx.createdAt != null + ? Text(DateFormat('dd/MM/yyyy HH:mm').format(tx.createdAt!)) + : null, + trailing: Text( + '${isCredit ? '+' : '-'}${currencyFormat.format(tx.amount)}', + style: TextStyle( + fontWeight: FontWeight.bold, + color: isCredit ? Colors.green : Colors.red, + ), + ), + ), + ); + }).toList(), + ); + }, + ), + ], + ), + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Rechargement — à connecter à l\'API')), + ); + }, + icon: const Icon(Icons.add), + label: const Text('Recharger'), + ), + ); + } +} diff --git a/lib/features/wash/domain/wash.dart b/lib/features/wash/domain/wash.dart new file mode 100644 index 0000000..46e4de4 --- /dev/null +++ b/lib/features/wash/domain/wash.dart @@ -0,0 +1,41 @@ +/// Modèle lavage (cycle en cours ou terminé). +class Wash { + const Wash({ + required this.uuid, + required this.machineUuid, + required this.machineName, + required this.status, + required this.cost, + this.startedAt, + this.endedAt, + this.durationMinutes, + }); + + final String uuid; + final String machineUuid; + final String machineName; + final String status; + final double cost; + final DateTime? startedAt; + final DateTime? endedAt; + final int? durationMinutes; + + factory Wash.fromJson(Map json) { + final machine = json['machine'] as Map?; + + return Wash( + uuid: json['uuid'] as String, + machineUuid: machine?['uuid'] as String? ?? json['machine_uuid'] as String? ?? '', + machineName: machine?['name'] as String? ?? 'Machine', + status: json['status'] as String? ?? 'pending_start', + cost: (json['cost'] as num?)?.toDouble() ?? 0, + startedAt: json['started_at'] != null + ? DateTime.tryParse(json['started_at'] as String) + : null, + endedAt: json['ended_at'] != null + ? DateTime.tryParse(json['ended_at'] as String) + : null, + durationMinutes: json['duration_minutes'] as int?, + ); + } +} diff --git a/lib/features/wash/presentation/wash_screen.dart b/lib/features/wash/presentation/wash_screen.dart new file mode 100644 index 0000000..7a6c645 --- /dev/null +++ b/lib/features/wash/presentation/wash_screen.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../domain/wash.dart'; + +/// Fournisseur de l'historique des lavages. +final washesProvider = FutureProvider>((ref) async { + final response = await ref.watch(apiClientProvider).get(ApiEndpoints.washes); + final data = response.data; + + List list; + if (data is List) { + list = data; + } else if (data is Map && data['data'] is List) { + list = data['data'] as List; + } else { + list = []; + } + + return list.map((json) => Wash.fromJson(json as Map)).toList(); +}); + +/// Écran historique et démarrage de lavage. +class WashScreen extends ConsumerWidget { + const WashScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final washesAsync = ref.watch(washesProvider); + + return Scaffold( + appBar: AppBar(title: const Text('Mes lavages')), + body: washesAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Erreur : $error'), + const SizedBox(height: 12), + ElevatedButton( + onPressed: () => ref.invalidate(washesProvider), + child: const Text('Réessayer'), + ), + ], + ), + ), + data: (washes) { + if (washes.isEmpty) { + return const Center( + child: Text( + 'Aucun lavage enregistré.\nScannez un QR code pour démarrer un cycle.', + textAlign: TextAlign.center, + ), + ); + } + + final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return RefreshIndicator( + onRefresh: () async => ref.invalidate(washesProvider), + child: ListView.separated( + padding: const EdgeInsets.all(16), + itemCount: washes.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final wash = washes[index]; + return Card( + child: ListTile( + leading: const Icon(Icons.local_laundry_service), + title: Text(wash.machineName), + subtitle: wash.startedAt != null + ? Text(DateFormat('dd/MM/yyyy HH:mm').format(wash.startedAt!)) + : null, + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(currencyFormat.format(wash.cost)), + Text(wash.status, style: Theme.of(context).textTheme.bodySmall), + ], + ), + ), + ); + }, + ), + ); + }, + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Scan QR — à connecter à l\'API /washes/start')), + ); + }, + icon: const Icon(Icons.qr_code_scanner), + label: const Text('Scanner'), + ), + ); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..2061303 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; + +import 'core/platform/app_platform.dart'; +import 'core/router/app_router.dart'; +import 'core/theme/app_theme.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + + if (!isMobilePlatformSupported) { + throw UnsupportedError( + 'Laverie Mobile cible Android et iOS uniquement (pas de web Flutter).', + ); + } + + runApp(const ProviderScope(child: LaverieApp())); +} + +/// Point d'entrée de l'application mobile Laverie Connectée. +class LaverieApp extends ConsumerWidget { + const LaverieApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final router = ref.watch(appRouterProvider); + + return MaterialApp.router( + title: 'Laverie Connectée', + debugShowCheckedModeBanner: false, + theme: AppTheme.light, + locale: const Locale('fr', 'FR'), + supportedLocales: const [Locale('fr', 'FR')], + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + routerConfig: router, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..9acbb37 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,551 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dio: + dependency: "direct main" + description: + name: dio + sha256: aff32c08f92787a557dd5c0145ac91536481831a01b4648136373cddb0e64f8c + url: "https://pub.dev" + source: hosted + version: "5.9.2" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "2f9e64323a7c3c7ef69567d5c800424a11f8337b8b228bad02524c9fb3c1f340" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: f02fd7d2a4dc512fec615529824fdd217fecb3a3d3de68360293a551f21634b3 + url: "https://pub.dev" + source: hosted + version: "14.8.1" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + url: "https://pub.dev" + source: hosted + version: "1.18.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" + url: "https://pub.dev" + source: hosted + version: "9.4.1" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.3 <4.0.0" + flutter: ">=3.38.4" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..9146b3c --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,30 @@ +name: laverie_mobile +description: > + Application mobile native Laverie Connectée (Android + iOS). + Pas de cible web Flutter — Android en priorité, iOS préparé. +publish_to: 'none' +version: 1.0.0+1 + +environment: + sdk: '>=3.2.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + cupertino_icons: ^1.0.8 + flutter_riverpod: ^2.6.1 + go_router: ^14.8.1 + dio: ^5.8.0+1 + flutter_secure_storage: ^9.2.4 + intl: ^0.20.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +flutter: + uses-material-design: true + # Plateformes : android + ios uniquement (générées via scripts/bootstrap_platforms.*) diff --git a/scripts/bootstrap_platforms.ps1 b/scripts/bootstrap_platforms.ps1 new file mode 100644 index 0000000..e79f085 --- /dev/null +++ b/scripts/bootstrap_platforms.ps1 @@ -0,0 +1,36 @@ +# Génère les dossiers plateforme Android + iOS uniquement (sans web). +# À exécuter une fois après clone, depuis le dossier mobile/. + +$ErrorActionPreference = "Stop" + +if (-not (Get-Command flutter -ErrorAction SilentlyContinue)) { + Write-Error "Flutter n'est pas dans le PATH. Installez-le : https://docs.flutter.dev/get-started/install/windows" +} + +Write-Host "Génération des plateformes Android et iOS (sans web)..." -ForegroundColor Cyan + +flutter create . ` + --org fr.laverie ` + --project-name laverie_mobile ` + --platforms android,ios + +flutter pub get + +# Autoriser HTTP clair en debug (API locale sans HTTPS) +$debugManifest = "android/app/src/debug/AndroidManifest.xml" +if (Test-Path $debugManifest) { + @" + + + + +"@ | Set-Content -Path $debugManifest -Encoding UTF8 + Write-Host "Android debug : cleartext HTTP activé ($debugManifest)" -ForegroundColor DarkGray +} + +Write-Host "" +Write-Host "Terminé. Lancez sur Android :" -ForegroundColor Green +Write-Host " flutter run -d android" +Write-Host "" +Write-Host "Sur appareil physique, précisez l'IP du backend :" -ForegroundColor Yellow +Write-Host " flutter run -d android --dart-define=API_BASE_URL=http://192.168.x.x:8000/api/v1" diff --git a/scripts/bootstrap_platforms.sh b/scripts/bootstrap_platforms.sh new file mode 100644 index 0000000..eac0230 --- /dev/null +++ b/scripts/bootstrap_platforms.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Génère les dossiers plateforme Android + iOS uniquement (sans web). +set -euo pipefail + +cd "$(dirname "$0")/.." + +if ! command -v flutter &>/dev/null; then + echo "Flutter introuvable. https://docs.flutter.dev/get-started/install" + exit 1 +fi + +echo "Génération des plateformes Android et iOS (sans web)..." + +flutter create . \ + --org fr.laverie \ + --project-name laverie_mobile \ + --platforms android,ios + +flutter pub get + +# Autoriser HTTP clair en debug (API locale) +DEBUG_MANIFEST="android/app/src/debug/AndroidManifest.xml" +if [ -f "$DEBUG_MANIFEST" ]; then + cat > "$DEBUG_MANIFEST" <<'EOF' + + + + +EOF + echo "Android debug : cleartext HTTP activé" +fi + +echo "" +echo "Android : flutter run -d android" +echo "iOS (macOS) : flutter run -d ios" diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..f9495fe --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:laverie_mobile/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} From bf191d6396ba3c99cdc34480b5a9afbf617a8ac9 Mon Sep 17 00:00:00 2001 From: bastien Date: Fri, 3 Jul 2026 19:02:48 +0200 Subject: [PATCH 2/7] =?UTF-8?q?Integration=20fonctionnalit=C3=A9s=20V1=20(?= =?UTF-8?q?=20resas=20+=20gestion=20machines?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.kotlin/errors/errors-1783091381042.log | 3 + android/app/src/main/AndroidManifest.xml | 2 + .../reports/problems/problems-report.html | 663 ++++++++++++++++++ android/gradle.properties | 5 +- ios/Runner/Info.plist | 2 + lib/core/api/api_client.dart | 31 +- lib/core/api/api_endpoints.dart | 6 + lib/core/api/api_response.dart | 58 ++ lib/core/auth/auth_provider.dart | 36 +- lib/core/auth/auth_repository.dart | 19 +- lib/core/router/app_router.dart | 85 ++- lib/core/theme/app_colors.dart | 47 ++ lib/core/theme/app_theme.dart | 108 ++- lib/core/theme/machine_status_theme.dart | 30 + lib/core/widgets/empty_state.dart | 56 ++ lib/core/widgets/machine_grid_layout.dart | 31 + lib/core/widgets/machine_widgets.dart | 450 ++++++++++++ lib/core/widgets/main_shell.dart | 104 +++ lib/core/widgets/screen_header.dart | 92 +++ lib/core/widgets/wallet_chip.dart | 74 ++ .../auth/presentation/auth_widgets.dart | 102 +++ .../auth/presentation/login_screen.dart | 189 ++++- .../auth/presentation/register_screen.dart | 138 ++-- .../auth/presentation/splash_screen.dart | 41 ++ .../booking/data/booking_repository.dart | 101 +++ lib/features/booking/domain/booking.dart | 7 + .../presentation/booking_modify_screen.dart | 224 ++++++ .../booking/presentation/bookings_screen.dart | 268 +++++-- .../data/establishment_repository.dart | 23 +- .../establishment_detail_screen.dart | 234 +++++-- .../home/presentation/home_screen.dart | 236 ++++--- .../machines/data/machine_repository.dart | 51 ++ .../machines/domain/machine_detail.dart | 52 ++ .../presentation/machine_action_screen.dart | 293 ++++++++ .../presentation/machine_booking_screen.dart | 212 ++++++ .../profile/presentation/profile_screen.dart | 117 ++-- .../wallet/data/wallet_repository.dart | 34 +- .../wallet/presentation/wallet_screen.dart | 246 ++++--- lib/features/wash/data/wash_repository.dart | 131 ++++ lib/features/wash/domain/wash.dart | 22 + lib/features/wash/domain/wash_progress.dart | 114 +++ .../wash/presentation/qr_scanner_screen.dart | 219 ++++++ .../wash/presentation/wash_screen.dart | 217 +++--- .../widgets/active_wash_progress_card.dart | 163 +++++ pubspec.lock | 8 + pubspec.yaml | 1 + 46 files changed, 4691 insertions(+), 654 deletions(-) create mode 100644 android/.kotlin/errors/errors-1783091381042.log create mode 100644 android/build/reports/problems/problems-report.html create mode 100644 lib/core/api/api_response.dart create mode 100644 lib/core/theme/app_colors.dart create mode 100644 lib/core/theme/machine_status_theme.dart create mode 100644 lib/core/widgets/empty_state.dart create mode 100644 lib/core/widgets/machine_grid_layout.dart create mode 100644 lib/core/widgets/machine_widgets.dart create mode 100644 lib/core/widgets/main_shell.dart create mode 100644 lib/core/widgets/screen_header.dart create mode 100644 lib/core/widgets/wallet_chip.dart create mode 100644 lib/features/auth/presentation/auth_widgets.dart create mode 100644 lib/features/auth/presentation/splash_screen.dart create mode 100644 lib/features/booking/data/booking_repository.dart create mode 100644 lib/features/booking/presentation/booking_modify_screen.dart create mode 100644 lib/features/machines/data/machine_repository.dart create mode 100644 lib/features/machines/domain/machine_detail.dart create mode 100644 lib/features/machines/presentation/machine_action_screen.dart create mode 100644 lib/features/machines/presentation/machine_booking_screen.dart create mode 100644 lib/features/wash/data/wash_repository.dart create mode 100644 lib/features/wash/domain/wash_progress.dart create mode 100644 lib/features/wash/presentation/qr_scanner_screen.dart create mode 100644 lib/features/wash/presentation/widgets/active_wash_progress_card.dart diff --git a/android/.kotlin/errors/errors-1783091381042.log b/android/.kotlin/errors/errors-1783091381042.log new file mode 100644 index 0000000..88185a8 --- /dev/null +++ b/android/.kotlin/errors/errors-1783091381042.log @@ -0,0 +1,3 @@ +kotlin version: 2.3.20 +error message: Daemon compilation failed + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index e47ed2c..1dff5c0 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,4 +1,6 @@ + + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties index e96108c..d489590 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -2,5 +2,8 @@ org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m android.useAndroidX=true # This newDsl flag was added by the Flutter template android.newDsl=false -# This builtInKotlin flag was added by the Flutter template +# Compatibilité plugins Flutter pas encore migrés vers le Kotlin intégré AGP 9 android.builtInKotlin=false +# Évite les erreurs de cache Kotlin cross-disques (C: pub cache / D: projet) sous Windows +kotlin.incremental=false +kotlin.compiler.execution.strategy=in-process diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index b6c147e..cce2aa4 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -47,6 +47,8 @@ + NSCameraUsageDescription + Scanner les QR codes des machines de laverie. UIApplicationSupportsIndirectInputEvents UILaunchStoryboardName diff --git a/lib/core/api/api_client.dart b/lib/core/api/api_client.dart index 6e5fd6e..08bbd88 100644 --- a/lib/core/api/api_client.dart +++ b/lib/core/api/api_client.dart @@ -9,7 +9,8 @@ class ApiClient { ApiClient({ required this.baseUrl, this.getAccessToken, - this.onUnauthorized, + this.onRefreshToken, + this.onSessionExpired, }) : _dio = Dio( BaseOptions( baseUrl: baseUrl, @@ -31,9 +32,27 @@ class ApiClient { handler.next(options); }, onError: (error, handler) async { - if (error.response?.statusCode == 401) { - await onUnauthorized?.call(); + final response = error.response; + final alreadyRetried = error.requestOptions.extra['auth_retried'] == true; + + if (response?.statusCode == 401 && !alreadyRetried && onRefreshToken != null) { + final newToken = await onRefreshToken!(); + if (newToken != null && newToken.isNotEmpty) { + final request = error.requestOptions; + request.extra['auth_retried'] = true; + request.headers['Authorization'] = 'Bearer $newToken'; + + try { + final retryResponse = await _dio.fetch(request); + return handler.resolve(retryResponse); + } on DioException catch (retryError) { + return handler.next(retryError); + } + } + + await onSessionExpired?.call(); } + handler.next(error); }, ), @@ -42,7 +61,8 @@ class ApiClient { final String baseUrl; final Future Function()? getAccessToken; - final Future Function()? onUnauthorized; + final Future Function()? onRefreshToken; + final Future Function()? onSessionExpired; final Dio _dio; Dio get dio => _dio; @@ -94,6 +114,7 @@ final apiClientProvider = Provider((ref) { return ApiClient( baseUrl: kApiBaseUrl, getAccessToken: () async => ref.read(authProvider).accessToken, - onUnauthorized: () async => authNotifier.logout(), + onRefreshToken: () => authNotifier.refreshAccessToken(), + onSessionExpired: () => authNotifier.sessionExpired(), ); }); diff --git a/lib/core/api/api_endpoints.dart b/lib/core/api/api_endpoints.dart index a8d9655..d91df54 100644 --- a/lib/core/api/api_endpoints.dart +++ b/lib/core/api/api_endpoints.dart @@ -1,5 +1,9 @@ /// Chemins des endpoints REST de l'API Laverie v1. abstract final class ApiEndpoints { + // Santé / monitoring + static const health = '/health'; + static const healthDb = '/health/db'; + // Authentification utilisateur static const authRegister = '/auth/register'; static const authLogin = '/auth/login'; @@ -17,6 +21,7 @@ abstract final class ApiEndpoints { static const establishments = '/establishments'; static String establishment(String uuid) => '/establishments/$uuid'; static String machine(String uuid) => '/machines/$uuid'; + static const machineLookup = '/machines/lookup'; static String machineAvailability(String uuid) => '/machines/$uuid/availability'; static String machinePricing(String uuid) => '/machines/$uuid/pricing'; @@ -24,6 +29,7 @@ abstract final class ApiEndpoints { static const bookings = '/bookings'; static String booking(String uuid) => '/bookings/$uuid'; static String bookingCancel(String uuid) => '/bookings/$uuid/cancel'; + static String bookingMove(String uuid) => '/bookings/$uuid/move'; // Lavages static const washes = '/washes'; diff --git a/lib/core/api/api_response.dart b/lib/core/api/api_response.dart new file mode 100644 index 0000000..3b4d361 --- /dev/null +++ b/lib/core/api/api_response.dart @@ -0,0 +1,58 @@ +import 'package:dio/dio.dart'; + +/// Helpers pour parser les réponses JSON de l'API Laverie (`success` + `data`). +abstract final class ApiResponse { static Map payload(dynamic data) { + if (data is Map) { + if (data['data'] is Map) { + return data['data'] as Map; + } + return data; + } + throw StateError('Réponse API inattendue'); + } + + static List list(dynamic data, String key) { + final value = payload(data)[key]; + if (value is List) { + return value; + } + return []; + } + + static Map object(dynamic data, String key) { + final value = payload(data)[key]; + if (value is Map) { + return value; + } + throw StateError('Champ API "$key" introuvable ou invalide'); + } + + static String errorMessage(DioException error, {String fallback = 'Erreur réseau'}) { + final response = error.response; + if (response?.data is Map) { + final data = response!.data as Map; + final message = data['message']; + if (message is String && message.isNotEmpty) { + return _sanitize(message); + } + } + + return switch (error.type) { + DioExceptionType.connectionTimeout || + DioExceptionType.sendTimeout || + DioExceptionType.receiveTimeout => + 'Délai d\'attente dépassé', + DioExceptionType.connectionError => + 'Connexion impossible', + _ => fallback, + }; + } + + /// Masque les détails SQL techniques pour l'utilisateur. + static String _sanitize(String message) { + if (message.contains('SQLSTATE') || message.contains('SQL:') || message.contains('must be of type')) { + return 'Erreur serveur — réessayez dans un instant'; + } + return message; + } +} \ No newline at end of file diff --git a/lib/core/auth/auth_provider.dart b/lib/core/auth/auth_provider.dart index c8b53dc..4d3546a 100644 --- a/lib/core/auth/auth_provider.dart +++ b/lib/core/auth/auth_provider.dart @@ -2,6 +2,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/api_client.dart'; import '../config/app_config.dart'; +import '../config/secure_storage_config.dart'; import '../../features/auth/domain/auth_user.dart'; import 'auth_repository.dart'; @@ -44,12 +45,33 @@ class AuthState { /// Gestionnaire d'état Riverpod pour l'authentification. class AuthNotifier extends StateNotifier { - AuthNotifier(this._repository) : super(const AuthState()) { + AuthNotifier(this._repository) : super(const AuthState(isLoading: true)) { _restoreSession(); } final AuthRepository _repository; + /// Tente de renouveler le token d'accès (appelé par le client API sur 401). + Future refreshAccessToken() async { + final refreshed = await _repository.refresh(); + if (refreshed == null) { + return null; + } + + state = state.copyWith( + accessToken: refreshed.accessToken, + refreshToken: refreshed.refreshToken, + user: refreshed.user ?? state.user, + ); + + return refreshed.accessToken; + } + + /// Session expirée après échec du refresh. + Future sessionExpired() async { + await logout(); + } + Future _restoreSession() async { state = state.copyWith(isLoading: true, clearError: true); @@ -149,8 +171,16 @@ class AuthNotifier extends StateNotifier { } final authRepositoryProvider = Provider((ref) { - // Client dédié à l'auth pour éviter une dépendance circulaire avec apiClientProvider. - return AuthRepository(apiClient: ApiClient(baseUrl: kApiBaseUrl)); + final storage = laverieSecureStorage; + + // Token lu depuis le stockage sécurisé (évite la dépendance circulaire avec authProvider). + return AuthRepository( + apiClient: ApiClient( + baseUrl: kApiBaseUrl, + getAccessToken: () => storage.read(key: AuthStorageKeys.accessToken), + ), + secureStorage: storage, + ); }); final authProvider = StateNotifierProvider((ref) { diff --git a/lib/core/auth/auth_repository.dart b/lib/core/auth/auth_repository.dart index 74f332c..1edf2b7 100644 --- a/lib/core/auth/auth_repository.dart +++ b/lib/core/auth/auth_repository.dart @@ -2,6 +2,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../api/api_client.dart'; import '../api/api_endpoints.dart'; +import '../api/api_response.dart'; import '../config/app_config.dart'; import '../config/secure_storage_config.dart'; import '../../features/auth/domain/auth_user.dart'; @@ -29,7 +30,7 @@ class AuthRepository { }, ); - final tokens = AuthTokens.fromJson(response.data as Map); + final tokens = AuthTokens.fromJson(ApiResponse.payload(response.data)); await _persistTokens(tokens); return tokens; } @@ -52,7 +53,7 @@ class AuthRepository { }, ); - final tokens = AuthTokens.fromJson(response.data as Map); + final tokens = AuthTokens.fromJson(ApiResponse.payload(response.data)); await _persistTokens(tokens); return tokens; } @@ -68,23 +69,21 @@ class AuthRepository { data: {'refresh_token': refreshToken}, ); - final tokens = AuthTokens.fromJson(response.data as Map); + final tokens = AuthTokens.fromJson(ApiResponse.payload(response.data)); await _persistTokens(tokens); return tokens; } Future fetchCurrentUser() async { final response = await _apiClient.get(ApiEndpoints.authMe); - final data = response.data; + final payload = ApiResponse.payload(response.data); + final userJson = payload['user'] as Map?; - if (data is Map) { - if (data.containsKey('data')) { - return AuthUser.fromJson(data['data'] as Map); - } - return AuthUser.fromJson(data); + if (userJson != null) { + return AuthUser.fromJson(userJson); } - return null; + return AuthUser.fromJson(payload); } Future logout() async { diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart index 0f62cd7..b498e2e 100644 --- a/lib/core/router/app_router.dart +++ b/lib/core/router/app_router.dart @@ -5,23 +5,34 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../auth/auth_provider.dart'; import '../../features/auth/presentation/login_screen.dart'; import '../../features/auth/presentation/register_screen.dart'; +import '../../features/auth/presentation/splash_screen.dart'; import '../../features/home/presentation/home_screen.dart'; import '../../features/establishments/presentation/establishment_detail_screen.dart'; import '../../features/wallet/presentation/wallet_screen.dart'; +import '../../features/booking/presentation/booking_modify_screen.dart'; import '../../features/booking/presentation/bookings_screen.dart'; +import '../../features/machines/presentation/machine_action_screen.dart'; +import '../../features/machines/presentation/machine_booking_screen.dart'; +import '../../features/wash/presentation/qr_scanner_screen.dart'; import '../../features/wash/presentation/wash_screen.dart'; import '../../features/profile/presentation/profile_screen.dart'; +import '../widgets/main_shell.dart'; /// Routes nommées de l'application. abstract final class AppRoutes { + static const splash = '/splash'; static const login = '/login'; static const register = '/register'; static const home = '/'; static const wallet = '/wallet'; static const bookings = '/bookings'; static const washes = '/washes'; + static const washScan = '/washes/scan'; static const profile = '/profile'; static const establishment = '/establishments/:uuid'; + static String machineAction(String uuid) => '/machines/$uuid/action'; + static String machineBooking(String uuid) => '/machines/$uuid/book'; + static String bookingModify(String uuid) => '/bookings/$uuid/edit'; } /// Configuration GoRouter avec redirection selon l'état d'authentification. @@ -29,12 +40,24 @@ final appRouterProvider = Provider((ref) { final authState = ref.watch(authProvider); return GoRouter( - initialLocation: AppRoutes.home, + initialLocation: AppRoutes.splash, refreshListenable: GoRouterRefreshStream(ref), redirect: (context, state) { + final location = state.matchedLocation; + final onSplash = location == AppRoutes.splash; + final isAuthRoute = location == AppRoutes.login || location == AppRoutes.register; + + // Restauration de session en cours → écran de chargement. + if (authState.isLoading) { + return onSplash ? null : AppRoutes.splash; + } + + // Session restaurée → quitter le splash. + if (onSplash) { + return authState.isAuthenticated ? AppRoutes.home : AppRoutes.login; + } + final isAuthenticated = authState.isAuthenticated; - final isAuthRoute = state.matchedLocation == AppRoutes.login || - state.matchedLocation == AppRoutes.register; if (!isAuthenticated && !isAuthRoute) { return AppRoutes.login; @@ -47,6 +70,10 @@ final appRouterProvider = Provider((ref) { return null; }, routes: [ + GoRoute( + path: AppRoutes.splash, + builder: (context, state) => const SplashScreen(), + ), GoRoute( path: AppRoutes.login, builder: (context, state) => const LoginScreen(), @@ -55,9 +82,30 @@ final appRouterProvider = Provider((ref) { path: AppRoutes.register, builder: (context, state) => const RegisterScreen(), ), - GoRoute( - path: AppRoutes.home, - builder: (context, state) => const HomeScreen(), + ShellRoute( + builder: (context, state, child) => MainShell(child: child), + routes: [ + GoRoute( + path: AppRoutes.home, + builder: (context, state) => const HomeScreen(), + ), + GoRoute( + path: AppRoutes.bookings, + builder: (context, state) => const BookingsScreen(), + ), + GoRoute( + path: AppRoutes.washes, + builder: (context, state) => const WashScreen(), + ), + GoRoute( + path: AppRoutes.wallet, + builder: (context, state) => const WalletScreen(), + ), + GoRoute( + path: AppRoutes.profile, + builder: (context, state) => const ProfileScreen(), + ), + ], ), GoRoute( path: AppRoutes.establishment, @@ -67,20 +115,29 @@ final appRouterProvider = Provider((ref) { }, ), GoRoute( - path: AppRoutes.wallet, - builder: (context, state) => const WalletScreen(), + path: AppRoutes.washScan, + builder: (context, state) => const QrScannerScreen(), ), GoRoute( - path: AppRoutes.bookings, - builder: (context, state) => const BookingsScreen(), + path: '/machines/:uuid/action', + builder: (context, state) { + final uuid = state.pathParameters['uuid']!; + return MachineActionScreen(machineUuid: uuid); + }, ), GoRoute( - path: AppRoutes.washes, - builder: (context, state) => const WashScreen(), + path: '/machines/:uuid/book', + builder: (context, state) { + final uuid = state.pathParameters['uuid']!; + return MachineBookingScreen(machineUuid: uuid); + }, ), GoRoute( - path: AppRoutes.profile, - builder: (context, state) => const ProfileScreen(), + path: '/bookings/:uuid/edit', + builder: (context, state) { + final uuid = state.pathParameters['uuid']!; + return BookingModifyScreen(bookingUuid: uuid); + }, ), ], ); diff --git a/lib/core/theme/app_colors.dart b/lib/core/theme/app_colors.dart new file mode 100644 index 0000000..19bf990 --- /dev/null +++ b/lib/core/theme/app_colors.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +/// Palette équilibrée — moderne sans excès « web app ». +abstract final class AppColors { + static const primary = Color(0xFF2563EB); + static const primaryDark = Color(0xFF1D4ED8); + static const secondary = Color(0xFF0D9488); + + static const background = Color(0xFFF1F5F9); + static const surface = Color(0xFFFFFFFF); + static const surfaceVariant = Color(0xFFE2E8F0); + static const divider = Color(0xFFE2E8F0); + + static const textPrimary = Color(0xFF0F172A); + static const textSecondary = Color(0xFF64748B); + + static const success = Color(0xFF059669); + static const warning = Color(0xFFD97706); + static const error = Color(0xFFDC2626); + + /// Statuts machines — code couleur type WashOnline. + static const machineAvailable = Color(0xFF16A34A); + static const machineRunning = Color(0xFF2563EB); + static const machineReserved = Color(0xFFEA580C); + static const machineOffline = Color(0xFF94A3B8); + + static const gradientPrimary = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF2563EB), Color(0xFF1D4ED8)], + ); + + static const gradientAccent = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF2563EB), Color(0xFF0D9488)], + ); + + static const gradientSoft = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFFEFF6FF), Color(0xFFF1F5F9)], + ); + + /// Deux accents alternés pour les cartes (pas d'arc-en-ciel). + static Color cardAccent(int index) => index.isEven ? primary : secondary; +} diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart index 58ff41a..06b8d0f 100644 --- a/lib/core/theme/app_theme.dart +++ b/lib/core/theme/app_theme.dart @@ -1,45 +1,121 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'app_colors.dart'; /// Thème visuel de l'application Laverie. class AppTheme { AppTheme._(); - static const Color _primary = Color(0xFF1565C0); - static const Color _secondary = Color(0xFF26A69A); - static ThemeData get light { - final colorScheme = ColorScheme.fromSeed( - seedColor: _primary, - secondary: _secondary, - brightness: Brightness.light, + const colorScheme = ColorScheme.light( + primary: AppColors.primary, + onPrimary: Colors.white, + primaryContainer: Color(0xFFDBEAFE), + onPrimaryContainer: AppColors.primaryDark, + secondary: AppColors.secondary, + onSecondary: Colors.white, + error: AppColors.error, + onError: Colors.white, + surface: AppColors.surface, + onSurface: AppColors.textPrimary, + onSurfaceVariant: AppColors.textSecondary, ); return ThemeData( useMaterial3: true, colorScheme: colorScheme, - appBarTheme: AppBarTheme( - centerTitle: true, - backgroundColor: colorScheme.primary, - foregroundColor: colorScheme.onPrimary, + scaffoldBackgroundColor: AppColors.background, + appBarTheme: const AppBarTheme( + centerTitle: false, elevation: 0, + scrolledUnderElevation: 0, + backgroundColor: AppColors.surface, + foregroundColor: AppColors.textPrimary, + surfaceTintColor: Colors.transparent, + systemOverlayStyle: SystemUiOverlayStyle.dark, + titleTextStyle: TextStyle( + color: AppColors.textPrimary, + fontSize: 18, + fontWeight: FontWeight.w600, + ), ), cardTheme: CardThemeData( elevation: 1, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shadowColor: Colors.black.withValues(alpha: 0.06), + color: AppColors.surface, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + margin: EdgeInsets.zero, ), + dividerTheme: const DividerThemeData(color: AppColors.divider, thickness: 1), inputDecorationTheme: InputDecorationTheme( - border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), filled: true, + fillColor: AppColors.surface, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: AppColors.divider), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: AppColors.primary, width: 1.5), + ), + prefixIconColor: AppColors.textSecondary, ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(48), + elevation: 0, + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + textStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + minimumSize: const Size.fromHeight(48), + foregroundColor: AppColors.primary, + side: const BorderSide(color: AppColors.divider), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), ), - floatingActionButtonTheme: FloatingActionButtonThemeData( - backgroundColor: colorScheme.secondary, - foregroundColor: colorScheme.onSecondary, + floatingActionButtonTheme: const FloatingActionButtonThemeData( + elevation: 3, + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + ), + navigationBarTheme: NavigationBarThemeData( + elevation: 0, + height: 64, + backgroundColor: AppColors.surface, + indicatorColor: AppColors.primary.withValues(alpha: 0.12), + surfaceTintColor: Colors.transparent, + labelTextStyle: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.selected)) { + return const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppColors.primary); + } + return const TextStyle(fontSize: 12, color: AppColors.textSecondary); + }), + iconTheme: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.selected)) { + return const IconThemeData(color: AppColors.primary, size: 24); + } + return const IconThemeData(color: AppColors.textSecondary, size: 24); + }), + ), + listTileTheme: const ListTileThemeData( + contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4), + ), + textTheme: const TextTheme( + headlineMedium: TextStyle(fontSize: 22, fontWeight: FontWeight.w600, color: AppColors.textPrimary), + titleMedium: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: AppColors.textPrimary), + bodyLarge: TextStyle(fontSize: 16, color: AppColors.textPrimary), + bodyMedium: TextStyle(fontSize: 14, color: AppColors.textSecondary), ), ); } diff --git a/lib/core/theme/machine_status_theme.dart b/lib/core/theme/machine_status_theme.dart new file mode 100644 index 0000000..0fa8b3a --- /dev/null +++ b/lib/core/theme/machine_status_theme.dart @@ -0,0 +1,30 @@ +import 'package:flutter/material.dart'; + +import 'app_colors.dart'; + +/// Couleurs et libellés des statuts machine (inspiré WashOnline, plus lisible). +abstract final class MachineStatusTheme { + static Color color(String status) => switch (status) { + 'available' => AppColors.machineAvailable, + 'running' => AppColors.machineRunning, + 'reserved' => AppColors.machineReserved, + 'maintenance' || 'offline' || 'error' => AppColors.machineOffline, + _ => AppColors.textSecondary, + }; + + static String label(String status) => switch (status) { + 'available' => 'Libre', + 'running' => 'En cours', + 'reserved' => 'Réservée', + 'maintenance' => 'Maintenance', + 'offline' => 'Hors ligne', + 'error' => 'Erreur', + _ => status, + }; + + static IconData iconForType(String type) => type.startsWith('dryer') + ? Icons.air_outlined + : Icons.water_drop_outlined; + + static bool canStart(String status) => status == 'available'; +} diff --git a/lib/core/widgets/empty_state.dart b/lib/core/widgets/empty_state.dart new file mode 100644 index 0000000..e4ce681 --- /dev/null +++ b/lib/core/widgets/empty_state.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; + +/// État vide avec icône dans un cercle coloré. +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.icon, + required this.title, + required this.subtitle, + this.iconColor, + this.actionLabel, + this.onAction, + }); + + final IconData icon; + final String title; + final String subtitle; + final Color? iconColor; + final String? actionLabel; + final VoidCallback? onAction; + + @override + Widget build(BuildContext context) { + final color = iconColor ?? AppColors.primary; + + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 72, + height: 72, + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + shape: BoxShape.circle, + ), + child: Icon(icon, size: 32, color: color), + ), + const SizedBox(height: 16), + Text(title, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 6), + Text(subtitle, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodyMedium), + if (actionLabel != null && onAction != null) ...[ + const SizedBox(height: 20), + OutlinedButton(onPressed: onAction, child: Text(actionLabel!)), + ], + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/machine_grid_layout.dart b/lib/core/widgets/machine_grid_layout.dart new file mode 100644 index 0000000..c04e915 --- /dev/null +++ b/lib/core/widgets/machine_grid_layout.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +/// Grille responsive pour les cartes machines (téléphone → tablette). +abstract final class MachineGridLayout { + static const _minTileWidth = 155.0; + static const _maxTileWidth = 190.0; + + static SliverGridDelegate delegate(BuildContext context) { + final width = MediaQuery.sizeOf(context).width; + const padding = 32.0; + final available = width - padding; + + if (available > _maxTileWidth * 3) { + return const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: _maxTileWidth, + mainAxisSpacing: 10, + crossAxisSpacing: 10, + childAspectRatio: 0.88, + ); + } + + final count = (available / _minTileWidth).floor().clamp(2, 3); + + return SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: count, + mainAxisSpacing: 10, + crossAxisSpacing: 10, + childAspectRatio: count >= 3 ? 0.85 : 0.92, + ); + } +} diff --git a/lib/core/widgets/machine_widgets.dart b/lib/core/widgets/machine_widgets.dart new file mode 100644 index 0000000..2a73fd8 --- /dev/null +++ b/lib/core/widgets/machine_widgets.dart @@ -0,0 +1,450 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +import '../router/app_router.dart'; +import '../theme/app_colors.dart'; +import '../theme/machine_status_theme.dart'; +import '../../features/establishments/domain/establishment.dart'; + +/// Légende des statuts machines. +class MachineStatusLegend extends StatelessWidget { + const MachineStatusLegend({super.key}); + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 12, + runSpacing: 6, + children: [ + _LegendDot(color: AppColors.machineAvailable, label: 'Libre'), + _LegendDot(color: AppColors.machineRunning, label: 'En cours'), + _LegendDot(color: AppColors.machineReserved, label: 'Réservée'), + _LegendDot(color: AppColors.machineOffline, label: 'Indisponible'), + ], + ); + } +} + +class _LegendDot extends StatelessWidget { + const _LegendDot({required this.color, required this.label}); + + final Color color; + final String label; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 5), + Text(label, style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 12)), + ], + ); + } +} + +/// Carte machine en grille — vue d'ensemble type WashOnline. +class MachineGridCard extends StatelessWidget { + const MachineGridCard({ + super.key, + required this.machine, + required this.onTap, + }); + + final Machine machine; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final statusColor = MachineStatusTheme.color(machine.status); + final canStart = MachineStatusTheme.canStart(machine.status); + + return Material( + color: AppColors.surface, + elevation: canStart ? 2 : 0, + shadowColor: statusColor.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(20), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(20), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: canStart ? statusColor.withValues(alpha: 0.35) : AppColors.divider, + width: canStart ? 1.5 : 1, + ), + ), + padding: const EdgeInsets.all(10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + MachineStatusTheme.iconForType(machine.type), + color: statusColor, + size: 20, + ), + ), + const Spacer(), + _StatusPill(status: machine.status), + ], + ), + const SizedBox(height: 10), + Text( + machine.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleMedium?.copyWith(fontSize: 14), + ), + const SizedBox(height: 2), + Text( + machine.typeLabel, + style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 11), + ), + if (canStart) ...[ + const Spacer(), + Text( + 'Démarrer', + style: TextStyle( + color: statusColor, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ], + ], + ), + ), + ), + ); + } +} + +class _StatusPill extends StatelessWidget { + const _StatusPill({required this.status}); + + final String status; + + @override + Widget build(BuildContext context) { + final color = MachineStatusTheme.color(status); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + MachineStatusTheme.label(status), + style: TextStyle(color: color, fontSize: 10, fontWeight: FontWeight.w700), + ), + ); + } +} + +/// Statistiques rapides du parc machines. +class MachineStatsRow extends StatelessWidget { + const MachineStatsRow({super.key, required this.machines}); + + final List machines; + + @override + Widget build(BuildContext context) { + final available = machines.where((m) => m.status == 'available').length; + final running = machines.where((m) => m.status == 'running').length; + final reserved = machines.where((m) => m.status == 'reserved').length; + + return Row( + children: [ + Expanded(child: _StatBox(value: '$available', label: 'Libres', color: AppColors.machineAvailable)), + const SizedBox(width: 8), + Expanded(child: _StatBox(value: '$running', label: 'En cours', color: AppColors.machineRunning)), + const SizedBox(width: 8), + Expanded(child: _StatBox(value: '$reserved', label: 'Réservées', color: AppColors.machineReserved)), + ], + ); + } +} + +class _StatBox extends StatelessWidget { + const _StatBox({required this.value, required this.label, required this.color}); + + final String value; + final String label; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(10), + ), + child: Column( + children: [ + Text(value, style: TextStyle(color: color, fontSize: 20, fontWeight: FontWeight.w700)), + Text(label, style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 11)), + ], + ), + ); + } +} + +/// Actions rapides — démarrage en quelques clics. +class QuickActionsRow extends StatelessWidget { + const QuickActionsRow({super.key}); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Expanded( + child: _QuickAction( + icon: Icons.qr_code_scanner_rounded, + label: 'Scanner', + color: AppColors.primary, + onTap: () => context.push(AppRoutes.washScan), + ), + ), + const SizedBox(width: 10), + Expanded( + child: _QuickAction( + icon: Icons.event_available_outlined, + label: 'Réserver', + color: AppColors.machineReserved, + onTap: () => context.go(AppRoutes.bookings), + ), + ), + const SizedBox(width: 10), + Expanded( + child: _QuickAction( + icon: Icons.add_card_outlined, + label: 'Recharger', + color: AppColors.secondary, + onTap: () => context.go(AppRoutes.wallet), + ), + ), + ], + ); + } +} + +class _QuickAction extends StatelessWidget { + const _QuickAction({ + required this.icon, + required this.label, + required this.color, + required this.onTap, + }); + + final IconData icon; + final String label; + final Color color; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.surface, + elevation: 1, + shadowColor: Colors.black.withValues(alpha: 0.06), + borderRadius: BorderRadius.circular(12), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 14), + child: Column( + children: [ + Icon(icon, color: color, size: 26), + const SizedBox(height: 6), + Text(label, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)), + ], + ), + ), + ), + ); + } +} + +/// Bannière lavage en cours. +class ActiveWashBanner extends StatelessWidget { + const ActiveWashBanner({ + super.key, + required this.machineName, + required this.onTap, + }); + + final String machineName; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.primary, + borderRadius: BorderRadius.circular(14), + elevation: 2, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(14), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.local_laundry_service, color: Colors.white), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Lavage en cours', + style: TextStyle(color: Colors.white70, fontSize: 12), + ), + Text( + machineName, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 16, + ), + ), + ], + ), + ), + const Icon(Icons.chevron_right, color: Colors.white), + ], + ), + ), + ), + ); + } +} + +/// Bottom sheet détail machine + actions. +class MachineActionSheet { + static Future show( + BuildContext context, { + required Machine machine, + required VoidCallback onStart, + VoidCallback? onReserve, + }) { + final statusColor = MachineStatusTheme.color(machine.status); + final canStart = MachineStatusTheme.canStart(machine.status); + + return showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (context) => Padding( + padding: EdgeInsets.fromLTRB(20, 16, 20, 20 + MediaQuery.of(context).padding.bottom), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: AppColors.divider, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 20), + Row( + children: [ + Container( + width: 52, + height: 52, + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(14), + ), + child: Icon( + MachineStatusTheme.iconForType(machine.type), + color: statusColor, + size: 28, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(machine.name, style: Theme.of(context).textTheme.titleMedium), + Text(machine.typeLabel, style: Theme.of(context).textTheme.bodyMedium), + ], + ), + ), + _StatusPill(status: machine.status), + ], + ), + const SizedBox(height: 20), + if (canStart) ...[ + ElevatedButton.icon( + onPressed: () { + Navigator.pop(context); + onStart(); + }, + icon: const Icon(Icons.play_arrow_rounded), + label: const Text('Démarrer maintenant'), + ), + const SizedBox(height: 10), + OutlinedButton.icon( + onPressed: () { + Navigator.pop(context); + onReserve?.call(); + }, + icon: const Icon(Icons.event_outlined), + label: const Text('Réserver un créneau'), + ), + ] else + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + machine.status == 'running' + ? 'Cette machine est en cours d\'utilisation.' + : machine.status == 'reserved' + ? 'Machine réservée — elle sera disponible sur votre créneau.' + : 'Machine indisponible pour le moment.', + textAlign: TextAlign.center, + style: TextStyle(color: statusColor, fontWeight: FontWeight.w500), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/main_shell.dart b/lib/core/widgets/main_shell.dart new file mode 100644 index 0000000..705f111 --- /dev/null +++ b/lib/core/widgets/main_shell.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../router/app_router.dart'; +import '../theme/app_colors.dart'; +import 'wallet_chip.dart'; + +/// Coque principale — navigation + solde visible (style WashOnline amélioré). +class MainShell extends ConsumerWidget { + const MainShell({super.key, required this.child}); + + final Widget child; + + static int _indexFromLocation(String location) { + if (location.startsWith(AppRoutes.bookings)) return 1; + if (location.startsWith(AppRoutes.washes)) return 2; + if (location.startsWith(AppRoutes.wallet)) return 3; + if (location.startsWith(AppRoutes.profile)) return 4; + return 0; + } + + static String _titleFromLocation(String location) { + if (location.startsWith(AppRoutes.bookings)) return 'Réservations'; + if (location.startsWith(AppRoutes.washes)) return 'Mes lavages'; + if (location.startsWith(AppRoutes.wallet)) return 'Portefeuille'; + if (location.startsWith(AppRoutes.profile)) return 'Mon profil'; + return 'Accueil'; + } + + static bool _showScanFab(String location) { + return location.startsWith(AppRoutes.bookings) || + location.startsWith(AppRoutes.washes); + } + + void _onTabTap(BuildContext context, int index) { + switch (index) { + case 0: + context.go(AppRoutes.home); + case 1: + context.go(AppRoutes.bookings); + case 2: + context.go(AppRoutes.washes); + case 3: + context.go(AppRoutes.wallet); + case 4: + context.go(AppRoutes.profile); + } + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final location = GoRouterState.of(context).uri.toString(); + final selectedIndex = _indexFromLocation(location); + final showScanFab = _showScanFab(location); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar( + title: Text(_titleFromLocation(location)), + actions: const [WalletChip()], + ), + body: child, + floatingActionButton: showScanFab + ? FloatingActionButton.extended( + onPressed: () => context.push(AppRoutes.washScan), + icon: const Icon(Icons.qr_code_scanner_rounded), + label: const Text('Scanner'), + ) + : null, + bottomNavigationBar: NavigationBar( + selectedIndex: selectedIndex, + onDestinationSelected: (index) => _onTabTap(context, index), + destinations: const [ + NavigationDestination( + icon: Icon(Icons.home_outlined), + selectedIcon: Icon(Icons.home_rounded), + label: 'Accueil', + ), + NavigationDestination( + icon: Icon(Icons.event_outlined), + selectedIcon: Icon(Icons.event), + label: 'Résa', + ), + NavigationDestination( + icon: Icon(Icons.local_laundry_service_outlined), + selectedIcon: Icon(Icons.local_laundry_service), + label: 'Lavages', + ), + NavigationDestination( + icon: Icon(Icons.account_balance_wallet_outlined), + selectedIcon: Icon(Icons.account_balance_wallet), + label: 'Wallet', + ), + NavigationDestination( + icon: Icon(Icons.person_outline), + selectedIcon: Icon(Icons.person), + label: 'Profil', + ), + ], + ), + ); + } +} diff --git a/lib/core/widgets/screen_header.dart b/lib/core/widgets/screen_header.dart new file mode 100644 index 0000000..5adffcd --- /dev/null +++ b/lib/core/widgets/screen_header.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; + +/// Badge de statut discret. +class StatusBadge extends StatelessWidget { + const StatusBadge({super.key, required this.label, required this.color}); + + final String label; + final Color color; + + factory StatusBadge.fromStatus(String status) { + final (label, color) = switch (status) { + 'available' || 'confirmed' || 'completed' => ('Disponible', AppColors.machineAvailable), + 'running' || 'active' || 'pending_start' => ('En cours', AppColors.machineRunning), + 'reserved' || 'pending' => ('Réservé', AppColors.machineReserved), + 'cancelled' => ('Annulé', AppColors.textSecondary), + _ => (status, AppColors.textSecondary), + }; + return StatusBadge(label: label, color: color); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + label, + style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.w600), + ), + ); + } +} + +/// Bandeau d'en-tête discret pour les écrans principaux. +class ScreenHeader extends StatelessWidget { + const ScreenHeader({ + super.key, + required this.title, + this.subtitle, + }); + + final String title; + final String? subtitle; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + margin: const EdgeInsets.fromLTRB(16, 8, 16, 12), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + gradient: AppColors.gradientAccent, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: AppColors.primary.withValues(alpha: 0.15), + blurRadius: 8, + offset: const Offset(0, 3), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 4), + Text( + subtitle!, + style: TextStyle( + color: Colors.white.withValues(alpha: 0.9), + fontSize: 13, + ), + ), + ], + ], + ), + ); + } +} diff --git a/lib/core/widgets/wallet_chip.dart b/lib/core/widgets/wallet_chip.dart new file mode 100644 index 0000000..114623c --- /dev/null +++ b/lib/core/widgets/wallet_chip.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../router/app_router.dart'; +import '../theme/app_colors.dart'; +import '../../features/wallet/data/wallet_repository.dart'; + +/// Solde portefeuille compact — toujours visible (comme WashOnline). +class WalletChip extends ConsumerWidget { + const WalletChip({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final walletAsync = ref.watch(walletProvider); + final format = NumberFormat.currency(locale: 'fr_FR', symbol: '€', decimalDigits: 2); + + return walletAsync.when( + loading: () => const Padding( + padding: EdgeInsets.only(right: 12), + child: SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)), + ), + error: (_, __) => _ChipButton( + label: '— €', + onTap: () => context.go(AppRoutes.wallet), + ), + data: (wallet) => _ChipButton( + label: format.format(wallet.currentBalance), + onTap: () => context.go(AppRoutes.wallet), + ), + ); + } +} + +class _ChipButton extends StatelessWidget { + const _ChipButton({required this.label, required this.onTap}); + + final String label; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(right: 8), + child: Material( + color: AppColors.primary.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.account_balance_wallet_outlined, size: 16, color: AppColors.primary), + const SizedBox(width: 6), + Text( + label, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w700, + fontSize: 13, + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/auth/presentation/auth_widgets.dart b/lib/features/auth/presentation/auth_widgets.dart new file mode 100644 index 0000000..2a5962f --- /dev/null +++ b/lib/features/auth/presentation/auth_widgets.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; + +import '../../../core/theme/app_colors.dart'; + +/// Fond et carte pour les écrans d'authentification. +class AuthScaffold extends StatelessWidget { + const AuthScaffold({ + super.key, + required this.child, + this.showBackButton = false, + }); + + final Widget child; + final bool showBackButton; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration(gradient: AppColors.gradientSoft), + child: SafeArea( + child: Column( + children: [ + if (showBackButton) + Align( + alignment: Alignment.centerLeft, + child: IconButton( + onPressed: () => Navigator.of(context).maybePop(), + icon: const Icon(Icons.arrow_back), + ), + ), + Expanded( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: child, + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// Carte blanche pour formulaires auth. +class AuthFormCard extends StatelessWidget { + const AuthFormCard({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Card( + elevation: 2, + shadowColor: Colors.black.withValues(alpha: 0.08), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(24), + child: child, + ), + ), + ); + } +} + +/// Logo et titre auth. +class AuthHeader extends StatelessWidget { + const AuthHeader({super.key, required this.subtitle}); + + final String subtitle; + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Container( + width: 64, + height: 64, + decoration: BoxDecoration( + gradient: AppColors.gradientPrimary, + borderRadius: BorderRadius.circular(16), + ), + child: const Icon(Icons.local_laundry_service_outlined, size: 32, color: Colors.white), + ), + const SizedBox(height: 16), + Text( + 'Laverie Connectée', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 8), + Text(subtitle, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodyMedium), + const SizedBox(height: 24), + ], + ); + } +} diff --git a/lib/features/auth/presentation/login_screen.dart b/lib/features/auth/presentation/login_screen.dart index c5f0805..df810f1 100644 --- a/lib/features/auth/presentation/login_screen.dart +++ b/lib/features/auth/presentation/login_screen.dart @@ -1,9 +1,19 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; import '../../../core/auth/auth_provider.dart'; import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../booking/data/booking_repository.dart'; +import '../../wallet/data/wallet_repository.dart'; +import '../../wash/data/wash_repository.dart'; +import 'auth_widgets.dart'; /// Écran de connexion utilisateur. class LoginScreen extends ConsumerStatefulWidget { @@ -17,6 +27,9 @@ class _LoginScreenState extends ConsumerState { final _formKey = GlobalKey(); final _emailController = TextEditingController(text: 'marie.dupont@demo.local'); final _passwordController = TextEditingController(text: 'password'); + bool _isCheckingHealth = false; + String? _healthResult; + bool _healthHasError = false; @override void dispose() { @@ -25,6 +38,79 @@ class _LoginScreenState extends ConsumerState { super.dispose(); } + Future _checkHealth() async { + setState(() { + _isCheckingHealth = true; + _healthResult = null; + _healthHasError = false; + }); + + final apiClient = ref.read(apiClientProvider); + final lines = [ + 'URL de base : ${apiClient.baseUrl}', + '', + ]; + var hasError = false; + + for (final entry in [ + ('API', ApiEndpoints.health), + ('Base de données', ApiEndpoints.healthDb), + ]) { + final label = entry.$1; + final path = entry.$2; + final url = '${apiClient.baseUrl}$path'; + + try { + final response = await apiClient.get(path); + lines.add('$label : OK (${response.statusCode})'); + lines.add('URL : $url'); + lines.add(_formatResponse(response.data)); + } on DioException catch (error) { + hasError = true; + lines.add('$label : Erreur'); + lines.add('URL : $url'); + lines.add(_formatDioError(error)); + } + lines.add(''); + } + + if (mounted) { + setState(() { + _isCheckingHealth = false; + _healthHasError = hasError; + _healthResult = lines.join('\n').trim(); + }); + } + } + + String _formatResponse(dynamic data) { + if (data is Map || data is List) { + return const JsonEncoder.withIndent(' ').convert(data); + } + return data?.toString() ?? ''; + } + + String _formatDioError(DioException error) { + final response = error.response; + if (response != null) { + final body = response.data; + if (body is Map || body is List) { + return 'HTTP ${response.statusCode}\n${_formatResponse(body)}'; + } + return 'HTTP ${response.statusCode}: $body'; + } + + return switch (error.type) { + DioExceptionType.connectionTimeout || + DioExceptionType.sendTimeout || + DioExceptionType.receiveTimeout => + 'Délai d\'attente dépassé', + DioExceptionType.connectionError => + 'Connexion impossible (${error.message ?? 'réseau injoignable'})', + _ => error.message ?? 'Erreur réseau', + }; + } + Future _submit() async { if (!_formKey.currentState!.validate()) return; @@ -34,6 +120,10 @@ class _LoginScreenState extends ConsumerState { ); if (success && mounted) { + ref.invalidate(washesProvider); + ref.invalidate(bookingsProvider); + ref.invalidate(walletProvider); + ref.invalidate(walletTransactionsProvider); context.go(AppRoutes.home); } } @@ -42,32 +132,15 @@ class _LoginScreenState extends ConsumerState { Widget build(BuildContext context) { final authState = ref.watch(authProvider); - return Scaffold( - body: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Form( - key: _formKey, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Icon(Icons.local_laundry_service, size: 72, color: Theme.of(context).colorScheme.primary), - const SizedBox(height: 16), - Text( - 'Laverie Connectée', - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.headlineMedium, - ), - const SizedBox(height: 8), - Text( - 'Connectez-vous pour réserver et laver', - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyMedium, - ), - const SizedBox(height: 32), - TextFormField( + return AuthScaffold( + child: AuthFormCard( + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const AuthHeader(subtitle: 'Connectez-vous pour réserver et laver'), + TextFormField( controller: _emailController, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( @@ -98,10 +171,25 @@ class _LoginScreenState extends ConsumerState { ), if (authState.error != null) ...[ const SizedBox(height: 12), - Text( - authState.error!, - style: TextStyle(color: Theme.of(context).colorScheme.error), - textAlign: TextAlign.center, + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: AppColors.error.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppColors.error.withValues(alpha: 0.3)), + ), + child: Row( + children: [ + const Icon(Icons.error_outline_rounded, color: AppColors.error, size: 20), + const SizedBox(width: 8), + Expanded( + child: Text( + authState.error!, + style: const TextStyle(color: AppColors.error), + ), + ), + ], + ), ), ], const SizedBox(height: 24), @@ -111,7 +199,7 @@ class _LoginScreenState extends ConsumerState { ? const SizedBox( height: 20, width: 20, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), ) : const Text('Se connecter'), ), @@ -120,12 +208,45 @@ class _LoginScreenState extends ConsumerState { onPressed: () => context.push(AppRoutes.register), child: const Text('Créer un compte'), ), + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _isCheckingHealth ? null : _checkHealth, + icon: _isCheckingHealth + ? const SizedBox( + height: 16, + width: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.monitor_heart_outlined, size: 18), + label: const Text('Vérifier l\'API'), + ), + if (_healthResult != null) ...[ + const SizedBox(height: 12), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: (_healthHasError ? AppColors.error : AppColors.primary) + .withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: (_healthHasError ? AppColors.error : AppColors.primary) + .withValues(alpha: 0.3), + ), + ), + child: SelectableText( + _healthResult!, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + fontFamily: 'monospace', + color: _healthHasError ? AppColors.error : AppColors.primaryDark, + ), + ), + ), + ], ], ), ), ), - ), - ), - ); + ); } } diff --git a/lib/features/auth/presentation/register_screen.dart b/lib/features/auth/presentation/register_screen.dart index c711f17..7d86cb0 100644 --- a/lib/features/auth/presentation/register_screen.dart +++ b/lib/features/auth/presentation/register_screen.dart @@ -4,6 +4,8 @@ import 'package:go_router/go_router.dart'; import '../../../core/auth/auth_provider.dart'; import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import 'auth_widgets.dart'; /// Écran d'inscription utilisateur. class RegisterScreen extends ConsumerStatefulWidget { @@ -53,72 +55,82 @@ class _RegisterScreenState extends ConsumerState { Widget build(BuildContext context) { final authState = ref.watch(authProvider); - return Scaffold( - appBar: AppBar(title: const Text('Inscription')), - body: SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Form( - key: _formKey, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - TextFormField( - controller: _firstNameController, - decoration: const InputDecoration(labelText: 'Prénom'), - validator: (v) => v == null || v.isEmpty ? 'Prénom requis' : null, + return AuthScaffold( + showBackButton: true, + child: AuthFormCard( + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const AuthHeader(subtitle: 'Créez votre compte en quelques secondes'), + TextFormField( + controller: _firstNameController, + decoration: const InputDecoration( + labelText: 'Prénom', + prefixIcon: Icon(Icons.person_outline_rounded), ), + validator: (v) => v == null || v.isEmpty ? 'Prénom requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _lastNameController, + decoration: const InputDecoration( + labelText: 'Nom', + prefixIcon: Icon(Icons.badge_outlined), + ), + validator: (v) => v == null || v.isEmpty ? 'Nom requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _emailController, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined), + ), + validator: (v) => v == null || v.isEmpty ? 'Email requis' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _phoneController, + keyboardType: TextInputType.phone, + decoration: const InputDecoration( + labelText: 'Téléphone (optionnel)', + prefixIcon: Icon(Icons.phone_outlined), + ), + ), + const SizedBox(height: 12), + TextFormField( + controller: _passwordController, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Mot de passe', + prefixIcon: Icon(Icons.lock_outline), + ), + validator: (v) { + if (v == null || v.length < 8) { + return 'Minimum 8 caractères'; + } + return null; + }, + ), + if (authState.error != null) ...[ const SizedBox(height: 12), - TextFormField( - controller: _lastNameController, - decoration: const InputDecoration(labelText: 'Nom'), - validator: (v) => v == null || v.isEmpty ? 'Nom requis' : null, - ), - const SizedBox(height: 12), - TextFormField( - controller: _emailController, - keyboardType: TextInputType.emailAddress, - decoration: const InputDecoration(labelText: 'Email'), - validator: (v) => v == null || v.isEmpty ? 'Email requis' : null, - ), - const SizedBox(height: 12), - TextFormField( - controller: _phoneController, - keyboardType: TextInputType.phone, - decoration: const InputDecoration(labelText: 'Téléphone (optionnel)'), - ), - const SizedBox(height: 12), - TextFormField( - controller: _passwordController, - obscureText: true, - decoration: const InputDecoration(labelText: 'Mot de passe'), - validator: (v) { - if (v == null || v.length < 8) { - return 'Minimum 8 caractères'; - } - return null; - }, - ), - if (authState.error != null) ...[ - const SizedBox(height: 12), - Text( - authState.error!, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - ], - const SizedBox(height: 24), - ElevatedButton( - onPressed: authState.isLoading ? null : _submit, - child: authState.isLoading - ? const SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Text('S\'inscrire'), - ), + Text(authState.error!, style: const TextStyle(color: AppColors.error)), ], - ), + const SizedBox(height: 24), + ElevatedButton( + onPressed: authState.isLoading ? null : _submit, + child: authState.isLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Text('S\'inscrire'), + ), + ], ), ), ), diff --git a/lib/features/auth/presentation/splash_screen.dart b/lib/features/auth/presentation/splash_screen.dart new file mode 100644 index 0000000..e6f7c4d --- /dev/null +++ b/lib/features/auth/presentation/splash_screen.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; + +import '../../../core/theme/app_colors.dart'; + +/// Écran affiché pendant la restauration de session au démarrage. +class SplashScreen extends StatelessWidget { + const SplashScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + width: double.infinity, + decoration: const BoxDecoration(gradient: AppColors.gradientSoft), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 72, + height: 72, + decoration: BoxDecoration( + gradient: AppColors.gradientPrimary, + borderRadius: BorderRadius.circular(18), + ), + child: const Icon(Icons.local_laundry_service_outlined, size: 36, color: Colors.white), + ), + const SizedBox(height: 20), + Text( + 'Laverie Connectée', + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 32), + const CircularProgressIndicator(), + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/booking/data/booking_repository.dart b/lib/features/booking/data/booking_repository.dart new file mode 100644 index 0000000..e6e9d4c --- /dev/null +++ b/lib/features/booking/data/booking_repository.dart @@ -0,0 +1,101 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; +import '../../../core/auth/auth_provider.dart'; +import '../domain/booking.dart'; + +/// Dépôt de données pour les réservations. +class BookingRepository { + BookingRepository(this._apiClient); + + final ApiClient _apiClient; + + Future> fetchBookings() async { + final response = await _apiClient.get(ApiEndpoints.bookings); + final list = ApiResponse.list(response.data, 'bookings'); + return list.map((json) => Booking.fromJson(json as Map)).toList(); + } + + Future fetchBooking(String uuid) async { + final response = await _apiClient.get(ApiEndpoints.booking(uuid)); + final json = ApiResponse.object(response.data, 'booking'); + return Booking.fromJson(json); + } + + Future createBooking({ + required String machineUuid, + required DateTime slotStart, + required DateTime slotEnd, + }) async { + try { + final response = await _apiClient.post( + ApiEndpoints.bookings, + data: { + 'machine_uuid': machineUuid, + 'slot_start': slotStart.toUtc().toIso8601String(), + 'slot_end': slotEnd.toUtc().toIso8601String(), + }, + ); + final json = ApiResponse.object(response.data, 'booking'); + return Booking.fromJson(json); + } on DioException catch (error) { + throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible de réserver')); + } + } + + Future cancelBooking(String uuid) async { + try { + final response = await _apiClient.patch(ApiEndpoints.bookingCancel(uuid)); + final json = ApiResponse.object(response.data, 'booking'); + return Booking.fromJson(json); + } on DioException catch (error) { + throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible d\'annuler')); + } + } + + Future moveBooking({ + required String uuid, + required DateTime slotStart, + required DateTime slotEnd, + }) async { + try { + final response = await _apiClient.patch( + ApiEndpoints.bookingMove(uuid), + data: { + 'slot_start': slotStart.toUtc().toIso8601String(), + 'slot_end': slotEnd.toUtc().toIso8601String(), + }, + ); + final json = ApiResponse.object(response.data, 'booking'); + return Booking.fromJson(json); + } on DioException catch (error) { + throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible de modifier')); + } + } +} + +class BookingException implements Exception { + BookingException(this.message); + final String message; + @override + String toString() => message; +} + +final bookingRepositoryProvider = Provider((ref) { + return BookingRepository(ref.watch(apiClientProvider)); +}); + +final bookingsProvider = FutureProvider>((ref) async { + final token = ref.watch(authProvider.select((state) => state.accessToken)); + if (token == null || token.isEmpty) { + throw StateError('Non authentifié'); + } + return ref.watch(bookingRepositoryProvider).fetchBookings(); +}); + +final bookingDetailProvider = FutureProvider.family((ref, uuid) async { + return ref.watch(bookingRepositoryProvider).fetchBooking(uuid); +}); diff --git a/lib/features/booking/domain/booking.dart b/lib/features/booking/domain/booking.dart index ce2b7cd..e5789d9 100644 --- a/lib/features/booking/domain/booking.dart +++ b/lib/features/booking/domain/booking.dart @@ -18,6 +18,13 @@ class Booking { final String status; final double bookingFee; + bool get canCancel => + (status == 'confirmed' || status == 'pending') && + slotStart != null && + slotStart!.isAfter(DateTime.now()); + + bool get canModify => canCancel; + factory Booking.fromJson(Map json) { final machine = json['machine'] as Map?; diff --git a/lib/features/booking/presentation/booking_modify_screen.dart b/lib/features/booking/presentation/booking_modify_screen.dart new file mode 100644 index 0000000..1386f09 --- /dev/null +++ b/lib/features/booking/presentation/booking_modify_screen.dart @@ -0,0 +1,224 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../machines/data/machine_repository.dart'; +import '../../machines/domain/machine_detail.dart'; +import '../data/booking_repository.dart'; +import '../domain/booking.dart'; + +/// Modification du créneau d'une réservation existante. +class BookingModifyScreen extends ConsumerStatefulWidget { + const BookingModifyScreen({super.key, required this.bookingUuid}); + + final String bookingUuid; + + @override + ConsumerState createState() => _BookingModifyScreenState(); +} + +class _BookingModifyScreenState extends ConsumerState { + DateTime? _selectedDate; + TimeSlot? _selectedSlot; + bool _isSaving = false; + + Future _confirmMove(Booking booking) async { + final slot = _selectedSlot; + if (slot == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Sélectionnez un nouveau créneau')), + ); + return; + } + + setState(() => _isSaving = true); + try { + await ref.read(bookingRepositoryProvider).moveBooking( + uuid: booking.uuid, + slotStart: slot.start, + slotEnd: slot.end, + ); + ref.invalidate(bookingsProvider); + ref.invalidate(bookingDetailProvider(booking.uuid)); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Créneau modifié avec succès'), + backgroundColor: AppColors.success, + ), + ); + context.go(AppRoutes.bookings); + } + } on BookingException catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(e.message), backgroundColor: AppColors.error), + ); + } + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + @override + Widget build(BuildContext context) { + final bookingAsync = ref.watch(bookingDetailProvider(widget.bookingUuid)); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar(title: const Text('Modifier le créneau')), + body: bookingAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, __) => const Center(child: Text('Réservation introuvable')), + data: (booking) { + if (!booking.canModify) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'Cette réservation ne peut plus être modifiée.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + ); + } + + final selectedDate = _selectedDate ?? + DateTime( + booking.slotStart!.year, + booking.slotStart!.month, + booking.slotStart!.day, + ); + + final availabilityAsync = ref.watch( + machineAvailabilityProvider((uuid: booking.machineUuid, date: selectedDate)), + ); + + return Column( + children: [ + Expanded( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(booking.machineName, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 4), + Text( + 'Créneau actuel', + style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 12), + ), + Text( + booking.slotStart != null && booking.slotEnd != null + ? '${DateFormat('EEEE dd MMM · HH:mm', 'fr_FR').format(booking.slotStart!)} – ${DateFormat('HH:mm').format(booking.slotEnd!)}' + : '—', + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ], + ), + ), + ), + const SizedBox(height: 20), + Text('Nouveau jour', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 10), + SizedBox( + height: 44, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: 6, + separatorBuilder: (_, __) => const SizedBox(width: 8), + itemBuilder: (context, index) { + final date = DateTime.now().add(Duration(days: index)); + final normalized = DateTime(date.year, date.month, date.day); + final isSelected = normalized.year == selectedDate.year && + normalized.month == selectedDate.month && + normalized.day == selectedDate.day; + + return ChoiceChip( + label: Text(DateFormat('EEE dd/MM', 'fr_FR').format(normalized)), + selected: isSelected, + onSelected: (_) => setState(() { + _selectedDate = normalized; + _selectedSlot = null; + }), + selectedColor: AppColors.primary.withValues(alpha: 0.15), + ); + }, + ), + ), + const SizedBox(height: 20), + Text('Nouveau créneau', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 12), + availabilityAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, __) => const Text('Impossible de charger les créneaux.'), + data: (slots) { + if (slots.isEmpty) { + return Text( + 'Aucun créneau disponible ce jour.', + style: Theme.of(context).textTheme.bodyMedium, + ); + } + return Wrap( + spacing: 8, + runSpacing: 8, + children: slots.map((slot) { + final label = + '${DateFormat('HH:mm').format(slot.start)} – ${DateFormat('HH:mm').format(slot.end)}'; + final isSelected = _selectedSlot?.start == slot.start; + + return FilterChip( + label: Text(label), + selected: isSelected, + onSelected: (_) => setState(() => _selectedSlot = slot), + selectedColor: AppColors.primary.withValues(alpha: 0.15), + checkmarkColor: AppColors.primary, + ); + }).toList(), + ); + }, + ), + ], + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: SizedBox( + width: double.infinity, + height: 56, + child: ElevatedButton.icon( + onPressed: _isSaving ? null : () => _confirmMove(booking), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + icon: _isSaving + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Icon(Icons.check_rounded, size: 24), + label: Text(_isSaving ? 'Enregistrement…' : 'Confirmer le changement'), + ), + ), + ), + ), + ], + ); + }, + ), + ); + } +} diff --git a/lib/features/booking/presentation/bookings_screen.dart b/lib/features/booking/presentation/bookings_screen.dart index 3c796c0..d4823c6 100644 --- a/lib/features/booking/presentation/bookings_screen.dart +++ b/lib/features/booking/presentation/bookings_screen.dart @@ -1,86 +1,228 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; -import '../../../core/api/api_client.dart'; -import '../../../core/api/api_endpoints.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/screen_header.dart'; +import '../data/booking_repository.dart'; import '../domain/booking.dart'; -/// Fournisseur des réservations de l'utilisateur connecté. -final bookingsProvider = FutureProvider>((ref) async { - final response = await ref.watch(apiClientProvider).get(ApiEndpoints.bookings); - final data = response.data; - - List list; - if (data is List) { - list = data; - } else if (data is Map && data['data'] is List) { - list = data['data'] as List; - } else { - list = []; - } - - return list - .map((json) => Booking.fromJson(json as Map)) - .toList(); -}); - -/// Écran listant les réservations de l'utilisateur. +/// Écran listant les réservations avec annulation et modification. class BookingsScreen extends ConsumerWidget { const BookingsScreen({super.key}); + Future _cancelBooking(BuildContext context, WidgetRef ref, Booking booking) async { + final slotLabel = booking.slotStart != null + ? DateFormat('EEEE dd MMM à HH:mm', 'fr_FR').format(booking.slotStart!) + : 'ce créneau'; + + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Annuler la réservation ?'), + content: Text( + 'Le créneau du $slotLabel sera libéré.\n\n' + 'Annulation gratuite plus de 2 h avant le créneau, sinon des frais peuvent s\'appliquer.', + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Non')), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + style: TextButton.styleFrom(foregroundColor: AppColors.error), + child: const Text('Oui, annuler'), + ), + ], + ), + ); + + if (confirmed != true || !context.mounted) return; + + try { + await ref.read(bookingRepositoryProvider).cancelBooking(booking.uuid); + ref.invalidate(bookingsProvider); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Réservation annulée'), + backgroundColor: AppColors.success, + ), + ); + } + } on BookingException catch (e) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(e.message), backgroundColor: AppColors.error), + ); + } + } + } + @override Widget build(BuildContext context, WidgetRef ref) { final bookingsAsync = ref.watch(bookingsProvider); - return Scaffold( - appBar: AppBar(title: const Text('Mes réservations')), - body: bookingsAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + return bookingsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => EmptyState( + icon: Icons.event_busy_outlined, + title: 'Erreur', + subtitle: 'Impossible de charger vos réservations.', + actionLabel: 'Réessayer', + onAction: () => ref.invalidate(bookingsProvider), + ), + data: (bookings) { + if (bookings.isEmpty) { + return EmptyState( + icon: Icons.event_outlined, + title: 'Aucune réservation', + subtitle: 'Réservez un créneau jusqu\'à 6 jours\nà l\'avance depuis une laverie.', + actionLabel: 'Voir les laveries', + onAction: () => context.go(AppRoutes.home), + ); + } + + final upcoming = bookings + .where((b) => b.status != 'cancelled' && b.status != 'completed' && b.status != 'no_show') + .toList(); + final past = bookings + .where((b) => b.status == 'cancelled' || b.status == 'completed' || b.status == 'no_show') + .toList(); + + return RefreshIndicator( + onRefresh: () async => ref.invalidate(bookingsProvider), + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 88), children: [ - Text('Erreur : $error'), - const SizedBox(height: 12), - ElevatedButton( - onPressed: () => ref.invalidate(bookingsProvider), - child: const Text('Réessayer'), + const ScreenHeader( + title: 'Mes créneaux', + subtitle: '30 min pour démarrer après notification', ), + if (upcoming.isNotEmpty) ...[ + Text('À venir', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + ...upcoming.map( + (b) => _BookingCard( + booking: b, + highlight: true, + onModify: b.canModify + ? () => context.push(AppRoutes.bookingModify(b.uuid)) + : null, + onCancel: b.canCancel ? () => _cancelBooking(context, ref, b) : null, + ), + ), + const SizedBox(height: 16), + ], + if (past.isNotEmpty) ...[ + Text('Passées', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + ...past.map((b) => _BookingCard(booking: b, highlight: false)), + ], ], ), - ), - data: (bookings) { - if (bookings.isEmpty) { - return const Center( - child: Text('Aucune réservation.\nRéservez un créneau depuis une laverie.'), - ); - } + ); + }, + ); + } +} - return RefreshIndicator( - onRefresh: () async => ref.invalidate(bookingsProvider), - child: ListView.separated( - padding: const EdgeInsets.all(16), - itemCount: bookings.length, - separatorBuilder: (_, __) => const SizedBox(height: 8), - itemBuilder: (context, index) { - final booking = bookings[index]; - return Card( - child: ListTile( - leading: const Icon(Icons.event), - title: Text(booking.machineName), - subtitle: Text( - booking.slotStart != null - ? DateFormat('dd/MM/yyyy HH:mm').format(booking.slotStart!) - : 'Créneau à confirmer', - ), - trailing: Chip(label: Text(booking.status)), +class _BookingCard extends StatelessWidget { + const _BookingCard({ + required this.booking, + required this.highlight, + this.onModify, + this.onCancel, + }); + + final Booking booking; + final bool highlight; + final VoidCallback? onModify; + final VoidCallback? onCancel; + + @override + Widget build(BuildContext context) { + final slotText = booking.slotStart != null + ? DateFormat('EEEE dd MMM · HH:mm', 'fr_FR').format(booking.slotStart!) + : 'Créneau à confirmer'; + + return Card( + margin: const EdgeInsets.only(bottom: 8), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: highlight + ? BorderSide(color: AppColors.machineReserved.withValues(alpha: 0.4)) + : BorderSide.none, + ), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 48, + height: 48, + decoration: BoxDecoration( + color: (highlight ? AppColors.machineReserved : AppColors.textSecondary) + .withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), ), - ); - }, + child: Icon( + Icons.event, + color: highlight ? AppColors.machineReserved : AppColors.textSecondary, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(booking.machineName, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 2), + Text(slotText, style: Theme.of(context).textTheme.bodyMedium), + ], + ), + ), + StatusBadge.fromStatus(booking.status), + ], ), - ); - }, + if (onModify != null || onCancel != null) ...[ + const SizedBox(height: 12), + Row( + children: [ + if (onModify != null) + Expanded( + child: OutlinedButton.icon( + onPressed: onModify, + icon: const Icon(Icons.edit_calendar_outlined, size: 18), + label: const Text('Modifier'), + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.primary, + padding: const EdgeInsets.symmetric(vertical: 10), + ), + ), + ), + if (onModify != null && onCancel != null) const SizedBox(width: 8), + if (onCancel != null) + Expanded( + child: OutlinedButton.icon( + onPressed: onCancel, + icon: const Icon(Icons.cancel_outlined, size: 18), + label: const Text('Annuler'), + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.error, + padding: const EdgeInsets.symmetric(vertical: 10), + ), + ), + ), + ], + ), + ], + ], + ), ), ); } diff --git a/lib/features/establishments/data/establishment_repository.dart b/lib/features/establishments/data/establishment_repository.dart index 682c14f..01b92db 100644 --- a/lib/features/establishments/data/establishment_repository.dart +++ b/lib/features/establishments/data/establishment_repository.dart @@ -2,6 +2,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../core/api/api_client.dart'; import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; import '../domain/establishment.dart'; /// Dépôt de données pour les établissements et machines. @@ -12,7 +13,7 @@ class EstablishmentRepository { Future> fetchEstablishments() async { final response = await _apiClient.get(ApiEndpoints.establishments); - final data = _extractList(response.data); + final data = ApiResponse.list(response.data, 'establishments'); return data .map((json) => Establishment.fromJson(json as Map)) @@ -21,27 +22,9 @@ class EstablishmentRepository { Future fetchEstablishment(String uuid) async { final response = await _apiClient.get(ApiEndpoints.establishment(uuid)); - final json = _extractObject(response.data); + final json = ApiResponse.object(response.data, 'establishment'); return Establishment.fromJson(json); } - - List _extractList(dynamic data) { - if (data is List) return data; - if (data is Map && data['data'] is List) { - return data['data'] as List; - } - return []; - } - - Map _extractObject(dynamic data) { - if (data is Map) { - if (data['data'] is Map) { - return data['data'] as Map; - } - return data; - } - throw StateError('Réponse API inattendue'); - } } final establishmentRepositoryProvider = Provider((ref) { diff --git a/lib/features/establishments/presentation/establishment_detail_screen.dart b/lib/features/establishments/presentation/establishment_detail_screen.dart index 2cbcd83..f5ca814 100644 --- a/lib/features/establishments/presentation/establishment_detail_screen.dart +++ b/lib/features/establishments/presentation/establishment_detail_screen.dart @@ -1,11 +1,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/machine_grid_layout.dart'; +import '../../../core/widgets/machine_widgets.dart'; import '../../establishments/data/establishment_repository.dart'; import '../../establishments/domain/establishment.dart'; -/// Écran de détail d'un établissement avec liste des machines. -class EstablishmentDetailScreen extends ConsumerWidget { +/// Écran laverie — grille machines. +class EstablishmentDetailScreen extends ConsumerStatefulWidget { const EstablishmentDetailScreen({ super.key, required this.establishmentUuid, @@ -14,99 +20,187 @@ class EstablishmentDetailScreen extends ConsumerWidget { final String establishmentUuid; @override - Widget build(BuildContext context, WidgetRef ref) { + ConsumerState createState() => _EstablishmentDetailScreenState(); +} + +class _EstablishmentDetailScreenState extends ConsumerState { + String _filter = 'all'; + + List _filterMachines(List machines) => switch (_filter) { + 'washer' => machines.where((m) => m.type.startsWith('washer')).toList(), + 'dryer' => machines.where((m) => m.type.startsWith('dryer')).toList(), + _ => machines, + }; + + @override + Widget build(BuildContext context) { final establishmentAsync = - ref.watch(establishmentDetailProvider(establishmentUuid)); + ref.watch(establishmentDetailProvider(widget.establishmentUuid)); return Scaffold( - appBar: AppBar(title: const Text('Détail laverie')), + backgroundColor: AppColors.background, + appBar: AppBar( + title: establishmentAsync.maybeWhen( + data: (e) => Text(e.name, overflow: TextOverflow.ellipsis), + orElse: () => const Text('Ma laverie'), + ), + ), body: establishmentAsync.when( loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('Erreur : $error'), - const SizedBox(height: 12), - ElevatedButton( - onPressed: () => - ref.invalidate(establishmentDetailProvider(establishmentUuid)), - child: const Text('Réessayer'), - ), - ], - ), + error: (error, _) => EmptyState( + icon: Icons.error_outline, + title: 'Erreur', + subtitle: '$error', + actionLabel: 'Réessayer', + onAction: () => ref.invalidate(establishmentDetailProvider(widget.establishmentUuid)), + ), + data: (establishment) => _EstablishmentBody( + establishment: establishment, + filter: _filter, + onFilterChanged: (value) => setState(() => _filter = value), + onRefresh: () async { + ref.invalidate(establishmentDetailProvider(widget.establishmentUuid)); + }, + machines: _filterMachines(establishment.machines), + onMachineTap: (machine) => context.push(AppRoutes.machineAction(machine.uuid)), ), - data: (establishment) => _EstablishmentBody(establishment: establishment), ), ); } } class _EstablishmentBody extends StatelessWidget { - const _EstablishmentBody({required this.establishment}); + const _EstablishmentBody({ + required this.establishment, + required this.filter, + required this.onFilterChanged, + required this.onRefresh, + required this.machines, + required this.onMachineTap, + }); final Establishment establishment; + final String filter; + final ValueChanged onFilterChanged; + final Future Function() onRefresh; + final List machines; + final ValueChanged onMachineTap; @override Widget build(BuildContext context) { - return ListView( - padding: const EdgeInsets.all(16), - children: [ - Text( - establishment.name, - style: Theme.of(context).textTheme.headlineSmall, - ), - const SizedBox(height: 4), - Text(establishment.fullAddress), - const SizedBox(height: 24), - Text( - 'Machines (${establishment.machines.length})', - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox(height: 8), - if (establishment.machines.isEmpty) - const Text('Aucune machine disponible') - else - ...establishment.machines.map((machine) => _MachineTile(machine: machine)), - ], + return RefreshIndicator( + onRefresh: onRefresh, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + gradient: AppColors.gradientAccent, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + establishment.name, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 4), + Text( + establishment.fullAddress, + style: TextStyle(color: Colors.white.withValues(alpha: 0.9), fontSize: 13), + ), + ], + ), + ), + const SizedBox(height: 16), + if (establishment.machines.isNotEmpty) ...[ + MachineStatsRow(machines: establishment.machines), + const SizedBox(height: 12), + const MachineStatusLegend(), + const SizedBox(height: 16), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _FilterChip( + label: 'Toutes', + selected: filter == 'all', + onTap: () => onFilterChanged('all'), + ), + const SizedBox(width: 8), + _FilterChip( + label: 'Lave-linge', + selected: filter == 'washer', + onTap: () => onFilterChanged('washer'), + ), + const SizedBox(width: 8), + _FilterChip( + label: 'Sèche-linge', + selected: filter == 'dryer', + onTap: () => onFilterChanged('dryer'), + ), + ], + ), + ), + const SizedBox(height: 16), + ], + if (establishment.machines.isEmpty) + const EmptyState( + icon: Icons.local_laundry_service_outlined, + title: 'Aucune machine', + subtitle: 'Cette laverie n\'a pas encore de machines.', + ) + else if (machines.isEmpty) + const EmptyState( + icon: Icons.filter_alt_outlined, + title: 'Aucun résultat', + subtitle: 'Aucune machine dans cette catégorie.', + ) + else + GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: MachineGridLayout.delegate(context), + itemCount: machines.length, + itemBuilder: (context, index) => MachineGridCard( + machine: machines[index], + onTap: () => onMachineTap(machines[index]), + ), + ), + ], + ), ); } } -class _MachineTile extends StatelessWidget { - const _MachineTile({required this.machine}); +class _FilterChip extends StatelessWidget { + const _FilterChip({ + required this.label, + required this.selected, + required this.onTap, + }); - final Machine machine; + final String label; + final bool selected; + final VoidCallback onTap; - Color _statusColor(BuildContext context) { - switch (machine.status) { - case 'available': - return Colors.green; - case 'running': - return Colors.blue; - case 'reserved': - return Colors.orange; - case 'maintenance': - case 'offline': - return Colors.red; - default: - return Colors.grey; - } - } - @override Widget build(BuildContext context) { - return Card( - child: ListTile( - leading: Icon( - machine.type.startsWith('washer') ? Icons.water_drop : Icons.air, - color: _statusColor(context), - ), - title: Text(machine.name), - subtitle: Text('${machine.typeLabel} — ${machine.statusLabel}'), - trailing: machine.isAvailable - ? const Chip(label: Text('Libre')) - : null, + return FilterChip( + label: Text(label), + selected: selected, + onSelected: (_) => onTap(), + selectedColor: AppColors.primary.withValues(alpha: 0.15), + checkmarkColor: AppColors.primary, + labelStyle: TextStyle( + color: selected ? AppColors.primary : AppColors.textSecondary, + fontWeight: selected ? FontWeight.w600 : FontWeight.normal, ), ); } diff --git a/lib/features/home/presentation/home_screen.dart b/lib/features/home/presentation/home_screen.dart index 2b6c9d4..e2aec53 100644 --- a/lib/features/home/presentation/home_screen.dart +++ b/lib/features/home/presentation/home_screen.dart @@ -2,104 +2,176 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import '../../../core/auth/auth_provider.dart'; import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/machine_widgets.dart'; import '../../establishments/data/establishment_repository.dart'; +import '../../establishments/domain/establishment.dart'; +import '../../wash/data/wash_repository.dart'; -/// Écran d'accueil — liste des laveries à proximité. +/// Tableau de bord — vue d'ensemble inspirée WashOnline, plus moderne. class HomeScreen extends ConsumerWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final establishmentsAsync = ref.watch(establishmentsProvider); + final washesAsync = ref.watch(washesProvider); + final user = ref.watch(authProvider).user; - return Scaffold( - appBar: AppBar( - title: const Text('Laveries'), - actions: [ - IconButton( - icon: const Icon(Icons.account_balance_wallet_outlined), - onPressed: () => context.push(AppRoutes.wallet), - ), - IconButton( - icon: const Icon(Icons.person_outline), - onPressed: () => context.push(AppRoutes.profile), - ), - ], + return establishmentsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => EmptyState( + icon: Icons.cloud_off_outlined, + title: 'Connexion impossible', + subtitle: 'Vérifiez que l\'API est démarrée\net que vous êtes sur le même réseau.', + actionLabel: 'Réessayer', + onAction: () => ref.invalidate(establishmentsProvider), ), - body: establishmentsAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.cloud_off, size: 48), - const SizedBox(height: 12), - Text( - 'Impossible de charger les laveries.\nVérifiez que l\'API est démarrée.', - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyLarge, - ), + data: (establishments) { + if (establishments.isEmpty) { + return const EmptyState( + icon: Icons.storefront_outlined, + title: 'Aucune laverie', + subtitle: 'Aucun établissement disponible pour le moment.', + ); + } + + final activeWash = washesAsync.maybeWhen( + data: (washes) { + for (final wash in washes) { + if (wash.status == 'running' || wash.status == 'pending_start' || wash.status == 'active') { + return wash; + } + } + return null; + }, + orElse: () => null, + ); + + return RefreshIndicator( + onRefresh: () async { + ref.invalidate(establishmentsProvider); + ref.invalidate(washesProvider); + }, + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), + children: [ + Text( + user?.firstName != null ? 'Bonjour ${user!.firstName} 👋' : 'Bienvenue', + style: Theme.of(context).textTheme.headlineMedium?.copyWith(fontSize: 20), + ), + const SizedBox(height: 4), + Text( + 'Votre laverie, dans votre poche.', + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 16), + const QuickActionsRow(), + if (activeWash != null) ...[ const SizedBox(height: 16), - ElevatedButton( - onPressed: () => ref.invalidate(establishmentsProvider), - child: const Text('Réessayer'), + ActiveWashBanner( + machineName: activeWash.machineName, + onTap: () => context.go(AppRoutes.washes), ), ], - ), - ), - ), - data: (establishments) { - if (establishments.isEmpty) { - return const Center(child: Text('Aucune laverie disponible')); - } - - return RefreshIndicator( - onRefresh: () async => ref.invalidate(establishmentsProvider), - child: ListView.separated( - padding: const EdgeInsets.all(16), - itemCount: establishments.length, - separatorBuilder: (_, __) => const SizedBox(height: 8), - itemBuilder: (context, index) { - final establishment = establishments[index]; - return Card( - child: ListTile( - leading: CircleAvatar( - child: Text(establishment.name.substring(0, 1)), - ), - title: Text(establishment.name), - subtitle: Text(establishment.fullAddress), - trailing: const Icon(Icons.chevron_right), + const SizedBox(height: 24), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Mes laveries', style: Theme.of(context).textTheme.titleMedium), + Text( + '${establishments.length}', + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + const SizedBox(height: 10), + ...establishments.map( + (establishment) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: _EstablishmentCard( + establishment: establishment, onTap: () => context.push('/establishments/${establishment.uuid}'), ), - ); - }, - ), - ); - }, - ), - bottomNavigationBar: NavigationBar( - selectedIndex: 0, - onDestinationSelected: (index) { - switch (index) { - case 0: - context.go(AppRoutes.home); - case 1: - context.push(AppRoutes.bookings); - case 2: - context.push(AppRoutes.washes); - case 3: - context.push(AppRoutes.wallet); - } - }, - destinations: const [ - NavigationDestination(icon: Icon(Icons.store), label: 'Laveries'), - NavigationDestination(icon: Icon(Icons.event), label: 'Réservations'), - NavigationDestination(icon: Icon(Icons.local_laundry_service), label: 'Lavages'), - NavigationDestination(icon: Icon(Icons.wallet), label: 'Wallet'), - ], + ), + ), + ], + ), + ); + }, + ); + } +} + +class _EstablishmentCard extends StatelessWidget { + const _EstablishmentCard({ + required this.establishment, + required this.onTap, + }); + + final Establishment establishment; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Container( + width: 48, + height: 48, + decoration: BoxDecoration( + gradient: AppColors.gradientPrimary, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.storefront_rounded, color: Colors.white), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(establishment.name, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 2), + Text( + establishment.fullAddress, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 8), + Row( + children: [ + Icon(Icons.grid_view_rounded, size: 14, color: AppColors.primary.withValues(alpha: 0.8)), + const SizedBox(width: 4), + Text( + 'Voir les machines', + style: TextStyle( + color: AppColors.primary, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ], + ), + ), + const Icon(Icons.chevron_right, color: AppColors.textSecondary), + ], + ), + ), ), ); } diff --git a/lib/features/machines/data/machine_repository.dart b/lib/features/machines/data/machine_repository.dart new file mode 100644 index 0000000..fb02df2 --- /dev/null +++ b/lib/features/machines/data/machine_repository.dart @@ -0,0 +1,51 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; +import '../domain/machine_detail.dart'; + +/// Dépôt de données machines (lookup, détail, créneaux). +class MachineRepository { + MachineRepository(this._apiClient); + + final ApiClient _apiClient; + + Future lookup({String? qrCode, String? machineUuid}) async { + final response = await _apiClient.get( + ApiEndpoints.machineLookup, + queryParameters: { + if (qrCode != null) 'qr_code': qrCode, + if (machineUuid != null) 'machine_uuid': machineUuid, + }, + ); + return MachineDetail.fromJson(ApiResponse.payload(response.data)); + } + + Future fetchDetail(String uuid) async { + final response = await _apiClient.get(ApiEndpoints.machine(uuid)); + return MachineDetail.fromJson(ApiResponse.payload(response.data)); + } + + Future> fetchAvailability(String uuid, DateTime date) async { + final response = await _apiClient.get( + ApiEndpoints.machineAvailability(uuid), + queryParameters: {'date': date.toIso8601String().split('T').first}, + ); + final slots = ApiResponse.payload(response.data)['slots'] as List? ?? []; + return slots.map((s) => TimeSlot.fromJson(s as Map)).toList(); + } +} + +final machineRepositoryProvider = Provider((ref) { + return MachineRepository(ref.watch(apiClientProvider)); +}); + +final machineDetailProvider = FutureProvider.family((ref, uuid) async { + return ref.watch(machineRepositoryProvider).fetchDetail(uuid); +}); + +final machineAvailabilityProvider = + FutureProvider.family, ({String uuid, DateTime date})>((ref, params) async { + return ref.watch(machineRepositoryProvider).fetchAvailability(params.uuid, params.date); +}); diff --git a/lib/features/machines/domain/machine_detail.dart b/lib/features/machines/domain/machine_detail.dart new file mode 100644 index 0000000..9946753 --- /dev/null +++ b/lib/features/machines/domain/machine_detail.dart @@ -0,0 +1,52 @@ +import '../../establishments/domain/establishment.dart'; + +/// Détails machine avec tarif et durée estimée. +class MachineDetail { + const MachineDetail({ + required this.machine, + required this.price, + required this.estimatedDurationMinutes, + this.establishmentName, + this.currency = 'EUR', + }); + + final Machine machine; + final double price; + final int estimatedDurationMinutes; + final String? establishmentName; + final String currency; + + factory MachineDetail.fromJson(Map json) { + final machineJson = json['machine'] as Map; + final pricing = json['pricing'] as Map?; + + String? establishmentName; + final establishment = machineJson['establishment']; + if (establishment is Map) { + establishmentName = establishment['name'] as String?; + } + + return MachineDetail( + machine: Machine.fromJson(machineJson), + price: (pricing?['price'] as num?)?.toDouble() ?? 0, + currency: pricing?['currency'] as String? ?? 'EUR', + estimatedDurationMinutes: json['estimated_duration_minutes'] as int? ?? 40, + establishmentName: establishmentName, + ); + } +} + +/// Créneau disponible pour réservation. +class TimeSlot { + const TimeSlot({required this.start, required this.end}); + + final DateTime start; + final DateTime end; + + factory TimeSlot.fromJson(Map json) { + return TimeSlot( + start: DateTime.parse(json['start'] as String), + end: DateTime.parse(json['end'] as String), + ); + } +} diff --git a/lib/features/machines/presentation/machine_action_screen.dart b/lib/features/machines/presentation/machine_action_screen.dart new file mode 100644 index 0000000..bdeb389 --- /dev/null +++ b/lib/features/machines/presentation/machine_action_screen.dart @@ -0,0 +1,293 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/machine_status_theme.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../wash/data/wash_repository.dart'; +import '../data/machine_repository.dart'; +import '../domain/machine_detail.dart'; + +/// Écran machine — infos + actions principales. +class MachineActionScreen extends ConsumerStatefulWidget { + const MachineActionScreen({super.key, required this.machineUuid}); + + final String machineUuid; + + @override + ConsumerState createState() => _MachineActionScreenState(); +} + +class _MachineActionScreenState extends ConsumerState { + bool _isStarting = false; + + Future _startWash(MachineDetail detail) async { + setState(() => _isStarting = true); + try { + await ref.read(washRepositoryProvider).startWashFromMachine(detail.machine.uuid); + ref.invalidate(washesProvider); + ref.invalidate(machineDetailProvider(widget.machineUuid)); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('${detail.machine.name} — cycle démarré !'), + backgroundColor: AppColors.success, + ), + ); + context.go(AppRoutes.washes); + } + } on WashStartException catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(e.message), backgroundColor: AppColors.error), + ); + } + } finally { + if (mounted) setState(() => _isStarting = false); + } + } + + @override + Widget build(BuildContext context) { + final detailAsync = ref.watch(machineDetailProvider(widget.machineUuid)); + final currency = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar(title: const Text('Machine')), + body: detailAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => EmptyState( + icon: Icons.error_outline, + title: 'Machine introuvable', + subtitle: error is DioException + ? 'Impossible de charger les informations.' + : '$error', + actionLabel: 'Retour', + onAction: () => context.pop(), + ), + data: (detail) => _MachineActionBody( + detail: detail, + currency: currency, + isStarting: _isStarting, + onStart: () => _startWash(detail), + onReserve: () => context.push(AppRoutes.machineBooking(widget.machineUuid)), + ), + ), + ); + } +} + +class _MachineActionBody extends StatelessWidget { + const _MachineActionBody({ + required this.detail, + required this.currency, + required this.isStarting, + required this.onStart, + required this.onReserve, + }); + + final MachineDetail detail; + final NumberFormat currency; + final bool isStarting; + final VoidCallback onStart; + final VoidCallback onReserve; + + @override + Widget build(BuildContext context) { + final machine = detail.machine; + final statusColor = MachineStatusTheme.color(machine.status); + final canStart = MachineStatusTheme.canStart(machine.status); + + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + gradient: AppColors.gradientAccent, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(14), + ), + child: Icon( + MachineStatusTheme.iconForType(machine.type), + color: Colors.white, + size: 28, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + machine.name, + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + Text( + machine.typeLabel, + style: TextStyle(color: Colors.white.withValues(alpha: 0.9)), + ), + if (detail.establishmentName != null) + Text( + detail.establishmentName!, + style: TextStyle( + color: Colors.white.withValues(alpha: 0.75), + fontSize: 12, + ), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + MachineStatusTheme.label(machine.status), + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 12), + ), + ), + ], + ), + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: _InfoTile( + icon: Icons.euro, + label: 'Prix du cycle', + value: currency.format(detail.price), + color: AppColors.primary, + ), + ), + const SizedBox(width: 10), + Expanded( + child: _InfoTile( + icon: Icons.schedule, + label: 'Durée estimée', + value: '~${detail.estimatedDurationMinutes} min', + color: AppColors.secondary, + ), + ), + ], + ), + if (!canStart) ...[ + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + machine.status == 'running' + ? 'Machine en cours d\'utilisation — vous pouvez réserver un créneau ultérieur.' + : 'Machine indisponible pour le moment — réservez un créneau.', + textAlign: TextAlign.center, + style: TextStyle(color: statusColor, fontWeight: FontWeight.w500), + ), + ), + ], + const SizedBox(height: 28), + SizedBox( + width: double.infinity, + height: 60, + child: ElevatedButton.icon( + onPressed: canStart && !isStarting ? onStart : null, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.machineAvailable, + disabledBackgroundColor: AppColors.machineAvailable.withValues(alpha: 0.4), + foregroundColor: Colors.white, + disabledForegroundColor: Colors.white70, + elevation: canStart ? 2 : 0, + shadowColor: AppColors.machineAvailable.withValues(alpha: 0.4), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700), + ), + icon: isStarting + ? const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white), + ) + : const Icon(Icons.play_arrow_rounded, size: 28), + label: Text(isStarting ? 'Démarrage…' : 'Commencer un lavage'), + ), + ), + const SizedBox(height: 14), + SizedBox( + width: double.infinity, + height: 56, + child: ElevatedButton.icon( + onPressed: onReserve, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + elevation: 2, + shadowColor: AppColors.primary.withValues(alpha: 0.35), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + icon: const Icon(Icons.event_available_outlined, size: 24), + label: const Text('Réserver un créneau'), + ), + ), + const SizedBox(height: 24), + ], + ); + } +} + +class _InfoTile extends StatelessWidget { + const _InfoTile({ + required this.icon, + required this.label, + required this.value, + required this.color, + }); + + final IconData icon; + final String label; + final String value; + final Color color; + + @override + Widget build(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, color: color, size: 22), + const SizedBox(height: 8), + Text(label, style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 12)), + const SizedBox(height: 2), + Text(value, style: Theme.of(context).textTheme.titleMedium), + ], + ), + ), + ); + } +} diff --git a/lib/features/machines/presentation/machine_booking_screen.dart b/lib/features/machines/presentation/machine_booking_screen.dart new file mode 100644 index 0000000..2e957b8 --- /dev/null +++ b/lib/features/machines/presentation/machine_booking_screen.dart @@ -0,0 +1,212 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/machine_status_theme.dart'; +import '../../booking/data/booking_repository.dart'; +import '../data/machine_repository.dart'; +import '../domain/machine_detail.dart'; + +/// Réservation de créneau pour une machine. +class MachineBookingScreen extends ConsumerStatefulWidget { + const MachineBookingScreen({super.key, required this.machineUuid}); + + final String machineUuid; + + @override + ConsumerState createState() => _MachineBookingScreenState(); +} + +class _MachineBookingScreenState extends ConsumerState { + DateTime _selectedDate = DateTime.now(); + TimeSlot? _selectedSlot; + bool _isBooking = false; + + Future _confirmBooking(MachineDetail detail) async { + final slot = _selectedSlot; + if (slot == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Sélectionnez un créneau horaire')), + ); + return; + } + + setState(() => _isBooking = true); + try { + await ref.read(bookingRepositoryProvider).createBooking( + machineUuid: detail.machine.uuid, + slotStart: slot.start, + slotEnd: slot.end, + ); + ref.invalidate(bookingsProvider); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Créneau réservé avec succès'), + backgroundColor: AppColors.success, + ), + ); + context.go(AppRoutes.bookings); + } + } on BookingException catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(e.message), backgroundColor: AppColors.error), + ); + } + } finally { + if (mounted) setState(() => _isBooking = false); + } + } + + @override + Widget build(BuildContext context) { + final detailAsync = ref.watch(machineDetailProvider(widget.machineUuid)); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar(title: const Text('Réserver un créneau')), + body: detailAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, __) => Center(child: Text('Machine introuvable', style: Theme.of(context).textTheme.titleMedium)), + data: (detail) { + final machine = detail.machine; + final availabilityAsync = ref.watch( + machineAvailabilityProvider((uuid: machine.uuid, date: _selectedDate)), + ); + + return Column( + children: [ + Expanded( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: ListTile( + leading: CircleAvatar( + backgroundColor: AppColors.primary.withValues(alpha: 0.1), + child: Icon( + MachineStatusTheme.iconForType(machine.type), + color: AppColors.primary, + ), + ), + title: Text(machine.name), + subtitle: Text( + [ + machine.typeLabel, + if (detail.establishmentName != null) detail.establishmentName, + ].join(' · '), + ), + ), + ), + const SizedBox(height: 20), + Text('Choisir un jour', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 10), + SizedBox( + height: 44, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: 6, + separatorBuilder: (_, __) => const SizedBox(width: 8), + itemBuilder: (context, index) { + final date = DateTime.now().add(Duration(days: index)); + final normalized = DateTime(date.year, date.month, date.day); + final isSelected = normalized.year == _selectedDate.year && + normalized.month == _selectedDate.month && + normalized.day == _selectedDate.day; + + return ChoiceChip( + label: Text(DateFormat('EEE dd/MM', 'fr_FR').format(normalized)), + selected: isSelected, + onSelected: (_) => setState(() { + _selectedDate = normalized; + _selectedSlot = null; + }), + selectedColor: AppColors.primary.withValues(alpha: 0.15), + ); + }, + ), + ), + const SizedBox(height: 20), + Text('Créneaux disponibles', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 4), + Text( + 'Vous aurez 30 min pour démarrer après le début du créneau.', + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 12), + availabilityAsync.when( + loading: () => const Center(child: Padding( + padding: EdgeInsets.all(24), + child: CircularProgressIndicator(), + )), + error: (_, __) => const Text('Impossible de charger les créneaux.'), + data: (slots) { + if (slots.isEmpty) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Text( + 'Aucun créneau disponible ce jour.', + style: Theme.of(context).textTheme.bodyMedium, + ), + ); + } + return Wrap( + spacing: 8, + runSpacing: 8, + children: slots.map((slot) { + final label = + '${DateFormat('HH:mm').format(slot.start)} – ${DateFormat('HH:mm').format(slot.end)}'; + final isSelected = _selectedSlot?.start == slot.start; + + return FilterChip( + label: Text(label), + selected: isSelected, + onSelected: (_) => setState(() => _selectedSlot = slot), + selectedColor: AppColors.primary.withValues(alpha: 0.15), + checkmarkColor: AppColors.primary, + ); + }).toList(), + ); + }, + ), + ], + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: SizedBox( + width: double.infinity, + height: 56, + child: ElevatedButton.icon( + onPressed: _isBooking ? null : () => _confirmBooking(detail), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + icon: _isBooking + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Icon(Icons.event_available_rounded, size: 24), + label: Text(_isBooking ? 'Réservation…' : 'Confirmer la réservation'), + ), + ), + ), + ), + ], + ); + }, + ), + ); + } +} diff --git a/lib/features/profile/presentation/profile_screen.dart b/lib/features/profile/presentation/profile_screen.dart index 9b8f41e..1a46dfe 100644 --- a/lib/features/profile/presentation/profile_screen.dart +++ b/lib/features/profile/presentation/profile_screen.dart @@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart'; import '../../../core/auth/auth_provider.dart'; import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; /// Écran profil utilisateur et déconnexion. class ProfileScreen extends ConsumerWidget { @@ -11,63 +12,73 @@ class ProfileScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final authState = ref.watch(authProvider); - final user = authState.user; + final user = ref.watch(authProvider).user; - return Scaffold( - appBar: AppBar(title: const Text('Mon profil')), - body: ListView( - padding: const EdgeInsets.all(16), - children: [ - Card( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - children: [ - CircleAvatar( - radius: 40, - child: Text( - user != null && user.firstName.isNotEmpty - ? user.firstName.substring(0, 1).toUpperCase() - : '?', - style: const TextStyle(fontSize: 32), + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(20), + child: Row( + children: [ + CircleAvatar( + radius: 28, + backgroundColor: AppColors.primary.withValues(alpha: 0.1), + child: Text( + user != null && user.firstName.isNotEmpty + ? user.firstName.substring(0, 1).toUpperCase() + : '?', + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w600, + color: AppColors.primary, ), ), - const SizedBox(height: 16), - Text( - user?.fullName ?? 'Utilisateur', - style: Theme.of(context).textTheme.titleLarge, + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(user?.fullName ?? 'Utilisateur', style: Theme.of(context).textTheme.titleMedium), + if (user?.email != null) + Text(user!.email, style: Theme.of(context).textTheme.bodyMedium), + ], ), - if (user?.email != null) ...[ - const SizedBox(height: 4), - Text(user!.email), - ], - ], + ), + ], + ), + ), + ), + const SizedBox(height: 8), + Card( + child: Column( + children: [ + ListTile( + leading: const Icon(Icons.language_outlined, color: AppColors.textSecondary), + title: const Text('Langue'), + trailing: Text(user?.locale ?? 'fr'), ), - ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.notifications_outlined, color: AppColors.textSecondary), + title: const Text('Notifications'), + trailing: const Icon(Icons.chevron_right, color: AppColors.textSecondary), + onTap: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Préférences — à implémenter')), + ); + }, + ), + ], ), - const SizedBox(height: 16), - ListTile( - leading: const Icon(Icons.language), - title: const Text('Langue'), - subtitle: Text(user?.locale ?? 'fr'), - ), - ListTile( - leading: const Icon(Icons.notifications_outlined), - title: const Text('Notifications'), - onTap: () { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Préférences — à implémenter')), - ); - }, - ), - const Divider(), - ListTile( - leading: Icon(Icons.logout, color: Theme.of(context).colorScheme.error), - title: Text( - 'Se déconnecter', - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), + ), + const SizedBox(height: 8), + Card( + child: ListTile( + leading: const Icon(Icons.logout, color: AppColors.error), + title: const Text('Se déconnecter', style: TextStyle(color: AppColors.error)), onTap: () async { await ref.read(authProvider.notifier).logout(); if (context.mounted) { @@ -75,8 +86,8 @@ class ProfileScreen extends ConsumerWidget { } }, ), - ], - ), + ), + ], ); } } diff --git a/lib/features/wallet/data/wallet_repository.dart b/lib/features/wallet/data/wallet_repository.dart index 58d29d8..06162c3 100644 --- a/lib/features/wallet/data/wallet_repository.dart +++ b/lib/features/wallet/data/wallet_repository.dart @@ -2,6 +2,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../core/api/api_client.dart'; import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; +import '../../../core/auth/auth_provider.dart'; import '../domain/wallet.dart'; /// Dépôt de données pour le portefeuille électronique. @@ -12,36 +14,18 @@ class WalletRepository { Future fetchWallet() async { final response = await _apiClient.get(ApiEndpoints.wallet); - final json = _extractObject(response.data); + final json = ApiResponse.object(response.data, 'wallet'); return Wallet.fromJson(json); } Future> fetchTransactions() async { final response = await _apiClient.get(ApiEndpoints.walletTransactions); - final list = _extractList(response.data); + final list = ApiResponse.list(response.data, 'transactions'); return list .map((json) => WalletTransaction.fromJson(json as Map)) .toList(); } - - List _extractList(dynamic data) { - if (data is List) return data; - if (data is Map && data['data'] is List) { - return data['data'] as List; - } - return []; - } - - Map _extractObject(dynamic data) { - if (data is Map) { - if (data['data'] is Map) { - return data['data'] as Map; - } - return data; - } - throw StateError('Réponse API inattendue'); - } } final walletRepositoryProvider = Provider((ref) { @@ -49,10 +33,20 @@ final walletRepositoryProvider = Provider((ref) { }); final walletProvider = FutureProvider((ref) async { + final token = ref.watch(authProvider.select((state) => state.accessToken)); + if (token == null || token.isEmpty) { + throw StateError('Non authentifié'); + } + return ref.watch(walletRepositoryProvider).fetchWallet(); }); final walletTransactionsProvider = FutureProvider>((ref) async { + final token = ref.watch(authProvider.select((state) => state.accessToken)); + if (token == null || token.isEmpty) { + throw StateError('Non authentifié'); + } + return ref.watch(walletRepositoryProvider).fetchTransactions(); }); diff --git a/lib/features/wallet/presentation/wallet_screen.dart b/lib/features/wallet/presentation/wallet_screen.dart index ed8c754..572b88d 100644 --- a/lib/features/wallet/presentation/wallet_screen.dart +++ b/lib/features/wallet/presentation/wallet_screen.dart @@ -1,116 +1,130 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:intl/intl.dart'; - -import '../data/wallet_repository.dart'; - -/// Écran du portefeuille électronique — solde et historique. -class WalletScreen extends ConsumerWidget { - const WalletScreen({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final walletAsync = ref.watch(walletProvider); - final transactionsAsync = ref.watch(walletTransactionsProvider); - final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); - - return Scaffold( - appBar: AppBar(title: const Text('Mon portefeuille')), - body: RefreshIndicator( - onRefresh: () async { - ref.invalidate(walletProvider); - ref.invalidate(walletTransactionsProvider); - }, - child: ListView( - padding: const EdgeInsets.all(16), - children: [ - walletAsync.when( - loading: () => const Card( - child: Padding( - padding: EdgeInsets.all(24), - child: Center(child: CircularProgressIndicator()), - ), - ), - error: (error, _) => Card( - child: Padding( - padding: const EdgeInsets.all(16), - child: Text('Erreur solde : $error'), - ), - ), - data: (wallet) => Card( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - children: [ - Text( - 'Solde disponible', - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox(height: 8), - Text( - currencyFormat.format(wallet.currentBalance), - style: Theme.of(context).textTheme.displaySmall?.copyWith( - color: Theme.of(context).colorScheme.primary, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - ), - ), - ), - const SizedBox(height: 24), - Text( - 'Historique', - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox(height: 8), - transactionsAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Text('Erreur historique : $error'), - data: (transactions) { - if (transactions.isEmpty) { - return const Text('Aucune transaction pour le moment'); - } - - return Column( - children: transactions.map((tx) { - final isCredit = tx.type == 'credit' || tx.type == 'refund'; - return Card( - child: ListTile( - leading: Icon( - isCredit ? Icons.add_circle_outline : Icons.remove_circle_outline, - color: isCredit ? Colors.green : Colors.red, - ), - title: Text(tx.type), - subtitle: tx.createdAt != null - ? Text(DateFormat('dd/MM/yyyy HH:mm').format(tx.createdAt!)) - : null, - trailing: Text( - '${isCredit ? '+' : '-'}${currencyFormat.format(tx.amount)}', - style: TextStyle( - fontWeight: FontWeight.bold, - color: isCredit ? Colors.green : Colors.red, - ), - ), - ), - ); - }).toList(), - ); - }, - ), - ], - ), - ), - floatingActionButton: FloatingActionButton.extended( - onPressed: () { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Rechargement — à connecter à l\'API')), - ); - }, - icon: const Icon(Icons.add), - label: const Text('Recharger'), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../data/wallet_repository.dart'; + +/// Écran du portefeuille électronique — solde et historique. +class WalletScreen extends ConsumerWidget { + const WalletScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final walletAsync = ref.watch(walletProvider); + final transactionsAsync = ref.watch(walletTransactionsProvider); + final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return RefreshIndicator( + onRefresh: () async { + ref.invalidate(walletProvider); + ref.invalidate(walletTransactionsProvider); + }, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + walletAsync.when( + loading: () => const SizedBox( + height: 120, + child: Center(child: CircularProgressIndicator()), + ), + error: (error, _) => Text('Erreur solde : $error'), + data: (wallet) => Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + gradient: AppColors.gradientAccent, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: AppColors.primary.withValues(alpha: 0.2), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Solde disponible', + style: TextStyle(color: Colors.white.withValues(alpha: 0.9), fontSize: 14), + ), + const SizedBox(height: 8), + Text( + currencyFormat.format(wallet.currentBalance), + style: const TextStyle( + color: Colors.white, + fontSize: 32, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + wallet.status == 'active' ? 'Compte actif' : wallet.status, + style: TextStyle(color: Colors.white.withValues(alpha: 0.85), fontSize: 13), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Rechargement — à connecter à l\'API')), + ); + }, + icon: const Icon(Icons.add), + label: const Text('Recharger'), + ), + const SizedBox(height: 24), + Text('Historique', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + transactionsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Text('Erreur historique : $error'), + data: (transactions) { + if (transactions.isEmpty) { + return const EmptyState( + icon: Icons.receipt_long_outlined, + title: 'Aucune transaction', + subtitle: 'Vos rechargements et débits apparaîtront ici.', + ); + } + + return Column( + children: transactions.map((tx) { + final isCredit = tx.type == 'credit' || tx.type == 'refund'; + final color = isCredit ? AppColors.success : AppColors.error; + + return Card( + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + leading: CircleAvatar( + backgroundColor: color.withValues(alpha: 0.1), + child: Icon( + isCredit ? Icons.add : Icons.remove, + color: color, + size: 20, + ), + ), + title: Text(tx.type), + subtitle: tx.createdAt != null + ? Text(DateFormat('dd/MM/yyyy HH:mm').format(tx.createdAt!)) + : null, + trailing: Text( + '${isCredit ? '+' : '-'}${currencyFormat.format(tx.amount)}', + style: TextStyle(fontWeight: FontWeight.w600, color: color), + ), + ), + ); + }).toList(), + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/features/wash/data/wash_repository.dart b/lib/features/wash/data/wash_repository.dart new file mode 100644 index 0000000..f33cce2 --- /dev/null +++ b/lib/features/wash/data/wash_repository.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/auth/auth_provider.dart'; +import '../../../core/api/api_client.dart'; +import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; +import '../domain/wash.dart'; + +/// Référence machine extraite d'un QR code scanné. +class QrMachineReference { + const QrMachineReference({ + this.machineUuid, + this.qrCode, + }); + + final String? machineUuid; + final String? qrCode; + + bool get isValid => + (machineUuid != null && machineUuid!.isNotEmpty) || + (qrCode != null && qrCode!.isNotEmpty); + + factory QrMachineReference.parse(String raw) { + final trimmed = raw.trim(); + if (trimmed.isEmpty) { + return const QrMachineReference(); + } + + try { + final decoded = jsonDecode(trimmed); + if (decoded is Map) { + return QrMachineReference( + machineUuid: decoded['machine_uuid'] as String?, + qrCode: decoded['qr_code'] as String?, + ); + } + } catch (_) { + // Contenu texte brut (ex. LAVERIE-DEMO-001). + } + + final uuidPattern = RegExp( + r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$', + ); + if (uuidPattern.hasMatch(trimmed)) { + return QrMachineReference(machineUuid: trimmed); + } + + return QrMachineReference(qrCode: trimmed); + } +} + +/// Dépôt de données pour les lavages. +class WashRepository { + WashRepository(this._apiClient); + + final ApiClient _apiClient; + + Future> fetchWashes() async { + final response = await _apiClient.get(ApiEndpoints.washes); + final list = ApiResponse.list(response.data, 'washes'); + + return list + .map((json) => Wash.fromJson(json as Map)) + .toList(); + } + + Future startWashFromMachine(String machineUuid) async { + try { + final response = await _apiClient.post( + ApiEndpoints.washesStart, + data: { + 'machine_uuid': machineUuid, + 'trigger_method': 'qr_code', + }, + ); + final washJson = ApiResponse.object(response.data, 'wash'); + return Wash.fromJson(washJson); + } on DioException catch (error) { + throw WashStartException(ApiResponse.errorMessage(error, fallback: 'Impossible de démarrer le lavage')); + } + } + + Future startWashFromQr(String scannedValue) async { + final reference = QrMachineReference.parse(scannedValue); + if (!reference.isValid) { + throw const FormatException('QR code invalide ou vide'); + } + + final payload = { + 'trigger_method': 'qr_code', + if (reference.machineUuid != null) 'machine_uuid': reference.machineUuid, + if (reference.qrCode != null) 'qr_code': reference.qrCode, + }; + + try { + final response = await _apiClient.post( + ApiEndpoints.washesStart, + data: payload, + ); + final washJson = ApiResponse.object(response.data, 'wash'); + return Wash.fromJson(washJson); + } on DioException catch (error) { + throw WashStartException(ApiResponse.errorMessage(error, fallback: 'Impossible de démarrer le lavage')); + } + } +} + +class WashStartException implements Exception { + WashStartException(this.message); + + final String message; + + @override + String toString() => message; +} + +final washRepositoryProvider = Provider((ref) { + return WashRepository(ref.watch(apiClientProvider)); +}); + +final washesProvider = FutureProvider>((ref) async { + final token = ref.watch(authProvider.select((state) => state.accessToken)); + if (token == null || token.isEmpty) { + throw StateError('Non authentifié'); + } + + return ref.watch(washRepositoryProvider).fetchWashes(); +}); diff --git a/lib/features/wash/domain/wash.dart b/lib/features/wash/domain/wash.dart index 46e4de4..cf0eee5 100644 --- a/lib/features/wash/domain/wash.dart +++ b/lib/features/wash/domain/wash.dart @@ -1,3 +1,5 @@ +import 'wash_progress.dart'; + /// Modèle lavage (cycle en cours ou terminé). class Wash { const Wash({ @@ -9,6 +11,9 @@ class Wash { this.startedAt, this.endedAt, this.durationMinutes, + this.machineType, + this.cycleEndsAt, + this.progress, }); final String uuid; @@ -19,14 +24,27 @@ class Wash { final DateTime? startedAt; final DateTime? endedAt; final int? durationMinutes; + final String? machineType; + final DateTime? cycleEndsAt; + final WashProgress? progress; + + WashProgress get liveProgress => WashProgress.compute( + startedAt: startedAt, + estimatedEndAt: progress?.estimatedEndAt ?? cycleEndsAt, + durationMinutes: durationMinutes, + machineType: machineType, + status: status, + ); factory Wash.fromJson(Map json) { final machine = json['machine'] as Map?; + final progressJson = json['progress'] as Map?; return Wash( uuid: json['uuid'] as String, machineUuid: machine?['uuid'] as String? ?? json['machine_uuid'] as String? ?? '', machineName: machine?['name'] as String? ?? 'Machine', + machineType: machine?['type'] as String?, status: json['status'] as String? ?? 'pending_start', cost: (json['cost'] as num?)?.toDouble() ?? 0, startedAt: json['started_at'] != null @@ -36,6 +54,10 @@ class Wash { ? DateTime.tryParse(json['ended_at'] as String) : null, durationMinutes: json['duration_minutes'] as int?, + cycleEndsAt: machine?['cycle_ends_at'] != null + ? DateTime.tryParse(machine!['cycle_ends_at'] as String) + : null, + progress: progressJson != null ? WashProgress.fromJson(progressJson) : null, ); } } diff --git a/lib/features/wash/domain/wash_progress.dart b/lib/features/wash/domain/wash_progress.dart new file mode 100644 index 0000000..d178b5b --- /dev/null +++ b/lib/features/wash/domain/wash_progress.dart @@ -0,0 +1,114 @@ +/// Progression d'un lavage en cours. +class WashProgress { + const WashProgress({ + required this.percent, + required this.phaseLabel, + this.phase, + this.estimatedEndAt, + this.remainingSeconds, + }); + + final int percent; + final String phaseLabel; + final String? phase; + final DateTime? estimatedEndAt; + final int? remainingSeconds; + + String get remainingLabel { + if (remainingSeconds == null) return ''; + final s = remainingSeconds!; + if (s <= 0) return 'Bientôt terminé'; + if (s < 60) return '$s s restantes'; + final min = (s / 60).ceil(); + return '$min min restantes'; + } + + factory WashProgress.fromJson(Map? json) { + if (json == null) { + return const WashProgress(percent: 0, phaseLabel: 'En cours'); + } + return WashProgress( + percent: json['percent'] as int? ?? 0, + phase: json['phase'] as String?, + phaseLabel: json['phase_label'] as String? ?? 'En cours', + estimatedEndAt: json['estimated_end_at'] != null + ? DateTime.tryParse(json['estimated_end_at'] as String) + : null, + remainingSeconds: json['remaining_seconds'] as int?, + ); + } + + /// Calcul local si pas de données API (rafraîchissement chaque seconde). + factory WashProgress.compute({ + required DateTime? startedAt, + required DateTime? estimatedEndAt, + required int? durationMinutes, + required String? machineType, + required String status, + }) { + if (status == 'pending_start') { + return const WashProgress(percent: 0, phaseLabel: 'En attente de démarrage', phase: 'pending'); + } + + final now = DateTime.now(); + final end = estimatedEndAt ?? + (startedAt != null && durationMinutes != null + ? startedAt.add(Duration(minutes: durationMinutes)) + : null); + + if (startedAt == null || end == null) { + return const WashProgress(percent: 5, phaseLabel: 'Démarrage…', phase: 'lock'); + } + + final total = end.difference(startedAt).inSeconds.clamp(1, 999999); + final elapsed = now.difference(startedAt).inSeconds.clamp(0, total); + final percent = ((elapsed / total) * 100).round().clamp(0, 99); + final remaining = end.difference(now).inSeconds.clamp(0, total); + + return WashProgress( + percent: percent, + phaseLabel: _phaseLabel(percent, machineType), + phase: _phase(percent, machineType), + estimatedEndAt: end, + remainingSeconds: remaining, + ); + } + + static String _phase(int percent, String? type) { + final isDryer = type?.startsWith('dryer') ?? false; + if (percent < 5) return 'lock'; + if (isDryer) { + if (percent < 15) return 'heat'; + if (percent < 85) return 'dry'; + return 'finish'; + } + if (percent < 15) return 'fill'; + if (percent < 55) return 'wash'; + if (percent < 75) return 'rinse'; + if (percent < 90) return 'spin'; + return 'finish'; + } + + static String _phaseLabel(int percent, String? type) { + switch (_phase(percent, type)) { + case 'lock': + return 'Verrouillage'; + case 'heat': + return 'Préchauffage'; + case 'dry': + return 'Séchage'; + case 'fill': + return 'Remplissage'; + case 'wash': + return 'Lavage'; + case 'rinse': + return 'Rinçage'; + case 'spin': + return 'Essorage'; + case 'finish': + return 'Finition'; + default: + return 'En cours'; + } + } +} diff --git a/lib/features/wash/presentation/qr_scanner_screen.dart b/lib/features/wash/presentation/qr_scanner_screen.dart new file mode 100644 index 0000000..7f6a47a --- /dev/null +++ b/lib/features/wash/presentation/qr_scanner_screen.dart @@ -0,0 +1,219 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; + +import '../../../core/api/api_response.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../machines/data/machine_repository.dart'; +import '../../wash/data/wash_repository.dart'; + +/// Écran de scan QR → page dédiée machine. +class QrScannerScreen extends ConsumerStatefulWidget { + const QrScannerScreen({super.key}); + + @override + ConsumerState createState() => _QrScannerScreenState(); +} + +class _QrScannerScreenState extends ConsumerState { + final MobileScannerController _controller = MobileScannerController( + detectionSpeed: DetectionSpeed.noDuplicates, + facing: CameraFacing.back, + ); + + bool _isProcessing = false; + String? _lastScannedValue; + + static const _frameSize = 260.0; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _onDetect(BarcodeCapture capture) async { + if (_isProcessing) return; + + final value = capture.barcodes.firstOrNull?.rawValue?.trim(); + if (value == null || value.isEmpty) return; + if (value == _lastScannedValue) return; + + setState(() { + _isProcessing = true; + _lastScannedValue = value; + }); + + await _controller.stop(); + + try { + final reference = QrMachineReference.parse(value); + if (!reference.isValid) { + throw const FormatException('QR code invalide'); + } + + final detail = await ref.read(machineRepositoryProvider).lookup( + qrCode: reference.qrCode, + machineUuid: reference.machineUuid, + ); + + if (!mounted) return; + + context.pop(); + context.push(AppRoutes.machineAction(detail.machine.uuid)); + } on DioException catch (error) { + if (!mounted) return; + _showErrorAndResume(ApiResponse.errorMessage(error, fallback: 'Machine introuvable')); + } on FormatException catch (error) { + if (!mounted) return; + _showErrorAndResume(error.message); + } catch (_) { + if (!mounted) return; + _showErrorAndResume('Impossible de lire ce QR code'); + } + } + + Future _showErrorAndResume(String message) async { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(message), backgroundColor: AppColors.error), + ); + + setState(() { + _isProcessing = false; + _lastScannedValue = null; + }); + + await _controller.start(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + title: const Text('Scanner une machine'), + backgroundColor: Colors.black, + foregroundColor: Colors.white, + actions: [ + IconButton( + tooltip: 'Lampe', + onPressed: () => _controller.toggleTorch(), + icon: const Icon(Icons.flash_on_rounded), + ), + ], + ), + body: Stack( + fit: StackFit.expand, + children: [ + MobileScanner( + controller: _controller, + onDetect: _onDetect, + ), + CustomPaint( + painter: _ScannerOverlayPainter(frameSize: _frameSize), + child: const SizedBox.expand(), + ), + Align( + alignment: Alignment.bottomCenter, + child: Container( + width: double.infinity, + padding: const EdgeInsets.fromLTRB(24, 24, 24, 32), + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Colors.transparent, Colors.black.withValues(alpha: 0.9)], + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Placez le QR code dans le cadre', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 16, + ), + ), + const SizedBox(height: 6), + Text( + 'Ex. démo : LAVERIE-DEMO-001', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white.withValues(alpha: 0.7), fontSize: 13), + ), + if (_isProcessing) ...[ + const SizedBox(height: 16), + const SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white), + ), + const SizedBox(height: 8), + const Text( + 'Identification de la machine…', + style: TextStyle(color: Colors.white70, fontSize: 13), + ), + ], + ], + ), + ), + ), + ], + ), + ); + } +} + +class _ScannerOverlayPainter extends CustomPainter { + _ScannerOverlayPainter({required this.frameSize}); + + final double frameSize; + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final rect = Rect.fromCenter(center: center, width: frameSize, height: frameSize); + final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(20)); + + canvas.drawPath( + Path.combine( + PathOperation.difference, + Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height)), + Path()..addRRect(rrect), + ), + Paint()..color = Colors.black.withValues(alpha: 0.55), + ); + + canvas.drawRRect( + rrect, + Paint() + ..color = Colors.white + ..style = PaintingStyle.stroke + ..strokeWidth = 2.5, + ); + + const cornerLen = 28.0; + final corner = Paint() + ..color = AppColors.primary + ..style = PaintingStyle.stroke + ..strokeWidth = 4 + ..strokeCap = StrokeCap.round; + + canvas.drawLine(rect.topLeft, rect.topLeft + const Offset(cornerLen, 0), corner); + canvas.drawLine(rect.topLeft, rect.topLeft + const Offset(0, cornerLen), corner); + canvas.drawLine(rect.topRight, rect.topRight + const Offset(-cornerLen, 0), corner); + canvas.drawLine(rect.topRight, rect.topRight + const Offset(0, cornerLen), corner); + canvas.drawLine(rect.bottomLeft, rect.bottomLeft + const Offset(cornerLen, 0), corner); + canvas.drawLine(rect.bottomLeft, rect.bottomLeft + const Offset(0, -cornerLen), corner); + canvas.drawLine(rect.bottomRight, rect.bottomRight + const Offset(-cornerLen, 0), corner); + canvas.drawLine(rect.bottomRight, rect.bottomRight + const Offset(0, -cornerLen), corner); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/features/wash/presentation/wash_screen.dart b/lib/features/wash/presentation/wash_screen.dart index 7a6c645..30a068c 100644 --- a/lib/features/wash/presentation/wash_screen.dart +++ b/lib/features/wash/presentation/wash_screen.dart @@ -1,103 +1,152 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; -import '../../../core/api/api_client.dart'; -import '../../../core/api/api_endpoints.dart'; +import '../../../core/api/api_response.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/screen_header.dart'; +import '../data/wash_repository.dart'; import '../domain/wash.dart'; +import '../domain/wash_progress.dart'; +import 'widgets/active_wash_progress_card.dart'; -/// Fournisseur de l'historique des lavages. -final washesProvider = FutureProvider>((ref) async { - final response = await ref.watch(apiClientProvider).get(ApiEndpoints.washes); - final data = response.data; +bool _isActiveWash(String status) => + status == 'running' || status == 'pending_start' || status == 'active'; - List list; - if (data is List) { - list = data; - } else if (data is Map && data['data'] is List) { - list = data['data'] as List; - } else { - list = []; - } - - return list.map((json) => Wash.fromJson(json as Map)).toList(); -}); - -/// Écran historique et démarrage de lavage. -class WashScreen extends ConsumerWidget { +/// Écran historique et lavages en cours avec progression. +class WashScreen extends ConsumerStatefulWidget { const WashScreen({super.key}); @override - Widget build(BuildContext context, WidgetRef ref) { + ConsumerState createState() => _WashScreenState(); +} + +class _WashScreenState extends ConsumerState { + Timer? _ticker; + + @override + void initState() { + super.initState(); + _ticker = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) setState(() {}); + }); + } + + @override + void dispose() { + _ticker?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { final washesAsync = ref.watch(washesProvider); - return Scaffold( - appBar: AppBar(title: const Text('Mes lavages')), - body: washesAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + return washesAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => EmptyState( + icon: Icons.error_outline, + title: 'Erreur de chargement', + subtitle: error is DioException + ? ApiResponse.errorMessage(error, fallback: 'Impossible de charger les lavages.') + : 'Impossible de charger les lavages.', + actionLabel: 'Réessayer', + onAction: () => ref.invalidate(washesProvider), + ), + data: (washes) { + if (washes.isEmpty) { + return EmptyState( + icon: Icons.qr_code_scanner_outlined, + title: 'Aucun lavage', + subtitle: 'Scannez une machine pour voir\nses infos et démarrer un cycle.', + actionLabel: 'Scanner', + onAction: () => context.push(AppRoutes.washScan), + ); + } + + final active = washes.where((w) => _isActiveWash(w.status)).toList(); + final history = washes.where((w) => !_isActiveWash(w.status)).toList(); + final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return RefreshIndicator( + onRefresh: () async => ref.invalidate(washesProvider), + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 88), children: [ - Text('Erreur : $error'), - const SizedBox(height: 12), - ElevatedButton( - onPressed: () => ref.invalidate(washesProvider), - child: const Text('Réessayer'), - ), + if (active.isNotEmpty) ...[ + const ScreenHeader( + title: 'En cours', + subtitle: 'Progression en temps réel', + ), + ...active.map((wash) { + final progress = _liveProgress(wash); + return ActiveWashProgressCard( + wash: wash, + format: currencyFormat, + progress: progress, + ); + }), + const SizedBox(height: 16), + ], + if (history.isNotEmpty) ...[ + Text('Historique', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 10), + ...history.map( + (wash) => Padding( + padding: const EdgeInsets.only(bottom: 8), + child: _HistoryWashTile(wash: wash, format: currencyFormat), + ), + ), + ], ], ), + ); + }, + ); + } + + WashProgress _liveProgress(Wash wash) { + if (wash.progress != null && wash.progress!.percent > 0) { + return WashProgress.compute( + startedAt: wash.startedAt, + estimatedEndAt: wash.progress!.estimatedEndAt ?? wash.cycleEndsAt, + durationMinutes: wash.durationMinutes, + machineType: wash.machineType, + status: wash.status, + ); + } + return wash.liveProgress; + } +} + +class _HistoryWashTile extends StatelessWidget { + const _HistoryWashTile({required this.wash, required this.format}); + + final Wash wash; + final NumberFormat format; + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: const CircleAvatar( + backgroundColor: Color(0xFFE2E8F0), + child: Icon(Icons.check_circle_outline, color: AppColors.success, size: 20), + ), + title: Text(wash.machineName), + subtitle: wash.startedAt != null + ? Text(DateFormat('dd/MM/yyyy · HH:mm').format(wash.startedAt!)) + : null, + trailing: Text( + format.format(wash.cost), + style: const TextStyle(fontWeight: FontWeight.w600), ), - data: (washes) { - if (washes.isEmpty) { - return const Center( - child: Text( - 'Aucun lavage enregistré.\nScannez un QR code pour démarrer un cycle.', - textAlign: TextAlign.center, - ), - ); - } - - final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); - - return RefreshIndicator( - onRefresh: () async => ref.invalidate(washesProvider), - child: ListView.separated( - padding: const EdgeInsets.all(16), - itemCount: washes.length, - separatorBuilder: (_, __) => const SizedBox(height: 8), - itemBuilder: (context, index) { - final wash = washes[index]; - return Card( - child: ListTile( - leading: const Icon(Icons.local_laundry_service), - title: Text(wash.machineName), - subtitle: wash.startedAt != null - ? Text(DateFormat('dd/MM/yyyy HH:mm').format(wash.startedAt!)) - : null, - trailing: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text(currencyFormat.format(wash.cost)), - Text(wash.status, style: Theme.of(context).textTheme.bodySmall), - ], - ), - ), - ); - }, - ), - ); - }, - ), - floatingActionButton: FloatingActionButton.extended( - onPressed: () { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Scan QR — à connecter à l\'API /washes/start')), - ); - }, - icon: const Icon(Icons.qr_code_scanner), - label: const Text('Scanner'), ), ); } diff --git a/lib/features/wash/presentation/widgets/active_wash_progress_card.dart b/lib/features/wash/presentation/widgets/active_wash_progress_card.dart new file mode 100644 index 0000000..df5dd34 --- /dev/null +++ b/lib/features/wash/presentation/widgets/active_wash_progress_card.dart @@ -0,0 +1,163 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../../../../core/theme/app_colors.dart'; +import '../../domain/wash.dart'; +import '../../domain/wash_progress.dart'; + +/// Carte lavage en cours avec pourcentage et étape du cycle. +class ActiveWashProgressCard extends StatelessWidget { + const ActiveWashProgressCard({ + super.key, + required this.wash, + required this.format, + this.progress, + }); + + final Wash wash; + final NumberFormat format; + final WashProgress? progress; + + @override + Widget build(BuildContext context) { + final p = progress ?? wash.liveProgress; + final steps = _stepsForType(wash.machineType); + final currentIndex = steps.indexWhere((s) => s.key == p.phase); + final activeStep = currentIndex >= 0 ? currentIndex : 0; + + return Card( + margin: const EdgeInsets.only(bottom: 10), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: AppColors.machineRunning.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.local_laundry_service, color: AppColors.machineRunning), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(wash.machineName, style: Theme.of(context).textTheme.titleMedium), + Text( + p.phaseLabel, + style: TextStyle( + color: AppColors.machineRunning, + fontWeight: FontWeight.w600, + fontSize: 13, + ), + ), + ], + ), + ), + Text( + '${p.percent}%', + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: AppColors.machineRunning, + ), + ), + ], + ), + const SizedBox(height: 14), + ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: p.percent / 100, + minHeight: 8, + backgroundColor: AppColors.machineRunning.withValues(alpha: 0.12), + color: AppColors.machineRunning, + ), + ), + const SizedBox(height: 14), + Row( + children: List.generate(steps.length, (index) { + final step = steps[index]; + final isDone = index < activeStep; + final isActive = index == activeStep; + final color = isDone || isActive + ? AppColors.machineRunning + : AppColors.textSecondary.withValues(alpha: 0.35); + + return Expanded( + child: Column( + children: [ + Icon( + isDone ? Icons.check_circle : step.icon, + size: 20, + color: color, + ), + const SizedBox(height: 4), + Text( + step.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 9, + fontWeight: isActive ? FontWeight.w700 : FontWeight.normal, + color: isActive ? AppColors.machineRunning : AppColors.textSecondary, + ), + ), + ], + ), + ); + }), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + p.remainingLabel.isNotEmpty ? p.remainingLabel : 'Cycle en cours…', + style: Theme.of(context).textTheme.bodyMedium, + ), + Text( + format.format(wash.cost), + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ], + ), + ], + ), + ), + ); + } + + static List<_WashStep> _stepsForType(String? type) { + if (type?.startsWith('dryer') ?? false) { + return const [ + _WashStep('lock', 'Verrou', Icons.lock_outline), + _WashStep('heat', 'Chauffe', Icons.whatshot_outlined), + _WashStep('dry', 'Sèche', Icons.air), + _WashStep('finish', 'Fin', Icons.check), + ]; + } + return const [ + _WashStep('lock', 'Verrou', Icons.lock_outline), + _WashStep('fill', 'Eau', Icons.water_drop_outlined), + _WashStep('wash', 'Lave', Icons.local_laundry_service_outlined), + _WashStep('rinse', 'Rince', Icons.waves_outlined), + _WashStep('spin', 'Essore', Icons.rotate_right), + _WashStep('finish', 'Fin', Icons.check), + ]; + } +} + +class _WashStep { + const _WashStep(this.key, this.label, this.icon); + final String key; + final String label; + final IconData icon; +} diff --git a/pubspec.lock b/pubspec.lock index 9acbb37..46ef13a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -317,6 +317,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" + mobile_scanner: + dependency: "direct main" + description: + name: mobile_scanner + sha256: d234581c090526676fd8fab4ada92f35c6746e3fb4f05a399665d75a399fb760 + url: "https://pub.dev" + source: hosted + version: "5.2.3" objective_c: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 9146b3c..d2adcfd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -17,6 +17,7 @@ dependencies: flutter_riverpod: ^2.6.1 go_router: ^14.8.1 dio: ^5.8.0+1 + mobile_scanner: ^5.2.3 flutter_secure_storage: ^9.2.4 intl: ^0.20.2 From 9f352b91d256b7c1307bd75aa4228cd75e8cfece Mon Sep 17 00:00:00 2001 From: bastien Date: Sat, 4 Jul 2026 22:46:14 +0200 Subject: [PATCH 3/7] =?UTF-8?q?Int=C3=A9gration=20fonctionnalites=20V1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- android/app/src/main/AndroidManifest.xml | 2 + .../fr/laverie/laverie_mobile/MainActivity.kt | 4 +- .../app/src/main/res/values-night/styles.xml | 2 +- android/app/src/main/res/values/styles.xml | 2 +- lib/core/config/app_config.dart | 7 + lib/core/router/app_router.dart | 6 + lib/core/theme/app_theme.dart | 15 +- lib/core/time/server_time.dart | 71 +++++ lib/core/time/server_time_sync.dart | 29 ++ .../booking/data/booking_repository.dart | 9 +- lib/features/booking/domain/booking.dart | 4 +- .../presentation/booking_modify_screen.dart | 16 +- .../booking/presentation/bookings_screen.dart | 6 +- .../presentation/machine_action_screen.dart | 14 - .../presentation/machine_booking_screen.dart | 21 +- .../wallet/data/wallet_repository.dart | 26 ++ lib/features/wallet/domain/payment.dart | 72 +++++ lib/features/wallet/domain/wallet.dart | 73 +++++ .../wallet/presentation/wallet_screen.dart | 268 +++++++++--------- .../presentation/wallet_top_up_screen.dart | 229 +++++++++++++++ lib/features/wash/domain/wash_progress.dart | 4 +- .../wash/presentation/wash_screen.dart | 3 +- lib/main.dart | 14 +- pubspec.lock | 64 +++++ pubspec.yaml | 2 + 25 files changed, 779 insertions(+), 184 deletions(-) create mode 100644 lib/core/time/server_time.dart create mode 100644 lib/core/time/server_time_sync.dart create mode 100644 lib/features/wallet/domain/payment.dart create mode 100644 lib/features/wallet/presentation/wallet_top_up_screen.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 1dff5c0..c4b1549 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,8 @@ + + - diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml index cb1ef88..71d378e 100644 --- a/android/app/src/main/res/values/styles.xml +++ b/android/app/src/main/res/values/styles.xml @@ -12,7 +12,7 @@ running. This Theme is only used starting with V2 of Flutter's Android embedding. --> - diff --git a/lib/core/config/app_config.dart b/lib/core/config/app_config.dart index c6da9b7..2ff0c6a 100644 --- a/lib/core/config/app_config.dart +++ b/lib/core/config/app_config.dart @@ -38,3 +38,10 @@ abstract final class AuthStorageKeys { static const accessToken = 'laverie_access_token'; static const refreshToken = 'laverie_refresh_token'; } + +/// Clé publique Stripe (test) — surcharge via `--dart-define=STRIPE_PUBLISHABLE_KEY=...` +const String _envStripePublishableKey = String.fromEnvironment('STRIPE_PUBLISHABLE_KEY'); + +final String kStripePublishableKey = _envStripePublishableKey.isNotEmpty + ? _envStripePublishableKey + : 'pk_test_51TpANRJRUgjTIwfBR9PoU4Lu201yD5R0JzvOv8Nmyva7ISX3GJPJ3IX4lSqnkg13siYwi3B9Qq0tIpEj6VCzeVFB00PSt9o0OA'; diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart index b498e2e..ae29898 100644 --- a/lib/core/router/app_router.dart +++ b/lib/core/router/app_router.dart @@ -9,6 +9,7 @@ import '../../features/auth/presentation/splash_screen.dart'; import '../../features/home/presentation/home_screen.dart'; import '../../features/establishments/presentation/establishment_detail_screen.dart'; import '../../features/wallet/presentation/wallet_screen.dart'; +import '../../features/wallet/presentation/wallet_top_up_screen.dart'; import '../../features/booking/presentation/booking_modify_screen.dart'; import '../../features/booking/presentation/bookings_screen.dart'; import '../../features/machines/presentation/machine_action_screen.dart'; @@ -25,6 +26,7 @@ abstract final class AppRoutes { static const register = '/register'; static const home = '/'; static const wallet = '/wallet'; + static const walletTopUp = '/wallet/top-up'; static const bookings = '/bookings'; static const washes = '/washes'; static const washScan = '/washes/scan'; @@ -118,6 +120,10 @@ final appRouterProvider = Provider((ref) { path: AppRoutes.washScan, builder: (context, state) => const QrScannerScreen(), ), + GoRoute( + path: AppRoutes.walletTopUp, + builder: (context, state) => const WalletTopUpScreen(), + ), GoRoute( path: '/machines/:uuid/action', builder: (context, state) { diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart index 06b8d0f..92b8db6 100644 --- a/lib/core/theme/app_theme.dart +++ b/lib/core/theme/app_theme.dart @@ -70,8 +70,21 @@ class AppTheme { style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(48), elevation: 0, - backgroundColor: AppColors.primary, + backgroundColor: AppColors.success, foregroundColor: Colors.white, + disabledBackgroundColor: AppColors.success.withValues(alpha: 0.4), + disabledForegroundColor: Colors.white70, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + textStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(48), + backgroundColor: AppColors.success, + foregroundColor: Colors.white, + disabledBackgroundColor: AppColors.success.withValues(alpha: 0.5), + disabledForegroundColor: Colors.white.withValues(alpha: 0.8), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), textStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16), ), diff --git a/lib/core/time/server_time.dart b/lib/core/time/server_time.dart new file mode 100644 index 0000000..f22469d --- /dev/null +++ b/lib/core/time/server_time.dart @@ -0,0 +1,71 @@ +import 'package:intl/intl.dart'; +import 'package:timezone/data/latest.dart' as tz_data; +import 'package:timezone/timezone.dart' as tz; + +/// Heure métier alignée sur le fuseau du serveur API (pas l'UTC ni le téléphone). +abstract final class ServerTime { + static const defaultTimezone = 'Europe/Paris'; + + static bool _initialized = false; + static tz.Location _location = tz.UTC; + + static Future initialize({String timezone = defaultTimezone}) async { + if (!_initialized) { + tz_data.initializeTimeZones(); + _initialized = true; + } + setTimezone(timezone); + } + + static void setTimezone(String timezone) { + if (!_initialized) { + tz_data.initializeTimeZones(); + _initialized = true; + } + _location = tz.getLocation(timezone); + } + + static String get timezone => _location.name; + + static tz.TZDateTime now() => tz.TZDateTime.now(_location); + + static DateTime startOfToday() { + final current = now(); + return DateTime(current.year, current.month, current.day); + } + + static DateTime? parse(String? iso) { + if (iso == null || iso.isEmpty) { + return null; + } + return DateTime.tryParse(iso); + } + + static tz.TZDateTime toServerTime(DateTime dateTime) { + return tz.TZDateTime.from(dateTime.toUtc(), _location); + } + + static String format( + DateTime? dateTime, { + required String pattern, + String locale = 'fr_FR', + }) { + if (dateTime == null) { + return ''; + } + + final server = toServerTime(dateTime); + return DateFormat(pattern, locale).format( + DateTime( + server.year, + server.month, + server.day, + server.hour, + server.minute, + server.second, + server.millisecond, + server.microsecond, + ), + ); + } +} diff --git a/lib/core/time/server_time_sync.dart b/lib/core/time/server_time_sync.dart new file mode 100644 index 0000000..dc1fc2d --- /dev/null +++ b/lib/core/time/server_time_sync.dart @@ -0,0 +1,29 @@ +import 'package:dio/dio.dart'; + +import '../api/api_endpoints.dart'; +import '../api/api_response.dart'; +import '../config/app_config.dart'; +import 'server_time.dart'; + +/// Synchronise le fuseau horaire applicatif avec l'API (`/health`). +Future syncServerTimezone() async { + try { + final client = Dio( + BaseOptions( + baseUrl: kApiBaseUrl, + connectTimeout: const Duration(seconds: 5), + receiveTimeout: const Duration(seconds: 5), + headers: {'Accept': 'application/json'}, + ), + ); + + final response = await client.get(ApiEndpoints.health); + final timezone = ApiResponse.payload(response.data)['timezone']; + + if (timezone is String && timezone.isNotEmpty) { + ServerTime.setTimezone(timezone); + } + } catch (_) { + // Conserve le fuseau par défaut (Europe/Paris). + } +} diff --git a/lib/features/booking/data/booking_repository.dart b/lib/features/booking/data/booking_repository.dart index e6e9d4c..5fd5896 100644 --- a/lib/features/booking/data/booking_repository.dart +++ b/lib/features/booking/data/booking_repository.dart @@ -5,6 +5,7 @@ import '../../../core/api/api_client.dart'; import '../../../core/api/api_endpoints.dart'; import '../../../core/api/api_response.dart'; import '../../../core/auth/auth_provider.dart'; +import '../../../core/time/server_time.dart'; import '../domain/booking.dart'; /// Dépôt de données pour les réservations. @@ -35,8 +36,8 @@ class BookingRepository { ApiEndpoints.bookings, data: { 'machine_uuid': machineUuid, - 'slot_start': slotStart.toUtc().toIso8601String(), - 'slot_end': slotEnd.toUtc().toIso8601String(), + 'slot_start': ServerTime.toServerTime(slotStart).toIso8601String(), + 'slot_end': ServerTime.toServerTime(slotEnd).toIso8601String(), }, ); final json = ApiResponse.object(response.data, 'booking'); @@ -65,8 +66,8 @@ class BookingRepository { final response = await _apiClient.patch( ApiEndpoints.bookingMove(uuid), data: { - 'slot_start': slotStart.toUtc().toIso8601String(), - 'slot_end': slotEnd.toUtc().toIso8601String(), + 'slot_start': ServerTime.toServerTime(slotStart).toIso8601String(), + 'slot_end': ServerTime.toServerTime(slotEnd).toIso8601String(), }, ); final json = ApiResponse.object(response.data, 'booking'); diff --git a/lib/features/booking/domain/booking.dart b/lib/features/booking/domain/booking.dart index e5789d9..35da128 100644 --- a/lib/features/booking/domain/booking.dart +++ b/lib/features/booking/domain/booking.dart @@ -1,3 +1,5 @@ +import '../../../core/time/server_time.dart'; + /// Modèle réservation de créneau machine. class Booking { const Booking({ @@ -21,7 +23,7 @@ class Booking { bool get canCancel => (status == 'confirmed' || status == 'pending') && slotStart != null && - slotStart!.isAfter(DateTime.now()); + slotStart!.isAfter(ServerTime.now()); bool get canModify => canCancel; diff --git a/lib/features/booking/presentation/booking_modify_screen.dart b/lib/features/booking/presentation/booking_modify_screen.dart index 1386f09..9a596c7 100644 --- a/lib/features/booking/presentation/booking_modify_screen.dart +++ b/lib/features/booking/presentation/booking_modify_screen.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart'; import '../../../core/router/app_router.dart'; import '../../../core/theme/app_colors.dart'; +import '../../../core/time/server_time.dart'; import '../../machines/data/machine_repository.dart'; import '../../machines/domain/machine_detail.dart'; import '../data/booking_repository.dart'; @@ -118,7 +118,7 @@ class _BookingModifyScreenState extends ConsumerState { ), Text( booking.slotStart != null && booking.slotEnd != null - ? '${DateFormat('EEEE dd MMM · HH:mm', 'fr_FR').format(booking.slotStart!)} – ${DateFormat('HH:mm').format(booking.slotEnd!)}' + ? '${ServerTime.format(booking.slotStart, pattern: 'EEEE dd MMM · HH:mm')} – ${ServerTime.format(booking.slotEnd, pattern: 'HH:mm')}' : '—', style: const TextStyle(fontWeight: FontWeight.w600), ), @@ -136,14 +136,14 @@ class _BookingModifyScreenState extends ConsumerState { itemCount: 6, separatorBuilder: (_, __) => const SizedBox(width: 8), itemBuilder: (context, index) { - final date = DateTime.now().add(Duration(days: index)); + final date = ServerTime.startOfToday().add(Duration(days: index)); final normalized = DateTime(date.year, date.month, date.day); final isSelected = normalized.year == selectedDate.year && normalized.month == selectedDate.month && normalized.day == selectedDate.day; return ChoiceChip( - label: Text(DateFormat('EEE dd/MM', 'fr_FR').format(normalized)), + label: Text(ServerTime.format(normalized, pattern: 'EEE dd/MM')), selected: isSelected, onSelected: (_) => setState(() { _selectedDate = normalized; @@ -172,7 +172,7 @@ class _BookingModifyScreenState extends ConsumerState { runSpacing: 8, children: slots.map((slot) { final label = - '${DateFormat('HH:mm').format(slot.start)} – ${DateFormat('HH:mm').format(slot.end)}'; + '${ServerTime.format(slot.start, pattern: 'HH:mm')} – ${ServerTime.format(slot.end, pattern: 'HH:mm')}'; final isSelected = _selectedSlot?.start == slot.start; return FilterChip( @@ -197,12 +197,6 @@ class _BookingModifyScreenState extends ConsumerState { height: 56, child: ElevatedButton.icon( onPressed: _isSaving ? null : () => _confirmMove(booking), - style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), - textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), - ), icon: _isSaving ? const SizedBox( width: 22, diff --git a/lib/features/booking/presentation/bookings_screen.dart b/lib/features/booking/presentation/bookings_screen.dart index d4823c6..2a0a3f2 100644 --- a/lib/features/booking/presentation/bookings_screen.dart +++ b/lib/features/booking/presentation/bookings_screen.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart'; import '../../../core/router/app_router.dart'; +import '../../../core/time/server_time.dart'; import '../../../core/theme/app_colors.dart'; import '../../../core/widgets/empty_state.dart'; import '../../../core/widgets/screen_header.dart'; @@ -16,7 +16,7 @@ class BookingsScreen extends ConsumerWidget { Future _cancelBooking(BuildContext context, WidgetRef ref, Booking booking) async { final slotLabel = booking.slotStart != null - ? DateFormat('EEEE dd MMM à HH:mm', 'fr_FR').format(booking.slotStart!) + ? ServerTime.format(booking.slotStart, pattern: 'EEEE dd MMM à HH:mm') : 'ce créneau'; final confirmed = await showDialog( @@ -144,7 +144,7 @@ class _BookingCard extends StatelessWidget { @override Widget build(BuildContext context) { final slotText = booking.slotStart != null - ? DateFormat('EEEE dd MMM · HH:mm', 'fr_FR').format(booking.slotStart!) + ? ServerTime.format(booking.slotStart, pattern: 'EEEE dd MMM · HH:mm') : 'Créneau à confirmer'; return Card( diff --git a/lib/features/machines/presentation/machine_action_screen.dart b/lib/features/machines/presentation/machine_action_screen.dart index bdeb389..4993bf1 100644 --- a/lib/features/machines/presentation/machine_action_screen.dart +++ b/lib/features/machines/presentation/machine_action_screen.dart @@ -215,16 +215,6 @@ class _MachineActionBody extends StatelessWidget { height: 60, child: ElevatedButton.icon( onPressed: canStart && !isStarting ? onStart : null, - style: ElevatedButton.styleFrom( - backgroundColor: AppColors.machineAvailable, - disabledBackgroundColor: AppColors.machineAvailable.withValues(alpha: 0.4), - foregroundColor: Colors.white, - disabledForegroundColor: Colors.white70, - elevation: canStart ? 2 : 0, - shadowColor: AppColors.machineAvailable.withValues(alpha: 0.4), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700), - ), icon: isStarting ? const SizedBox( width: 24, @@ -244,10 +234,6 @@ class _MachineActionBody extends StatelessWidget { style: ElevatedButton.styleFrom( backgroundColor: AppColors.primary, foregroundColor: Colors.white, - elevation: 2, - shadowColor: AppColors.primary.withValues(alpha: 0.35), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), ), icon: const Icon(Icons.event_available_outlined, size: 24), label: const Text('Réserver un créneau'), diff --git a/lib/features/machines/presentation/machine_booking_screen.dart b/lib/features/machines/presentation/machine_booking_screen.dart index 2e957b8..5c829ff 100644 --- a/lib/features/machines/presentation/machine_booking_screen.dart +++ b/lib/features/machines/presentation/machine_booking_screen.dart @@ -1,11 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart'; import '../../../core/router/app_router.dart'; import '../../../core/theme/app_colors.dart'; import '../../../core/theme/machine_status_theme.dart'; +import '../../../core/time/server_time.dart'; import '../../booking/data/booking_repository.dart'; import '../data/machine_repository.dart'; import '../domain/machine_detail.dart'; @@ -21,7 +21,7 @@ class MachineBookingScreen extends ConsumerStatefulWidget { } class _MachineBookingScreenState extends ConsumerState { - DateTime _selectedDate = DateTime.now(); + DateTime _selectedDate = ServerTime.startOfToday(); TimeSlot? _selectedSlot; bool _isBooking = false; @@ -112,14 +112,14 @@ class _MachineBookingScreenState extends ConsumerState { itemCount: 6, separatorBuilder: (_, __) => const SizedBox(width: 8), itemBuilder: (context, index) { - final date = DateTime.now().add(Duration(days: index)); + final date = ServerTime.startOfToday().add(Duration(days: index)); final normalized = DateTime(date.year, date.month, date.day); final isSelected = normalized.year == _selectedDate.year && normalized.month == _selectedDate.month && normalized.day == _selectedDate.day; return ChoiceChip( - label: Text(DateFormat('EEE dd/MM', 'fr_FR').format(normalized)), + label: Text(ServerTime.format(normalized, pattern: 'EEE dd/MM')), selected: isSelected, onSelected: (_) => setState(() { _selectedDate = normalized; @@ -159,7 +159,7 @@ class _MachineBookingScreenState extends ConsumerState { runSpacing: 8, children: slots.map((slot) { final label = - '${DateFormat('HH:mm').format(slot.start)} – ${DateFormat('HH:mm').format(slot.end)}'; + '${ServerTime.format(slot.start, pattern: 'HH:mm')} – ${ServerTime.format(slot.end, pattern: 'HH:mm')}'; final isSelected = _selectedSlot?.start == slot.start; return FilterChip( @@ -183,14 +183,9 @@ class _MachineBookingScreenState extends ConsumerState { width: double.infinity, height: 56, child: ElevatedButton.icon( - onPressed: _isBooking ? null : () => _confirmBooking(detail), - style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, - foregroundColor: Colors.white, - elevation: 0, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), - textStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), - ), + onPressed: (_isBooking || _selectedSlot == null) + ? null + : () => _confirmBooking(detail), icon: _isBooking ? const SizedBox( width: 22, diff --git a/lib/features/wallet/data/wallet_repository.dart b/lib/features/wallet/data/wallet_repository.dart index 06162c3..1bf518c 100644 --- a/lib/features/wallet/data/wallet_repository.dart +++ b/lib/features/wallet/data/wallet_repository.dart @@ -4,6 +4,7 @@ import '../../../core/api/api_client.dart'; import '../../../core/api/api_endpoints.dart'; import '../../../core/api/api_response.dart'; import '../../../core/auth/auth_provider.dart'; +import '../domain/payment.dart'; import '../domain/wallet.dart'; /// Dépôt de données pour le portefeuille électronique. @@ -26,6 +27,31 @@ class WalletRepository { .map((json) => WalletTransaction.fromJson(json as Map)) .toList(); } + + Future initiateTopUp({ + required double amount, + required String idempotencyKey, + }) async { + final response = await _apiClient.post( + ApiEndpoints.walletTopUpInitiate, + data: { + 'amount': amount, + 'idempotency_key': idempotencyKey, + }, + ); + + final json = ApiResponse.object(response.data, 'payment'); + return PaymentTransaction.fromJson(json); + } + + Future confirmTopUp({required String paymentUuid}) async { + final response = await _apiClient.post( + ApiEndpoints.walletTopUpConfirm, + data: {'payment_uuid': paymentUuid}, + ); + + return TopUpResult.fromJson(ApiResponse.payload(response.data)); + } } final walletRepositoryProvider = Provider((ref) { diff --git a/lib/features/wallet/domain/payment.dart b/lib/features/wallet/domain/payment.dart new file mode 100644 index 0000000..e7e5647 --- /dev/null +++ b/lib/features/wallet/domain/payment.dart @@ -0,0 +1,72 @@ +/// Transaction de paiement externe (rechargement wallet). +class PaymentTransaction { + const PaymentTransaction({ + required this.uuid, + required this.provider, + required this.amount, + required this.currency, + required this.status, + this.providerPaymentId, + this.stripe, + }); + + final String uuid; + final String provider; + final String? providerPaymentId; + final double amount; + final String currency; + final String status; + final StripePaymentDetails? stripe; + + factory PaymentTransaction.fromJson(Map json) { + final stripeJson = json['stripe']; + return PaymentTransaction( + uuid: json['uuid'] as String, + provider: json['provider'] as String, + providerPaymentId: json['provider_payment_id'] as String?, + amount: (json['amount'] as num).toDouble(), + currency: json['currency'] as String, + status: json['status'] as String, + stripe: stripeJson is Map + ? StripePaymentDetails.fromJson(stripeJson) + : null, + ); + } +} + +class StripePaymentDetails { + const StripePaymentDetails({ + required this.paymentIntentId, + required this.clientSecret, + required this.publishableKey, + }); + + final String paymentIntentId; + final String clientSecret; + final String publishableKey; + + factory StripePaymentDetails.fromJson(Map json) { + return StripePaymentDetails( + paymentIntentId: json['payment_intent_id'] as String, + clientSecret: json['client_secret'] as String, + publishableKey: json['publishable_key'] as String, + ); + } +} + +class TopUpResult { + const TopUpResult({ + required this.payment, + required this.balance, + }); + + final PaymentTransaction payment; + final double balance; + + factory TopUpResult.fromJson(Map json) { + return TopUpResult( + payment: PaymentTransaction.fromJson(json['payment'] as Map), + balance: (json['balance'] as num).toDouble(), + ); + } +} diff --git a/lib/features/wallet/domain/wallet.dart b/lib/features/wallet/domain/wallet.dart index 1eaa580..d85fc60 100644 --- a/lib/features/wallet/domain/wallet.dart +++ b/lib/features/wallet/domain/wallet.dart @@ -27,6 +27,7 @@ class WalletTransaction { required this.amount, required this.balanceAfter, required this.createdAt, + this.metadata = const {}, }); final String uuid; @@ -34,6 +35,64 @@ class WalletTransaction { final double amount; final double balanceAfter; final DateTime? createdAt; + final Map metadata; + + String get displayLabel { + final label = metadata['label']; + if (label is String && label.isNotEmpty) { + return label; + } + + return switch (type) { + 'credit' => 'Crédit', + 'debit' => 'Débit', + 'refund' => 'Remboursement', + 'hold' => 'Blocage', + 'release' => 'Libération', + 'adjustment' => 'Ajustement', + _ => type, + }; + } + + String? get displaySubtitle { + final stripeMap = _asStringMap(metadata['stripe']); + if (stripeMap != null) { + final brand = stripeMap['card_brand']; + final last4 = stripeMap['card_last4']; + if (brand is String && last4 is String) { + return '${_formatCardBrand(brand)} •••• $last4'; + } + + final paymentIntentId = stripeMap['payment_intent_id']; + if (paymentIntentId is String && paymentIntentId.isNotEmpty) { + return 'Stripe $paymentIntentId'; + } + } + + final providerPaymentId = metadata['provider_payment_id']; + if (providerPaymentId is String && providerPaymentId.isNotEmpty) { + return providerPaymentId; + } + + return null; + } + + static Map? _asStringMap(dynamic value) { + if (value == null) return null; + if (value is Map) return value; + if (value is Map) return Map.from(value); + return null; + } + + static String _formatCardBrand(String brand) { + if (brand.isEmpty) return 'Carte'; + return switch (brand.toLowerCase()) { + 'visa' => 'Visa', + 'mastercard' => 'Mastercard', + 'amex' => 'Amex', + _ => brand[0].toUpperCase() + brand.substring(1), + }; + } factory WalletTransaction.fromJson(Map json) { return WalletTransaction( @@ -44,6 +103,20 @@ class WalletTransaction { createdAt: json['created_at'] != null ? DateTime.tryParse(json['created_at'] as String) : null, + metadata: _parseMetadata(json['metadata']), ); } + + static Map _parseMetadata(dynamic value) { + if (value == null) { + return const {}; + } + if (value is Map) { + return value; + } + if (value is Map) { + return Map.from(value); + } + return const {}; + } } diff --git a/lib/features/wallet/presentation/wallet_screen.dart b/lib/features/wallet/presentation/wallet_screen.dart index 572b88d..667b136 100644 --- a/lib/features/wallet/presentation/wallet_screen.dart +++ b/lib/features/wallet/presentation/wallet_screen.dart @@ -1,130 +1,138 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:intl/intl.dart'; - -import '../../../core/theme/app_colors.dart'; -import '../../../core/widgets/empty_state.dart'; -import '../data/wallet_repository.dart'; - -/// Écran du portefeuille électronique — solde et historique. -class WalletScreen extends ConsumerWidget { - const WalletScreen({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final walletAsync = ref.watch(walletProvider); - final transactionsAsync = ref.watch(walletTransactionsProvider); - final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); - - return RefreshIndicator( - onRefresh: () async { - ref.invalidate(walletProvider); - ref.invalidate(walletTransactionsProvider); - }, - child: ListView( - padding: const EdgeInsets.all(16), - children: [ - walletAsync.when( - loading: () => const SizedBox( - height: 120, - child: Center(child: CircularProgressIndicator()), - ), - error: (error, _) => Text('Erreur solde : $error'), - data: (wallet) => Container( - padding: const EdgeInsets.all(20), - decoration: BoxDecoration( - gradient: AppColors.gradientAccent, - borderRadius: BorderRadius.circular(14), - boxShadow: [ - BoxShadow( - color: AppColors.primary.withValues(alpha: 0.2), - blurRadius: 10, - offset: const Offset(0, 4), - ), - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - 'Solde disponible', - style: TextStyle(color: Colors.white.withValues(alpha: 0.9), fontSize: 14), - ), - const SizedBox(height: 8), - Text( - currencyFormat.format(wallet.currentBalance), - style: const TextStyle( - color: Colors.white, - fontSize: 32, - fontWeight: FontWeight.w700, - ), - ), - const SizedBox(height: 4), - Text( - wallet.status == 'active' ? 'Compte actif' : wallet.status, - style: TextStyle(color: Colors.white.withValues(alpha: 0.85), fontSize: 13), - ), - ], - ), - ), - ), - const SizedBox(height: 16), - ElevatedButton.icon( - onPressed: () { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Rechargement — à connecter à l\'API')), - ); - }, - icon: const Icon(Icons.add), - label: const Text('Recharger'), - ), - const SizedBox(height: 24), - Text('Historique', style: Theme.of(context).textTheme.titleMedium), - const SizedBox(height: 8), - transactionsAsync.when( - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => Text('Erreur historique : $error'), - data: (transactions) { - if (transactions.isEmpty) { - return const EmptyState( - icon: Icons.receipt_long_outlined, - title: 'Aucune transaction', - subtitle: 'Vos rechargements et débits apparaîtront ici.', - ); - } - - return Column( - children: transactions.map((tx) { - final isCredit = tx.type == 'credit' || tx.type == 'refund'; - final color = isCredit ? AppColors.success : AppColors.error; - - return Card( - margin: const EdgeInsets.only(bottom: 8), - child: ListTile( - leading: CircleAvatar( - backgroundColor: color.withValues(alpha: 0.1), - child: Icon( - isCredit ? Icons.add : Icons.remove, - color: color, - size: 20, - ), - ), - title: Text(tx.type), - subtitle: tx.createdAt != null - ? Text(DateFormat('dd/MM/yyyy HH:mm').format(tx.createdAt!)) - : null, - trailing: Text( - '${isCredit ? '+' : '-'}${currencyFormat.format(tx.amount)}', - style: TextStyle(fontWeight: FontWeight.w600, color: color), - ), - ), - ); - }).toList(), - ); - }, - ), - ], - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/time/server_time.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../data/wallet_repository.dart'; + +/// Écran du portefeuille électronique — solde et historique. +class WalletScreen extends ConsumerWidget { + const WalletScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final walletAsync = ref.watch(walletProvider); + final transactionsAsync = ref.watch(walletTransactionsProvider); + final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return RefreshIndicator( + onRefresh: () async { + ref.invalidate(walletProvider); + ref.invalidate(walletTransactionsProvider); + }, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + walletAsync.when( + loading: () => const SizedBox( + height: 120, + child: Center(child: CircularProgressIndicator()), + ), + error: (error, _) => Text('Erreur solde : $error'), + data: (wallet) => Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + gradient: AppColors.gradientAccent, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: AppColors.primary.withValues(alpha: 0.2), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Solde disponible', + style: TextStyle(color: Colors.white.withValues(alpha: 0.9), fontSize: 14), + ), + const SizedBox(height: 8), + Text( + currencyFormat.format(wallet.currentBalance), + style: const TextStyle( + color: Colors.white, + fontSize: 32, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + wallet.status == 'active' ? 'Compte actif' : wallet.status, + style: TextStyle(color: Colors.white.withValues(alpha: 0.85), fontSize: 13), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: () => context.push(AppRoutes.walletTopUp), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + ), + icon: const Icon(Icons.add), + label: const Text('Recharger'), + ), + const SizedBox(height: 24), + Text('Historique', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + transactionsAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, _) => Text('Erreur historique : $error'), + data: (transactions) { + if (transactions.isEmpty) { + return const EmptyState( + icon: Icons.receipt_long_outlined, + title: 'Aucune transaction', + subtitle: 'Vos rechargements et débits apparaîtront ici.', + ); + } + + return Column( + children: transactions.map((tx) { + final isCredit = tx.type == 'credit' || tx.type == 'refund'; + final color = isCredit ? AppColors.success : AppColors.error; + + return Card( + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + leading: CircleAvatar( + backgroundColor: color.withValues(alpha: 0.1), + child: Icon( + isCredit ? Icons.add : Icons.remove, + color: color, + size: 20, + ), + ), + title: Text(tx.displayLabel), + subtitle: tx.createdAt != null + ? Text( + [ + ServerTime.format(tx.createdAt, pattern: 'dd/MM/yyyy HH:mm'), + if (tx.displaySubtitle != null) tx.displaySubtitle, + ].join(' · '), + ) + : (tx.displaySubtitle != null ? Text(tx.displaySubtitle!) : null), + trailing: Text( + '${isCredit ? '+' : '-'}${currencyFormat.format(tx.amount)}', + style: TextStyle(fontWeight: FontWeight.w600, color: color), + ), + ), + ); + }).toList(), + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/features/wallet/presentation/wallet_top_up_screen.dart b/lib/features/wallet/presentation/wallet_top_up_screen.dart new file mode 100644 index 0000000..0d62f4e --- /dev/null +++ b/lib/features/wallet/presentation/wallet_top_up_screen.dart @@ -0,0 +1,229 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_stripe/flutter_stripe.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +import '../../../core/api/api_response.dart'; +import '../../../core/time/server_time.dart'; +import '../../../core/theme/app_colors.dart'; +import '../data/wallet_repository.dart'; + +const _presetAmounts = [10.0, 20.0, 50.0]; +const _minAmount = 5.0; +const _maxAmount = 150.0; + +/// Écran de rechargement du portefeuille via Stripe Payment Sheet. +class WalletTopUpScreen extends ConsumerStatefulWidget { + const WalletTopUpScreen({super.key}); + + @override + ConsumerState createState() => _WalletTopUpScreenState(); +} + +class _WalletTopUpScreenState extends ConsumerState { + final _amountController = TextEditingController(); + double? _selectedPreset; + bool _isProcessing = false; + + @override + void dispose() { + _amountController.dispose(); + super.dispose(); + } + + double? get _amount { + if (_selectedPreset != null) { + return _selectedPreset; + } + + final raw = _amountController.text.trim().replaceAll(',', '.'); + if (raw.isEmpty) { + return null; + } + + return double.tryParse(raw); + } + + String? _validateAmount(double? amount) { + if (amount == null) { + return 'Saisissez un montant'; + } + if (amount < _minAmount || amount > _maxAmount) { + return 'Montant entre $_minAmount € et $_maxAmount €'; + } + return null; + } + + bool get _canPay => !_isProcessing && _validateAmount(_amount) == null; + + Future _pay() async { + final amount = _amount; + final validationError = _validateAmount(amount); + if (validationError != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(validationError)), + ); + return; + } + + setState(() => _isProcessing = true); + + try { + final idempotencyKey = + 'topup-${ServerTime.now().millisecondsSinceEpoch}'; + final payment = await ref.read(walletRepositoryProvider).initiateTopUp( + amount: amount!, + idempotencyKey: idempotencyKey, + ); + + if (payment.provider == 'stripe') { + final stripe = payment.stripe; + if (stripe == null) { + throw StateError('Réponse Stripe incomplète'); + } + + Stripe.publishableKey = stripe.publishableKey; + await Stripe.instance.applySettings(); + + await Stripe.instance.initPaymentSheet( + paymentSheetParameters: SetupPaymentSheetParameters( + paymentIntentClientSecret: stripe.clientSecret, + merchantDisplayName: 'Laverie Connectée', + ), + ); + + await Stripe.instance.presentPaymentSheet(); + } + + final result = await ref.read(walletRepositoryProvider).confirmTopUp( + paymentUuid: payment.uuid, + ); + + ref.invalidate(walletProvider); + ref.invalidate(walletTransactionsProvider); + + if (!mounted) return; + + final currency = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Rechargement confirmé — nouveau solde : ${currency.format(result.balance)}', + ), + backgroundColor: AppColors.success, + ), + ); + context.pop(); + } on StripeException catch (e) { + if (!mounted) return; + final message = e.error.localizedMessage ?? 'Paiement annulé'; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(message)), + ); + } on DioException catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(ApiResponse.errorMessage(e, fallback: 'Erreur de paiement')), + backgroundColor: AppColors.error, + ), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('$e'), + backgroundColor: AppColors.error, + ), + ); + } finally { + if (mounted) { + setState(() => _isProcessing = false); + } + } + } + + @override + Widget build(BuildContext context) { + final currency = NumberFormat.currency(locale: 'fr_FR', symbol: '€'); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar(title: const Text('Recharger')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Text( + 'Choisissez le montant à ajouter à votre portefeuille.', + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 20), + Wrap( + spacing: 10, + runSpacing: 10, + children: _presetAmounts.map((amount) { + final selected = _selectedPreset == amount; + return ChoiceChip( + label: Text(currency.format(amount)), + selected: selected, + onSelected: _isProcessing + ? null + : (value) { + setState(() { + _selectedPreset = value ? amount : null; + if (value) { + _amountController.clear(); + } + }); + }, + ); + }).toList(), + ), + const SizedBox(height: 24), + Text('Ou saisissez un montant', style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 8), + TextField( + controller: _amountController, + enabled: !_isProcessing, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')), + ], + decoration: InputDecoration( + suffixText: '€', + hintText: 'Ex. 15', + helperText: 'Entre ${currency.format(_minAmount)} et ${currency.format(_maxAmount)}', + border: const OutlineInputBorder(), + ), + onChanged: (_) => setState(() => _selectedPreset = null), + ), + const SizedBox(height: 32), + FilledButton.icon( + onPressed: _canPay ? _pay : null, + icon: _isProcessing + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Icon(Icons.lock_outline), + label: Text(_isProcessing ? 'Paiement en cours…' : 'Payer'), + ), + const SizedBox(height: 16), + Center( + child: Text( + 'Paiement sécurisé par Stripe', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.textSecondary, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/wash/domain/wash_progress.dart b/lib/features/wash/domain/wash_progress.dart index d178b5b..daef636 100644 --- a/lib/features/wash/domain/wash_progress.dart +++ b/lib/features/wash/domain/wash_progress.dart @@ -1,3 +1,5 @@ +import '../../../core/time/server_time.dart'; + /// Progression d'un lavage en cours. class WashProgress { const WashProgress({ @@ -50,7 +52,7 @@ class WashProgress { return const WashProgress(percent: 0, phaseLabel: 'En attente de démarrage', phase: 'pending'); } - final now = DateTime.now(); + final now = ServerTime.now(); final end = estimatedEndAt ?? (startedAt != null && durationMinutes != null ? startedAt.add(Duration(minutes: durationMinutes)) diff --git a/lib/features/wash/presentation/wash_screen.dart b/lib/features/wash/presentation/wash_screen.dart index 30a068c..e94108f 100644 --- a/lib/features/wash/presentation/wash_screen.dart +++ b/lib/features/wash/presentation/wash_screen.dart @@ -9,6 +9,7 @@ import 'package:intl/intl.dart'; import '../../../core/api/api_response.dart'; import '../../../core/router/app_router.dart'; import '../../../core/theme/app_colors.dart'; +import '../../../core/time/server_time.dart'; import '../../../core/widgets/empty_state.dart'; import '../../../core/widgets/screen_header.dart'; import '../data/wash_repository.dart'; @@ -141,7 +142,7 @@ class _HistoryWashTile extends StatelessWidget { ), title: Text(wash.machineName), subtitle: wash.startedAt != null - ? Text(DateFormat('dd/MM/yyyy · HH:mm').format(wash.startedAt!)) + ? Text(ServerTime.format(wash.startedAt, pattern: 'dd/MM/yyyy · HH:mm')) : null, trailing: Text( format.format(wash.cost), diff --git a/lib/main.dart b/lib/main.dart index 2061303..288c7b6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,12 +1,16 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_stripe/flutter_stripe.dart'; +import 'core/config/app_config.dart'; import 'core/platform/app_platform.dart'; +import 'core/time/server_time.dart'; +import 'core/time/server_time_sync.dart'; import 'core/router/app_router.dart'; import 'core/theme/app_theme.dart'; -void main() { +void main() async { WidgetsFlutterBinding.ensureInitialized(); if (!isMobilePlatformSupported) { @@ -15,6 +19,14 @@ void main() { ); } + await ServerTime.initialize(); + await syncServerTimezone(); + + if (kStripePublishableKey.isNotEmpty) { + Stripe.publishableKey = kStripePublishableKey; + await Stripe.instance.applySettings(); + } + runApp(const ProviderScope(child: LaverieApp())); } diff --git a/pubspec.lock b/pubspec.lock index 46ef13a..4ae49e5 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -179,6 +179,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + flutter_stripe: + dependency: "direct main" + description: + name: flutter_stripe + sha256: e6984ab5600546df29ef081795b26bb88d2a6978dbb2e5953f2cb76ac7ab62d2 + url: "https://pub.dev" + source: hosted + version: "13.0.0" flutter_test: dependency: "direct dev" description: flutter @@ -189,6 +197,14 @@ packages: description: flutter source: sdk version: "0.0.0" + freezed_annotation: + dependency: transitive + description: + name: freezed_annotation + sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8" + url: "https://pub.dev" + source: hosted + version: "3.1.0" go_router: dependency: "direct main" description: @@ -205,6 +221,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.2" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" http_parser: dependency: transitive description: @@ -245,6 +269,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" leak_tracker: dependency: transitive description: @@ -482,6 +514,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + stripe_android: + dependency: transitive + description: + name: stripe_android + sha256: "8d14fe209c4a2589786b08cab7cf0620bab23e8604d0285826a49612bc75e305" + url: "https://pub.dev" + source: hosted + version: "13.0.0" + stripe_ios: + dependency: transitive + description: + name: stripe_ios + sha256: "4f270dfa2e82b6653919473c48d4bf8b463efdcf096386b89e0efeb0928e58f4" + url: "https://pub.dev" + source: hosted + version: "13.0.0" + stripe_platform_interface: + dependency: transitive + description: + name: stripe_platform_interface + sha256: a0bac657a075aacccbd97368bfc1c57b742f28e5811734e3df09bff891c2d514 + url: "https://pub.dev" + source: hosted + version: "13.0.0" term_glyph: dependency: transitive description: @@ -498,6 +554,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.11" + timezone: + dependency: "direct main" + description: + name: timezone + sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb" + url: "https://pub.dev" + source: hosted + version: "0.11.1" typed_data: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index d2adcfd..544eccf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -20,6 +20,8 @@ dependencies: mobile_scanner: ^5.2.3 flutter_secure_storage: ^9.2.4 intl: ^0.20.2 + flutter_stripe: ^13.0.0 + timezone: ^0.11.1 dev_dependencies: flutter_test: From ffa463baf1d6f2f6b4a4ac8575a225034489609a Mon Sep 17 00:00:00 2001 From: bastien Date: Sat, 4 Jul 2026 22:48:14 +0200 Subject: [PATCH 4/7] Ajout documentation --- documentation/CDC_App_Flutter.md | 447 ++++++++++++++++++++++++++++ documentation/CDC_App_Flutter_v2.md | 430 ++++++++++++++++++++++++++ 2 files changed, 877 insertions(+) create mode 100644 documentation/CDC_App_Flutter.md create mode 100644 documentation/CDC_App_Flutter_v2.md diff --git a/documentation/CDC_App_Flutter.md b/documentation/CDC_App_Flutter.md new file mode 100644 index 0000000..c168002 --- /dev/null +++ b/documentation/CDC_App_Flutter.md @@ -0,0 +1,447 @@ +# Cahier des Charges — Application Utilisateur Mobile & Web +## Projet : Laverie Connectée — App Flutter +**Version :** 1.0 +**Date :** 2026-06-27 +**Stack principale :** Flutter 3.x (Android / iOS / Web) + +--- + +## 1. Contexte & Objectifs + +### 1.1 Contexte +Application grand public permettant aux utilisateurs de : +- Localiser les laveries disponibles +- Gérer leur porte-monnaie électronique +- Réserver un créneau machine +- Déclencher un lavage par QR code +- Suivre leurs lavages et consulter leur historique + +### 1.2 Cibles plateformes +| Plateforme | Version minimale | Distribution | +|------------|-----------------|--------------| +| Android | 8.0 (API 26) | Google Play Store | +| iOS | 15.0 | Apple App Store | +| Web | Chrome 100+, Safari 15+, Firefox 100+ | PWA hébergée | + +### 1.3 Contraintes +- L'app doit rester **utilisable hors-ligne** pour les fonctions de consultation (solde en cache, historique) +- Respect strict du **RGPD** : collecte minimale, consentements explicites, droit à l'effacement +- L'application doit rester **connectée en arrière-plan** pour recevoir les notifications push + +--- + +## 2. Stack Technique + +| Composant | Technologie | Version | Justification | +|-----------|-------------|---------|---------------| +| Framework UI | Flutter | 3.x (stable) | Codebase unique Android/iOS/Web | +| Langage | Dart | 3.x | Null-safety, typage fort | +| State management | Riverpod | 2.x | Réactivité, testabilité, pas de BuildContext dependency | +| Navigation | GoRouter | 13.x | Deep links, routing déclaratif | +| HTTP Client | Dio | 5.x | Intercepteurs JWT, retry automatique | +| Cache local | Hive | 2.x | Clé-valeur rapide, offline-first | +| Auth persistence | flutter_secure_storage | 9.x | Stockage sécurisé tokens (Keychain / Keystore) | +| Notifications push | firebase_messaging | 15.x | FCM Android/Web + APNs iOS | +| QR Code scan | mobile_scanner | 5.x | Caméra native, performant | +| Paiement in-app | flutter_stripe | 10.x | Stripe SDK officiel | +| Géolocalisation | geolocator | 13.x | Localisation établissements | +| Cartes | flutter_map + OpenStreetMap | — | Affichage carte sans coût API Google | +| Internationalisation | flutter_localizations | (Flutter) | fr / en au minimum | +| Tests | flutter_test + Mockito | — | Unit + widget + integration tests | +| CI/CD | GitHub Actions + Fastlane | — | Build, test, déploiement stores | +| Monitoring | Firebase Crashlytics | — | Crashes prod | +| Analytics | Firebase Analytics | — | Entonnoirs, rétention | + +--- + +## 3. Architecture de l'Application + +### 3.1 Pattern architectural : Clean Architecture + Feature-first + +``` +lib/ +├── core/ +│ ├── api/ +│ │ ├── api_client.dart # Instance Dio configurée +│ │ ├── interceptors/ +│ │ │ ├── auth_interceptor.dart # Injection Bearer token +│ │ │ └── retry_interceptor.dart # Retry sur 401 avec refresh +│ │ └── api_exception.dart +│ ├── cache/ +│ │ └── hive_service.dart # Abstraction cache local +│ ├── router/ +│ │ └── app_router.dart # GoRouter centralisé +│ ├── theme/ +│ │ ├── app_theme.dart +│ │ └── app_colors.dart +│ └── utils/ +│ ├── currency_formatter.dart +│ └── date_formatter.dart +│ +├── features/ +│ ├── auth/ +│ │ ├── data/ +│ │ │ ├── auth_repository.dart +│ │ │ └── models/auth_token.dart +│ │ ├── domain/ +│ │ │ └── providers/auth_provider.dart +│ │ └── presentation/ +│ │ ├── login_screen.dart +│ │ └── register_screen.dart +│ │ +│ ├── wallet/ +│ │ ├── data/ +│ │ ├── domain/ +│ │ └── presentation/ +│ │ ├── wallet_screen.dart +│ │ ├── transaction_history_screen.dart +│ │ └── top_up_screen.dart +│ │ +│ ├── establishments/ +│ │ ├── data/ +│ │ ├── domain/ +│ │ └── presentation/ +│ │ ├── map_screen.dart +│ │ ├── establishment_list_screen.dart +│ │ └── establishment_detail_screen.dart +│ │ +│ ├── machines/ +│ │ ├── data/ +│ │ ├── domain/ +│ │ └── presentation/ +│ │ ├── machine_card_widget.dart +│ │ └── machine_detail_screen.dart +│ │ +│ ├── booking/ +│ │ ├── data/ +│ │ ├── domain/ +│ │ └── presentation/ +│ │ ├── slot_picker_screen.dart +│ │ ├── booking_confirm_screen.dart +│ │ └── my_bookings_screen.dart +│ │ +│ ├── wash/ +│ │ ├── data/ +│ │ ├── domain/ +│ │ └── presentation/ +│ │ ├── qr_scanner_screen.dart +│ │ ├── wash_confirm_screen.dart +│ │ └── wash_active_screen.dart +│ │ +│ ├── notifications/ +│ │ └── notification_service.dart +│ │ +│ └── profile/ +│ └── presentation/ +│ ├── profile_screen.dart +│ └── gdpr_settings_screen.dart +│ +└── main.dart +``` + +### 3.2 Flux d'authentification + +``` +App start + └── AuthProvider.check() + ├── Token valide → HomeScreen + ├── Token expiré → RefreshToken() + │ ├── Succès → HomeScreen + │ └── Échec → LoginScreen + └── Pas de token → OnboardingScreen +``` + +### 3.3 Gestion du token JWT + +- `AuthInterceptor` (Dio) : inject `Authorization: Bearer ` sur chaque requête +- Sur 401 : appel automatique à `/auth/refresh` → retry de la requête originale +- Tokens stockés dans `flutter_secure_storage` (Keychain iOS / Keystore Android) +- Sur Web : stockage en `sessionStorage` chiffré (pas de `localStorage` pour les tokens) + +--- + +## 4. Écrans & Parcours Utilisateur + +### 4.1 Navigation principale (Bottom Navigation Bar) + +``` +┌─────────────────────────────────────────────┐ +│ 🗺 Carte │ 💰 Wallet │ 📅 Réservations │ 👤 Profil │ +└─────────────────────────────────────────────┘ +``` + +### 4.2 Onboarding & Inscription + +**Écran 1 — Bienvenue** +- Logo + baseline +- CTA : "Se connecter" / "Créer un compte" + +**Écran 2 — Inscription (multi-étapes)** +- Étape 1 : Email + mot de passe (+ confirmation) +- Étape 2 : Prénom, nom, téléphone, date de naissance +- Étape 3 : Consentements RGPD (cases à cocher individuelles, non pré-cochées) + - Traitement des données (obligatoire) + - Communications marketing (optionnel) + - Analyse d'utilisation (optionnel) +- Étape 4 : Code parrainage (optionnel) +- Confirmation email requise avant accès complet + +**Règles de validation :** +- Email : format RFC 5322 +- Mot de passe : 8 caractères minimum, 1 majuscule, 1 chiffre +- Téléphone : format E.164 (`+33XXXXXXXXX`) +- Date de naissance : 16 ans minimum + +### 4.3 Carte & Établissements + +**Écran Carte (`MapScreen`)** +- Carte OpenStreetMap centrée sur la position utilisateur +- Marqueurs pour chaque établissement (couleur selon disponibilité) + - 🟢 Machines disponibles + - 🟡 Toutes occupées, créneaux libres + - 🔴 Toutes occupées, aucun créneau proche +- Tap sur marqueur → sheet inférieure avec résumé +- Bouton liste (switch vue liste / carte) + +**Écran Détail Établissement** +- Nom, adresse, horaires +- Liste des machines avec statut temps réel (polling 30s ou WebSocket si dispo) +- Pour chaque machine : type, statut, prochain créneau libre, tarif actuel +- CTA : "Réserver" ou "Scanner & Lancer" + +### 4.4 Porte-monnaie + +**Écran Wallet** +- Solde affiché en grand (avec animation de mise à jour) +- Bouton "Recharger" bien visible +- Historique des 10 dernières transactions +- Lien "Voir tout" + +**Écran Historique** +- Liste paginée (infinite scroll) +- Filtres : Type (débit/crédit), Période +- Chaque entrée : icône type, montant coloré, source, date/heure, solde après +- Export CSV (optionnel, v2) + +**Parcours Rechargement** +1. Saisie du montant (suggestions : 10€, 20€, 50€) +2. Sélection du fournisseur de paiement (si plusieurs disponibles) +3. Redirection vers Stripe Checkout (WebView sécurisée) ou SDK natif +4. Retour sur l'app via deep link `laverie://wallet/topup-result` +5. Confirmation animée + mise à jour du solde +6. Notification push de confirmation + +**Contraintes :** +- Montant minimum : 5€, maximum : 150€ par rechargement +- Affichage du solde en cache si hors-ligne + +### 4.5 Réservation d'un Créneau + +**Écran Sélection de Créneau (`SlotPickerScreen`)** +- Sélecteur de date (calendrier scrollable, 14 jours maximum) +- Pour la date sélectionnée : grille horaire avec créneaux libres/occupés +- Mise en évidence du prix par créneau (heure creuse / heure pleine) +- Information : "Supplément réservation : +1.00€" + +**Écran Confirmation Réservation** +- Récapitulatif : machine, date/heure, durée, prix total +- Solde actuel et solde après débit +- Mention pénalité no-show +- Bouton "Confirmer et débiter X.XX€" + +**Écran Mes Réservations** +- Onglets : À venir / Passées +- Chaque réservation : statut badge, machine, créneau, montant +- Actions possibles : "Annuler", "Déplacer" (si > 2h) +- Countdown pour les réservations imminentes + +**Règles métier UI :** +- Créneau non réservable si solde insuffisant → CTA "Recharger d'abord" +- Annulation : popup de confirmation avec montant remboursé affiché +- Déplacement : ouvre SlotPickerScreen avec le même contexte machine + +### 4.6 Déclenchement d'un Lavage par QR Code + +**Écran Scanner QR (`QrScannerScreen`)** +- Vue caméra plein écran avec cadre de scan +- Feedback visuel à la détection (vibration + flash vert) +- Fallback : saisie manuelle du code machine + +**Flux post-scan :** +1. Identification de la machine via le QR +2. Appel API → vérification statut + tarif +3. Affichage récap : machine, programme, prix estimé, solde après +4. Bouton "Lancer le lavage" +5. Animation de confirmation (spinner → ✓) +6. Écran "Lavage en cours" avec countdown + +**Écran Lavage Actif (`WashActiveScreen`)** +- Machine + établissement +- Barre de progression avec temps restant (mise à jour polling API 30s) +- Montant débité +- Notification push à la fin du cycle + +### 4.7 Notifications Push + +**Configuration :** +- Demande de permission notifications à l'inscription (après onboarding) +- Sur iOS : `UNUserNotificationCenter.requestAuthorization` +- Sur Android 13+ : `POST_NOTIFICATIONS` permission +- Token FCM/APNs envoyé à l'API à chaque démarrage de l'app (mise à jour si changé) + +**Gestion en foreground :** +- Affichage d'une bannière in-app (snackbar stylisée) +- Tap → navigation vers l'écran pertinent + +**Deep links depuis notification :** +| Notification | Deep link | +|---|---| +| Rechargement confirmé | `laverie://wallet` | +| Réservation confirmée | `laverie://bookings/{uuid}` | +| Rappel créneau | `laverie://bookings/{uuid}` | +| Lavage terminé | `laverie://washes/{uuid}` | +| Promo disponible | `laverie://establishments/{uuid}` | + +### 4.8 Profil & Paramètres + +**Écran Profil** +- Informations personnelles (modifiables) +- Mes statistiques : nombre de lavages, total dépensé, économies promos +- Code parrainage personnel (copiable, partageable) +- Gestion notifications (toggle par type) +- Paramètres RGPD +- Déconnexion + +**Écran Paramètres RGPD** +- Visualisation des consentements donnés (avec date) +- Toggle individuel pour chaque consentement +- Bouton "Télécharger mes données" (export JSON, v2) +- Bouton "Supprimer mon compte" (confirmation en deux étapes + délai 30 jours) + +--- + +## 5. Gestion de l'État (Riverpod) + +### 5.1 Providers principaux + +```dart +// Auth +final authProvider = StateNotifierProvider + +// Wallet +final walletProvider = FutureProvider +final transactionsProvider = StateNotifierProvider + +// Establishments +final establishmentsProvider = FutureProvider.family // by uuid +final nearbyEstablishmentsProvider = FutureProvider> + +// Machines +final machineStatusProvider = StreamProvider.family // polling 30s + +// Bookings +final bookingsProvider = StateNotifierProvider +final slotAvailabilityProvider = FutureProvider.family, SlotQuery> + +// Active wash +final activeWashProvider = StreamProvider // null si aucun lavage en cours +``` + +### 5.2 Stratégie offline-first (Hive) + +| Donnée | Cache | TTL | +|--------|-------|-----| +| Solde wallet | Oui | Jusqu'au prochain refresh | +| Historique transactions | Oui (50 dernières) | 24h | +| Établissements (liste) | Oui | 1h | +| Disponibilités machines | Non | — | +| Réservations | Oui | 30 min | + +En cas d'absence de réseau : affichage des données en cache avec badge "Données hors-ligne". + +--- + +## 6. Sécurité + +### 6.1 Stockage +- Tokens JWT : `flutter_secure_storage` (AES-256 sur Android, Keychain sur iOS) +- Aucune donnée sensible dans `SharedPreferences` +- Sur Web : pas de localStorage, session uniquement + +### 6.2 Réseau +- Certificate pinning en production (via `dio` custom `HttpClient`) +- Timeout : 10s connexion, 30s réception +- Toutes les requêtes en HTTPS (TLS 1.3) + +### 6.3 QR Code +- Vérification côté serveur (le QR code seul ne suffit pas à déclencher un lavage) +- Rate limiting API sur `/washes/start` : 3 req/min/user + +--- + +## 7. Performance & UX + +- **Splash screen** natif (Android 12 Splash API, iOS UILaunchScreen) +- **Skeleton loaders** sur toutes les listes et cartes pendant le chargement +- **Optimistic UI** : affichage anticipé des mises à jour (ex: annulation réservation) +- **Pull-to-refresh** sur toutes les listes +- **Pagination infinie** sur l'historique des transactions +- **Animations** : transitions de pages fluides (Hero, Fade), animation solde wallet + +--- + +## 8. Tests + +| Type | Outil | Portée | +|------|-------|--------| +| Tests unitaires | `flutter_test` | Providers Riverpod, formatters, validators | +| Tests widgets | `flutter_test` | Tous les écrans principaux | +| Tests d'intégration | `integration_test` | Parcours critiques (inscription, rechargement, scan QR) | +| Tests golden | `golden_toolkit` | Composants UI clés (cohérence visuelle) | + +**Parcours critiques à couvrir en intégration :** +1. Inscription complète → vérification email → connexion +2. Rechargement porte-monnaie (mock Stripe) +3. Réservation créneau → annulation → vérification remboursement +4. Scan QR → lancement lavage → fin de cycle + +--- + +## 9. CI/CD + +### 9.1 Pipeline GitHub Actions + +```yaml +# Sur chaque PR : +- flutter analyze # Linting strict +- flutter test # Tests unitaires + widgets +- flutter build apk --release # Vérification build Android +- flutter build ios --release # Vérification build iOS (macOS runner) +- flutter build web # Vérification build Web + +# Sur merge main : +- Fastlane → TestFlight (iOS) +- Fastlane → Play Store Internal Track (Android) +- Deploy Web → hébergement (Firebase Hosting ou VPS) +``` + +### 9.2 Flavors + +| Flavor | API URL | Firebase projet | Build suffix | +|--------|---------|-----------------|--------------| +| dev | `http://localhost:8000` | laverie-dev | `.dev` | +| staging | `https://api-staging.laverie.app` | laverie-staging | `.staging` | +| production | `https://api.laverie.app` | laverie-prod | — | + +--- + +## 10. Livrables attendus + +- [ ] Code source Flutter (GitHub, repository dédié) +- [ ] Flavors configurés (dev / staging / prod) +- [ ] `README.md` avec instructions setup complet +- [ ] Fichiers de configuration Firebase (`google-services.json`, `GoogleService-Info.plist`) +- [ ] Fichiers de signature Android (`.keystore`) documentés +- [ ] Screenshots pour les stores (5 par plateforme minimum) +- [ ] Suite de tests (couverture > 70% sur la logique métier) +- [ ] Build release Android (`.aab`) + iOS (`.ipa`) prêts à soumettre diff --git a/documentation/CDC_App_Flutter_v2.md b/documentation/CDC_App_Flutter_v2.md new file mode 100644 index 0000000..2eced5a --- /dev/null +++ b/documentation/CDC_App_Flutter_v2.md @@ -0,0 +1,430 @@ +# Cahier des Charges — Application Utilisateur Mobile & Web +## Projet : Laverie Connectée — App Flutter +**Version :** 2.0 +**Stack principale :** Flutter 3.x (Android / iOS / Web) +**Positionnement :** V1 démontrable, centrée sur les parcours critiques + +--- + +## 1. Contexte & Objectifs + +### 1.1 Objectif produit +Application grand public permettant aux utilisateurs de : +- localiser les laveries disponibles, +- consulter l'état des machines, +- recharger leur porte-monnaie, +- réserver un créneau, +- lancer un lavage, +- suivre l'historique de leurs opérations. + +### 1.2 Objectif projet V1 +La V1 doit être : +- démontrable rapidement, +- cohérente côté métier, +- simple à maintenir, +- compatible avec une future montée en version sans refonte majeure. + +### 1.3 Contraintes +- support Android / iOS en priorité, +- support Web utilitaire possible, sans promesse d'expérience équivalente à une app web dédiée, +- mode hors-ligne limité aux consultations simples, +- conformité RGPD minimale dès la V1, +- intégration machine pouvant être simulée pour la démo. + +--- + +## 2. Périmètre fonctionnel + +### 2.1 MVP V1 +- inscription / connexion, +- maintien de session, +- liste des laveries, +- détail d'une laverie, +- consultation des machines et de leur statut, +- wallet avec solde et historique simple, +- rechargement wallet, +- réservation d'un créneau, +- affichage des réservations, +- lancement d'un lavage, +- écran de lavage en cours, +- notifications transactionnelles, +- profil utilisateur, +- gestion simple des consentements. + +### 2.2 V2 prévue +- fidélité, +- parrainage, +- abonnements, +- promotions marketing avancées, +- export de données, +- statistiques utilisateur plus poussées, +- expérience offline enrichie, +- recommandations de cycles. + +### 2.3 Hors périmètre V1 +- chat, +- avis, +- FAQ dynamique, +- IA / photo d'étiquette, +- moteur prédictif, +- marketing automation complexe. + +--- + +## 3. Stack Technique + +| Composant | Technologie | Version | Commentaire | +|-----------|-------------|---------|-------------| +| Framework UI | Flutter | 3.x | Base unique mobile + web | +| Langage | Dart | 3.x | Null-safety | +| State management | Riverpod | 2.x | Testable, clair | +| Navigation | GoRouter | 13.x | Routing déclaratif | +| HTTP | Dio | 5.x | Intercepteurs auth | +| Stockage sécurisé | flutter_secure_storage | 9.x | Tokens | +| Cache local | Hive | 2.x | Suffisant pour V1 | +| Push | firebase_messaging | 15.x | Android / iOS / Web | +| QR scan | mobile_scanner | 5.x | Scan machine | +| Paiement | flutter_stripe | 10.x | Si Stripe retenu en V1 | +| Géolocalisation | geolocator | 13.x | Recherche proximité | +| Cartographie | flutter_map + OSM | — | Coût faible | +| Crash reporting | Firebase Crashlytics | — | Monitoring mobile | +| Tests | flutter_test + integration_test | — | Couverture critique | + +### 3.1 Remarque Web +Le support Flutter Web est accepté comme **surface utilitaire** pour V1. Il ne doit pas être présenté comme un site web marketing riche ou fortement orienté SEO. + +--- + +## 4. Architecture applicative + +### 4.1 Organisation recommandée + +``` +lib/ +├── core/ +│ ├── api/ +│ ├── auth/ +│ ├── cache/ +│ ├── router/ +│ ├── theme/ +│ └── utils/ +├── features/ +│ ├── auth/ +│ ├── establishments/ +│ ├── machines/ +│ ├── wallet/ +│ ├── booking/ +│ ├── wash/ +│ ├── notifications/ +│ └── profile/ +└── main.dart +``` + +### 4.2 Principes +- séparation claire data / state / presentation, +- providers Riverpod par domaine, +- toute logique réseau centralisée, +- aucune règle métier critique uniquement côté client, +- compatibilité avec un mode démonstration si l'intégration machine n'est pas prête. + +--- + +## 5. Authentification + +### 5.1 Flux attendu +```text +Lancement app +→ lecture des tokens +→ si access token valide : accès direct +→ sinon tentative refresh +→ sinon retour login +``` + +### 5.2 Règles +- access token court, +- refresh token persistant, +- déconnexion complète si refresh invalide, +- aucun stockage de token sensible dans SharedPreferences. + +### 5.3 Web +Sur Web, éviter `localStorage` pour les tokens. Si le backend le permet, privilégier une stratégie plus sûre à long terme. Pour V1, une stratégie simple et limitée peut être tolérée, mais elle doit être documentée comme compromis technique. + +--- + +## 6. Parcours utilisateur V1 + +## 6.1 Onboarding / inscription + +### Écrans +- Bienvenue +- Connexion +- Inscription +- Vérification email si activée en V1 + +### Champs d'inscription +- prénom +- nom +- email +- téléphone +- mot de passe +- date de naissance +- consentements RGPD + +### Règles +- consentement traitement données obligatoire, +- consentements marketing et analytics séparés, +- validations simples mais strictes. + +--- + +## 6.2 Laveries et machines + +### Écran liste / carte +- liste des établissements, +- carte facultative si le délai est tendu, +- indicateur de disponibilité globale. + +### Écran détail établissement +- nom, adresse, horaires, +- liste des machines, +- statut de chaque machine, +- prochain créneau disponible, +- CTA réservation, +- CTA lancement lavage. + +### Statuts V1 affichés +- disponible, +- réservée, +- en cours, +- maintenance, +- hors ligne, +- erreur. + +--- + +## 6.3 Wallet + +### Écran wallet +- solde actuel, +- bouton recharger, +- dernières transactions, +- message si données en cache. + +### Historique +- liste simple paginée, +- type, +- montant, +- date, +- libellé métier. + +### Rechargement V1 +Parcours recommandé : +1. saisie montant, +2. lancement du paiement, +3. retour app, +4. confirmation backend, +5. mise à jour solde. + +### Contraintes V1 +- montant min et max configurables, +- aucune confiance dans le seul retour client, +- affichage clair des états : en cours / confirmé / échoué. + +--- + +## 6.4 Réservation + +### Écran sélection de créneau +- choix date, +- créneaux disponibles, +- prix total, +- supplément réservation si applicable, +- indication pénalité no-show. + +### Écran confirmation +- récapitulatif machine, +- créneau, +- prix, +- solde avant / après, +- bouton de confirmation. + +### Écran mes réservations +- onglets à venir / passées, +- statut, +- actions : annuler, déplacer si autorisé. + +### Règles UI +- si solde insuffisant, proposer rechargement, +- si réservation non déplaçable, expliquer pourquoi, +- afficher clairement les règles d'annulation. + +--- + +## 6.5 Lavage + +### Démarrage +Deux modes possibles selon intégration : +- scan QR, +- démarrage depuis une réservation active. + +### Flux V1 +1. identification machine, +2. vérification disponibilité, +3. affichage prix / programme si nécessaire, +4. confirmation utilisateur, +5. demande de démarrage, +6. affichage de l'état `en cours`. + +### Écran lavage actif +- machine, +- laverie, +- heure de début, +- temps estimé restant si disponible, +- statut actualisé. + +### Mode démo +Si aucune vraie intégration machine n'est disponible, un mode simulation doit permettre d'afficher un cycle complet crédible. + +--- + +## 6.6 Notifications + +### Notifications V1 +- rechargement confirmé, +- réservation confirmée, +- rappel de créneau, +- lavage terminé, +- no-show détecté si applicable. + +### Deep links +Les notifications doivent pouvoir ouvrir l'écran concerné : +- wallet, +- réservation, +- lavage, +- établissement. + +--- + +## 6.7 Profil + +### Écran profil +- informations personnelles, +- préférences de notification, +- consentements, +- déconnexion, +- suppression de compte si disponible en V1, sinon message préparant la V2. + +--- + +## 7. Gestion d'état + +### Providers principaux +```dart +final authProvider = StateNotifierProvider(...); +final establishmentsProvider = FutureProvider>(...); +final establishmentDetailProvider = FutureProvider.family(...); +final walletProvider = FutureProvider(...); +final bookingsProvider = StateNotifierProvider(...); +final washProvider = StateNotifierProvider(...); +``` + +### Stratégie V1 +- refresh manuel sur les écrans critiques, +- polling simple si nécessaire pour le lavage actif, +- éviter une architecture temps réel trop complexe pour la V1 si elle met en risque le planning. + +--- + +## 8. Offline-first + +### Ce qui est caché localement en V1 +| Donnée | Cache | +|---|---| +| Solde wallet | Oui | +| Dernières transactions | Oui | +| Liste établissements | Oui | +| Réservations récentes | Oui | +| Disponibilité machine temps réel | Non | + +### Règle +Le hors-ligne V1 est **consultatif**, pas transactionnel. + +--- + +## 9. Sécurité + +### 9.1 Stockage +- tokens en stockage sécurisé, +- aucune donnée sensible en clair, +- purge des tokens en déconnexion. + +### 9.2 Réseau +- HTTPS obligatoire, +- timeouts définis, +- retry mesuré, +- certificate pinning seulement si tu es sûr de pouvoir l'opérer correctement, sinon à repousser plutôt que mal implémenter. + +### 9.3 QR code +- le QR seul ne déclenche jamais directement un lavage, +- validation serveur obligatoire, +- contrôle de cohérence utilisateur / machine / statut. + +--- + +## 10. UX / performance + +### Priorités V1 +- écrans rapides, +- états de chargement propres, +- erreurs compréhensibles, +- navigation simple, +- pas d'animations complexes non essentielles. + +### À éviter en V1 si délai serré +- sur-optimisation visuelle, +- offline avancé, +- temps réel sophistiqué, +- effets UI coûteux sans valeur métier. + +--- + +## 11. Mode démonstration + +L'application doit pouvoir être connectée à un environnement de démonstration permettant : +- données multi-laveries fictives, +- wallet de test, +- réservations simulées, +- cycles machine simulés, +- notifications de test. + +Ce mode doit être suffisamment crédible pour une démonstration client de fin de mois. + +--- + +## 12. Tests + +| Type | Outil | Portée | +|------|-------|--------| +| Unitaires | flutter_test | Providers, validateurs, formatters | +| Widgets | flutter_test | Écrans clés | +| Intégration | integration_test | Connexion, wallet, réservation, lavage | + +### Parcours critiques à couvrir +1. connexion utilisateur, +2. affichage des laveries, +3. rechargement wallet, +4. réservation d'un créneau, +5. démarrage d'un lavage en mode simulation, +6. réception d'une notification. + +--- + +## 13. Livrables attendus + +- code source Flutter, +- configuration dev / staging / prod, +- README d'installation, +- configuration push, +- build de démonstration, +- dataset ou compte de démo, +- couverture de tests sur les flux critiques. From 1c13103c01acab4ed35102bce296fbba709acac6 Mon Sep 17 00:00:00 2001 From: bastien Date: Sat, 4 Jul 2026 22:55:52 +0200 Subject: [PATCH 5/7] Jenkins file --- Jenkinsfile | 1 + 1 file changed, 1 insertion(+) create mode 100644 Jenkinsfile diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..522ad46 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1 @@ +flutterAndroidPipeline(name: 'laundry', api: '36') From a4c44236785850b9e0edb8adcc27fa29ce24c16e Mon Sep 17 00:00:00 2001 From: bastien Date: Sun, 5 Jul 2026 00:01:55 +0200 Subject: [PATCH 6/7] maj tests --- lib/core/auth/auth_provider.dart | 2 +- lib/core/widgets/machine_widgets.dart | 2 +- .../home/presentation/home_screen.dart | 2 +- .../widgets/active_wash_progress_card.dart | 2 +- test/widget_test.dart | 29 +++++-------------- 5 files changed, 11 insertions(+), 26 deletions(-) diff --git a/lib/core/auth/auth_provider.dart b/lib/core/auth/auth_provider.dart index 4d3546a..263c654 100644 --- a/lib/core/auth/auth_provider.dart +++ b/lib/core/auth/auth_provider.dart @@ -171,7 +171,7 @@ class AuthNotifier extends StateNotifier { } final authRepositoryProvider = Provider((ref) { - final storage = laverieSecureStorage; + const storage = laverieSecureStorage; // Token lu depuis le stockage sécurisé (évite la dépendance circulaire avec authProvider). return AuthRepository( diff --git a/lib/core/widgets/machine_widgets.dart b/lib/core/widgets/machine_widgets.dart index 2a73fd8..dee9a42 100644 --- a/lib/core/widgets/machine_widgets.dart +++ b/lib/core/widgets/machine_widgets.dart @@ -12,7 +12,7 @@ class MachineStatusLegend extends StatelessWidget { @override Widget build(BuildContext context) { - return Wrap( + return const Wrap( spacing: 12, runSpacing: 6, children: [ diff --git a/lib/features/home/presentation/home_screen.dart b/lib/features/home/presentation/home_screen.dart index e2aec53..b5ecb8d 100644 --- a/lib/features/home/presentation/home_screen.dart +++ b/lib/features/home/presentation/home_screen.dart @@ -155,7 +155,7 @@ class _EstablishmentCard extends StatelessWidget { children: [ Icon(Icons.grid_view_rounded, size: 14, color: AppColors.primary.withValues(alpha: 0.8)), const SizedBox(width: 4), - Text( + const Text( 'Voir les machines', style: TextStyle( color: AppColors.primary, diff --git a/lib/features/wash/presentation/widgets/active_wash_progress_card.dart b/lib/features/wash/presentation/widgets/active_wash_progress_card.dart index df5dd34..c39373a 100644 --- a/lib/features/wash/presentation/widgets/active_wash_progress_card.dart +++ b/lib/features/wash/presentation/widgets/active_wash_progress_card.dart @@ -51,7 +51,7 @@ class ActiveWashProgressCard extends StatelessWidget { Text(wash.machineName, style: Theme.of(context).textTheme.titleMedium), Text( p.phaseLabel, - style: TextStyle( + style: const TextStyle( color: AppColors.machineRunning, fontWeight: FontWeight.w600, fontSize: 13, diff --git a/test/widget_test.dart b/test/widget_test.dart index f9495fe..9421e23 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,30 +1,15 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:laverie_mobile/main.dart'; +import 'package:laverie_mobile/features/auth/presentation/splash_screen.dart'; void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); + testWidgets('SplashScreen affiche le titre de l\'application', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: SplashScreen()), + ); - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + expect(find.text('Laverie Connectée'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); }); } From 844cd2c8c9dc3c764a8478a875fc2017a8a231e3 Mon Sep 17 00:00:00 2001 From: bastien Date: Sun, 5 Jul 2026 00:42:40 +0200 Subject: [PATCH 7/7] version 0.0.1 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 544eccf..5e3ca22 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: > Application mobile native Laverie Connectée (Android + iOS). Pas de cible web Flutter — Android en priorité, iOS préparé. publish_to: 'none' -version: 1.0.0+1 +version: 0.0.1 environment: sdk: '>=3.2.0 <4.0.0'