commit 46558a5ec842eea07b49f2695b2e62217993a298 Author: Abderrahim-Mouhcine Date: Sun Aug 16 19:59:55 2026 +0100 Initial upload: fin65-mobile diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..da47f56 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# 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: "924134a44c189315be2148659913dda1671cbe99" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: android + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: ios + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: linux + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: macos + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: web + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + - platform: windows + create_revision: 924134a44c189315be2148659913dda1671cbe99 + base_revision: 924134a44c189315be2148659913dda1671cbe99 + + # 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 new file mode 100644 index 0000000..9ca8e16 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# fin65_mobile + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/README_ICON_PATCH.md b/README_ICON_PATCH.md new file mode 100644 index 0000000..5df3bbf --- /dev/null +++ b/README_ICON_PATCH.md @@ -0,0 +1,43 @@ +# FIN65 - Patch icône Android + +Ce patch remplace l’icône de l’application mobile Flutter FIN65. + +## Fichiers inclus + +```text +assets/icon/app_icon.png +assets/icon/adaptive_foreground.png +flutter_launcher_icons.yaml +apply_fin65_android_icon.bat +remove_icon_config_only.bat +``` + +## Installation + +1. Décompresse ce dossier. +2. Lance : + +```powershell +.\apply_fin65_android_icon.bat +``` + +Le script va : +- copier les images dans `D:\07-Logiciels\20-FIN65\fin65_mobile\assets\icon` +- ajouter `flutter_launcher_icons` en dépendance de développement +- générer les icônes Android natives +- lancer `flutter clean` et `flutter pub get` + +## Après application + +Relance l’application : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +Si l'ancienne icône reste visible sur le téléphone : +- désinstalle l'app FIN65 du téléphone ; +- relance `flutter run`. + +Android garde parfois l’icône en cache, parce que même les pixels ont maintenant de l’inertie administrative. diff --git a/README_MOBILE_DASHBOARD_COLORS_V2_7_1.md b/README_MOBILE_DASHBOARD_COLORS_V2_7_1.md new file mode 100644 index 0000000..bd25233 --- /dev/null +++ b/README_MOBILE_DASHBOARD_COLORS_V2_7_1.md @@ -0,0 +1,45 @@ +# FIN65 Mobile - Dashboard couleurs V2.7.1 + +Ce patch ajoute des couleurs aux rubriques du dashboard mobile. + +## Couleurs ajoutées + +- Disponible réel : vert +- Balance prévisionnelle : bleu +- Solde total : violet +- Balance réelle : vert si positif, rouge si négatif +- Revenus réels : vert +- Dépenses réelles : rouge +- Dépenses échéancier : orange +- Transferts prévus : bleu +- Provisions prévues : violet + +## Installation + +Décompresse le ZIP, puis lance : + +```powershell +.\apply_mobile_dashboard_colors_v2_7_1.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Rollback + +Le script sauvegarde les anciens fichiers ici : + +```text +D:\07-Logiciels\20-FIN65\fin65_mobile\backup_before_mobile_dashboard_colors_v271 +``` + +Fichiers sauvegardés : + +```text +dashboard.dart.bak +home_screen.dart.bak +``` diff --git a/README_MOBILE_DASHBOARD_COLORS_V2_7_2_FIX.md b/README_MOBILE_DASHBOARD_COLORS_V2_7_2_FIX.md new file mode 100644 index 0000000..3272b12 --- /dev/null +++ b/README_MOBILE_DASHBOARD_COLORS_V2_7_2_FIX.md @@ -0,0 +1,36 @@ +# FIN65 Mobile - Dashboard couleurs V2.7.2 FIX + +Corrige l'erreur : + +```text +'_MetricCard' is already declared in this scope +``` + +## Cause + +Le patch V2.7.1 a laissé deux déclarations de `_MetricCard` dans `home_screen.dart`. Oui, Flutter n'aime pas qu'on lui présente deux jumeaux avec le même passeport. + +## Installation + +Décompresse ce ZIP, puis lance : + +```powershell +.\apply_mobile_dashboard_colors_v2_7_2_fix.bat +``` + +Puis : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Contrôle + +Le script affiche les lignes contenant : + +```text +class _MetricCard +``` + +Il doit y en avoir une seule. diff --git a/README_MOBILE_DASHBOARD_SCHEDULED_INFOS_V2_7.md b/README_MOBILE_DASHBOARD_SCHEDULED_INFOS_V2_7.md new file mode 100644 index 0000000..9f9b3fb --- /dev/null +++ b/README_MOBILE_DASHBOARD_SCHEDULED_INFOS_V2_7.md @@ -0,0 +1,63 @@ +# FIN65 Mobile - Dashboard avec infos Échéancier V2.7 + +Ce patch ajoute au tableau de bord mobile les infos renvoyées par le backend après le patch Échéancier. + +## Ajouts visibles sur mobile + +Dans l’accueil mobile : + +- `Balance prévisionnelle du mois` +- bloc `Prévisionnel du mois` + - dépenses prévues restantes + - revenus prévus échéancier + - dépenses échéancier + - transferts prévus + - provisions prévues + +## Ce que ce patch ne fait pas encore + +Il n’ajoute pas encore une vraie page mobile pour créer/modifier l’Échéancier. +Il affiche les infos du backend sur l’accueil mobile. On évite de recréer tout un mini-Excel dans un écran de téléphone, par respect pour les pouces humains. + +## Installation + +Décompresse ce ZIP, puis lance : + +```powershell +.\apply_mobile_dashboard_scheduled_infos_v2_7.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Test + +1. Vérifie que l’URL API mobile pointe vers le serveur : + +```text +http://192.168.1.53:8000 +``` + +2. Dans l’app mobile : + - Synchronisation + - Synchroniser maintenant + +3. Reviens à l’accueil : les cartes de prévisionnel doivent apparaître. + +## Important + +Le backend doit déjà renvoyer les nouveaux champs `/dashboard` : + +```text +scheduled_expenses_remaining_total +scheduled_income_remaining_total +scheduled_transfer_remaining_total +scheduled_provision_remaining_total +projected_month_balance +``` + +Si le mobile affiche 0, vérifie d’abord que l’échéancier existe bien sur le web et que l’opération est dans le mois courant. diff --git a/README_MOBILE_OFFLINE_SQLITE.md b/README_MOBILE_OFFLINE_SQLITE.md new file mode 100644 index 0000000..148d384 --- /dev/null +++ b/README_MOBILE_OFFLINE_SQLITE.md @@ -0,0 +1,145 @@ +# FIN65 Mobile V2 - Offline-first SQLite + +Cette version ajoute une vraie base locale SQLite côté mobile. + +## Ce que ça change + +- L'app affiche les dernières données connues même si le backend PC est éteint. +- L'app garde localement : + - les comptes ; + - les catégories ; + - le dashboard ; + - les dernières transactions ; + - les opérations en attente. +- Si le backend est indisponible, une nouvelle dépense/recette/transfert est placée dans une file d'attente locale. +- Quand le backend revient, le bouton "Synchroniser" envoie les opérations en attente, puis recharge les données fraîches. + +## Installation dans le projet Flutter existant + +Depuis : + +```powershell +D:\07-Logiciels\20-FIN65\fin65_mobile +``` + +Copie/remplace depuis ce ZIP : + +```text +pubspec.yaml +lib\ +README_MOBILE_OFFLINE_SQLITE.md +``` + +Puis lance : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +$env:PUB_CACHE = "D:\07-Logiciels\20-FIN65\.pub-cache" +flutter clean +Remove-Item -Recurse -Force .\.dart_tool -ErrorAction SilentlyContinue +Remove-Item -Recurse -Force .\build -ErrorAction SilentlyContinue +Remove-Item -Force .\pubspec.lock -ErrorAction SilentlyContinue +flutter pub get +flutter run +``` + +## Backend + +Le backend reste la source officielle des données. + +```powershell +cd D:\07-Logiciels\20-FIN65\finance_app_backend +py -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload +``` + +Dans l'app mobile, configurer l'URL : + +```text +http://IP_DU_PC:8000 +``` + +## Règles de synchronisation + +- Les créations mobiles sont synchronisées plus tard. +- Les modifications/suppressions hors ligne ne sont pas encore activées pour éviter les conflits. +- Les soldes affichés hors ligne sont des soldes estimés quand il existe des opérations en attente. + +## V2.1 - Correctif locale FR + +Correction de l'erreur Flutter : + +```text +LocaleDataException: Locale data has not been initialized +``` + +Le fichier `lib/main.dart` initialise maintenant les données de formatage : + +```dart +WidgetsFlutterBinding.ensureInitialized(); +await initializeDateFormatting('fr_FR', null); +``` + +## V2.2 - Correctif sauvegarde hors ligne + +Correction du problème observé lors de l'enregistrement d'une dépense avec le backend éteint. + +Changements : +- le formulaire attend maintenant le rechargement SQLite local avant de fermer l'écran ; +- les erreurs de rechargement/synchronisation sont affichées au lieu de produire un écran noir ; +- `ErrorWidget` affiche une erreur lisible si un widget Flutter échoue ; +- validation plus stricte des comptes source/cible. + + +## V2.3 - Boutons rapides + +Ajout de raccourcis dans l'écran d'ajout rapide : + +- dépenses rapides : Courses, Essence, Restaurant, Café, Transport, Santé, Abonnement, Retrait cash ; +- recettes rapides : Salaire, Remboursement, Prime, Vente ; +- transferts rapides : Épargne, Provision, Banque → Cash, Cash → Banque ; +- montants rapides : 10, 20, 50, 100, 200, 500, 1000. + +Les boutons pré-remplissent le libellé et essaient d'associer automatiquement une catégorie existante quand le nom est proche. + + +## V2.4.1 - Correctif build bouton fixe + +Correction de compilation : le bouton `Enregistrer` fixe est maintenant déclaré dans l'écran principal d'ajout rapide, pas dans le composant interne des boutons rapides. + + +## V2.5 - Page Synchronisation + verrouillage PIN + +Ajouts : +- vraie page `Synchronisation` avec statut backend, URL API, dernière synchro, file d'attente locale et bouton de synchronisation ; +- accès à la page depuis l’icône nuage dans la barre du haut ; +- badge avec le nombre d’opérations en attente ; +- écran `Sécurité` dans les paramètres ; +- activation/changement/désactivation du PIN ; +- verrouillage automatique de l’app quand elle passe en arrière-plan ; +- demande du PIN au prochain retour dans l’app. + +Note : +- Le PIN protège l’accès local à l’app. +- Si le backend est exposé sur Internet, il faudra aussi ajouter une vraie authentification serveur. + + +## V2.6 - Déverrouillage par empreinte + +Ajouts : +- dépendance Flutter `local_auth` ; +- activation/désactivation de l'empreinte dans `Paramètres > Sécurité` ; +- déverrouillage par empreinte sur l'écran de verrouillage ; +- le PIN reste toujours disponible en secours ; +- patch Android inclus dans `android_biometrics_patch`. + +Installation : +1. Remplacer `lib`, `pubspec.yaml` et `README_MOBILE_OFFLINE_SQLITE.md`. +2. Lancer `flutter pub get`. +3. Lancer le patch Android : + `android_biometrics_patch\apply_android_biometrics_patch.bat` +4. Relancer `flutter run`. + +Important : +- Active d’abord le PIN dans l’app. +- Ensuite seulement active l’empreinte. +- L’empreinte dépend des empreintes déjà configurées dans Android. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..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..4e768e7 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,43 @@ +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 = "com.example.fin65_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 = "com.example.fin65_mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 24 + 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") + } + } +} + +flutter { + source = "../.." +} + + + + diff --git a/android/app/build.gradle.kts.before_biometric_20260709_004453.bak b/android/app/build.gradle.kts.before_biometric_20260709_004453.bak new file mode 100644 index 0000000..d268259 --- /dev/null +++ b/android/app/build.gradle.kts.before_biometric_20260709_004453.bak @@ -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 = "com.example.fin65_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 = "com.example.fin65_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/build.gradle.kts.before_gradle_repair_20260709_004714.bak b/android/app/build.gradle.kts.before_gradle_repair_20260709_004714.bak new file mode 100644 index 0000000..dbb6d94 --- /dev/null +++ b/android/app/build.gradle.kts.before_gradle_repair_20260709_004714.bak @@ -0,0 +1,46 @@ +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 = "com.example.fin65_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 = "com.example.fin65_mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 24 + 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/build.gradle.kts.before_java_mainactivity_20260709_005700.bak b/android/app/build.gradle.kts.before_java_mainactivity_20260709_005700.bak new file mode 100644 index 0000000..9c4e33d --- /dev/null +++ b/android/app/build.gradle.kts.before_java_mainactivity_20260709_005700.bak @@ -0,0 +1,42 @@ +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 = "com.example.fin65_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 = "com.example.fin65_mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 24 + 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") + } + } +} + +flutter { + source = "../.." +} + + + diff --git a/android/app/build.gradle.kts.before_mainactivity_repair_20260709_005421.bak b/android/app/build.gradle.kts.before_mainactivity_repair_20260709_005421.bak new file mode 100644 index 0000000..1f5e746 --- /dev/null +++ b/android/app/build.gradle.kts.before_mainactivity_repair_20260709_005421.bak @@ -0,0 +1,41 @@ +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 = "com.example.fin65_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 = "com.example.fin65_mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 24 + 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") + } + } +} + +flutter { + source = "../.." +} + + diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b270328 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml.before_biometric_20260709_004453.bak b/android/app/src/main/AndroidManifest.xml.before_biometric_20260709_004453.bak new file mode 100644 index 0000000..b2d0722 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml.before_biometric_20260709_004453.bak @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + diff --git a/android/app/src/main/AndroidManifest.xml.before_java_mainactivity_20260709_005700.bak b/android/app/src/main/AndroidManifest.xml.before_java_mainactivity_20260709_005700.bak new file mode 100644 index 0000000..b270328 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml.before_java_mainactivity_20260709_005700.bak @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml.before_mainactivity_repair_20260709_005421.bak b/android/app/src/main/AndroidManifest.xml.before_mainactivity_repair_20260709_005421.bak new file mode 100644 index 0000000..d6d3ae7 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml.before_mainactivity_repair_20260709_005421.bak @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml.broken_20260709_001315.bak b/android/app/src/main/AndroidManifest.xml.broken_20260709_001315.bak new file mode 100644 index 0000000..7bc818d --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml.broken_20260709_001315.bak @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java b/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java new file mode 100644 index 0000000..5d6ee4f --- /dev/null +++ b/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java @@ -0,0 +1,6 @@ +package com.example.fin65_mobile; + +import io.flutter.embedding.android.FlutterFragmentActivity; + +public class MainActivity extends FlutterFragmentActivity { +} \ No newline at end of file diff --git a/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java.before_bom_fix_20260709_005841.bak b/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java.before_bom_fix_20260709_005841.bak new file mode 100644 index 0000000..4c3986d --- /dev/null +++ b/android/app/src/main/java/com/example/fin65_mobile/MainActivity.java.before_bom_fix_20260709_005841.bak @@ -0,0 +1,6 @@ +package com.example.fin65_mobile; + +import io.flutter.embedding.android.FlutterFragmentActivity; + +public class MainActivity extends FlutterFragmentActivity { +} diff --git a/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_biometric_20260709_004453.bak b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_biometric_20260709_004453.bak new file mode 100644 index 0000000..7237abb --- /dev/null +++ b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_biometric_20260709_004453.bak @@ -0,0 +1,5 @@ +package com.example.fin65_mobile + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_mainactivity_repair_20260709_005421.bak b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_mainactivity_repair_20260709_005421.bak new file mode 100644 index 0000000..f5e8472 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.before_mainactivity_repair_20260709_005421.bak @@ -0,0 +1,6 @@ +package com.example.fin65_mobile + +import io.flutter.embedding.android.FlutterFragmentActivity + +class MainActivity : FlutterFragmentActivity() + diff --git a/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.disabled_20260709_005700 b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.disabled_20260709_005700 new file mode 100644 index 0000000..e5fd0ed --- /dev/null +++ b/android/app/src/main/kotlin/com/example/fin65_mobile/MainActivity.kt.disabled_20260709_005700 @@ -0,0 +1,5 @@ +package com.example.fin65_mobile + +import io.flutter.embedding.android.FlutterFragmentActivity + +class MainActivity : FlutterFragmentActivity() 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-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..80b730f --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..80b730f --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..49f4edd Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8958985 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..b597fca Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..738c10e Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..3cf7114 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..dd8253b Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..0d97344 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..a46788b Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..7a5854a Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..fd17041 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..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/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..0cfdac6 --- /dev/null +++ b/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #0F172A + 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/android_biometrics_patch/README_ANDROID_BIOMETRICS_PATCH.md b/android_biometrics_patch/README_ANDROID_BIOMETRICS_PATCH.md new file mode 100644 index 0000000..9ef63ba --- /dev/null +++ b/android_biometrics_patch/README_ANDROID_BIOMETRICS_PATCH.md @@ -0,0 +1,29 @@ +# FIN65 - Patch Android biométrie + +Ce patch prépare Android pour `local_auth`. + +Il fait : +- ajoute `android.permission.USE_BIOMETRIC` dans `AndroidManifest.xml` ; +- garde `android.permission.INTERNET` ; +- garde `android:usesCleartextTraffic="true"` ; +- force le label `FIN65` ; +- modifie `MainActivity` pour hériter de `FlutterFragmentActivity` ; +- tente de mettre `minSdk` à 24 si nécessaire ; +- lance `flutter clean` et `flutter pub get`. + +## Utilisation + +Depuis ce dossier : + +```powershell +.\apply_android_biometrics_patch.bat +``` + +Puis : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +Des sauvegardes `.before_biometric_*.bak` sont créées avant modification. diff --git a/android_biometrics_patch/apply_android_biometrics_patch.bat b/android_biometrics_patch/apply_android_biometrics_patch.bat new file mode 100644 index 0000000..ed4e796 --- /dev/null +++ b/android_biometrics_patch/apply_android_biometrics_patch.bat @@ -0,0 +1,4 @@ +@echo off +setlocal + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0apply_android_biometrics_patch.ps1" diff --git a/android_biometrics_patch/apply_android_biometrics_patch.ps1 b/android_biometrics_patch/apply_android_biometrics_patch.ps1 new file mode 100644 index 0000000..3f6b388 --- /dev/null +++ b/android_biometrics_patch/apply_android_biometrics_patch.ps1 @@ -0,0 +1,128 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$Manifest = Join-Path $MobileDir "android\app\src\main\AndroidManifest.xml" +$AndroidDir = Join-Path $MobileDir "android\app\src\main" +$KotlinRoot = Join-Path $AndroidDir "kotlin" +$JavaRoot = Join-Path $AndroidDir "java" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Patch Android biometrie" +Write-Host "==========================================" +Write-Host "" + +if (!(Test-Path $MobileDir)) { + Write-Host "[ERREUR] Dossier mobile introuvable : $MobileDir" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +if (!(Test-Path $Manifest)) { + Write-Host "[ERREUR] AndroidManifest.xml introuvable : $Manifest" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$Stamp = Get-Date -Format "yyyyMMdd_HHmmss" +Copy-Item $Manifest "$Manifest.before_biometric_$Stamp.bak" -Force + +[xml]$xml = Get-Content $Manifest +$manifestNode = $xml.manifest +$androidNs = "http://schemas.android.com/apk/res/android" + +function Ensure-Permission($name) { + $existing = $manifestNode.'uses-permission' | Where-Object { + $_.GetAttribute("name", $androidNs) -eq $name + } + if ($null -eq $existing) { + $perm = $xml.CreateElement("uses-permission") + $attr = $xml.CreateAttribute("android", "name", $androidNs) + $attr.Value = $name + [void]$perm.Attributes.Append($attr) + [void]$manifestNode.InsertBefore($perm, $manifestNode.FirstChild) + Write-Host "Permission ajoutee : $name" + } else { + Write-Host "Permission deja presente : $name" + } +} + +Ensure-Permission "android.permission.INTERNET" +Ensure-Permission "android.permission.USE_BIOMETRIC" + +$app = $manifestNode.application +if ($app -ne $null) { + $app.SetAttribute("label", $androidNs, "FIN65") + $app.SetAttribute("icon", $androidNs, "@mipmap/ic_launcher") + $app.SetAttribute("roundIcon", $androidNs, "@mipmap/ic_launcher_round") + $app.SetAttribute("usesCleartextTraffic", $androidNs, "true") +} + +$xml.Save($Manifest) +Write-Host "AndroidManifest.xml mis a jour." + +# MainActivity: local_auth Android demande FlutterFragmentActivity. +$mainFiles = @() +if (Test-Path $KotlinRoot) { + $mainFiles += Get-ChildItem $KotlinRoot -Recurse -Filter MainActivity.kt -ErrorAction SilentlyContinue +} +if (Test-Path $JavaRoot) { + $mainFiles += Get-ChildItem $JavaRoot -Recurse -Filter MainActivity.java -ErrorAction SilentlyContinue +} + +if ($mainFiles.Count -eq 0) { + Write-Host "[ATTENTION] MainActivity introuvable. Aucun patch FragmentActivity applique." -ForegroundColor Yellow +} else { + foreach ($file in $mainFiles) { + Copy-Item $file.FullName "$($file.FullName).before_biometric_$Stamp.bak" -Force + $text = Get-Content $file.FullName -Raw + + if ($file.Extension -eq ".kt") { + $text = $text -replace "import io\.flutter\.embedding\.android\.FlutterActivity", "import io.flutter.embedding.android.FlutterFragmentActivity" + if ($text -notmatch "FlutterFragmentActivity") { + $text = $text -replace "package ([^\r\n]+)", "package `$1`n`nimport io.flutter.embedding.android.FlutterFragmentActivity" + } + $text = $text -replace ":\s*FlutterActivity\(\)", ": FlutterFragmentActivity()" + $text = $text -replace "extends\s+FlutterActivity", "extends FlutterFragmentActivity" + Set-Content $file.FullName $text -Encoding UTF8 + Write-Host "MainActivity.kt mis a jour : $($file.FullName)" + } + + if ($file.Extension -eq ".java") { + $text = $text -replace "import io\.flutter\.embedding\.android\.FlutterActivity;", "import io.flutter.embedding.android.FlutterFragmentActivity;" + if ($text -notmatch "FlutterFragmentActivity") { + $text = $text -replace "(package [^;]+;)", "`$1`n`nimport io.flutter.embedding.android.FlutterFragmentActivity;" + } + $text = $text -replace "extends\s+FlutterActivity", "extends FlutterFragmentActivity" + Set-Content $file.FullName $text -Encoding UTF8 + Write-Host "MainActivity.java mis a jour : $($file.FullName)" + } + } +} + +# Tente de relever minSdk a 24 si un fichier Gradle classique existe. +$gradleFiles = @( + (Join-Path $MobileDir "android\app\build.gradle"), + (Join-Path $MobileDir "android\app\build.gradle.kts") +) + +foreach ($g in $gradleFiles) { + if (Test-Path $g) { + Copy-Item $g "$g.before_biometric_$Stamp.bak" -Force + $text = Get-Content $g -Raw + $text = $text -replace "minSdkVersion\s+flutter\.minSdkVersion", "minSdkVersion 24" + $text = $text -replace "minSdk\s*=\s*flutter\.minSdkVersion", "minSdk = 24" + $text = $text -replace "minSdkVersion\s+\d+", "minSdkVersion 24" + $text = $text -replace "minSdk\s*=\s*\d+", "minSdk = 24" + Set-Content $g $text -Encoding UTF8 + Write-Host "Gradle minSdk verifie : $g" + } +} + +Set-Location $MobileDir +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Patch Android biometrie termine." +Write-Host "Relance maintenant : flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/apply_fin65_android_icon.bat b/apply_fin65_android_icon.bat new file mode 100644 index 0000000..8343238 --- /dev/null +++ b/apply_fin65_android_icon.bat @@ -0,0 +1,79 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Remplacer l'icone Android Flutter +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +echo. +echo ========================================== +echo FIN65 - Remplacement icone Android +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + echo. + pause + exit /b 1 +) + +cd /d "%MOBILE_DIR%" + +if not exist "pubspec.yaml" ( + echo [ERREUR] pubspec.yaml introuvable dans : + echo %MOBILE_DIR% + echo. + pause + exit /b 1 +) + +mkdir "assets\icon" >nul 2>&1 + +copy /Y "%~dp0assets\icon\app_icon.png" "assets\icon\app_icon.png" >nul +copy /Y "%~dp0assets\icon\adaptive_foreground.png" "assets\icon\adaptive_foreground.png" >nul +copy /Y "%~dp0flutter_launcher_icons.yaml" "flutter_launcher_icons.yaml" >nul + +echo Icones copiees dans : +echo %MOBILE_DIR%\assets\icon +echo. + +echo Ajout/verif du package flutter_launcher_icons... +flutter pub add --dev flutter_launcher_icons +if errorlevel 1 ( + echo. + echo [ERREUR] Impossible d'ajouter flutter_launcher_icons. + echo Verifie la connexion internet et Flutter. + pause + exit /b 1 +) + +echo. +echo Generation des icones Android... +dart run flutter_launcher_icons +if errorlevel 1 ( + echo. + echo [ERREUR] Generation des icones echouee. + pause + exit /b 1 +) + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Icone FIN65 appliquee. +echo ========================================== +echo. +echo Relance ensuite : +echo flutter run +echo. +pause diff --git a/apply_mobile_dashboard_colors_v2_7_1.bat b/apply_mobile_dashboard_colors_v2_7_1.bat new file mode 100644 index 0000000..e302efe --- /dev/null +++ b/apply_mobile_dashboard_colors_v2_7_1.bat @@ -0,0 +1,54 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 Mobile - Dashboard couleurs V2.7.1 +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +echo. +echo ========================================== +echo FIN65 Mobile - Dashboard couleurs V2.7.1 +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +set "BACKUP_DIR=%MOBILE_DIR%\backup_before_mobile_dashboard_colors_v271" +mkdir "%BACKUP_DIR%" >nul 2>&1 + +if exist "%MOBILE_DIR%\lib\models\dashboard.dart" ( + copy /Y "%MOBILE_DIR%\lib\models\dashboard.dart" "%BACKUP_DIR%\dashboard.dart.bak" >nul +) + +if exist "%MOBILE_DIR%\lib\screens\home_screen.dart" ( + copy /Y "%MOBILE_DIR%\lib\screens\home_screen.dart" "%BACKUP_DIR%\home_screen.dart.bak" >nul +) + +copy /Y "%~dp0lib\models\dashboard.dart" "%MOBILE_DIR%\lib\models\dashboard.dart" >nul +copy /Y "%~dp0lib\screens\home_screen.dart" "%MOBILE_DIR%\lib\screens\home_screen.dart" >nul + +cd /d "%MOBILE_DIR%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Patch couleurs applique. +echo ========================================== +echo. +echo Relance maintenant : +echo flutter run +echo. +pause diff --git a/apply_mobile_dashboard_colors_v2_7_2_fix.bat b/apply_mobile_dashboard_colors_v2_7_2_fix.bat new file mode 100644 index 0000000..588cb62 --- /dev/null +++ b/apply_mobile_dashboard_colors_v2_7_2_fix.bat @@ -0,0 +1,58 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 Mobile - Dashboard couleurs V2.7.2 fix duplicate class +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +echo. +echo ========================================== +echo FIN65 Mobile - Couleurs V2.7.2 FIX +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +set "BACKUP_DIR=%MOBILE_DIR%\backup_before_mobile_dashboard_colors_v272" +mkdir "%BACKUP_DIR%" >nul 2>&1 + +if exist "%MOBILE_DIR%\lib\models\dashboard.dart" ( + copy /Y "%MOBILE_DIR%\lib\models\dashboard.dart" "%BACKUP_DIR%\dashboard.dart.bak" >nul +) + +if exist "%MOBILE_DIR%\lib\screens\home_screen.dart" ( + copy /Y "%MOBILE_DIR%\lib\screens\home_screen.dart" "%BACKUP_DIR%\home_screen.dart.bak" >nul +) + +copy /Y "%~dp0lib\models\dashboard.dart" "%MOBILE_DIR%\lib\models\dashboard.dart" >nul +copy /Y "%~dp0lib\screens\home_screen.dart" "%MOBILE_DIR%\lib\screens\home_screen.dart" >nul + +cd /d "%MOBILE_DIR%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo Verification rapide... +findstr /N /C:"class _MetricCard" lib\screens\home_screen.dart + +echo. +echo ========================================== +echo Fix applique. Il doit y avoir UNE seule ligne _MetricCard. +echo ========================================== +echo. +echo Relance maintenant : +echo flutter run +echo. +pause diff --git a/apply_mobile_dashboard_scheduled_infos_v2_7.bat b/apply_mobile_dashboard_scheduled_infos_v2_7.bat new file mode 100644 index 0000000..769785e --- /dev/null +++ b/apply_mobile_dashboard_scheduled_infos_v2_7.bat @@ -0,0 +1,66 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 Mobile - Dashboard avec infos echeancier V2.7 +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +echo. +echo ========================================== +echo FIN65 Mobile - Infos echeancier V2.7 +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +if not exist "%MOBILE_DIR%\lib\models" ( + echo [ERREUR] Dossier models introuvable. + pause + exit /b 1 +) + +if not exist "%MOBILE_DIR%\lib\screens" ( + echo [ERREUR] Dossier screens introuvable. + pause + exit /b 1 +) + +set "BACKUP_DIR=%MOBILE_DIR%\backup_before_mobile_dashboard_scheduled_v27" +mkdir "%BACKUP_DIR%" >nul 2>&1 + +if exist "%MOBILE_DIR%\lib\models\dashboard.dart" ( + copy /Y "%MOBILE_DIR%\lib\models\dashboard.dart" "%BACKUP_DIR%\dashboard.dart.bak" >nul +) + +if exist "%MOBILE_DIR%\lib\screens\home_screen.dart" ( + copy /Y "%MOBILE_DIR%\lib\screens\home_screen.dart" "%BACKUP_DIR%\home_screen.dart.bak" >nul +) + +copy /Y "%~dp0lib\models\dashboard.dart" "%MOBILE_DIR%\lib\models\dashboard.dart" >nul +copy /Y "%~dp0lib\screens\home_screen.dart" "%MOBILE_DIR%\lib\screens\home_screen.dart" >nul + +cd /d "%MOBILE_DIR%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Patch mobile applique. +echo ========================================== +echo. +echo Relance maintenant : +echo flutter run +echo. +pause diff --git a/assets/icon/adaptive_foreground.png b/assets/icon/adaptive_foreground.png new file mode 100644 index 0000000..21eb579 Binary files /dev/null and b/assets/icon/adaptive_foreground.png differ diff --git a/assets/icon/app_icon.png b/assets/icon/app_icon.png new file mode 100644 index 0000000..231689d Binary files /dev/null and b/assets/icon/app_icon.png differ diff --git a/backup_before_biometrics_stability_v262/app_lock_gate.dart.bak b/backup_before_biometrics_stability_v262/app_lock_gate.dart.bak new file mode 100644 index 0000000..1914fab --- /dev/null +++ b/backup_before_biometrics_stability_v262/app_lock_gate.dart.bak @@ -0,0 +1,251 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../services/security_service.dart'; + +class AppLockGate extends StatefulWidget { + const AppLockGate({ + super.key, + required this.securityService, + required this.child, + }); + + final SecurityService securityService; + final Widget child; + + @override + State createState() => _AppLockGateState(); +} + +class _AppLockGateState extends State with WidgetsBindingObserver { + bool _checking = true; + bool _locked = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _loadLockState(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) { + _lockIfNeeded(); + } + } + + Future _loadLockState() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted) return; + setState(() { + _locked = enabled; + _checking = false; + }); + } + + Future _lockIfNeeded() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted || !enabled) return; + setState(() => _locked = true); + } + + void _unlock() { + setState(() => _locked = false); + } + + @override + Widget build(BuildContext context) { + if (_checking) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + if (_locked) { + return PinUnlockScreen( + securityService: widget.securityService, + onUnlocked: _unlock, + ); + } + + return widget.child; + } +} + +class PinUnlockScreen extends StatefulWidget { + const PinUnlockScreen({ + super.key, + required this.securityService, + required this.onUnlocked, + }); + + final SecurityService securityService; + final VoidCallback onUnlocked; + + @override + State createState() => _PinUnlockScreenState(); +} + +class _PinUnlockScreenState extends State { + final _pinController = TextEditingController(); + bool _checking = false; + bool _checkingBiometric = false; + bool _biometricEnabled = false; + bool _biometricAvailable = false; + bool _biometricAttempted = false; + String? _error; + + @override + void initState() { + super.initState(); + _loadBiometricState(); + } + + @override + void dispose() { + _pinController.dispose(); + super.dispose(); + } + + Future _loadBiometricState() async { + final enabled = await widget.securityService.isBiometricEnabled(); + final available = await widget.securityService.isBiometricAvailable(); + + if (!mounted) return; + setState(() { + _biometricEnabled = enabled; + _biometricAvailable = available; + }); + + if (enabled && available && !_biometricAttempted) { + _biometricAttempted = true; + await Future.delayed(const Duration(milliseconds: 250)); + if (mounted) await _unlockWithBiometrics(); + } + } + + Future _unlockWithBiometrics() async { + setState(() { + _checkingBiometric = true; + _error = null; + }); + + final ok = await widget.securityService.authenticateWithBiometrics(); + + if (!mounted) return; + + if (ok) { + widget.onUnlocked(); + } else { + setState(() { + _checkingBiometric = false; + _error = 'Empreinte refusée ou annulée. Utilise le PIN.'; + }); + } + } + + Future _unlock() async { + setState(() { + _checking = true; + _error = null; + }); + + final ok = await widget.securityService.verifyPin(_pinController.text.trim()); + + if (!mounted) return; + + if (ok) { + _pinController.clear(); + widget.onUnlocked(); + } else { + HapticFeedback.vibrate(); + setState(() { + _checking = false; + _error = 'PIN incorrect.'; + }); + } + } + + @override + Widget build(BuildContext context) { + final showBiometric = _biometricEnabled && _biometricAvailable; + + return Scaffold( + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.all(24), + children: [ + Icon(showBiometric ? Icons.fingerprint : Icons.lock, size: 64), + const SizedBox(height: 16), + Text( + 'FIN65 verrouillé', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 8), + Text( + showBiometric + ? 'Déverrouille avec ton empreinte ou ton PIN.' + : 'Entre ton PIN pour accéder aux données locales.', + textAlign: TextAlign.center, + ), + if (showBiometric) ...[ + const SizedBox(height: 24), + FilledButton.icon( + onPressed: _checkingBiometric ? null : _unlockWithBiometrics, + icon: _checkingBiometric + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.fingerprint), + label: Text(_checkingBiometric ? 'Vérification...' : 'Utiliser l’empreinte'), + ), + ], + const SizedBox(height: 24), + TextField( + controller: _pinController, + autofocus: !showBiometric, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: 'PIN', + border: const OutlineInputBorder(), + errorText: _error, + counterText: '', + ), + onSubmitted: (_) => _checking ? null : _unlock(), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _checking ? null : _unlock, + icon: _checking + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.lock_open), + label: Text(_checking ? 'Vérification...' : 'Déverrouiller avec le PIN'), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/backup_before_biometrics_stability_v262/security_screen.dart.bak b/backup_before_biometrics_stability_v262/security_screen.dart.bak new file mode 100644 index 0000000..783ccfa --- /dev/null +++ b/backup_before_biometrics_stability_v262/security_screen.dart.bak @@ -0,0 +1,399 @@ +import 'package:flutter/material.dart'; +import 'package:local_auth/local_auth.dart'; + +import '../services/security_service.dart'; + +class SecurityScreen extends StatefulWidget { + const SecurityScreen({ + super.key, + required this.securityService, + }); + + final SecurityService securityService; + + @override + State createState() => _SecurityScreenState(); +} + +class _SecurityScreenState extends State { + final _currentPinController = TextEditingController(); + final _newPinController = TextEditingController(); + final _confirmPinController = TextEditingController(); + + bool _loading = true; + bool _saving = false; + bool _enabled = false; + bool _biometricAvailable = false; + bool _biometricEnabled = false; + List _availableBiometrics = const []; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _currentPinController.dispose(); + _newPinController.dispose(); + _confirmPinController.dispose(); + super.dispose(); + } + + Future _load() async { + final enabled = await widget.securityService.isPinEnabled(); + final biometricAvailable = await widget.securityService.isBiometricAvailable(); + final biometricEnabled = await widget.securityService.isBiometricEnabled(); + final availableBiometrics = await widget.securityService.getAvailableBiometrics(); + + if (!mounted) return; + setState(() { + _enabled = enabled; + _biometricAvailable = biometricAvailable; + _biometricEnabled = biometricEnabled; + _availableBiometrics = availableBiometrics; + _loading = false; + }); + } + + Future _verifyCurrentPinFromFieldIfNeeded() async { + if (!_enabled) return true; + + final current = _currentPinController.text.trim(); + final ok = await widget.securityService.verifyPin(current); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + return true; + } + + Future _askCurrentPinDialog({ + required String title, + required String actionLabel, + }) async { + final controller = TextEditingController(); + + final result = await showDialog( + context: context, + barrierDismissible: true, + builder: (context) { + return AlertDialog( + title: Text(title), + content: TextField( + controller: controller, + autofocus: true, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + counterText: '', + ), + onSubmitted: (_) => Navigator.of(context).pop(controller.text.trim()), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Annuler'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(controller.text.trim()), + child: Text(actionLabel), + ), + ], + ); + }, + ); + + controller.dispose(); + return result?.trim(); + } + + Future _askAndVerifyCurrentPin({ + required String title, + required String actionLabel, + }) async { + final pin = await _askCurrentPinDialog( + title: title, + actionLabel: actionLabel, + ); + + if (pin == null) { + setState(() => _message = 'Action annulée.'); + return false; + } + + final ok = await widget.securityService.verifyPin(pin); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + + return true; + } + + Future _savePin() async { + final newPin = _newPinController.text.trim(); + final confirm = _confirmPinController.text.trim(); + + if (newPin != confirm) { + setState(() => _message = 'Le nouveau PIN et la confirmation ne correspondent pas.'); + return; + } + + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinFromFieldIfNeeded(); + if (!currentOk) return; + + await widget.securityService.setPin(newPin); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN activé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _disablePin() async { + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _askAndVerifyCurrentPin( + title: 'Désactiver le verrouillage PIN', + actionLabel: 'Désactiver', + ); + if (!currentOk) return; + + await widget.securityService.disablePin(); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN et biométrie désactivés.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _toggleBiometrics(bool value) async { + if (_saving) return; + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (value) { + if (!_enabled) { + setState(() => _message = 'Active d’abord un PIN avant la biométrie.'); + return; + } + + if (!_biometricAvailable) { + setState(() => _message = 'Aucune empreinte/biométrie disponible sur ce téléphone.'); + return; + } + + final currentOk = await _askAndVerifyCurrentPin( + title: 'Activer l’empreinte', + actionLabel: 'Continuer', + ); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(true); + + final confirmed = await widget.securityService.authenticateWithBiometrics(); + if (!confirmed) { + await widget.securityService.setBiometricEnabled(false); + setState(() => _message = 'Empreinte annulée ou refusée. Biométrie non activée.'); + return; + } + } else { + final currentOk = await _askAndVerifyCurrentPin( + title: 'Désactiver l’empreinte', + actionLabel: 'Désactiver', + ); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(false); + } + + await _load(); + + setState(() { + _message = value + ? 'Déverrouillage par empreinte activé.' + : 'Déverrouillage par empreinte désactivé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _biometricLabel() { + if (_availableBiometrics.isEmpty) return 'Aucune biométrie détectée.'; + + final labels = _availableBiometrics.map((type) { + return switch (type) { + BiometricType.fingerprint => 'empreinte', + BiometricType.face => 'visage', + BiometricType.iris => 'iris', + BiometricType.strong => 'biométrie forte', + BiometricType.weak => 'biométrie faible', + }; + }).toSet().join(', '); + + return 'Disponible : $labels.'; + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: const Center(child: CircularProgressIndicator()), + ); + } + + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: SwitchListTile( + value: _enabled, + onChanged: null, + secondary: Icon(_enabled ? Icons.lock : Icons.lock_open), + title: const Text('Verrouillage PIN'), + subtitle: Text( + _enabled + ? 'Activé. L’app se verrouille à la fermeture ou au changement d’application.' + : 'Désactivé. Tes données locales sont accessibles sans PIN.', + ), + ), + ), + if (_enabled) ...[ + const SizedBox(height: 12), + Card( + child: SwitchListTile( + value: _biometricEnabled, + onChanged: _saving || !_biometricAvailable ? null : _toggleBiometrics, + secondary: const Icon(Icons.fingerprint), + title: const Text('Déverrouillage par empreinte'), + subtitle: Text( + _biometricAvailable + ? '${_biometricLabel()} Appuie sur l’interrupteur, entre le PIN actuel, puis valide l’empreinte.' + : 'Aucune empreinte/biométrie disponible ou configurée sur ce téléphone.', + ), + ), + ), + ], + const SizedBox(height: 16), + if (_enabled) ...[ + TextField( + controller: _currentPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + helperText: 'Uniquement nécessaire pour changer le PIN.', + counterText: '', + ), + ), + const SizedBox(height: 12), + ], + TextField( + controller: _newPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: _enabled ? 'Nouveau PIN' : 'PIN', + border: const OutlineInputBorder(), + helperText: '4 à 8 chiffres.', + counterText: '', + ), + ), + const SizedBox(height: 12), + TextField( + controller: _confirmPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'Confirmer le PIN', + border: OutlineInputBorder(), + counterText: '', + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _saving ? null : _savePin, + icon: const Icon(Icons.save), + label: Text(_enabled ? 'Changer le PIN' : 'Activer le PIN'), + ), + if (_enabled) ...[ + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _saving ? null : _disablePin, + icon: const Icon(Icons.lock_open), + label: const Text('Désactiver le PIN'), + ), + ], + if (_message != null) ...[ + const SizedBox(height: 16), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 24), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Le PIN protège l’accès local à l’application. L’empreinte utilise la sécurité biométrique du téléphone. Le PIN reste le secours si l’empreinte échoue.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/backup_before_mobile_dashboard_colors_v271/dashboard.dart.bak b/backup_before_mobile_dashboard_colors_v271/dashboard.dart.bak new file mode 100644 index 0000000..6a6a3f2 --- /dev/null +++ b/backup_before_mobile_dashboard_colors_v271/dashboard.dart.bak @@ -0,0 +1,223 @@ +import 'account.dart'; + +class ReconciliationStatus { + final int accountId; + final String accountName; + final double appBalance; + final bool checkedToday; + final double? realBalance; + final double? difference; + + ReconciliationStatus({ + required this.accountId, + required this.accountName, + required this.appBalance, + required this.checkedToday, + this.realBalance, + this.difference, + }); + + factory ReconciliationStatus.fromJson(Map json) { + return ReconciliationStatus( + accountId: json['account_id'] as int, + accountName: json['account_name'] as String, + appBalance: (json['app_balance'] as num? ?? 0).toDouble(), + checkedToday: json['checked_today'] is int + ? (json['checked_today'] as int) == 1 + : json['checked_today'] as bool? ?? false, + realBalance: (json['real_balance'] as num?)?.toDouble(), + difference: (json['difference'] as num?)?.toDouble(), + ); + } + + Map toJson() { + return { + 'account_id': accountId, + 'account_name': accountName, + 'app_balance': appBalance, + 'checked_today': checkedToday, + 'real_balance': realBalance, + 'difference': difference, + }; + } + + ReconciliationStatus copyWith({ + double? appBalance, + bool? checkedToday, + double? realBalance, + double? difference, + }) { + return ReconciliationStatus( + accountId: accountId, + accountName: accountName, + appBalance: appBalance ?? this.appBalance, + checkedToday: checkedToday ?? this.checkedToday, + realBalance: realBalance ?? this.realBalance, + difference: difference ?? this.difference, + ); + } +} + +class DashboardData { + final String month; + final double totalBalance; + final double availableAfterReserves; + final double monthlyIncome; + final double monthlyExpenses; + final double monthlyBalance; + final double provisionsCurrentTotal; + final double provisionsTargetTotal; + final double monthlyChargesRemainingTotal; + final double monthlyTransferRemainingTotal; + final double monthlyProvisionOperationRemainingTotal; + + // Nouveaux champs backend : échéancier / opérations prévues ponctuelles. + final double scheduledExpensesRemainingTotal; + final double scheduledIncomeRemainingTotal; + final double scheduledTransferRemainingTotal; + final double scheduledProvisionRemainingTotal; + final double scheduledNetRemainingTotal; + final double projectedMonthBalance; + + final List accounts; + final List reconciliationsToday; + + DashboardData({ + required this.month, + required this.totalBalance, + required this.availableAfterReserves, + required this.monthlyIncome, + required this.monthlyExpenses, + required this.monthlyBalance, + required this.provisionsCurrentTotal, + required this.provisionsTargetTotal, + required this.monthlyChargesRemainingTotal, + required this.monthlyTransferRemainingTotal, + required this.monthlyProvisionOperationRemainingTotal, + required this.scheduledExpensesRemainingTotal, + required this.scheduledIncomeRemainingTotal, + required this.scheduledTransferRemainingTotal, + required this.scheduledProvisionRemainingTotal, + required this.scheduledNetRemainingTotal, + required this.projectedMonthBalance, + required this.accounts, + required this.reconciliationsToday, + }); + + double get plannedExpensesTotal => + monthlyChargesRemainingTotal + scheduledExpensesRemainingTotal; + + double get plannedTransfersTotal => + monthlyTransferRemainingTotal + scheduledTransferRemainingTotal; + + double get plannedProvisionsTotal => + monthlyProvisionOperationRemainingTotal + scheduledProvisionRemainingTotal; + + bool get hasScheduledInfo => + scheduledExpensesRemainingTotal != 0 || + scheduledIncomeRemainingTotal != 0 || + scheduledTransferRemainingTotal != 0 || + scheduledProvisionRemainingTotal != 0; + + factory DashboardData.fromJson(Map json) { + final availableRaw = json['available_after_reserves'] ?? json['total_balance'] ?? 0; + + final monthlyBalance = (json['monthly_balance'] as num? ?? 0).toDouble(); + final scheduledIncome = (json['scheduled_income_remaining_total'] as num? ?? 0).toDouble(); + final scheduledExpenses = (json['scheduled_expenses_remaining_total'] as num? ?? 0).toDouble(); + + return DashboardData( + month: json['month'] as String? ?? '', + totalBalance: (json['total_balance'] as num? ?? 0).toDouble(), + availableAfterReserves: (availableRaw as num).toDouble(), + monthlyIncome: (json['monthly_income'] as num? ?? 0).toDouble(), + monthlyExpenses: (json['monthly_expenses'] as num? ?? 0).toDouble(), + monthlyBalance: monthlyBalance, + provisionsCurrentTotal: (json['provisions_current_total'] as num? ?? 0).toDouble(), + provisionsTargetTotal: (json['provisions_target_total'] as num? ?? 0).toDouble(), + monthlyChargesRemainingTotal: (json['monthly_charges_remaining_total'] as num? ?? 0).toDouble(), + monthlyTransferRemainingTotal: (json['monthly_transfer_remaining_total'] as num? ?? 0).toDouble(), + monthlyProvisionOperationRemainingTotal: (json['monthly_provision_operation_remaining_total'] as num? ?? 0).toDouble(), + scheduledExpensesRemainingTotal: scheduledExpenses, + scheduledIncomeRemainingTotal: scheduledIncome, + scheduledTransferRemainingTotal: (json['scheduled_transfer_remaining_total'] as num? ?? 0).toDouble(), + scheduledProvisionRemainingTotal: (json['scheduled_provision_remaining_total'] as num? ?? 0).toDouble(), + scheduledNetRemainingTotal: (json['scheduled_net_remaining_total'] as num? ?? (scheduledIncome - scheduledExpenses)).toDouble(), + projectedMonthBalance: (json['projected_month_balance'] as num? ?? (monthlyBalance + scheduledIncome - scheduledExpenses)).toDouble(), + accounts: (json['accounts'] as List? ?? []) + .map((e) => Account.fromJson(e as Map)) + .toList(), + reconciliationsToday: (json['reconciliations_today'] as List? ?? []) + .map((e) => ReconciliationStatus.fromJson(e as Map)) + .toList(), + ); + } + + Map toJson() { + return { + 'month': month, + 'total_balance': totalBalance, + 'available_after_reserves': availableAfterReserves, + 'monthly_income': monthlyIncome, + 'monthly_expenses': monthlyExpenses, + 'monthly_balance': monthlyBalance, + 'provisions_current_total': provisionsCurrentTotal, + 'provisions_target_total': provisionsTargetTotal, + 'monthly_charges_remaining_total': monthlyChargesRemainingTotal, + 'monthly_transfer_remaining_total': monthlyTransferRemainingTotal, + 'monthly_provision_operation_remaining_total': monthlyProvisionOperationRemainingTotal, + 'scheduled_expenses_remaining_total': scheduledExpensesRemainingTotal, + 'scheduled_income_remaining_total': scheduledIncomeRemainingTotal, + 'scheduled_transfer_remaining_total': scheduledTransferRemainingTotal, + 'scheduled_provision_remaining_total': scheduledProvisionRemainingTotal, + 'scheduled_net_remaining_total': scheduledNetRemainingTotal, + 'projected_month_balance': projectedMonthBalance, + 'accounts': accounts.map((e) => e.toJson()).toList(), + 'reconciliations_today': reconciliationsToday.map((e) => e.toJson()).toList(), + }; + } + + DashboardData copyWith({ + String? month, + double? totalBalance, + double? availableAfterReserves, + double? monthlyIncome, + double? monthlyExpenses, + double? monthlyBalance, + double? provisionsCurrentTotal, + double? provisionsTargetTotal, + double? monthlyChargesRemainingTotal, + double? monthlyTransferRemainingTotal, + double? monthlyProvisionOperationRemainingTotal, + double? scheduledExpensesRemainingTotal, + double? scheduledIncomeRemainingTotal, + double? scheduledTransferRemainingTotal, + double? scheduledProvisionRemainingTotal, + double? scheduledNetRemainingTotal, + double? projectedMonthBalance, + List? accounts, + List? reconciliationsToday, + }) { + return DashboardData( + month: month ?? this.month, + totalBalance: totalBalance ?? this.totalBalance, + availableAfterReserves: availableAfterReserves ?? this.availableAfterReserves, + monthlyIncome: monthlyIncome ?? this.monthlyIncome, + monthlyExpenses: monthlyExpenses ?? this.monthlyExpenses, + monthlyBalance: monthlyBalance ?? this.monthlyBalance, + provisionsCurrentTotal: provisionsCurrentTotal ?? this.provisionsCurrentTotal, + provisionsTargetTotal: provisionsTargetTotal ?? this.provisionsTargetTotal, + monthlyChargesRemainingTotal: monthlyChargesRemainingTotal ?? this.monthlyChargesRemainingTotal, + monthlyTransferRemainingTotal: monthlyTransferRemainingTotal ?? this.monthlyTransferRemainingTotal, + monthlyProvisionOperationRemainingTotal: monthlyProvisionOperationRemainingTotal ?? this.monthlyProvisionOperationRemainingTotal, + scheduledExpensesRemainingTotal: scheduledExpensesRemainingTotal ?? this.scheduledExpensesRemainingTotal, + scheduledIncomeRemainingTotal: scheduledIncomeRemainingTotal ?? this.scheduledIncomeRemainingTotal, + scheduledTransferRemainingTotal: scheduledTransferRemainingTotal ?? this.scheduledTransferRemainingTotal, + scheduledProvisionRemainingTotal: scheduledProvisionRemainingTotal ?? this.scheduledProvisionRemainingTotal, + scheduledNetRemainingTotal: scheduledNetRemainingTotal ?? this.scheduledNetRemainingTotal, + projectedMonthBalance: projectedMonthBalance ?? this.projectedMonthBalance, + accounts: accounts ?? this.accounts, + reconciliationsToday: reconciliationsToday ?? this.reconciliationsToday, + ); + } +} diff --git a/backup_before_mobile_dashboard_colors_v271/home_screen.dart.bak b/backup_before_mobile_dashboard_colors_v271/home_screen.dart.bak new file mode 100644 index 0000000..f0376aa --- /dev/null +++ b/backup_before_mobile_dashboard_colors_v271/home_screen.dart.bak @@ -0,0 +1,758 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/transaction_item.dart'; +import '../services/sync_service.dart'; +import 'quick_transaction_screen.dart'; +import 'settings_screen.dart'; +import 'sync_screen.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key, required this.syncService}); + + final SyncService syncService; + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + DashboardData? _dashboard; + List _accounts = []; + List _categories = []; + List _transactions = []; + int _pendingCount = 0; + DateTime? _lastSyncAt; + bool _isOnline = false; + bool _loading = true; + bool _syncing = false; + String? _message; + + final _money = NumberFormat.currency(locale: 'fr_FR', symbol: 'MAD ', decimalDigits: 2); + final _date = DateFormat('dd/MM/yyyy HH:mm', 'fr_FR'); + + @override + void initState() { + super.initState(); + _bootstrap(); + } + + Future _bootstrap() async { + try { + final local = await widget.syncService.loadLocalSnapshot( + isOnline: false, + message: 'Données locales chargées.', + ); + _applySnapshot(local, loading: false); + await _synchronize(); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _message = 'Erreur locale : $e'; + }); + } + } + + void _applySnapshot(SyncSnapshot snapshot, {bool? loading}) { + if (!mounted) return; + setState(() { + _dashboard = snapshot.dashboard; + _accounts = snapshot.accounts; + _categories = snapshot.categories; + _transactions = snapshot.transactions; + _pendingCount = snapshot.pendingCount; + _lastSyncAt = snapshot.lastSyncAt; + _isOnline = snapshot.isOnline; + _message = snapshot.message; + if (loading != null) _loading = loading; + }); + } + + Future _synchronize() async { + if (_syncing) return; + + setState(() { + _syncing = true; + _message = 'Synchronisation...'; + }); + + try { + final snapshot = await widget.syncService.synchronize(); + if (!mounted) return; + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Erreur de synchronisation : $e'; + _loading = false; + }); + } finally { + if (mounted) { + setState(() => _syncing = false); + } + } + } + + Future _reloadLocalAfterSave() async { + try { + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: _isOnline + ? 'Opération enregistrée.' + : 'Opération en attente de synchronisation.', + ); + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Opération enregistrée localement, mais rechargement écran échoué : $e'; + _loading = false; + }); + } + } + + Future _openQuickAdd() async { + if (_accounts.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Crée d’abord au moins un compte dans la version web, puis synchronise.')), + ); + return; + } + + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => QuickTransactionScreen( + syncService: widget.syncService, + accounts: _accounts, + categories: _categories, + onSaved: _reloadLocalAfterSave, + ), + ), + ); + } + + +Future _openSyncScreen() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SyncScreen(syncService: widget.syncService), + ), + ); + + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: null, + ); + _applySnapshot(snapshot, loading: false); +} + + Future _openSettings() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsScreen(apiService: widget.syncService.apiService), + ), + ); + await _synchronize(); + } + + @override + Widget build(BuildContext context) { + final dashboard = _dashboard; + + return Scaffold( + appBar: AppBar( + title: const Text('FIN65'), + actions: [ + IconButton( + tooltip: 'Page synchronisation', + onPressed: _openSyncScreen, + icon: Badge( + isLabelVisible: _pendingCount > 0, + label: Text('$_pendingCount'), + child: const Icon(Icons.cloud_sync), + ), + ), + IconButton( + tooltip: 'Synchroniser', + onPressed: _syncing ? null : _synchronize, + icon: _syncing + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + ), + IconButton(onPressed: _openSettings, icon: const Icon(Icons.settings)), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _openQuickAdd, + icon: const Icon(Icons.add), + label: const Text('Ajouter'), + ), + body: RefreshIndicator( + onRefresh: _synchronize, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ + _SyncBanner( + isOnline: _isOnline, + pendingCount: _pendingCount, + lastSyncAt: _lastSyncAt, + formatter: _date, + message: _message, + ), + const SizedBox(height: 12), + if (dashboard != null) ...[ + _DashboardCards( + dashboard: dashboard, + money: _money, + hasPending: _pendingCount > 0, + ), + const SizedBox(height: 16), + ] else + const _EmptyCacheCard(), + _SectionTitle(title: 'Comptes', action: _pendingCount > 0 ? 'Solde estimé' : 'Solde app'), + const SizedBox(height: 8), + if (_accounts.isEmpty) + const Card(child: ListTile(title: Text('Aucun compte en cache. Synchronise avec le backend.'))) + else + ..._accounts.map((a) => _AccountTile(account: a, money: _money)), + const SizedBox(height: 16), + _SectionTitle(title: 'Dernières transactions'), + const SizedBox(height: 8), + if (_transactions.isEmpty) + const Card(child: ListTile(title: Text('Aucune transaction en cache.'))) + else + ..._transactions.map( + (t) => _TransactionTile( + transaction: t, + accounts: _accounts, + categories: _categories, + money: _money, + ), + ), + const SizedBox(height: 90), + ], + ), + ), + ); + } +} + +class _SyncBanner extends StatelessWidget { + const _SyncBanner({ + required this.isOnline, + required this.pendingCount, + required this.lastSyncAt, + required this.formatter, + this.message, + }); + + final bool isOnline; + final int pendingCount; + final DateTime? lastSyncAt; + final DateFormat formatter; + final String? message; + + @override + Widget build(BuildContext context) { + final title = isOnline ? 'Connecté au backend' : 'Mode hors ligne'; + final subtitleParts = []; + + if (lastSyncAt != null) { + subtitleParts.add('Dernière synchro : ${formatter.format(lastSyncAt!.toLocal())}'); + } else { + subtitleParts.add('Aucune synchronisation réussie'); + } + + if (pendingCount > 0) { + subtitleParts.add('$pendingCount opération(s) en attente'); + } + + if (message != null && message!.isNotEmpty) { + subtitleParts.add(message!); + } + + return Card( + child: ListTile( + leading: Icon(isOnline ? Icons.cloud_done : Icons.cloud_off), + title: Text(title), + subtitle: Text(subtitleParts.join('\n')), + ), + ); + } +} + +class _EmptyCacheCard extends StatelessWidget { + const _EmptyCacheCard(); + + @override + Widget build(BuildContext context) { + return const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text( + 'Aucune donnée locale. Lance le backend PC une première fois, configure l’URL API, puis synchronise.', + ), + ), + ); + } +} + +class _DashboardCards extends StatelessWidget { + const _DashboardCards({ + required this.dashboard, + required this.money, + required this.hasPending, + }); + + final DashboardData dashboard; + final NumberFormat money; + final bool hasPending; + + @override + Widget build(BuildContext context) { + final labelSuffix = hasPending ? ' estimé' : ''; + + return Column( + children: [ + _MetricCard( + title: 'Disponible réel$labelSuffix', + value: money.format(dashboard.availableAfterReserves), + icon: Icons.account_balance_wallet, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + const SizedBox(height: 8), + _MetricCard( + title: 'Balance prévisionnelle du mois', + value: money.format(dashboard.projectedMonthBalance), + icon: Icons.insights, + backgroundColor: const Color(0xFFE3F2FD), + accentColor: const Color(0xFF1565C0), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Solde total$labelSuffix', + value: money.format(dashboard.totalBalance), + icon: Icons.savings, + compact: true, + backgroundColor: const Color(0xFFF3E5F5), + accentColor: const Color(0xFF6A1B9A), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Balance réelle', + value: money.format(dashboard.monthlyBalance), + icon: Icons.trending_up, + compact: true, + backgroundColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFFE8F5E9) + : const Color(0xFFFFEBEE), + accentColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFF2E7D32) + : const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Revenus réels', + value: money.format(dashboard.monthlyIncome), + icon: Icons.arrow_downward, + compact: true, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Dépenses réelles', + value: money.format(dashboard.monthlyExpenses), + icon: Icons.arrow_upward, + compact: true, + backgroundColor: const Color(0xFFFFEBEE), + accentColor: const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + _PlannedInfoCard(dashboard: dashboard, money: money), + ], + ); + } +} + +class _PlannedInfoCard extends StatelessWidget { + const _PlannedInfoCard({ + required this.dashboard, + required this.money, + }); + + final DashboardData dashboard; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + final rows = <_InfoRow>[ + _InfoRow( + 'Dépenses prévues restantes', + dashboard.plannedExpensesTotal, + Icons.event_busy, + const Color(0xFFFFEBEE), + const Color(0xFFC62828), + ), + _InfoRow( + 'Revenus prévus échéancier', + dashboard.scheduledIncomeRemainingTotal, + Icons.event_available, + const Color(0xFFE8F5E9), + const Color(0xFF2E7D32), + ), + _InfoRow( + 'Dépenses échéancier', + dashboard.scheduledExpensesRemainingTotal, + Icons.calendar_month, + const Color(0xFFFFF3E0), + const Color(0xFFEF6C00), + ), + _InfoRow( + 'Transferts prévus', + dashboard.plannedTransfersTotal, + Icons.swap_horiz, + const Color(0xFFE3F2FD), + const Color(0xFF1565C0), + ), + _InfoRow( + 'Provisions prévues', + dashboard.plannedProvisionsTotal, + Icons.inventory_2, + const Color(0xFFF3E5F5), + const Color(0xFF6A1B9A), + ), + ]; + + return Card( + color: const Color(0xFFFAFAFA), + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: const Color(0xFFE3F2FD), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.event_note, color: Color(0xFF1565C0)), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Prévisionnel du mois', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w800, + ), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Inclut les opérations mensuelles et l’échéancier ponctuel du backend.', + style: Theme.of(context).textTheme.bodySmall, + ), + const Divider(height: 20), + ...rows.map( + (row) => Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9), + decoration: BoxDecoration( + color: row.backgroundColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: row.accentColor.withOpacity(0.22)), + ), + child: Row( + children: [ + Icon(row.icon, size: 20, color: row.accentColor), + const SizedBox(width: 10), + Expanded( + child: Text( + row.label, + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w700, + ), + ), + ), + Text( + money.format(row.value), + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _InfoRow { + const _InfoRow( + this.label, + this.value, + this.icon, + this.backgroundColor, + this.accentColor, + ); + + final String label; + final double value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; +} + +class _MetricCard extends StatelessWidget { + const _MetricCard({ + required this.title, + required this.value, + required this.icon, + required this.backgroundColor, + required this.accentColor, + this.compact = false, + }); + + final String title; + final String value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; + final bool compact; + + @override + Widget build(BuildContext context) { + return Card( + color: backgroundColor, + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: EdgeInsets.all(compact ? 12 : 16), + child: Row( + children: [ + Container( + width: compact ? 34 : 42, + height: compact ? 34 : 42, + decoration: BoxDecoration( + color: accentColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, size: compact ? 21 : 27, color: accentColor), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: accentColor, + fontWeight: FontWeight.w700, + ), + ), + Text( + value, + style: (compact + ? Theme.of(context).textTheme.titleMedium + : Theme.of(context).textTheme.headlineSmall) + ?.copyWith( + color: accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _MetricCard extends StatelessWidget { + const _MetricCard({ + required this.title, + required this.value, + required this.icon, + this.compact = false, + }); + + final String title; + final String value; + final IconData icon; + final bool compact; + + @override + Widget build(BuildContext context) { + return Card( + child: Padding( + padding: EdgeInsets.all(compact ? 12 : 16), + child: Row( + children: [ + Icon(icon, size: compact ? 24 : 32), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: Theme.of(context).textTheme.bodySmall), + Text( + value, + style: compact + ? Theme.of(context).textTheme.titleMedium + : Theme.of(context).textTheme.headlineSmall, + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle({required this.title, this.action}); + + final String title; + final String? action; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(title, style: Theme.of(context).textTheme.titleLarge), + const Spacer(), + if (action != null) Text(action!, style: Theme.of(context).textTheme.bodySmall), + ], + ); + } +} + +class _AccountTile extends StatelessWidget { + const _AccountTile({required this.account, required this.money}); + + final Account account; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.account_balance), + title: Text(account.name), + subtitle: Text(account.type), + trailing: Text( + money.format(account.appBalance), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} + +class _TransactionTile extends StatelessWidget { + const _TransactionTile({ + required this.transaction, + required this.accounts, + required this.categories, + required this.money, + }); + + final TransactionItem transaction; + final List accounts; + final List categories; + final NumberFormat money; + + Account? _findAccount(int? id) { + if (id == null) return null; + for (final account in accounts) { + if (account.id == id) return account; + } + return null; + } + + Category? _findCategory(int? id) { + if (id == null) return null; + for (final category in categories) { + if (category.id == id) return category; + } + return null; + } + + @override + Widget build(BuildContext context) { + final account = _findAccount(transaction.accountId); + final target = _findAccount(transaction.targetAccountId); + final category = _findCategory(transaction.categoryId); + + final typeLabel = switch (transaction.type) { + 'expense' => 'Dépense', + 'income' => 'Recette', + 'transfer' => 'Transfert', + _ => transaction.type, + }; + + final accountLabel = transaction.type == 'transfer' + ? '${account?.name ?? transaction.accountId} → ${target?.name ?? transaction.targetAccountId}' + : account?.name ?? 'Compte ${transaction.accountId}'; + + return Card( + child: ListTile( + leading: Icon(transaction.isPending ? Icons.schedule_send : Icons.receipt_long), + title: Text(transaction.label), + subtitle: Text( + '${transaction.isPending ? 'EN ATTENTE • ' : ''}$typeLabel • $accountLabel${category == null ? '' : ' • ${category.name}'}', + ), + trailing: Text( + money.format(transaction.amount), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} diff --git a/backup_before_mobile_dashboard_colors_v272/dashboard.dart.bak b/backup_before_mobile_dashboard_colors_v272/dashboard.dart.bak new file mode 100644 index 0000000..6a6a3f2 --- /dev/null +++ b/backup_before_mobile_dashboard_colors_v272/dashboard.dart.bak @@ -0,0 +1,223 @@ +import 'account.dart'; + +class ReconciliationStatus { + final int accountId; + final String accountName; + final double appBalance; + final bool checkedToday; + final double? realBalance; + final double? difference; + + ReconciliationStatus({ + required this.accountId, + required this.accountName, + required this.appBalance, + required this.checkedToday, + this.realBalance, + this.difference, + }); + + factory ReconciliationStatus.fromJson(Map json) { + return ReconciliationStatus( + accountId: json['account_id'] as int, + accountName: json['account_name'] as String, + appBalance: (json['app_balance'] as num? ?? 0).toDouble(), + checkedToday: json['checked_today'] is int + ? (json['checked_today'] as int) == 1 + : json['checked_today'] as bool? ?? false, + realBalance: (json['real_balance'] as num?)?.toDouble(), + difference: (json['difference'] as num?)?.toDouble(), + ); + } + + Map toJson() { + return { + 'account_id': accountId, + 'account_name': accountName, + 'app_balance': appBalance, + 'checked_today': checkedToday, + 'real_balance': realBalance, + 'difference': difference, + }; + } + + ReconciliationStatus copyWith({ + double? appBalance, + bool? checkedToday, + double? realBalance, + double? difference, + }) { + return ReconciliationStatus( + accountId: accountId, + accountName: accountName, + appBalance: appBalance ?? this.appBalance, + checkedToday: checkedToday ?? this.checkedToday, + realBalance: realBalance ?? this.realBalance, + difference: difference ?? this.difference, + ); + } +} + +class DashboardData { + final String month; + final double totalBalance; + final double availableAfterReserves; + final double monthlyIncome; + final double monthlyExpenses; + final double monthlyBalance; + final double provisionsCurrentTotal; + final double provisionsTargetTotal; + final double monthlyChargesRemainingTotal; + final double monthlyTransferRemainingTotal; + final double monthlyProvisionOperationRemainingTotal; + + // Nouveaux champs backend : échéancier / opérations prévues ponctuelles. + final double scheduledExpensesRemainingTotal; + final double scheduledIncomeRemainingTotal; + final double scheduledTransferRemainingTotal; + final double scheduledProvisionRemainingTotal; + final double scheduledNetRemainingTotal; + final double projectedMonthBalance; + + final List accounts; + final List reconciliationsToday; + + DashboardData({ + required this.month, + required this.totalBalance, + required this.availableAfterReserves, + required this.monthlyIncome, + required this.monthlyExpenses, + required this.monthlyBalance, + required this.provisionsCurrentTotal, + required this.provisionsTargetTotal, + required this.monthlyChargesRemainingTotal, + required this.monthlyTransferRemainingTotal, + required this.monthlyProvisionOperationRemainingTotal, + required this.scheduledExpensesRemainingTotal, + required this.scheduledIncomeRemainingTotal, + required this.scheduledTransferRemainingTotal, + required this.scheduledProvisionRemainingTotal, + required this.scheduledNetRemainingTotal, + required this.projectedMonthBalance, + required this.accounts, + required this.reconciliationsToday, + }); + + double get plannedExpensesTotal => + monthlyChargesRemainingTotal + scheduledExpensesRemainingTotal; + + double get plannedTransfersTotal => + monthlyTransferRemainingTotal + scheduledTransferRemainingTotal; + + double get plannedProvisionsTotal => + monthlyProvisionOperationRemainingTotal + scheduledProvisionRemainingTotal; + + bool get hasScheduledInfo => + scheduledExpensesRemainingTotal != 0 || + scheduledIncomeRemainingTotal != 0 || + scheduledTransferRemainingTotal != 0 || + scheduledProvisionRemainingTotal != 0; + + factory DashboardData.fromJson(Map json) { + final availableRaw = json['available_after_reserves'] ?? json['total_balance'] ?? 0; + + final monthlyBalance = (json['monthly_balance'] as num? ?? 0).toDouble(); + final scheduledIncome = (json['scheduled_income_remaining_total'] as num? ?? 0).toDouble(); + final scheduledExpenses = (json['scheduled_expenses_remaining_total'] as num? ?? 0).toDouble(); + + return DashboardData( + month: json['month'] as String? ?? '', + totalBalance: (json['total_balance'] as num? ?? 0).toDouble(), + availableAfterReserves: (availableRaw as num).toDouble(), + monthlyIncome: (json['monthly_income'] as num? ?? 0).toDouble(), + monthlyExpenses: (json['monthly_expenses'] as num? ?? 0).toDouble(), + monthlyBalance: monthlyBalance, + provisionsCurrentTotal: (json['provisions_current_total'] as num? ?? 0).toDouble(), + provisionsTargetTotal: (json['provisions_target_total'] as num? ?? 0).toDouble(), + monthlyChargesRemainingTotal: (json['monthly_charges_remaining_total'] as num? ?? 0).toDouble(), + monthlyTransferRemainingTotal: (json['monthly_transfer_remaining_total'] as num? ?? 0).toDouble(), + monthlyProvisionOperationRemainingTotal: (json['monthly_provision_operation_remaining_total'] as num? ?? 0).toDouble(), + scheduledExpensesRemainingTotal: scheduledExpenses, + scheduledIncomeRemainingTotal: scheduledIncome, + scheduledTransferRemainingTotal: (json['scheduled_transfer_remaining_total'] as num? ?? 0).toDouble(), + scheduledProvisionRemainingTotal: (json['scheduled_provision_remaining_total'] as num? ?? 0).toDouble(), + scheduledNetRemainingTotal: (json['scheduled_net_remaining_total'] as num? ?? (scheduledIncome - scheduledExpenses)).toDouble(), + projectedMonthBalance: (json['projected_month_balance'] as num? ?? (monthlyBalance + scheduledIncome - scheduledExpenses)).toDouble(), + accounts: (json['accounts'] as List? ?? []) + .map((e) => Account.fromJson(e as Map)) + .toList(), + reconciliationsToday: (json['reconciliations_today'] as List? ?? []) + .map((e) => ReconciliationStatus.fromJson(e as Map)) + .toList(), + ); + } + + Map toJson() { + return { + 'month': month, + 'total_balance': totalBalance, + 'available_after_reserves': availableAfterReserves, + 'monthly_income': monthlyIncome, + 'monthly_expenses': monthlyExpenses, + 'monthly_balance': monthlyBalance, + 'provisions_current_total': provisionsCurrentTotal, + 'provisions_target_total': provisionsTargetTotal, + 'monthly_charges_remaining_total': monthlyChargesRemainingTotal, + 'monthly_transfer_remaining_total': monthlyTransferRemainingTotal, + 'monthly_provision_operation_remaining_total': monthlyProvisionOperationRemainingTotal, + 'scheduled_expenses_remaining_total': scheduledExpensesRemainingTotal, + 'scheduled_income_remaining_total': scheduledIncomeRemainingTotal, + 'scheduled_transfer_remaining_total': scheduledTransferRemainingTotal, + 'scheduled_provision_remaining_total': scheduledProvisionRemainingTotal, + 'scheduled_net_remaining_total': scheduledNetRemainingTotal, + 'projected_month_balance': projectedMonthBalance, + 'accounts': accounts.map((e) => e.toJson()).toList(), + 'reconciliations_today': reconciliationsToday.map((e) => e.toJson()).toList(), + }; + } + + DashboardData copyWith({ + String? month, + double? totalBalance, + double? availableAfterReserves, + double? monthlyIncome, + double? monthlyExpenses, + double? monthlyBalance, + double? provisionsCurrentTotal, + double? provisionsTargetTotal, + double? monthlyChargesRemainingTotal, + double? monthlyTransferRemainingTotal, + double? monthlyProvisionOperationRemainingTotal, + double? scheduledExpensesRemainingTotal, + double? scheduledIncomeRemainingTotal, + double? scheduledTransferRemainingTotal, + double? scheduledProvisionRemainingTotal, + double? scheduledNetRemainingTotal, + double? projectedMonthBalance, + List? accounts, + List? reconciliationsToday, + }) { + return DashboardData( + month: month ?? this.month, + totalBalance: totalBalance ?? this.totalBalance, + availableAfterReserves: availableAfterReserves ?? this.availableAfterReserves, + monthlyIncome: monthlyIncome ?? this.monthlyIncome, + monthlyExpenses: monthlyExpenses ?? this.monthlyExpenses, + monthlyBalance: monthlyBalance ?? this.monthlyBalance, + provisionsCurrentTotal: provisionsCurrentTotal ?? this.provisionsCurrentTotal, + provisionsTargetTotal: provisionsTargetTotal ?? this.provisionsTargetTotal, + monthlyChargesRemainingTotal: monthlyChargesRemainingTotal ?? this.monthlyChargesRemainingTotal, + monthlyTransferRemainingTotal: monthlyTransferRemainingTotal ?? this.monthlyTransferRemainingTotal, + monthlyProvisionOperationRemainingTotal: monthlyProvisionOperationRemainingTotal ?? this.monthlyProvisionOperationRemainingTotal, + scheduledExpensesRemainingTotal: scheduledExpensesRemainingTotal ?? this.scheduledExpensesRemainingTotal, + scheduledIncomeRemainingTotal: scheduledIncomeRemainingTotal ?? this.scheduledIncomeRemainingTotal, + scheduledTransferRemainingTotal: scheduledTransferRemainingTotal ?? this.scheduledTransferRemainingTotal, + scheduledProvisionRemainingTotal: scheduledProvisionRemainingTotal ?? this.scheduledProvisionRemainingTotal, + scheduledNetRemainingTotal: scheduledNetRemainingTotal ?? this.scheduledNetRemainingTotal, + projectedMonthBalance: projectedMonthBalance ?? this.projectedMonthBalance, + accounts: accounts ?? this.accounts, + reconciliationsToday: reconciliationsToday ?? this.reconciliationsToday, + ); + } +} diff --git a/backup_before_mobile_dashboard_colors_v272/home_screen.dart.bak b/backup_before_mobile_dashboard_colors_v272/home_screen.dart.bak new file mode 100644 index 0000000..b1176d0 --- /dev/null +++ b/backup_before_mobile_dashboard_colors_v272/home_screen.dart.bak @@ -0,0 +1,715 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/transaction_item.dart'; +import '../services/sync_service.dart'; +import 'quick_transaction_screen.dart'; +import 'settings_screen.dart'; +import 'sync_screen.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key, required this.syncService}); + + final SyncService syncService; + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + DashboardData? _dashboard; + List _accounts = []; + List _categories = []; + List _transactions = []; + int _pendingCount = 0; + DateTime? _lastSyncAt; + bool _isOnline = false; + bool _loading = true; + bool _syncing = false; + String? _message; + + final _money = NumberFormat.currency(locale: 'fr_FR', symbol: 'MAD ', decimalDigits: 2); + final _date = DateFormat('dd/MM/yyyy HH:mm', 'fr_FR'); + + @override + void initState() { + super.initState(); + _bootstrap(); + } + + Future _bootstrap() async { + try { + final local = await widget.syncService.loadLocalSnapshot( + isOnline: false, + message: 'Données locales chargées.', + ); + _applySnapshot(local, loading: false); + await _synchronize(); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _message = 'Erreur locale : $e'; + }); + } + } + + void _applySnapshot(SyncSnapshot snapshot, {bool? loading}) { + if (!mounted) return; + setState(() { + _dashboard = snapshot.dashboard; + _accounts = snapshot.accounts; + _categories = snapshot.categories; + _transactions = snapshot.transactions; + _pendingCount = snapshot.pendingCount; + _lastSyncAt = snapshot.lastSyncAt; + _isOnline = snapshot.isOnline; + _message = snapshot.message; + if (loading != null) _loading = loading; + }); + } + + Future _synchronize() async { + if (_syncing) return; + + setState(() { + _syncing = true; + _message = 'Synchronisation...'; + }); + + try { + final snapshot = await widget.syncService.synchronize(); + if (!mounted) return; + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Erreur de synchronisation : $e'; + _loading = false; + }); + } finally { + if (mounted) { + setState(() => _syncing = false); + } + } + } + + Future _reloadLocalAfterSave() async { + try { + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: _isOnline + ? 'Opération enregistrée.' + : 'Opération en attente de synchronisation.', + ); + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Opération enregistrée localement, mais rechargement écran échoué : $e'; + _loading = false; + }); + } + } + + Future _openQuickAdd() async { + if (_accounts.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Crée d’abord au moins un compte dans la version web, puis synchronise.')), + ); + return; + } + + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => QuickTransactionScreen( + syncService: widget.syncService, + accounts: _accounts, + categories: _categories, + onSaved: _reloadLocalAfterSave, + ), + ), + ); + } + + +Future _openSyncScreen() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SyncScreen(syncService: widget.syncService), + ), + ); + + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: null, + ); + _applySnapshot(snapshot, loading: false); +} + + Future _openSettings() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsScreen(apiService: widget.syncService.apiService), + ), + ); + await _synchronize(); + } + + @override + Widget build(BuildContext context) { + final dashboard = _dashboard; + + return Scaffold( + appBar: AppBar( + title: const Text('FIN65'), + actions: [ + IconButton( + tooltip: 'Page synchronisation', + onPressed: _openSyncScreen, + icon: Badge( + isLabelVisible: _pendingCount > 0, + label: Text('$_pendingCount'), + child: const Icon(Icons.cloud_sync), + ), + ), + IconButton( + tooltip: 'Synchroniser', + onPressed: _syncing ? null : _synchronize, + icon: _syncing + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + ), + IconButton(onPressed: _openSettings, icon: const Icon(Icons.settings)), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _openQuickAdd, + icon: const Icon(Icons.add), + label: const Text('Ajouter'), + ), + body: RefreshIndicator( + onRefresh: _synchronize, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ + _SyncBanner( + isOnline: _isOnline, + pendingCount: _pendingCount, + lastSyncAt: _lastSyncAt, + formatter: _date, + message: _message, + ), + const SizedBox(height: 12), + if (dashboard != null) ...[ + _DashboardCards( + dashboard: dashboard, + money: _money, + hasPending: _pendingCount > 0, + ), + const SizedBox(height: 16), + ] else + const _EmptyCacheCard(), + _SectionTitle(title: 'Comptes', action: _pendingCount > 0 ? 'Solde estimé' : 'Solde app'), + const SizedBox(height: 8), + if (_accounts.isEmpty) + const Card(child: ListTile(title: Text('Aucun compte en cache. Synchronise avec le backend.'))) + else + ..._accounts.map((a) => _AccountTile(account: a, money: _money)), + const SizedBox(height: 16), + _SectionTitle(title: 'Dernières transactions'), + const SizedBox(height: 8), + if (_transactions.isEmpty) + const Card(child: ListTile(title: Text('Aucune transaction en cache.'))) + else + ..._transactions.map( + (t) => _TransactionTile( + transaction: t, + accounts: _accounts, + categories: _categories, + money: _money, + ), + ), + const SizedBox(height: 90), + ], + ), + ), + ); + } +} + +class _SyncBanner extends StatelessWidget { + const _SyncBanner({ + required this.isOnline, + required this.pendingCount, + required this.lastSyncAt, + required this.formatter, + this.message, + }); + + final bool isOnline; + final int pendingCount; + final DateTime? lastSyncAt; + final DateFormat formatter; + final String? message; + + @override + Widget build(BuildContext context) { + final title = isOnline ? 'Connecté au backend' : 'Mode hors ligne'; + final subtitleParts = []; + + if (lastSyncAt != null) { + subtitleParts.add('Dernière synchro : ${formatter.format(lastSyncAt!.toLocal())}'); + } else { + subtitleParts.add('Aucune synchronisation réussie'); + } + + if (pendingCount > 0) { + subtitleParts.add('$pendingCount opération(s) en attente'); + } + + if (message != null && message!.isNotEmpty) { + subtitleParts.add(message!); + } + + return Card( + child: ListTile( + leading: Icon(isOnline ? Icons.cloud_done : Icons.cloud_off), + title: Text(title), + subtitle: Text(subtitleParts.join('\n')), + ), + ); + } +} + +class _EmptyCacheCard extends StatelessWidget { + const _EmptyCacheCard(); + + @override + Widget build(BuildContext context) { + return const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text( + 'Aucune donnée locale. Lance le backend PC une première fois, configure l’URL API, puis synchronise.', + ), + ), + ); + } +} + +class _DashboardCards extends StatelessWidget { + const _DashboardCards({ + required this.dashboard, + required this.money, + required this.hasPending, + }); + + final DashboardData dashboard; + final NumberFormat money; + final bool hasPending; + + @override + Widget build(BuildContext context) { + final labelSuffix = hasPending ? ' estimé' : ''; + + return Column( + children: [ + _MetricCard( + title: 'Disponible réel$labelSuffix', + value: money.format(dashboard.availableAfterReserves), + icon: Icons.account_balance_wallet, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + const SizedBox(height: 8), + _MetricCard( + title: 'Balance prévisionnelle du mois', + value: money.format(dashboard.projectedMonthBalance), + icon: Icons.insights, + backgroundColor: const Color(0xFFE3F2FD), + accentColor: const Color(0xFF1565C0), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Solde total$labelSuffix', + value: money.format(dashboard.totalBalance), + icon: Icons.savings, + compact: true, + backgroundColor: const Color(0xFFF3E5F5), + accentColor: const Color(0xFF6A1B9A), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Balance réelle', + value: money.format(dashboard.monthlyBalance), + icon: Icons.trending_up, + compact: true, + backgroundColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFFE8F5E9) + : const Color(0xFFFFEBEE), + accentColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFF2E7D32) + : const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Revenus réels', + value: money.format(dashboard.monthlyIncome), + icon: Icons.arrow_downward, + compact: true, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Dépenses réelles', + value: money.format(dashboard.monthlyExpenses), + icon: Icons.arrow_upward, + compact: true, + backgroundColor: const Color(0xFFFFEBEE), + accentColor: const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + _PlannedInfoCard(dashboard: dashboard, money: money), + ], + ); + } +} + +class _PlannedInfoCard extends StatelessWidget { + const _PlannedInfoCard({ + required this.dashboard, + required this.money, + }); + + final DashboardData dashboard; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + final rows = <_InfoRow>[ + _InfoRow( + 'Dépenses prévues restantes', + dashboard.plannedExpensesTotal, + Icons.event_busy, + const Color(0xFFFFEBEE), + const Color(0xFFC62828), + ), + _InfoRow( + 'Revenus prévus échéancier', + dashboard.scheduledIncomeRemainingTotal, + Icons.event_available, + const Color(0xFFE8F5E9), + const Color(0xFF2E7D32), + ), + _InfoRow( + 'Dépenses échéancier', + dashboard.scheduledExpensesRemainingTotal, + Icons.calendar_month, + const Color(0xFFFFF3E0), + const Color(0xFFEF6C00), + ), + _InfoRow( + 'Transferts prévus', + dashboard.plannedTransfersTotal, + Icons.swap_horiz, + const Color(0xFFE3F2FD), + const Color(0xFF1565C0), + ), + _InfoRow( + 'Provisions prévues', + dashboard.plannedProvisionsTotal, + Icons.inventory_2, + const Color(0xFFF3E5F5), + const Color(0xFF6A1B9A), + ), + ]; + + return Card( + color: const Color(0xFFFAFAFA), + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: const Color(0xFFE3F2FD), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.event_note, color: Color(0xFF1565C0)), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Prévisionnel du mois', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w800, + ), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Inclut les opérations mensuelles et l’échéancier ponctuel du backend.', + style: Theme.of(context).textTheme.bodySmall, + ), + const Divider(height: 20), + ...rows.map( + (row) => Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9), + decoration: BoxDecoration( + color: row.backgroundColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: row.accentColor.withOpacity(0.22)), + ), + child: Row( + children: [ + Icon(row.icon, size: 20, color: row.accentColor), + const SizedBox(width: 10), + Expanded( + child: Text( + row.label, + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w700, + ), + ), + ), + Text( + money.format(row.value), + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _InfoRow { + const _InfoRow( + this.label, + this.value, + this.icon, + this.backgroundColor, + this.accentColor, + ); + + final String label; + final double value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; +} + +class _MetricCard extends StatelessWidget { + const _MetricCard({ + required this.title, + required this.value, + required this.icon, + required this.backgroundColor, + required this.accentColor, + this.compact = false, + }); + + final String title; + final String value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; + final bool compact; + + @override + Widget build(BuildContext context) { + return Card( + color: backgroundColor, + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: EdgeInsets.all(compact ? 12 : 16), + child: Row( + children: [ + Container( + width: compact ? 34 : 42, + height: compact ? 34 : 42, + decoration: BoxDecoration( + color: accentColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, size: compact ? 21 : 27, color: accentColor), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: accentColor, + fontWeight: FontWeight.w700, + ), + ), + Text( + value, + style: (compact + ? Theme.of(context).textTheme.titleMedium + : Theme.of(context).textTheme.headlineSmall) + ?.copyWith( + color: accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle({required this.title, this.action}); + + final String title; + final String? action; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(title, style: Theme.of(context).textTheme.titleLarge), + const Spacer(), + if (action != null) Text(action!, style: Theme.of(context).textTheme.bodySmall), + ], + ); + } +} + +class _AccountTile extends StatelessWidget { + const _AccountTile({required this.account, required this.money}); + + final Account account; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.account_balance), + title: Text(account.name), + subtitle: Text(account.type), + trailing: Text( + money.format(account.appBalance), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} + +class _TransactionTile extends StatelessWidget { + const _TransactionTile({ + required this.transaction, + required this.accounts, + required this.categories, + required this.money, + }); + + final TransactionItem transaction; + final List accounts; + final List categories; + final NumberFormat money; + + Account? _findAccount(int? id) { + if (id == null) return null; + for (final account in accounts) { + if (account.id == id) return account; + } + return null; + } + + Category? _findCategory(int? id) { + if (id == null) return null; + for (final category in categories) { + if (category.id == id) return category; + } + return null; + } + + @override + Widget build(BuildContext context) { + final account = _findAccount(transaction.accountId); + final target = _findAccount(transaction.targetAccountId); + final category = _findCategory(transaction.categoryId); + + final typeLabel = switch (transaction.type) { + 'expense' => 'Dépense', + 'income' => 'Recette', + 'transfer' => 'Transfert', + _ => transaction.type, + }; + + final accountLabel = transaction.type == 'transfer' + ? '${account?.name ?? transaction.accountId} → ${target?.name ?? transaction.targetAccountId}' + : account?.name ?? 'Compte ${transaction.accountId}'; + + return Card( + child: ListTile( + leading: Icon(transaction.isPending ? Icons.schedule_send : Icons.receipt_long), + title: Text(transaction.label), + subtitle: Text( + '${transaction.isPending ? 'EN ATTENTE • ' : ''}$typeLabel • $accountLabel${category == null ? '' : ' • ${category.name}'}', + ), + trailing: Text( + money.format(transaction.amount), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} diff --git a/backup_before_mobile_dashboard_scheduled_v27/dashboard.dart.bak b/backup_before_mobile_dashboard_scheduled_v27/dashboard.dart.bak new file mode 100644 index 0000000..6a6a3f2 --- /dev/null +++ b/backup_before_mobile_dashboard_scheduled_v27/dashboard.dart.bak @@ -0,0 +1,223 @@ +import 'account.dart'; + +class ReconciliationStatus { + final int accountId; + final String accountName; + final double appBalance; + final bool checkedToday; + final double? realBalance; + final double? difference; + + ReconciliationStatus({ + required this.accountId, + required this.accountName, + required this.appBalance, + required this.checkedToday, + this.realBalance, + this.difference, + }); + + factory ReconciliationStatus.fromJson(Map json) { + return ReconciliationStatus( + accountId: json['account_id'] as int, + accountName: json['account_name'] as String, + appBalance: (json['app_balance'] as num? ?? 0).toDouble(), + checkedToday: json['checked_today'] is int + ? (json['checked_today'] as int) == 1 + : json['checked_today'] as bool? ?? false, + realBalance: (json['real_balance'] as num?)?.toDouble(), + difference: (json['difference'] as num?)?.toDouble(), + ); + } + + Map toJson() { + return { + 'account_id': accountId, + 'account_name': accountName, + 'app_balance': appBalance, + 'checked_today': checkedToday, + 'real_balance': realBalance, + 'difference': difference, + }; + } + + ReconciliationStatus copyWith({ + double? appBalance, + bool? checkedToday, + double? realBalance, + double? difference, + }) { + return ReconciliationStatus( + accountId: accountId, + accountName: accountName, + appBalance: appBalance ?? this.appBalance, + checkedToday: checkedToday ?? this.checkedToday, + realBalance: realBalance ?? this.realBalance, + difference: difference ?? this.difference, + ); + } +} + +class DashboardData { + final String month; + final double totalBalance; + final double availableAfterReserves; + final double monthlyIncome; + final double monthlyExpenses; + final double monthlyBalance; + final double provisionsCurrentTotal; + final double provisionsTargetTotal; + final double monthlyChargesRemainingTotal; + final double monthlyTransferRemainingTotal; + final double monthlyProvisionOperationRemainingTotal; + + // Nouveaux champs backend : échéancier / opérations prévues ponctuelles. + final double scheduledExpensesRemainingTotal; + final double scheduledIncomeRemainingTotal; + final double scheduledTransferRemainingTotal; + final double scheduledProvisionRemainingTotal; + final double scheduledNetRemainingTotal; + final double projectedMonthBalance; + + final List accounts; + final List reconciliationsToday; + + DashboardData({ + required this.month, + required this.totalBalance, + required this.availableAfterReserves, + required this.monthlyIncome, + required this.monthlyExpenses, + required this.monthlyBalance, + required this.provisionsCurrentTotal, + required this.provisionsTargetTotal, + required this.monthlyChargesRemainingTotal, + required this.monthlyTransferRemainingTotal, + required this.monthlyProvisionOperationRemainingTotal, + required this.scheduledExpensesRemainingTotal, + required this.scheduledIncomeRemainingTotal, + required this.scheduledTransferRemainingTotal, + required this.scheduledProvisionRemainingTotal, + required this.scheduledNetRemainingTotal, + required this.projectedMonthBalance, + required this.accounts, + required this.reconciliationsToday, + }); + + double get plannedExpensesTotal => + monthlyChargesRemainingTotal + scheduledExpensesRemainingTotal; + + double get plannedTransfersTotal => + monthlyTransferRemainingTotal + scheduledTransferRemainingTotal; + + double get plannedProvisionsTotal => + monthlyProvisionOperationRemainingTotal + scheduledProvisionRemainingTotal; + + bool get hasScheduledInfo => + scheduledExpensesRemainingTotal != 0 || + scheduledIncomeRemainingTotal != 0 || + scheduledTransferRemainingTotal != 0 || + scheduledProvisionRemainingTotal != 0; + + factory DashboardData.fromJson(Map json) { + final availableRaw = json['available_after_reserves'] ?? json['total_balance'] ?? 0; + + final monthlyBalance = (json['monthly_balance'] as num? ?? 0).toDouble(); + final scheduledIncome = (json['scheduled_income_remaining_total'] as num? ?? 0).toDouble(); + final scheduledExpenses = (json['scheduled_expenses_remaining_total'] as num? ?? 0).toDouble(); + + return DashboardData( + month: json['month'] as String? ?? '', + totalBalance: (json['total_balance'] as num? ?? 0).toDouble(), + availableAfterReserves: (availableRaw as num).toDouble(), + monthlyIncome: (json['monthly_income'] as num? ?? 0).toDouble(), + monthlyExpenses: (json['monthly_expenses'] as num? ?? 0).toDouble(), + monthlyBalance: monthlyBalance, + provisionsCurrentTotal: (json['provisions_current_total'] as num? ?? 0).toDouble(), + provisionsTargetTotal: (json['provisions_target_total'] as num? ?? 0).toDouble(), + monthlyChargesRemainingTotal: (json['monthly_charges_remaining_total'] as num? ?? 0).toDouble(), + monthlyTransferRemainingTotal: (json['monthly_transfer_remaining_total'] as num? ?? 0).toDouble(), + monthlyProvisionOperationRemainingTotal: (json['monthly_provision_operation_remaining_total'] as num? ?? 0).toDouble(), + scheduledExpensesRemainingTotal: scheduledExpenses, + scheduledIncomeRemainingTotal: scheduledIncome, + scheduledTransferRemainingTotal: (json['scheduled_transfer_remaining_total'] as num? ?? 0).toDouble(), + scheduledProvisionRemainingTotal: (json['scheduled_provision_remaining_total'] as num? ?? 0).toDouble(), + scheduledNetRemainingTotal: (json['scheduled_net_remaining_total'] as num? ?? (scheduledIncome - scheduledExpenses)).toDouble(), + projectedMonthBalance: (json['projected_month_balance'] as num? ?? (monthlyBalance + scheduledIncome - scheduledExpenses)).toDouble(), + accounts: (json['accounts'] as List? ?? []) + .map((e) => Account.fromJson(e as Map)) + .toList(), + reconciliationsToday: (json['reconciliations_today'] as List? ?? []) + .map((e) => ReconciliationStatus.fromJson(e as Map)) + .toList(), + ); + } + + Map toJson() { + return { + 'month': month, + 'total_balance': totalBalance, + 'available_after_reserves': availableAfterReserves, + 'monthly_income': monthlyIncome, + 'monthly_expenses': monthlyExpenses, + 'monthly_balance': monthlyBalance, + 'provisions_current_total': provisionsCurrentTotal, + 'provisions_target_total': provisionsTargetTotal, + 'monthly_charges_remaining_total': monthlyChargesRemainingTotal, + 'monthly_transfer_remaining_total': monthlyTransferRemainingTotal, + 'monthly_provision_operation_remaining_total': monthlyProvisionOperationRemainingTotal, + 'scheduled_expenses_remaining_total': scheduledExpensesRemainingTotal, + 'scheduled_income_remaining_total': scheduledIncomeRemainingTotal, + 'scheduled_transfer_remaining_total': scheduledTransferRemainingTotal, + 'scheduled_provision_remaining_total': scheduledProvisionRemainingTotal, + 'scheduled_net_remaining_total': scheduledNetRemainingTotal, + 'projected_month_balance': projectedMonthBalance, + 'accounts': accounts.map((e) => e.toJson()).toList(), + 'reconciliations_today': reconciliationsToday.map((e) => e.toJson()).toList(), + }; + } + + DashboardData copyWith({ + String? month, + double? totalBalance, + double? availableAfterReserves, + double? monthlyIncome, + double? monthlyExpenses, + double? monthlyBalance, + double? provisionsCurrentTotal, + double? provisionsTargetTotal, + double? monthlyChargesRemainingTotal, + double? monthlyTransferRemainingTotal, + double? monthlyProvisionOperationRemainingTotal, + double? scheduledExpensesRemainingTotal, + double? scheduledIncomeRemainingTotal, + double? scheduledTransferRemainingTotal, + double? scheduledProvisionRemainingTotal, + double? scheduledNetRemainingTotal, + double? projectedMonthBalance, + List? accounts, + List? reconciliationsToday, + }) { + return DashboardData( + month: month ?? this.month, + totalBalance: totalBalance ?? this.totalBalance, + availableAfterReserves: availableAfterReserves ?? this.availableAfterReserves, + monthlyIncome: monthlyIncome ?? this.monthlyIncome, + monthlyExpenses: monthlyExpenses ?? this.monthlyExpenses, + monthlyBalance: monthlyBalance ?? this.monthlyBalance, + provisionsCurrentTotal: provisionsCurrentTotal ?? this.provisionsCurrentTotal, + provisionsTargetTotal: provisionsTargetTotal ?? this.provisionsTargetTotal, + monthlyChargesRemainingTotal: monthlyChargesRemainingTotal ?? this.monthlyChargesRemainingTotal, + monthlyTransferRemainingTotal: monthlyTransferRemainingTotal ?? this.monthlyTransferRemainingTotal, + monthlyProvisionOperationRemainingTotal: monthlyProvisionOperationRemainingTotal ?? this.monthlyProvisionOperationRemainingTotal, + scheduledExpensesRemainingTotal: scheduledExpensesRemainingTotal ?? this.scheduledExpensesRemainingTotal, + scheduledIncomeRemainingTotal: scheduledIncomeRemainingTotal ?? this.scheduledIncomeRemainingTotal, + scheduledTransferRemainingTotal: scheduledTransferRemainingTotal ?? this.scheduledTransferRemainingTotal, + scheduledProvisionRemainingTotal: scheduledProvisionRemainingTotal ?? this.scheduledProvisionRemainingTotal, + scheduledNetRemainingTotal: scheduledNetRemainingTotal ?? this.scheduledNetRemainingTotal, + projectedMonthBalance: projectedMonthBalance ?? this.projectedMonthBalance, + accounts: accounts ?? this.accounts, + reconciliationsToday: reconciliationsToday ?? this.reconciliationsToday, + ); + } +} diff --git a/backup_before_mobile_dashboard_scheduled_v27/home_screen.dart.bak b/backup_before_mobile_dashboard_scheduled_v27/home_screen.dart.bak new file mode 100644 index 0000000..cbd116c --- /dev/null +++ b/backup_before_mobile_dashboard_scheduled_v27/home_screen.dart.bak @@ -0,0 +1,603 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/transaction_item.dart'; +import '../services/sync_service.dart'; +import 'quick_transaction_screen.dart'; +import 'settings_screen.dart'; +import 'sync_screen.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key, required this.syncService}); + + final SyncService syncService; + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + DashboardData? _dashboard; + List _accounts = []; + List _categories = []; + List _transactions = []; + int _pendingCount = 0; + DateTime? _lastSyncAt; + bool _isOnline = false; + bool _loading = true; + bool _syncing = false; + String? _message; + + final _money = NumberFormat.currency(locale: 'fr_FR', symbol: 'MAD ', decimalDigits: 2); + final _date = DateFormat('dd/MM/yyyy HH:mm', 'fr_FR'); + + @override + void initState() { + super.initState(); + _bootstrap(); + } + + Future _bootstrap() async { + try { + final local = await widget.syncService.loadLocalSnapshot( + isOnline: false, + message: 'Données locales chargées.', + ); + _applySnapshot(local, loading: false); + await _synchronize(); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _message = 'Erreur locale : $e'; + }); + } + } + + void _applySnapshot(SyncSnapshot snapshot, {bool? loading}) { + if (!mounted) return; + setState(() { + _dashboard = snapshot.dashboard; + _accounts = snapshot.accounts; + _categories = snapshot.categories; + _transactions = snapshot.transactions; + _pendingCount = snapshot.pendingCount; + _lastSyncAt = snapshot.lastSyncAt; + _isOnline = snapshot.isOnline; + _message = snapshot.message; + if (loading != null) _loading = loading; + }); + } + + Future _synchronize() async { + if (_syncing) return; + + setState(() { + _syncing = true; + _message = 'Synchronisation...'; + }); + + try { + final snapshot = await widget.syncService.synchronize(); + if (!mounted) return; + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Erreur de synchronisation : $e'; + _loading = false; + }); + } finally { + if (mounted) { + setState(() => _syncing = false); + } + } + } + + Future _reloadLocalAfterSave() async { + try { + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: _isOnline + ? 'Opération enregistrée.' + : 'Opération en attente de synchronisation.', + ); + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Opération enregistrée localement, mais rechargement écran échoué : $e'; + _loading = false; + }); + } + } + + Future _openQuickAdd() async { + if (_accounts.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Crée d’abord au moins un compte dans la version web, puis synchronise.')), + ); + return; + } + + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => QuickTransactionScreen( + syncService: widget.syncService, + accounts: _accounts, + categories: _categories, + onSaved: _reloadLocalAfterSave, + ), + ), + ); + } + + +Future _openSyncScreen() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SyncScreen(syncService: widget.syncService), + ), + ); + + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: null, + ); + _applySnapshot(snapshot, loading: false); +} + + Future _openSettings() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsScreen(apiService: widget.syncService.apiService), + ), + ); + await _synchronize(); + } + + @override + Widget build(BuildContext context) { + final dashboard = _dashboard; + + return Scaffold( + appBar: AppBar( + title: const Text('FIN65'), + actions: [ + IconButton( + tooltip: 'Page synchronisation', + onPressed: _openSyncScreen, + icon: Badge( + isLabelVisible: _pendingCount > 0, + label: Text('$_pendingCount'), + child: const Icon(Icons.cloud_sync), + ), + ), + IconButton( + tooltip: 'Synchroniser', + onPressed: _syncing ? null : _synchronize, + icon: _syncing + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + ), + IconButton(onPressed: _openSettings, icon: const Icon(Icons.settings)), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _openQuickAdd, + icon: const Icon(Icons.add), + label: const Text('Ajouter'), + ), + body: RefreshIndicator( + onRefresh: _synchronize, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ + _SyncBanner( + isOnline: _isOnline, + pendingCount: _pendingCount, + lastSyncAt: _lastSyncAt, + formatter: _date, + message: _message, + ), + const SizedBox(height: 12), + if (dashboard != null) ...[ + _DashboardCards( + dashboard: dashboard, + money: _money, + hasPending: _pendingCount > 0, + ), + const SizedBox(height: 16), + ] else + const _EmptyCacheCard(), + _SectionTitle(title: 'Comptes', action: _pendingCount > 0 ? 'Solde estimé' : 'Solde app'), + const SizedBox(height: 8), + if (_accounts.isEmpty) + const Card(child: ListTile(title: Text('Aucun compte en cache. Synchronise avec le backend.'))) + else + ..._accounts.map((a) => _AccountTile(account: a, money: _money)), + const SizedBox(height: 16), + _SectionTitle(title: 'Dernières transactions'), + const SizedBox(height: 8), + if (_transactions.isEmpty) + const Card(child: ListTile(title: Text('Aucune transaction en cache.'))) + else + ..._transactions.map( + (t) => _TransactionTile( + transaction: t, + accounts: _accounts, + categories: _categories, + money: _money, + ), + ), + const SizedBox(height: 90), + ], + ), + ), + ); + } +} + +class _SyncBanner extends StatelessWidget { + const _SyncBanner({ + required this.isOnline, + required this.pendingCount, + required this.lastSyncAt, + required this.formatter, + this.message, + }); + + final bool isOnline; + final int pendingCount; + final DateTime? lastSyncAt; + final DateFormat formatter; + final String? message; + + @override + Widget build(BuildContext context) { + final title = isOnline ? 'Connecté au backend' : 'Mode hors ligne'; + final subtitleParts = []; + + if (lastSyncAt != null) { + subtitleParts.add('Dernière synchro : ${formatter.format(lastSyncAt!.toLocal())}'); + } else { + subtitleParts.add('Aucune synchronisation réussie'); + } + + if (pendingCount > 0) { + subtitleParts.add('$pendingCount opération(s) en attente'); + } + + if (message != null && message!.isNotEmpty) { + subtitleParts.add(message!); + } + + return Card( + child: ListTile( + leading: Icon(isOnline ? Icons.cloud_done : Icons.cloud_off), + title: Text(title), + subtitle: Text(subtitleParts.join('\n')), + ), + ); + } +} + +class _EmptyCacheCard extends StatelessWidget { + const _EmptyCacheCard(); + + @override + Widget build(BuildContext context) { + return const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text( + 'Aucune donnée locale. Lance le backend PC une première fois, configure l’URL API, puis synchronise.', + ), + ), + ); + } +} + +class _DashboardCards extends StatelessWidget { + const _DashboardCards({ + required this.dashboard, + required this.money, + required this.hasPending, + }); + + final DashboardData dashboard; + final NumberFormat money; + final bool hasPending; + + @override + Widget build(BuildContext context) { + final labelSuffix = hasPending ? ' estimé' : ''; + + return Column( + children: [ + _MetricCard( + title: 'Disponible réel$labelSuffix', + value: money.format(dashboard.availableAfterReserves), + icon: Icons.account_balance_wallet, + ), + const SizedBox(height: 8), + _MetricCard( + title: 'Balance prévisionnelle du mois', + value: money.format(dashboard.projectedMonthBalance), + icon: Icons.insights, + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Solde total$labelSuffix', + value: money.format(dashboard.totalBalance), + icon: Icons.savings, + compact: true, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Balance réelle', + value: money.format(dashboard.monthlyBalance), + icon: Icons.trending_up, + compact: true, + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Revenus réels', + value: money.format(dashboard.monthlyIncome), + icon: Icons.arrow_downward, + compact: true, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Dépenses réelles', + value: money.format(dashboard.monthlyExpenses), + icon: Icons.arrow_upward, + compact: true, + ), + ), + ], + ), + const SizedBox(height: 8), + _PlannedInfoCard(dashboard: dashboard, money: money), + ], + ); + } +} + +class _PlannedInfoCard extends StatelessWidget { + const _PlannedInfoCard({ + required this.dashboard, + required this.money, + }); + + final DashboardData dashboard; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + final rows = <_InfoRow>[ + _InfoRow('Dépenses prévues restantes', dashboard.plannedExpensesTotal), + _InfoRow('Revenus prévus échéancier', dashboard.scheduledIncomeRemainingTotal), + _InfoRow('Dépenses échéancier', dashboard.scheduledExpensesRemainingTotal), + _InfoRow('Transferts prévus', dashboard.plannedTransfersTotal), + _InfoRow('Provisions prévues', dashboard.plannedProvisionsTotal), + ]; + + return Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.event_note), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Prévisionnel du mois', + style: Theme.of(context).textTheme.titleMedium, + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Inclut les opérations mensuelles et l’échéancier ponctuel du backend.', + style: Theme.of(context).textTheme.bodySmall, + ), + const Divider(height: 20), + ...rows.map( + (row) => Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + children: [ + Expanded(child: Text(row.label)), + Text( + money.format(row.value), + style: const TextStyle(fontWeight: FontWeight.w700), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _InfoRow { + const _InfoRow(this.label, this.value); + + final String label; + final double value; +} + +class _MetricCard extends StatelessWidget { + const _MetricCard({ + required this.title, + required this.value, + required this.icon, + this.compact = false, + }); + + final String title; + final String value; + final IconData icon; + final bool compact; + + @override + Widget build(BuildContext context) { + return Card( + child: Padding( + padding: EdgeInsets.all(compact ? 12 : 16), + child: Row( + children: [ + Icon(icon, size: compact ? 24 : 32), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: Theme.of(context).textTheme.bodySmall), + Text( + value, + style: compact + ? Theme.of(context).textTheme.titleMedium + : Theme.of(context).textTheme.headlineSmall, + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle({required this.title, this.action}); + + final String title; + final String? action; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(title, style: Theme.of(context).textTheme.titleLarge), + const Spacer(), + if (action != null) Text(action!, style: Theme.of(context).textTheme.bodySmall), + ], + ); + } +} + +class _AccountTile extends StatelessWidget { + const _AccountTile({required this.account, required this.money}); + + final Account account; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.account_balance), + title: Text(account.name), + subtitle: Text(account.type), + trailing: Text( + money.format(account.appBalance), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} + +class _TransactionTile extends StatelessWidget { + const _TransactionTile({ + required this.transaction, + required this.accounts, + required this.categories, + required this.money, + }); + + final TransactionItem transaction; + final List accounts; + final List categories; + final NumberFormat money; + + Account? _findAccount(int? id) { + if (id == null) return null; + for (final account in accounts) { + if (account.id == id) return account; + } + return null; + } + + Category? _findCategory(int? id) { + if (id == null) return null; + for (final category in categories) { + if (category.id == id) return category; + } + return null; + } + + @override + Widget build(BuildContext context) { + final account = _findAccount(transaction.accountId); + final target = _findAccount(transaction.targetAccountId); + final category = _findCategory(transaction.categoryId); + + final typeLabel = switch (transaction.type) { + 'expense' => 'Dépense', + 'income' => 'Recette', + 'transfer' => 'Transfert', + _ => transaction.type, + }; + + final accountLabel = transaction.type == 'transfer' + ? '${account?.name ?? transaction.accountId} → ${target?.name ?? transaction.targetAccountId}' + : account?.name ?? 'Compte ${transaction.accountId}'; + + return Card( + child: ListTile( + leading: Icon(transaction.isPending ? Icons.schedule_send : Icons.receipt_long), + title: Text(transaction.label), + subtitle: Text( + '${transaction.isPending ? 'EN ATTENTE • ' : ''}$typeLabel • $accountLabel${category == null ? '' : ' • ${category.name}'}', + ), + trailing: Text( + money.format(transaction.amount), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} diff --git a/fin65_android_gradle_repair_biometrics/README_REPAIR_GRADLE_BIOMETRICS.md b/fin65_android_gradle_repair_biometrics/README_REPAIR_GRADLE_BIOMETRICS.md new file mode 100644 index 0000000..396f2ae --- /dev/null +++ b/fin65_android_gradle_repair_biometrics/README_REPAIR_GRADLE_BIOMETRICS.md @@ -0,0 +1,36 @@ +# FIN65 - Réparation Gradle biométrie + +Ce patch corrige l'erreur : + +```text +build.gradle.kts +kotlin { + compilerOptions { + jvmTarget = ... + } +} +Unresolved reference 'compilerOptions' +``` + +L'ancien patch Android biométrie a ajouté un bloc Kotlin DSL invalide dans `android/app/build.gradle.kts`. + +## Utilisation + +Décompresse ce ZIP puis lance : + +```powershell +.\repair_gradle_biometrics.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +Le script : +- sauvegarde `build.gradle.kts` ; +- supprime le bloc `kotlin { compilerOptions { ... } }` invalide ; +- garde `minSdk = 24` ; +- lance `flutter clean` et `flutter pub get`. diff --git a/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat b/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat new file mode 100644 index 0000000..01de3fb --- /dev/null +++ b/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat @@ -0,0 +1,4 @@ +@echo off +setlocal + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0repair_gradle_biometrics.bat.ps1" diff --git a/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat.ps1 b/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat.ps1 new file mode 100644 index 0000000..f544cce --- /dev/null +++ b/fin65_android_gradle_repair_biometrics/repair_gradle_biometrics.bat.ps1 @@ -0,0 +1,89 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$GradleKts = Join-Path $MobileDir "android\app\build.gradle.kts" +$GradleGroovy = Join-Path $MobileDir "android\app\build.gradle" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Repair Gradle biometrie" +Write-Host "==========================================" +Write-Host "" + +function Backup-File($path) { + if (Test-Path $path) { + $Stamp = Get-Date -Format "yyyyMMdd_HHmmss" + Copy-Item $path "$path.before_gradle_repair_$Stamp.bak" -Force + Write-Host "Sauvegarde : $path.before_gradle_repair_$Stamp.bak" + } +} + +if (!(Test-Path $MobileDir)) { + Write-Host "[ERREUR] Dossier mobile introuvable : $MobileDir" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +if (Test-Path $GradleKts) { + Backup-File $GradleKts + + $text = Get-Content $GradleKts -Raw + + # Supprime le bloc Kotlin DSL invalide ajouté par l'ancien patch : + # kotlin { + # compilerOptions { + # jvmTarget = ... + # } + # } + $text = [regex]::Replace( + $text, + '(?ms)^\s*kotlin\s*\{\s*compilerOptions\s*\{.*?\}\s*\}\s*$', + '' + ) + + # Forcer minSdk a 24 sans toucher au reste. + $text = [regex]::Replace($text, 'minSdk\s*=\s*flutter\.minSdkVersion', 'minSdk = 24') + $text = [regex]::Replace($text, 'minSdk\s*=\s*\d+', 'minSdk = 24') + $text = [regex]::Replace($text, 'minSdkVersion\s+flutter\.minSdkVersion', 'minSdkVersion 24') + $text = [regex]::Replace($text, 'minSdkVersion\s+\d+', 'minSdkVersion 24') + + Set-Content -Path $GradleKts -Value $text -Encoding UTF8 + Write-Host "build.gradle.kts repare." +} elseif (Test-Path $GradleGroovy) { + Backup-File $GradleGroovy + + $text = Get-Content $GradleGroovy -Raw + $text = [regex]::Replace( + $text, + '(?ms)^\s*kotlin\s*\{\s*compilerOptions\s*\{.*?\}\s*\}\s*$', + '' + ) + $text = [regex]::Replace($text, 'minSdkVersion\s+flutter\.minSdkVersion', 'minSdkVersion 24') + $text = [regex]::Replace($text, 'minSdkVersion\s+\d+', 'minSdkVersion 24') + Set-Content -Path $GradleGroovy -Value $text -Encoding UTF8 + Write-Host "build.gradle repare." +} else { + Write-Host "[ERREUR] Aucun build.gradle(.kts) trouve." -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +Set-Location $MobileDir + +Write-Host "" +Write-Host "Verification rapide :" +if (Test-Path $GradleKts) { + Select-String -Path $GradleKts -Pattern "kotlin \{|compilerOptions|jvmTarget|minSdk" | ForEach-Object { Write-Host $_.Line } +} else { + Select-String -Path $GradleGroovy -Pattern "kotlin \{|compilerOptions|jvmTarget|minSdk" | ForEach-Object { Write-Host $_.Line } +} + +Write-Host "" +Write-Host "Nettoyage Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Reparation Gradle terminee." +Write-Host "Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_android_icon_direct_patch_v2/README_ICON_DIRECT_PATCH_V2.md b/fin65_android_icon_direct_patch_v2/README_ICON_DIRECT_PATCH_V2.md new file mode 100644 index 0000000..564eb3f --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/README_ICON_DIRECT_PATCH_V2.md @@ -0,0 +1,33 @@ +# FIN65 - Patch icône Android direct V2 + +Cette version corrige l'erreur PowerShell : + +```text +The regular expression pattern android:label="[^]* is not valid +``` + +## Utilisation + +Décompresse le ZIP puis lance : + +```powershell +.\apply_fin65_android_icon_direct_v2.bat +``` + +Ensuite relance : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Si l’icône ne change pas + +Android garde parfois l’ancienne icône en cache. + +Dans ce cas : +1. synchronise toutes les opérations en attente ; +2. désinstalle l'app du téléphone ; +3. relance `flutter run`. + +Attention : désinstaller l’app supprime la base SQLite locale mobile. diff --git a/fin65_android_icon_direct_patch_v2/apply_fin65_android_icon_direct_v2.bat b/fin65_android_icon_direct_patch_v2/apply_fin65_android_icon_direct_v2.bat new file mode 100644 index 0000000..d26e6fd --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/apply_fin65_android_icon_direct_v2.bat @@ -0,0 +1,86 @@ +@echo off +setlocal enabledelayedexpansion + +REM ============================================================ +REM FIN65 - Patch icone Android direct V2 +REM Corrige le probleme de regex PowerShell dans le .bat precedent. +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" +set "RES_DIR=%MOBILE_DIR%\android\app\src\main\res" +set "MANIFEST=%MOBILE_DIR%\android\app\src\main\AndroidManifest.xml" + +echo. +echo ========================================== +echo FIN65 - Patch icone Android direct V2 +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +if not exist "%RES_DIR%" ( + echo [ERREUR] Dossier res Android introuvable : + echo %RES_DIR% + pause + exit /b 1 +) + +if not exist "%MANIFEST%" ( + echo [ERREUR] AndroidManifest.xml introuvable : + echo %MANIFEST% + pause + exit /b 1 +) + +cd /d "%MOBILE_DIR%" + +echo Copie des icones natives Android... + +for %%D in (mipmap-mdpi mipmap-hdpi mipmap-xhdpi mipmap-xxhdpi mipmap-xxxhdpi mipmap-anydpi-v26 values) do ( + if not exist "%RES_DIR%\%%D" mkdir "%RES_DIR%\%%D" + copy /Y "%~dp0generated_res\%%D\*" "%RES_DIR%\%%D\" >nul +) + +echo. +echo Mise a jour du label et de l'icone dans AndroidManifest.xml... + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0patch_manifest_icon.ps1" -ManifestPath "%MANIFEST%" +if errorlevel 1 ( + echo. + echo [ERREUR] Patch du Manifest echoue. + pause + exit /b 1 +) + +echo. +echo Verification rapide : +findstr /C:"android:label" "%MANIFEST%" +findstr /C:"android:icon" "%MANIFEST%" +findstr /C:"android:roundIcon" "%MANIFEST%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Icone native FIN65 appliquee. +echo ========================================== +echo. +echo Relance : +echo flutter run +echo. +echo Si l'ancienne icone reste visible, Android garde le cache : +echo 1. Synchronise les operations en attente. +echo 2. Desinstalle l'app du telephone. +echo 3. Relance flutter run. +echo. +pause diff --git a/fin65_android_icon_direct_patch_v2/fin65_icon_preview.png b/fin65_android_icon_direct_patch_v2/fin65_icon_preview.png new file mode 100644 index 0000000..ba6fbea Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/fin65_icon_preview.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher.xml b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..80b730f --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher_round.xml b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..80b730f --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..49f4edd Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher_foreground.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8958985 Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..b597fca Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher_foreground.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..738c10e Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..3cf7114 Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher_foreground.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..dd8253b Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..0d97344 Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher_foreground.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..a46788b Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..7a5854a Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher_foreground.png b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..fd17041 Binary files /dev/null and b/fin65_android_icon_direct_patch_v2/generated_res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/fin65_android_icon_direct_patch_v2/generated_res/values/ic_launcher_background.xml b/fin65_android_icon_direct_patch_v2/generated_res/values/ic_launcher_background.xml new file mode 100644 index 0000000..0cfdac6 --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/generated_res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #0F172A + diff --git a/fin65_android_icon_direct_patch_v2/patch_manifest_icon.ps1 b/fin65_android_icon_direct_patch_v2/patch_manifest_icon.ps1 new file mode 100644 index 0000000..7d57520 --- /dev/null +++ b/fin65_android_icon_direct_patch_v2/patch_manifest_icon.ps1 @@ -0,0 +1,30 @@ +param( + [Parameter(Mandatory=$true)] + [string]$ManifestPath +) + +if (!(Test-Path $ManifestPath)) { + Write-Host "[ERREUR] AndroidManifest.xml introuvable : $ManifestPath" -ForegroundColor Red + exit 1 +} + +$text = Get-Content $ManifestPath -Raw + +# Remplace les attributs existants. +$text = [regex]::Replace($text, 'android:label="[^"]*"', 'android:label="FIN65"') +$text = [regex]::Replace($text, 'android:icon="[^"]*"', 'android:icon="@mipmap/ic_launcher"') +$text = [regex]::Replace($text, 'android:roundIcon="[^"]*"', 'android:roundIcon="@mipmap/ic_launcher_round"') + +# Ajoute les attributs s'ils n'existaient pas. +if ($text -notmatch 'android:label=') { + $text = $text -replace ' introuvable." -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$app.SetAttribute("label", $androidNs, "FIN65") +$app.SetAttribute("icon", $androidNs, "@mipmap/ic_launcher") +$app.SetAttribute("roundIcon", $androidNs, "@mipmap/ic_launcher_round") +$app.SetAttribute("usesCleartextTraffic", $androidNs, "true") + +# Chercher l'activité launcher. +$activities = @($app.activity) +$launcherActivity = $null + +foreach ($a in $activities) { + if ($null -eq $a) { continue } + + $hasLauncher = $false + foreach ($f in @($a.'intent-filter')) { + if ($null -eq $f) { continue } + foreach ($cat in @($f.category)) { + if ($cat.GetAttribute("name", $androidNs) -eq "android.intent.category.LAUNCHER") { + $hasLauncher = $true + } + } + } + + if ($hasLauncher) { + $launcherActivity = $a + break + } +} + +if ($null -eq $launcherActivity) { + if ($activities.Count -gt 0 -and $null -ne $activities[0]) { + $launcherActivity = $activities[0] + } else { + $launcherActivity = $xml.CreateElement("activity") + [void]$app.PrependChild($launcherActivity) + } +} + +$launcherActivity.SetAttribute("name", $androidNs, "$PackageName.MainActivity") +$launcherActivity.SetAttribute("exported", $androidNs, "true") +$launcherActivity.SetAttribute("launchMode", $androidNs, "singleTop") +$launcherActivity.SetAttribute("taskAffinity", $androidNs, "") +$launcherActivity.SetAttribute("theme", $androidNs, "@style/LaunchTheme") +$launcherActivity.SetAttribute("configChanges", $androidNs, "orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode") +$launcherActivity.SetAttribute("hardwareAccelerated", $androidNs, "true") +$launcherActivity.SetAttribute("windowSoftInputMode", $androidNs, "adjustResize") + +# S'assurer du meta-data NormalTheme. +$hasNormalTheme = $false +foreach ($md in @($launcherActivity.'meta-data')) { + if ($null -ne $md -and $md.GetAttribute("name", $androidNs) -eq "io.flutter.embedding.android.NormalTheme") { + $hasNormalTheme = $true + } +} +if (!$hasNormalTheme) { + $meta = $xml.CreateElement("meta-data") + $meta.SetAttribute("name", $androidNs, "io.flutter.embedding.android.NormalTheme") + $meta.SetAttribute("resource", $androidNs, "@style/NormalTheme") + [void]$launcherActivity.PrependChild($meta) +} + +# S'assurer du launcher intent-filter. +$hasLauncherFilter = $false +foreach ($f in @($launcherActivity.'intent-filter')) { + if ($null -eq $f) { continue } + foreach ($cat in @($f.category)) { + if ($cat.GetAttribute("name", $androidNs) -eq "android.intent.category.LAUNCHER") { + $hasLauncherFilter = $true + } + } +} +if (!$hasLauncherFilter) { + $filter = $xml.CreateElement("intent-filter") + $action = $xml.CreateElement("action") + $action.SetAttribute("name", $androidNs, "android.intent.action.MAIN") + [void]$filter.AppendChild($action) + $category = $xml.CreateElement("category") + $category.SetAttribute("name", $androidNs, "android.intent.category.LAUNCHER") + [void]$filter.AppendChild($category) + [void]$launcherActivity.AppendChild($filter) +} + +# S'assurer du flutterEmbedding. +$hasFlutterEmbedding = $false +foreach ($md in @($app.'meta-data')) { + if ($null -ne $md -and $md.GetAttribute("name", $androidNs) -eq "flutterEmbedding") { + $hasFlutterEmbedding = $true + } +} +if (!$hasFlutterEmbedding) { + $md = $xml.CreateElement("meta-data") + $md.SetAttribute("name", $androidNs, "flutterEmbedding") + $md.SetAttribute("value", $androidNs, "2") + [void]$app.AppendChild($md) +} + +$xml.Save($Manifest) +Write-Host "" +Write-Host "AndroidManifest.xml mis a jour." + +# 5) Gradle : nettoyer bloc Kotlin erroné et garder minSdk 24. +if (Test-Path $GradleKts) { + $text = Get-Content $GradleKts -Raw + $text = [regex]::Replace($text, '(?ms)^\s*kotlin\s*\{\s*compilerOptions\s*\{.*?\}\s*\}\s*$', '') + $text = [regex]::Replace($text, 'minSdk\s*=\s*flutter\.minSdkVersion', 'minSdk = 24') + $text = [regex]::Replace($text, 'minSdk\s*=\s*\d+', 'minSdk = 24') + Set-Content -Path $GradleKts -Value $text -Encoding UTF8 + Write-Host "build.gradle.kts verifie." +} +if (Test-Path $GradleGroovy) { + $text = Get-Content $GradleGroovy -Raw + $text = [regex]::Replace($text, '(?ms)^\s*kotlin\s*\{\s*compilerOptions\s*\{.*?\}\s*\}\s*$', '') + $text = [regex]::Replace($text, 'minSdkVersion\s+flutter\.minSdkVersion', 'minSdkVersion 24') + $text = [regex]::Replace($text, 'minSdkVersion\s+\d+', 'minSdkVersion 24') + Set-Content -Path $GradleGroovy -Value $text -Encoding UTF8 + Write-Host "build.gradle verifie." +} + +Write-Host "" +Write-Host "Verification des fichiers MainActivity restants :" +Get-ChildItem $AndroidMain -Recurse -Include MainActivity.kt,MainActivity.java -ErrorAction SilentlyContinue | ForEach-Object { + Write-Host " - $($_.FullName)" +} + +Set-Location $MobileDir + +Write-Host "" +Write-Host "Nettoyage Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Reparation MainActivity Java terminee." +Write-Host "Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_android_mainactivity_repair_biometrics/README_REPAIR_MAINACTIVITY_BIOMETRICS.md b/fin65_android_mainactivity_repair_biometrics/README_REPAIR_MAINACTIVITY_BIOMETRICS.md new file mode 100644 index 0000000..fbc4f2b --- /dev/null +++ b/fin65_android_mainactivity_repair_biometrics/README_REPAIR_MAINACTIVITY_BIOMETRICS.md @@ -0,0 +1,43 @@ +# FIN65 - Réparation MainActivity biométrie + +Ce patch corrige le crash Android : + +```text +ClassNotFoundException: +Didn't find class "com.example.fin65_mobile.MainActivity" +``` + +La compilation réussit, mais Android ne trouve pas la classe lancée par le Manifest. Donc l'APK s'installe, puis l'app crashe au démarrage. Très théâtral, très Android. + +## Ce que le script fait + +- détecte le package Android depuis `build.gradle.kts` ; +- recrée `MainActivity.kt` au bon endroit ; +- utilise `FlutterFragmentActivity`, nécessaire pour la biométrie ; +- force le Manifest à pointer vers la classe complète : + `com.example.fin65_mobile.MainActivity` +- garde : + - `INTERNET` + - `USE_BIOMETRIC` + - `usesCleartextTraffic=true` + - icône FIN65 + - label FIN65 +- supprime si besoin le bloc Gradle Kotlin invalide revenu par accident ; +- lance `flutter clean` et `flutter pub get`. + +## Utilisation + +Décompresse puis lance : + +```powershell +.\repair_mainactivity_biometrics.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +Ne relance pas les anciens patchs biométrie après celui-ci. diff --git a/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat b/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat new file mode 100644 index 0000000..9c4c9e7 --- /dev/null +++ b/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat @@ -0,0 +1,4 @@ +@echo off +setlocal + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0repair_mainactivity_biometrics.bat.ps1" diff --git a/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat.ps1 b/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat.ps1 new file mode 100644 index 0000000..1479c33 --- /dev/null +++ b/fin65_android_mainactivity_repair_biometrics/repair_mainactivity_biometrics.bat.ps1 @@ -0,0 +1,245 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$AndroidMain = Join-Path $MobileDir "android\app\src\main" +$Manifest = Join-Path $AndroidMain "AndroidManifest.xml" +$GradleKts = Join-Path $MobileDir "android\app\build.gradle.kts" +$GradleGroovy = Join-Path $MobileDir "android\app\build.gradle" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Repair MainActivity biometrie" +Write-Host "==========================================" +Write-Host "" + +if (!(Test-Path $MobileDir)) { + Write-Host "[ERREUR] Dossier mobile introuvable : $MobileDir" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +if (!(Test-Path $Manifest)) { + Write-Host "[ERREUR] AndroidManifest.xml introuvable : $Manifest" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$Stamp = Get-Date -Format "yyyyMMdd_HHmmss" + +function Backup-File($Path) { + if (Test-Path $Path) { + Copy-Item $Path "$Path.before_mainactivity_repair_$Stamp.bak" -Force + Write-Host "Sauvegarde : $Path.before_mainactivity_repair_$Stamp.bak" + } +} + +Backup-File $Manifest +if (Test-Path $GradleKts) { Backup-File $GradleKts } +if (Test-Path $GradleGroovy) { Backup-File $GradleGroovy } + +# 1) Déterminer package/namespace Android. +$PackageName = "com.example.fin65_mobile" + +if (Test-Path $GradleKts) { + $g = Get-Content $GradleKts -Raw + $m = [regex]::Match($g, 'namespace\s*=\s*"([^"]+)"') + if ($m.Success) { $PackageName = $m.Groups[1].Value } + $m2 = [regex]::Match($g, 'applicationId\s*=\s*"([^"]+)"') + if ($m2.Success) { $PackageName = $m2.Groups[1].Value } +} elseif (Test-Path $GradleGroovy) { + $g = Get-Content $GradleGroovy -Raw + $m = [regex]::Match($g, 'namespace\s+["'']([^"'']+)["'']') + if ($m.Success) { $PackageName = $m.Groups[1].Value } + $m2 = [regex]::Match($g, 'applicationId\s+["'']([^"'']+)["'']') + if ($m2.Success) { $PackageName = $m2.Groups[1].Value } +} + +Write-Host "Package Android retenu : $PackageName" + +# 2) Créer MainActivity.kt au bon endroit avec FlutterFragmentActivity. +$PackagePath = $PackageName.Replace(".", "\") +$KotlinDir = Join-Path $AndroidMain "kotlin\$PackagePath" +$MainActivity = Join-Path $KotlinDir "MainActivity.kt" + +if (!(Test-Path $KotlinDir)) { + New-Item -ItemType Directory -Force -Path $KotlinDir | Out-Null +} + +if (Test-Path $MainActivity) { + Backup-File $MainActivity +} + +$MainActivityText = @" +package $PackageName + +import io.flutter.embedding.android.FlutterFragmentActivity + +class MainActivity : FlutterFragmentActivity() +"@ + +Set-Content -Path $MainActivity -Value $MainActivityText -Encoding UTF8 +Write-Host "MainActivity.kt recrée : $MainActivity" + +# 3) Patch Manifest sans casser XML. +[xml]$xml = Get-Content $Manifest +$androidNs = "http://schemas.android.com/apk/res/android" +$manifestNode = $xml.manifest + +function Ensure-Permission($name) { + $existing = $manifestNode.'uses-permission' | Where-Object { + $_.GetAttribute("name", $androidNs) -eq $name + } + if ($null -eq $existing) { + $perm = $xml.CreateElement("uses-permission") + $attr = $xml.CreateAttribute("android", "name", $androidNs) + $attr.Value = $name + [void]$perm.Attributes.Append($attr) + [void]$manifestNode.InsertBefore($perm, $manifestNode.FirstChild) + Write-Host "Permission ajoutee : $name" + } else { + Write-Host "Permission deja presente : $name" + } +} + +Ensure-Permission "android.permission.INTERNET" +Ensure-Permission "android.permission.USE_BIOMETRIC" + +$app = $manifestNode.application +if ($null -eq $app) { + Write-Host "[ERREUR] Balise introuvable dans AndroidManifest.xml" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$app.SetAttribute("label", $androidNs, "FIN65") +$app.SetAttribute("icon", $androidNs, "@mipmap/ic_launcher") +$app.SetAttribute("roundIcon", $androidNs, "@mipmap/ic_launcher_round") +$app.SetAttribute("usesCleartextTraffic", $androidNs, "true") + +$activities = @($app.activity) +$mainActivityNode = $null + +foreach ($a in $activities) { + if ($null -ne $a) { + $name = $a.GetAttribute("name", $androidNs) + $exported = $a.GetAttribute("exported", $androidNs) + $hasLauncher = $false + + foreach ($f in @($a.'intent-filter')) { + if ($null -ne $f) { + foreach ($cat in @($f.category)) { + if ($cat.GetAttribute("name", $androidNs) -eq "android.intent.category.LAUNCHER") { + $hasLauncher = $true + } + } + } + } + + if ($hasLauncher -or $name -like "*MainActivity*") { + $mainActivityNode = $a + break + } + } +} + +if ($null -eq $mainActivityNode) { + $mainActivityNode = $xml.CreateElement("activity") + [void]$app.PrependChild($mainActivityNode) +} + +$mainActivityNode.SetAttribute("name", $androidNs, "$PackageName.MainActivity") +$mainActivityNode.SetAttribute("exported", $androidNs, "true") +$mainActivityNode.SetAttribute("launchMode", $androidNs, "singleTop") +$mainActivityNode.SetAttribute("taskAffinity", $androidNs, "") +$mainActivityNode.SetAttribute("theme", $androidNs, "@style/LaunchTheme") +$mainActivityNode.SetAttribute("configChanges", $androidNs, "orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode") +$mainActivityNode.SetAttribute("hardwareAccelerated", $androidNs, "true") +$mainActivityNode.SetAttribute("windowSoftInputMode", $androidNs, "adjustResize") + +# Ajouter NormalTheme s'il manque. +$hasNormalTheme = $false +foreach ($md in @($mainActivityNode.'meta-data')) { + if ($null -ne $md -and $md.GetAttribute("name", $androidNs) -eq "io.flutter.embedding.android.NormalTheme") { + $hasNormalTheme = $true + } +} +if (!$hasNormalTheme) { + $meta = $xml.CreateElement("meta-data") + $meta.SetAttribute("name", $androidNs, "io.flutter.embedding.android.NormalTheme") + $meta.SetAttribute("resource", $androidNs, "@style/NormalTheme") + [void]$mainActivityNode.PrependChild($meta) +} + +# Ajouter launcher intent-filter s'il manque. +$hasLauncherFilter = $false +foreach ($f in @($mainActivityNode.'intent-filter')) { + if ($null -ne $f) { + foreach ($cat in @($f.category)) { + if ($cat.GetAttribute("name", $androidNs) -eq "android.intent.category.LAUNCHER") { + $hasLauncherFilter = $true + } + } + } +} +if (!$hasLauncherFilter) { + $filter = $xml.CreateElement("intent-filter") + + $action = $xml.CreateElement("action") + $action.SetAttribute("name", $androidNs, "android.intent.action.MAIN") + [void]$filter.AppendChild($action) + + $category = $xml.CreateElement("category") + $category.SetAttribute("name", $androidNs, "android.intent.category.LAUNCHER") + [void]$filter.AppendChild($category) + + [void]$mainActivityNode.AppendChild($filter) +} + +# Ajouter flutterEmbedding s'il manque. +$hasFlutterEmbedding = $false +foreach ($md in @($app.'meta-data')) { + if ($null -ne $md -and $md.GetAttribute("name", $androidNs) -eq "flutterEmbedding") { + $hasFlutterEmbedding = $true + } +} +if (!$hasFlutterEmbedding) { + $md = $xml.CreateElement("meta-data") + $md.SetAttribute("name", $androidNs, "flutterEmbedding") + $md.SetAttribute("value", $androidNs, "2") + [void]$app.AppendChild($md) +} + +$xml.Save($Manifest) +Write-Host "AndroidManifest.xml mis a jour." + +# 4) Nettoyer les MainActivity douteuses : ne pas supprimer, juste les afficher. +Write-Host "" +Write-Host "MainActivity detectees :" +Get-ChildItem (Join-Path $AndroidMain "kotlin") -Recurse -Filter MainActivity.kt -ErrorAction SilentlyContinue | ForEach-Object { + Write-Host " - $($_.FullName)" +} +Get-ChildItem (Join-Path $AndroidMain "java") -Recurse -Filter MainActivity.java -ErrorAction SilentlyContinue | ForEach-Object { + Write-Host " - $($_.FullName)" +} + +# 5) Gradle : garder minSdk = 24, supprimer bloc Kotlin invalide si revenu. +if (Test-Path $GradleKts) { + $text = Get-Content $GradleKts -Raw + $text = [regex]::Replace($text, '(?ms)^\s*kotlin\s*\{\s*compilerOptions\s*\{.*?\}\s*\}\s*$', '') + $text = [regex]::Replace($text, 'minSdk\s*=\s*flutter\.minSdkVersion', 'minSdk = 24') + $text = [regex]::Replace($text, 'minSdk\s*=\s*\d+', 'minSdk = 24') + Set-Content -Path $GradleKts -Value $text -Encoding UTF8 + Write-Host "build.gradle.kts verifie." +} + +Set-Location $MobileDir + +Write-Host "" +Write-Host "Nettoyage Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Reparation terminee." +Write-Host "Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_android_manifest_repair/README_REPAIR_MANIFEST.md b/fin65_android_manifest_repair/README_REPAIR_MANIFEST.md new file mode 100644 index 0000000..283c325 --- /dev/null +++ b/fin65_android_manifest_repair/README_REPAIR_MANIFEST.md @@ -0,0 +1,34 @@ +# FIN65 - Réparation AndroidManifest.xml + +Ce patch répare `AndroidManifest.xml` après l'erreur : + +```text +Error parsing LocalFile: android/app/src/main/AndroidManifest.xml +Please ensure that the android manifest is a valid XML document +``` + +## Utilisation + +Décompresse ce ZIP puis lance : + +```powershell +.\repair_fin65_android_manifest.bat +``` + +Le script : +1. sauvegarde l'ancien Manifest cassé ; +2. réécrit un Manifest Flutter propre ; +3. garde : + - `android:label="FIN65"` + - `android:icon="@mipmap/ic_launcher"` + - `android:roundIcon="@mipmap/ic_launcher_round"` + - `android:usesCleartextTraffic="true"` + - permission Internet ; +4. lance `flutter clean` et `flutter pub get`. + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` diff --git a/fin65_android_manifest_repair/repair_fin65_android_manifest.bat b/fin65_android_manifest_repair/repair_fin65_android_manifest.bat new file mode 100644 index 0000000..ea91e1a --- /dev/null +++ b/fin65_android_manifest_repair/repair_fin65_android_manifest.bat @@ -0,0 +1,11 @@ +@echo off +setlocal + +echo. +echo ========================================== +echo FIN65 - Repair AndroidManifest.xml +echo ========================================== +echo. + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0repair_fin65_android_manifest.ps1" + diff --git a/fin65_android_manifest_repair/repair_fin65_android_manifest.ps1 b/fin65_android_manifest_repair/repair_fin65_android_manifest.ps1 new file mode 100644 index 0000000..7e0e55e --- /dev/null +++ b/fin65_android_manifest_repair/repair_fin65_android_manifest.ps1 @@ -0,0 +1,83 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$Manifest = Join-Path $MobileDir "android\app\src\main\AndroidManifest.xml" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Repair AndroidManifest.xml" +Write-Host "==========================================" +Write-Host "" + +if (!(Test-Path $MobileDir)) { + Write-Host "[ERREUR] Dossier mobile introuvable : $MobileDir" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$ManifestDir = Split-Path $Manifest -Parent +if (!(Test-Path $ManifestDir)) { + Write-Host "[ERREUR] Dossier Manifest introuvable : $ManifestDir" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +if (Test-Path $Manifest) { + $Stamp = Get-Date -Format "yyyyMMdd_HHmmss" + $Backup = "$Manifest.broken_$Stamp.bak" + Copy-Item $Manifest $Backup -Force + Write-Host "Sauvegarde de l'ancien Manifest :" + Write-Host $Backup + Write-Host "" +} + +$Xml = @' + + + + + + + + + + + + + + + +'@ + +Set-Content -Path $Manifest -Value $Xml -Encoding UTF8 + +Write-Host "AndroidManifest.xml repare :" +Write-Host $Manifest +Write-Host "" + +Set-Location $MobileDir + +Write-Host "Verification Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Termine. Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_biometrics_activation_ui_fix/README_FIX_ACTIVATION_EMPREINTE.md b/fin65_biometrics_activation_ui_fix/README_FIX_ACTIVATION_EMPREINTE.md new file mode 100644 index 0000000..84bb73b --- /dev/null +++ b/fin65_biometrics_activation_ui_fix/README_FIX_ACTIVATION_EMPREINTE.md @@ -0,0 +1,46 @@ +# FIN65 - Fix activation empreinte V2.6.1 + +Ce patch corrige l'écran Sécurité. + +## Problème + +L'écran affichait : + +```text +PIN actuel incorrect. +``` + +quand on essayait d'activer l'empreinte, parce que l'ancien écran utilisait le champ `PIN actuel` visible dans la page. C'était peu clair, donc naturellement ça a créé une erreur inutile. L'espèce humaine et les interfaces mal pensées, une vieille histoire. + +## Correction + +Maintenant, quand tu actives l'empreinte : + +1. tu appuies sur l'interrupteur `Déverrouillage par empreinte` ; +2. une boîte de dialogue demande le PIN actuel ; +3. Android demande l'empreinte ; +4. si l'empreinte est validée, l'option est activée. + +Le champ `PIN actuel` sur la page sert maintenant surtout à changer le PIN. + +## Installation + +Décompresse puis lance : + +```powershell +.\apply_biometric_activation_ui_fix.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Test + +1. Ouvre `Paramètres > Sécurité`. +2. Active `Déverrouillage par empreinte`. +3. Entre le PIN actuel dans la boîte de dialogue. +4. Pose le doigt quand Android le demande. diff --git a/fin65_biometrics_activation_ui_fix/apply_biometric_activation_ui_fix.bat b/fin65_biometrics_activation_ui_fix/apply_biometric_activation_ui_fix.bat new file mode 100644 index 0000000..18179fd --- /dev/null +++ b/fin65_biometrics_activation_ui_fix/apply_biometric_activation_ui_fix.bat @@ -0,0 +1,62 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Fix activation empreinte V2.6.1 +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" +set "TARGET=%MOBILE_DIR%\lib\screens\security_screen.dart" + +echo. +echo ========================================== +echo FIN65 - Fix activation empreinte V2.6.1 +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +if not exist "%MOBILE_DIR%\lib\screens" ( + echo [ERREUR] Dossier screens introuvable : + echo %MOBILE_DIR%\lib\screens + pause + exit /b 1 +) + +for /f "tokens=1-4 delims=/ " %%a in ("%date%") do set DATESTAMP=%%d%%b%%c +set TIMESTAMP=%time::=% +set TIMESTAMP=%TIMESTAMP: =0% +set BACKUP=%TARGET%.before_biometric_ui_fix_%DATESTAMP%_%TIMESTAMP%.bak + +if exist "%TARGET%" ( + copy /Y "%TARGET%" "%BACKUP%" >nul + echo Sauvegarde : + echo %BACKUP% + echo. +) + +copy /Y "%~dp0lib\screens\security_screen.dart" "%TARGET%" >nul + +cd /d "%MOBILE_DIR%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Fix activation empreinte applique. +echo ========================================== +echo. +echo Relance maintenant : +echo flutter run +echo. +pause diff --git a/fin65_biometrics_activation_ui_fix/lib/screens/security_screen.dart b/fin65_biometrics_activation_ui_fix/lib/screens/security_screen.dart new file mode 100644 index 0000000..783ccfa --- /dev/null +++ b/fin65_biometrics_activation_ui_fix/lib/screens/security_screen.dart @@ -0,0 +1,399 @@ +import 'package:flutter/material.dart'; +import 'package:local_auth/local_auth.dart'; + +import '../services/security_service.dart'; + +class SecurityScreen extends StatefulWidget { + const SecurityScreen({ + super.key, + required this.securityService, + }); + + final SecurityService securityService; + + @override + State createState() => _SecurityScreenState(); +} + +class _SecurityScreenState extends State { + final _currentPinController = TextEditingController(); + final _newPinController = TextEditingController(); + final _confirmPinController = TextEditingController(); + + bool _loading = true; + bool _saving = false; + bool _enabled = false; + bool _biometricAvailable = false; + bool _biometricEnabled = false; + List _availableBiometrics = const []; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _currentPinController.dispose(); + _newPinController.dispose(); + _confirmPinController.dispose(); + super.dispose(); + } + + Future _load() async { + final enabled = await widget.securityService.isPinEnabled(); + final biometricAvailable = await widget.securityService.isBiometricAvailable(); + final biometricEnabled = await widget.securityService.isBiometricEnabled(); + final availableBiometrics = await widget.securityService.getAvailableBiometrics(); + + if (!mounted) return; + setState(() { + _enabled = enabled; + _biometricAvailable = biometricAvailable; + _biometricEnabled = biometricEnabled; + _availableBiometrics = availableBiometrics; + _loading = false; + }); + } + + Future _verifyCurrentPinFromFieldIfNeeded() async { + if (!_enabled) return true; + + final current = _currentPinController.text.trim(); + final ok = await widget.securityService.verifyPin(current); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + return true; + } + + Future _askCurrentPinDialog({ + required String title, + required String actionLabel, + }) async { + final controller = TextEditingController(); + + final result = await showDialog( + context: context, + barrierDismissible: true, + builder: (context) { + return AlertDialog( + title: Text(title), + content: TextField( + controller: controller, + autofocus: true, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + counterText: '', + ), + onSubmitted: (_) => Navigator.of(context).pop(controller.text.trim()), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Annuler'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(controller.text.trim()), + child: Text(actionLabel), + ), + ], + ); + }, + ); + + controller.dispose(); + return result?.trim(); + } + + Future _askAndVerifyCurrentPin({ + required String title, + required String actionLabel, + }) async { + final pin = await _askCurrentPinDialog( + title: title, + actionLabel: actionLabel, + ); + + if (pin == null) { + setState(() => _message = 'Action annulée.'); + return false; + } + + final ok = await widget.securityService.verifyPin(pin); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + + return true; + } + + Future _savePin() async { + final newPin = _newPinController.text.trim(); + final confirm = _confirmPinController.text.trim(); + + if (newPin != confirm) { + setState(() => _message = 'Le nouveau PIN et la confirmation ne correspondent pas.'); + return; + } + + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinFromFieldIfNeeded(); + if (!currentOk) return; + + await widget.securityService.setPin(newPin); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN activé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _disablePin() async { + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _askAndVerifyCurrentPin( + title: 'Désactiver le verrouillage PIN', + actionLabel: 'Désactiver', + ); + if (!currentOk) return; + + await widget.securityService.disablePin(); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN et biométrie désactivés.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _toggleBiometrics(bool value) async { + if (_saving) return; + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (value) { + if (!_enabled) { + setState(() => _message = 'Active d’abord un PIN avant la biométrie.'); + return; + } + + if (!_biometricAvailable) { + setState(() => _message = 'Aucune empreinte/biométrie disponible sur ce téléphone.'); + return; + } + + final currentOk = await _askAndVerifyCurrentPin( + title: 'Activer l’empreinte', + actionLabel: 'Continuer', + ); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(true); + + final confirmed = await widget.securityService.authenticateWithBiometrics(); + if (!confirmed) { + await widget.securityService.setBiometricEnabled(false); + setState(() => _message = 'Empreinte annulée ou refusée. Biométrie non activée.'); + return; + } + } else { + final currentOk = await _askAndVerifyCurrentPin( + title: 'Désactiver l’empreinte', + actionLabel: 'Désactiver', + ); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(false); + } + + await _load(); + + setState(() { + _message = value + ? 'Déverrouillage par empreinte activé.' + : 'Déverrouillage par empreinte désactivé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _biometricLabel() { + if (_availableBiometrics.isEmpty) return 'Aucune biométrie détectée.'; + + final labels = _availableBiometrics.map((type) { + return switch (type) { + BiometricType.fingerprint => 'empreinte', + BiometricType.face => 'visage', + BiometricType.iris => 'iris', + BiometricType.strong => 'biométrie forte', + BiometricType.weak => 'biométrie faible', + }; + }).toSet().join(', '); + + return 'Disponible : $labels.'; + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: const Center(child: CircularProgressIndicator()), + ); + } + + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: SwitchListTile( + value: _enabled, + onChanged: null, + secondary: Icon(_enabled ? Icons.lock : Icons.lock_open), + title: const Text('Verrouillage PIN'), + subtitle: Text( + _enabled + ? 'Activé. L’app se verrouille à la fermeture ou au changement d’application.' + : 'Désactivé. Tes données locales sont accessibles sans PIN.', + ), + ), + ), + if (_enabled) ...[ + const SizedBox(height: 12), + Card( + child: SwitchListTile( + value: _biometricEnabled, + onChanged: _saving || !_biometricAvailable ? null : _toggleBiometrics, + secondary: const Icon(Icons.fingerprint), + title: const Text('Déverrouillage par empreinte'), + subtitle: Text( + _biometricAvailable + ? '${_biometricLabel()} Appuie sur l’interrupteur, entre le PIN actuel, puis valide l’empreinte.' + : 'Aucune empreinte/biométrie disponible ou configurée sur ce téléphone.', + ), + ), + ), + ], + const SizedBox(height: 16), + if (_enabled) ...[ + TextField( + controller: _currentPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + helperText: 'Uniquement nécessaire pour changer le PIN.', + counterText: '', + ), + ), + const SizedBox(height: 12), + ], + TextField( + controller: _newPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: _enabled ? 'Nouveau PIN' : 'PIN', + border: const OutlineInputBorder(), + helperText: '4 à 8 chiffres.', + counterText: '', + ), + ), + const SizedBox(height: 12), + TextField( + controller: _confirmPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'Confirmer le PIN', + border: OutlineInputBorder(), + counterText: '', + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _saving ? null : _savePin, + icon: const Icon(Icons.save), + label: Text(_enabled ? 'Changer le PIN' : 'Activer le PIN'), + ), + if (_enabled) ...[ + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _saving ? null : _disablePin, + icon: const Icon(Icons.lock_open), + label: const Text('Désactiver le PIN'), + ), + ], + if (_message != null) ...[ + const SizedBox(height: 16), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 24), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Le PIN protège l’accès local à l’application. L’empreinte utilise la sécurité biométrique du téléphone. Le PIN reste le secours si l’empreinte échoue.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/fin65_biometrics_local_auth_api_fix/README_FIX_LOCAL_AUTH_API.md b/fin65_biometrics_local_auth_api_fix/README_FIX_LOCAL_AUTH_API.md new file mode 100644 index 0000000..f7e1e3c --- /dev/null +++ b/fin65_biometrics_local_auth_api_fix/README_FIX_LOCAL_AUTH_API.md @@ -0,0 +1,40 @@ +# FIN65 - Fix local_auth API + +Ce patch corrige l'erreur : + +```text +No named parameter with the name 'options' +Not a constant expression: AuthenticationOptions +``` + +Ton projet a résolu une version de `local_auth` où l'appel doit être écrit avec les paramètres directs : + +```dart +authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, +) +``` + +et non avec : + +```dart +options: AuthenticationOptions(...) +``` + +## Utilisation + +Décompresse ce ZIP, puis lance : + +```powershell +.\fix_local_auth_api.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` diff --git a/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat b/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat new file mode 100644 index 0000000..0f0019f --- /dev/null +++ b/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat @@ -0,0 +1,4 @@ +@echo off +setlocal + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0fix_local_auth_api.bat.ps1" diff --git a/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat.ps1 b/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat.ps1 new file mode 100644 index 0000000..698e902 --- /dev/null +++ b/fin65_biometrics_local_auth_api_fix/fix_local_auth_api.bat.ps1 @@ -0,0 +1,80 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$SecurityService = Join-Path $MobileDir "lib\services\security_service.dart" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Fix local_auth API" +Write-Host "==========================================" +Write-Host "" + +if (!(Test-Path $SecurityService)) { + Write-Host "[ERREUR] Fichier introuvable : $SecurityService" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$Stamp = Get-Date -Format "yyyyMMdd_HHmmss" +Copy-Item $SecurityService "$SecurityService.before_local_auth_fix_$Stamp.bak" -Force +Write-Host "Sauvegarde : $SecurityService.before_local_auth_fix_$Stamp.bak" + +$text = Get-Content $SecurityService -Raw + +# Remplace l'appel local_auth récent : +# authenticate(localizedReason: ..., options: AuthenticationOptions(...)) +# par l'API compatible avec la version résolue dans ton projet : +# authenticate(localizedReason: ..., biometricOnly: true, stickyAuth: true, useErrorDialogs: true) +$oldBlock = @' + return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + options: const AuthenticationOptions( + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, + ), + ); +'@ + +$newBlock = @' + return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, + ); +'@ + +if ($text.Contains($oldBlock)) { + $text = $text.Replace($oldBlock, $newBlock) +} else { + # Fallback regex au cas où l'indentation varie. + $pattern = "(?ms)return await _localAuth\.authenticate\(\s*localizedReason:\s*'Déverrouiller FIN65',\s*options:\s*(?:const\s*)?AuthenticationOptions\(\s*biometricOnly:\s*true,\s*stickyAuth:\s*true,\s*useErrorDialogs:\s*true,\s*\),\s*\);" + $replacement = @" +return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, + ); +"@ + $text = [regex]::Replace($text, $pattern, $replacement) +} + +Set-Content -Path $SecurityService -Value $text -Encoding UTF8 + +Write-Host "" +Write-Host "Verification :" +Select-String -Path $SecurityService -Pattern "authenticate|AuthenticationOptions|biometricOnly|stickyAuth|useErrorDialogs" | ForEach-Object { Write-Host $_.Line } + +Set-Location $MobileDir + +Write-Host "" +Write-Host "Nettoyage Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Fix local_auth termine." +Write-Host "Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_biometrics_local_auth_minimal_fix/README_FIX_LOCAL_AUTH_MINIMAL.md b/fin65_biometrics_local_auth_minimal_fix/README_FIX_LOCAL_AUTH_MINIMAL.md new file mode 100644 index 0000000..829a978 --- /dev/null +++ b/fin65_biometrics_local_auth_minimal_fix/README_FIX_LOCAL_AUTH_MINIMAL.md @@ -0,0 +1,33 @@ +# FIN65 - Fix local_auth minimal + +Ce correctif répond à l'erreur : + +```text +No named parameter with the name 'stickyAuth' +``` + +Ta version installée de `local_auth` accepte l'appel direct, mais pas `stickyAuth`. + +Le script remplace l'appel par la version minimale : + +```dart +return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, +); +``` + +## Utilisation + +Décompresse puis lance : + +```powershell +.\fix_local_auth_minimal.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` diff --git a/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat b/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat new file mode 100644 index 0000000..a5c6de6 --- /dev/null +++ b/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat @@ -0,0 +1,4 @@ +@echo off +setlocal + +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0fix_local_auth_minimal.bat.ps1" diff --git a/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat.ps1 b/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat.ps1 new file mode 100644 index 0000000..024cd79 --- /dev/null +++ b/fin65_biometrics_local_auth_minimal_fix/fix_local_auth_minimal.bat.ps1 @@ -0,0 +1,59 @@ +$MobileDir = "D:\07-Logiciels\20-FIN65\fin65_mobile" +$SecurityService = Join-Path $MobileDir "lib\services\security_service.dart" + +Write-Host "" +Write-Host "==========================================" +Write-Host " FIN65 - Fix local_auth minimal" +Write-Host "==========================================" +Write-Host "" + +if (!(Test-Path $SecurityService)) { + Write-Host "[ERREUR] Fichier introuvable : $SecurityService" -ForegroundColor Red + Read-Host "Appuie sur Entree pour fermer" + exit 1 +} + +$Stamp = Get-Date -Format "yyyyMMdd_HHmmss" +Copy-Item $SecurityService "$SecurityService.before_local_auth_minimal_fix_$Stamp.bak" -Force +Write-Host "Sauvegarde : $SecurityService.before_local_auth_minimal_fix_$Stamp.bak" + +$text = Get-Content $SecurityService -Raw + +# Corrige l'appel local_auth vers la forme la plus compatible avec la version installee : +# pas de options:, pas de stickyAuth:, pas de useErrorDialogs:. +# On garde biometricOnly, que ta version semble accepter. +$pattern = "(?ms)return await _localAuth\.authenticate\(\s*localizedReason:\s*'Déverrouiller FIN65',.*?\);" +$replacement = @" +return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + ); +"@ + +$newText = [regex]::Replace($text, $pattern, $replacement) + +if ($newText -eq $text) { + Write-Host "[ATTENTION] Aucun bloc authenticate remplace. Affichage des lignes concernees :" -ForegroundColor Yellow + Select-String -Path $SecurityService -Pattern "authenticate|biometricOnly|stickyAuth|useErrorDialogs|AuthenticationOptions" | ForEach-Object { Write-Host $_.Line } +} else { + Set-Content -Path $SecurityService -Value $newText -Encoding UTF8 + Write-Host "security_service.dart corrige." +} + +Write-Host "" +Write-Host "Verification :" +Select-String -Path $SecurityService -Pattern "authenticate|biometricOnly|stickyAuth|useErrorDialogs|AuthenticationOptions" | ForEach-Object { Write-Host $_.Line } + +Set-Location $MobileDir + +Write-Host "" +Write-Host "Nettoyage Flutter..." +flutter clean +flutter pub get + +Write-Host "" +Write-Host "Fix local_auth minimal termine." +Write-Host "Relance maintenant :" +Write-Host "flutter run" +Write-Host "" +Read-Host "Appuie sur Entree pour fermer" diff --git a/fin65_biometrics_stability_fix_v2_6_2/README_BIOMETRICS_STABILITY_FIX_V2_6_2.md b/fin65_biometrics_stability_fix_v2_6_2/README_BIOMETRICS_STABILITY_FIX_V2_6_2.md new file mode 100644 index 0000000..5d3522d --- /dev/null +++ b/fin65_biometrics_stability_fix_v2_6_2/README_BIOMETRICS_STABILITY_FIX_V2_6_2.md @@ -0,0 +1,46 @@ +# FIN65 - Fix stabilité biométrie V2.6.2 + +Ce patch corrige l'erreur Flutter : + +```text +Failed assertion: '_dependents.isEmpty': is not true. +``` + +## Cause probable + +Le fix précédent ouvrait une boîte de dialogue Flutter puis lançait l'authentification biométrique Android dans le même flux. Flutter n'a pas apprécié ce petit numéro de cirque entre navigation, dialogue et prompt système. + +## Correction + +Cette version simplifie le flux : + +- plus de boîte de dialogue Flutter pour activer l'empreinte ; +- plus de lancement automatique de l'empreinte au verrouillage ; +- l’empreinte s’active depuis l’écran Sécurité après avoir entré le PIN actuel dans le champ visible ; +- au verrouillage, l’utilisateur appuie manuellement sur `Utiliser l’empreinte`. + +## Installation + +Décompresse puis lance : + +```powershell +.\apply_biometrics_stability_fix_v2_6_2.bat +``` + +Ensuite : + +```powershell +cd D:\07-Logiciels\20-FIN65\fin65_mobile +flutter run +``` + +## Test + +1. Paramètres > Sécurité. +2. Entre le PIN actuel dans le champ `PIN actuel`. +3. Active l’interrupteur empreinte. +4. Mets l’app en arrière-plan. +5. Rouvre l’app. +6. Appuie sur `Utiliser l’empreinte`. + +Cette version est volontairement moins magique, donc moins susceptible de s’écrouler comme une étagère IKEA montée avec colère. diff --git a/fin65_biometrics_stability_fix_v2_6_2/apply_biometrics_stability_fix_v2_6_2.bat b/fin65_biometrics_stability_fix_v2_6_2/apply_biometrics_stability_fix_v2_6_2.bat new file mode 100644 index 0000000..a2c713b --- /dev/null +++ b/fin65_biometrics_stability_fix_v2_6_2/apply_biometrics_stability_fix_v2_6_2.bat @@ -0,0 +1,60 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Fix stabilite biometrie V2.6.2 +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +echo. +echo ========================================== +echo FIN65 - Fix stabilite biometrie V2.6.2 +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + pause + exit /b 1 +) + +if not exist "%MOBILE_DIR%\lib\screens" ( + echo [ERREUR] Dossier screens introuvable. + pause + exit /b 1 +) + +set "BACKUP_DIR=%MOBILE_DIR%\backup_before_biometrics_stability_v262" +mkdir "%BACKUP_DIR%" >nul 2>&1 + +if exist "%MOBILE_DIR%\lib\screens\security_screen.dart" ( + copy /Y "%MOBILE_DIR%\lib\screens\security_screen.dart" "%BACKUP_DIR%\security_screen.dart.bak" >nul +) + +if exist "%MOBILE_DIR%\lib\screens\app_lock_gate.dart" ( + copy /Y "%MOBILE_DIR%\lib\screens\app_lock_gate.dart" "%BACKUP_DIR%\app_lock_gate.dart.bak" >nul +) + +copy /Y "%~dp0lib\screens\security_screen.dart" "%MOBILE_DIR%\lib\screens\security_screen.dart" >nul +copy /Y "%~dp0lib\screens\app_lock_gate.dart" "%MOBILE_DIR%\lib\screens\app_lock_gate.dart" >nul + +cd /d "%MOBILE_DIR%" + +echo. +echo Nettoyage Flutter... +flutter clean +flutter pub get + +echo. +echo ========================================== +echo Fix stabilite biometrie applique. +echo ========================================== +echo. +echo Relance maintenant : +echo flutter run +echo. +pause diff --git a/fin65_biometrics_stability_fix_v2_6_2/lib/screens/app_lock_gate.dart b/fin65_biometrics_stability_fix_v2_6_2/lib/screens/app_lock_gate.dart new file mode 100644 index 0000000..c450735 --- /dev/null +++ b/fin65_biometrics_stability_fix_v2_6_2/lib/screens/app_lock_gate.dart @@ -0,0 +1,248 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../services/security_service.dart'; + +class AppLockGate extends StatefulWidget { + const AppLockGate({ + super.key, + required this.securityService, + required this.child, + }); + + final SecurityService securityService; + final Widget child; + + @override + State createState() => _AppLockGateState(); +} + +class _AppLockGateState extends State with WidgetsBindingObserver { + bool _checking = true; + bool _locked = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _loadLockState(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) { + _lockIfNeeded(); + } + } + + Future _loadLockState() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted) return; + setState(() { + _locked = enabled; + _checking = false; + }); + } + + Future _lockIfNeeded() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted || !enabled) return; + setState(() => _locked = true); + } + + void _unlock() { + setState(() => _locked = false); + } + + @override + Widget build(BuildContext context) { + if (_checking) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + if (_locked) { + return PinUnlockScreen( + securityService: widget.securityService, + onUnlocked: _unlock, + ); + } + + return widget.child; + } +} + +class PinUnlockScreen extends StatefulWidget { + const PinUnlockScreen({ + super.key, + required this.securityService, + required this.onUnlocked, + }); + + final SecurityService securityService; + final VoidCallback onUnlocked; + + @override + State createState() => _PinUnlockScreenState(); +} + +class _PinUnlockScreenState extends State { + final _pinController = TextEditingController(); + bool _checking = false; + bool _checkingBiometric = false; + bool _biometricEnabled = false; + bool _biometricAvailable = false; + String? _error; + + @override + void initState() { + super.initState(); + _loadBiometricState(); + } + + @override + void dispose() { + _pinController.dispose(); + super.dispose(); + } + + Future _loadBiometricState() async { + final enabled = await widget.securityService.isBiometricEnabled(); + final available = await widget.securityService.isBiometricAvailable(); + + if (!mounted) return; + setState(() { + _biometricEnabled = enabled; + _biometricAvailable = available; + }); + } + + Future _unlockWithBiometrics() async { + if (_checkingBiometric) return; + + setState(() { + _checkingBiometric = true; + _error = null; + }); + + final ok = await widget.securityService.authenticateWithBiometrics(); + + if (!mounted) return; + + if (ok) { + widget.onUnlocked(); + } else { + setState(() { + _checkingBiometric = false; + _error = 'Empreinte refusée ou annulée. Utilise le PIN.'; + }); + } + } + + Future _unlock() async { + if (_checking) return; + + setState(() { + _checking = true; + _error = null; + }); + + final ok = await widget.securityService.verifyPin(_pinController.text.trim()); + + if (!mounted) return; + + if (ok) { + _pinController.clear(); + widget.onUnlocked(); + } else { + HapticFeedback.vibrate(); + setState(() { + _checking = false; + _error = 'PIN incorrect.'; + }); + } + } + + @override + Widget build(BuildContext context) { + final showBiometric = _biometricEnabled && _biometricAvailable; + + return Scaffold( + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.all(24), + children: [ + Icon(showBiometric ? Icons.fingerprint : Icons.lock, size: 64), + const SizedBox(height: 16), + Text( + 'FIN65 verrouillé', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 8), + Text( + showBiometric + ? 'Déverrouille avec ton empreinte ou ton PIN.' + : 'Entre ton PIN pour accéder aux données locales.', + textAlign: TextAlign.center, + ), + if (showBiometric) ...[ + const SizedBox(height: 24), + FilledButton.icon( + onPressed: _checkingBiometric ? null : _unlockWithBiometrics, + icon: _checkingBiometric + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.fingerprint), + label: Text(_checkingBiometric ? 'Vérification...' : 'Utiliser l’empreinte'), + ), + ], + const SizedBox(height: 24), + TextField( + controller: _pinController, + autofocus: !showBiometric, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: 'PIN', + border: const OutlineInputBorder(), + errorText: _error, + counterText: '', + ), + onSubmitted: (_) => _checking ? null : _unlock(), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _checking ? null : _unlock, + icon: _checking + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.lock_open), + label: Text(_checking ? 'Vérification...' : 'Déverrouiller avec le PIN'), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/fin65_biometrics_stability_fix_v2_6_2/lib/screens/security_screen.dart b/fin65_biometrics_stability_fix_v2_6_2/lib/screens/security_screen.dart new file mode 100644 index 0000000..c3349fd --- /dev/null +++ b/fin65_biometrics_stability_fix_v2_6_2/lib/screens/security_screen.dart @@ -0,0 +1,311 @@ +import 'package:flutter/material.dart'; +import 'package:local_auth/local_auth.dart'; + +import '../services/security_service.dart'; + +class SecurityScreen extends StatefulWidget { + const SecurityScreen({ + super.key, + required this.securityService, + }); + + final SecurityService securityService; + + @override + State createState() => _SecurityScreenState(); +} + +class _SecurityScreenState extends State { + final _currentPinController = TextEditingController(); + final _newPinController = TextEditingController(); + final _confirmPinController = TextEditingController(); + + bool _loading = true; + bool _saving = false; + bool _enabled = false; + bool _biometricAvailable = false; + bool _biometricEnabled = false; + List _availableBiometrics = const []; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _currentPinController.dispose(); + _newPinController.dispose(); + _confirmPinController.dispose(); + super.dispose(); + } + + Future _load() async { + final enabled = await widget.securityService.isPinEnabled(); + final biometricAvailable = await widget.securityService.isBiometricAvailable(); + final biometricEnabled = await widget.securityService.isBiometricEnabled(); + final availableBiometrics = await widget.securityService.getAvailableBiometrics(); + + if (!mounted) return; + setState(() { + _enabled = enabled; + _biometricAvailable = biometricAvailable; + _biometricEnabled = biometricEnabled; + _availableBiometrics = availableBiometrics; + _loading = false; + }); + } + + Future _verifyCurrentPinFromField() async { + final current = _currentPinController.text.trim(); + final ok = await widget.securityService.verifyPin(current); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + return true; + } + + Future _savePin() async { + final newPin = _newPinController.text.trim(); + final confirm = _confirmPinController.text.trim(); + + if (newPin != confirm) { + setState(() => _message = 'Le nouveau PIN et la confirmation ne correspondent pas.'); + return; + } + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (_enabled) { + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + } + + await widget.securityService.setPin(newPin); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN activé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _disablePin() async { + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + + await widget.securityService.disablePin(); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN et biométrie désactivés.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _toggleBiometrics(bool value) async { + if (_saving) return; + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (!_enabled) { + setState(() => _message = 'Active d’abord un PIN avant la biométrie.'); + return; + } + + if (value && !_biometricAvailable) { + setState(() => _message = 'Aucune empreinte/biométrie disponible sur ce téléphone.'); + return; + } + + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(value); + _currentPinController.clear(); + + await _load(); + + setState(() { + _message = value + ? 'Déverrouillage par empreinte activé. Verrouille l’app puis teste avec le bouton empreinte.' + : 'Déverrouillage par empreinte désactivé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _biometricLabel() { + if (_availableBiometrics.isEmpty) return 'Aucune biométrie détectée.'; + + final labels = _availableBiometrics.map((type) { + return switch (type) { + BiometricType.fingerprint => 'empreinte', + BiometricType.face => 'visage', + BiometricType.iris => 'iris', + BiometricType.strong => 'biométrie forte', + BiometricType.weak => 'biométrie faible', + }; + }).toSet().join(', '); + + return 'Disponible : $labels.'; + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: const Center(child: CircularProgressIndicator()), + ); + } + + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: SwitchListTile( + value: _enabled, + onChanged: null, + secondary: Icon(_enabled ? Icons.lock : Icons.lock_open), + title: const Text('Verrouillage PIN'), + subtitle: Text( + _enabled + ? 'Activé. L’app se verrouille à la fermeture ou au changement d’application.' + : 'Désactivé. Tes données locales sont accessibles sans PIN.', + ), + ), + ), + if (_enabled) ...[ + const SizedBox(height: 12), + Card( + child: SwitchListTile( + value: _biometricEnabled, + onChanged: _saving || !_biometricAvailable ? null : _toggleBiometrics, + secondary: const Icon(Icons.fingerprint), + title: const Text('Déverrouillage par empreinte'), + subtitle: Text( + _biometricAvailable + ? '${_biometricLabel()} Entre le PIN actuel ci-dessous puis active l’interrupteur.' + : 'Aucune empreinte/biométrie disponible ou configurée sur ce téléphone.', + ), + ), + ), + ], + const SizedBox(height: 16), + if (_enabled) ...[ + TextField( + controller: _currentPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + helperText: 'Nécessaire pour changer le PIN, désactiver le PIN ou activer/désactiver l’empreinte.', + counterText: '', + ), + ), + const SizedBox(height: 12), + ], + TextField( + controller: _newPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: _enabled ? 'Nouveau PIN' : 'PIN', + border: const OutlineInputBorder(), + helperText: '4 à 8 chiffres.', + counterText: '', + ), + ), + const SizedBox(height: 12), + TextField( + controller: _confirmPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'Confirmer le PIN', + border: OutlineInputBorder(), + counterText: '', + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _saving ? null : _savePin, + icon: const Icon(Icons.save), + label: Text(_enabled ? 'Changer le PIN' : 'Activer le PIN'), + ), + if (_enabled) ...[ + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _saving ? null : _disablePin, + icon: const Icon(Icons.lock_open), + label: const Text('Désactiver le PIN'), + ), + ], + if (_message != null) ...[ + const SizedBox(height: 16), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 24), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Le PIN protège l’accès local à l’application. L’empreinte utilise la sécurité biométrique du téléphone. Le PIN reste le secours si l’empreinte échoue.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/fin65_start_mobile_scripts/README_START_MOBILE.md b/fin65_start_mobile_scripts/README_START_MOBILE.md new file mode 100644 index 0000000..93a8be7 --- /dev/null +++ b/fin65_start_mobile_scripts/README_START_MOBILE.md @@ -0,0 +1,59 @@ +# FIN65 - Scripts mobile Android + +## Script principal recommandé + +Copie ce fichier dans : + +```text +D:\07-Logiciels\20-FIN65\ +``` + +Puis lance : + +```text +start_fin65_mobile_flutter.bat +``` + +Il démarre l'application mobile Flutter depuis : + +```text +D:\07-Logiciels\20-FIN65\fin65_mobile +``` + +avec le cache Pub : + +```text +D:\07-Logiciels\20-FIN65\.pub-cache +``` + +## Fichiers inclus + +### `start_fin65_mobile_flutter.bat` + +Lance l'app en mode Flutter debug : + +```powershell +flutter run -d 2304FPN6DG +``` + +C'est le script à utiliser pendant le développement. + +### `open_fin65_android_app.bat` + +Ouvre seulement l'application déjà installée sur le téléphone. + +Ne recompile pas. + +### `install_fin65_android_debug.bat` + +Compile et installe l'APK debug sans rester connecté à `flutter run`. + +## Important + +Le backend se lance séparément avec : + +```text +start_fin65_backend.bat +``` + +L'application mobile peut fonctionner hors ligne, puis synchroniser quand le backend est de nouveau lancé. diff --git a/fin65_start_mobile_scripts/install_fin65_android_debug.bat b/fin65_start_mobile_scripts/install_fin65_android_debug.bat new file mode 100644 index 0000000..5cbe4a1 --- /dev/null +++ b/fin65_start_mobile_scripts/install_fin65_android_debug.bat @@ -0,0 +1,69 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Installer APK debug Android sans flutter run +REM Compile l'APK debug puis l'installe sur le telephone. +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" +set "DEVICE_ID=2304FPN6DG" +set "APK_PATH=%MOBILE_DIR%\build\app\outputs\flutter-apk\app-debug.apk" + +echo. +echo ========================================== +echo FIN65 - Build et installation APK +echo ========================================== +echo. + +cd /d "%MOBILE_DIR%" || ( + echo [ERREUR] Dossier mobile introuvable. + pause + exit /b 1 +) + +echo PUB_CACHE : +echo %PUB_CACHE% +echo. + +flutter pub get +if errorlevel 1 ( + echo [ERREUR] flutter pub get a echoue. + pause + exit /b 1 +) + +flutter build apk --debug +if errorlevel 1 ( + echo [ERREUR] build APK echoue. + pause + exit /b 1 +) + +if not exist "%APK_PATH%" ( + echo [ERREUR] APK introuvable : + echo %APK_PATH% + pause + exit /b 1 +) + +if "%DEVICE_ID%"=="" ( + adb install -r "%APK_PATH%" +) else ( + adb -s %DEVICE_ID% install -r "%APK_PATH%" +) + +if errorlevel 1 ( + echo [ERREUR] Installation APK echouee. + pause + exit /b 1 +) + +echo. +echo APK installe. +echo Tu peux ouvrir l'app avec : +echo open_fin65_android_app.bat +echo. +pause diff --git a/fin65_start_mobile_scripts/open_fin65_android_app.bat b/fin65_start_mobile_scripts/open_fin65_android_app.bat new file mode 100644 index 0000000..949ffe4 --- /dev/null +++ b/fin65_start_mobile_scripts/open_fin65_android_app.bat @@ -0,0 +1,51 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Ouvrir l'application Android deja installee +REM Ne recompile pas. Lance juste l'app sur le telephone. +REM ============================================================ + +set "DEVICE_ID=2304FPN6DG" +set "PACKAGE_NAME=com.example.fin65_mobile" + +echo. +echo ========================================== +echo FIN65 - Ouvrir app Android installee +echo ========================================== +echo. + +adb version >nul 2>&1 +if errorlevel 1 ( + echo [ERREUR] adb n'est pas reconnu. + echo Lance plutot start_fin65_mobile_flutter.bat ou verifie Android Platform Tools. + echo. + pause + exit /b 1 +) + +echo Appareils ADB : +adb devices +echo. + +echo Ouverture de l'application %PACKAGE_NAME%... +echo. + +if "%DEVICE_ID%"=="" ( + adb shell monkey -p %PACKAGE_NAME% -c android.intent.category.LAUNCHER 1 +) else ( + adb -s %DEVICE_ID% shell monkey -p %PACKAGE_NAME% -c android.intent.category.LAUNCHER 1 +) + +if errorlevel 1 ( + echo. + echo [ERREUR] Impossible d'ouvrir l'application. + echo Verifie que le telephone est connecte et que l'app est installee. + echo. + pause + exit /b 1 +) + +echo. +echo Application lancee. +pause diff --git a/fin65_start_mobile_scripts/start_fin65_mobile_flutter.bat b/fin65_start_mobile_scripts/start_fin65_mobile_flutter.bat new file mode 100644 index 0000000..73d38fc --- /dev/null +++ b/fin65_start_mobile_scripts/start_fin65_mobile_flutter.bat @@ -0,0 +1,91 @@ +@echo off +setlocal + +REM ============================================================ +REM FIN65 - Demarrage application mobile Android via Flutter +REM Projet attendu : +REM D:\07-Logiciels\20-FIN65\fin65_mobile +REM ============================================================ + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +REM Ton telephone vu dans les logs Flutter. +REM Laisse vide pour laisser Flutter choisir automatiquement. +set "DEVICE_ID=2304FPN6DG" + +echo. +echo ========================================== +echo FIN65 - Application Android Flutter +echo ========================================== +echo. + +if not exist "%MOBILE_DIR%" ( + echo [ERREUR] Dossier mobile introuvable : + echo %MOBILE_DIR% + echo. + pause + exit /b 1 +) + +cd /d "%MOBILE_DIR%" + +if not exist "pubspec.yaml" ( + echo [ERREUR] pubspec.yaml introuvable dans : + echo %MOBILE_DIR% + echo. + pause + exit /b 1 +) + +if not exist "lib\main.dart" ( + echo [ERREUR] lib\main.dart introuvable. + echo. + pause + exit /b 1 +) + +echo Dossier mobile : +echo %CD% +echo. +echo PUB_CACHE : +echo %PUB_CACHE% +echo. + +echo Verification Flutter... +flutter --version >nul 2>&1 +if errorlevel 1 ( + echo [ERREUR] Flutter n'est pas reconnu dans ce terminal. + echo Verifie que Flutter est dans le PATH. + echo. + pause + exit /b 1 +) + +echo Appareils detectes : +flutter devices +echo. + +echo Recuperation des dependances... +flutter pub get +if errorlevel 1 ( + echo. + echo [ERREUR] flutter pub get a echoue. + pause + exit /b 1 +) + +echo. +echo Lancement de FIN65 mobile... +echo. + +if "%DEVICE_ID%"=="" ( + flutter run +) else ( + flutter run -d %DEVICE_ID% +) + +echo. +echo Application arretee. +pause diff --git a/flutter_launcher_icons.yaml b/flutter_launcher_icons.yaml new file mode 100644 index 0000000..83f4715 --- /dev/null +++ b/flutter_launcher_icons.yaml @@ -0,0 +1,7 @@ +flutter_launcher_icons: + android: true + ios: false + image_path: "assets/icon/app_icon.png" + adaptive_icon_background: "#0F172A" + adaptive_icon_foreground: "assets/icon/adaptive_foreground.png" + min_sdk_android: 23 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..748f2cb --- /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 = com.example.fin65Mobile; + 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 = com.example.fin65Mobile.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 = com.example.fin65Mobile.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 = com.example.fin65Mobile.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 = com.example.fin65Mobile; + 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 = com.example.fin65Mobile; + 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 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..27c9645 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Fin65 Mobile + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + fin65_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/config/app_config.dart b/lib/config/app_config.dart new file mode 100644 index 0000000..da6296a --- /dev/null +++ b/lib/config/app_config.dart @@ -0,0 +1,4 @@ +class AppConfig { + static const String defaultApiBaseUrl = 'http://10.0.2.2:8000'; + static const int defaultTransactionLimit = 50; +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..01bc1ed --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; +import 'package:intl/date_symbol_data_local.dart'; + +import 'screens/home_screen.dart'; +import 'services/offline_store.dart'; +import 'services/sync_service.dart'; +import 'services/api_service.dart'; +import 'services/security_service.dart'; +import 'screens/app_lock_gate.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await initializeDateFormatting('fr_FR', null); + + ErrorWidget.builder = (FlutterErrorDetails details) { + return Material( + child: SafeArea( + child: Padding( + padding: const EdgeInsets.all(16), + child: SingleChildScrollView( + child: Text( + 'Erreur FIN65 mobile :\n\n${details.exceptionAsString()}', + style: const TextStyle(fontSize: 14), + ), + ), + ), + ), + ); + }; + + runApp(const Fin65MobileApp()); +} + +class Fin65MobileApp extends StatelessWidget { + const Fin65MobileApp({super.key}); + + @override + Widget build(BuildContext context) { + final store = OfflineStore.instance; + final apiService = ApiService(store: store); + final syncService = SyncService( + offlineStore: store, + apiService: apiService, + ); + + return MaterialApp( + title: 'FIN65', + debugShowCheckedModeBanner: false, + theme: ThemeData( + colorSchemeSeed: const Color(0xFF1F6FEB), + useMaterial3: true, + cardTheme: const CardThemeData( + margin: EdgeInsets.symmetric(vertical: 4), + ), + ), + home: AppLockGate( + securityService: SecurityService(store: store), + child: HomeScreen(syncService: syncService), + ), + ); + } +} diff --git a/lib/models/account.dart b/lib/models/account.dart new file mode 100644 index 0000000..40fd0bd --- /dev/null +++ b/lib/models/account.dart @@ -0,0 +1,90 @@ +class Account { + final int id; + final String name; + final String type; + final String currency; + final double initialBalance; + final double appBalance; + final bool isActive; + + Account({ + required this.id, + required this.name, + required this.type, + required this.currency, + required this.initialBalance, + required this.appBalance, + required this.isActive, + }); + + factory Account.fromJson(Map json) { + return Account( + id: json['id'] as int, + name: json['name'] as String, + type: json['type'] as String, + currency: json['currency'] as String? ?? 'MAD', + initialBalance: (json['initial_balance'] as num? ?? 0).toDouble(), + appBalance: (json['app_balance'] as num? ?? 0).toDouble(), + isActive: json['is_active'] is int + ? (json['is_active'] as int) == 1 + : json['is_active'] as bool? ?? true, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'type': type, + 'currency': currency, + 'initial_balance': initialBalance, + 'app_balance': appBalance, + 'is_active': isActive, + }; + } + + Map toDbMap() { + return { + 'id': id, + 'name': name, + 'type': type, + 'currency': currency, + 'initial_balance': initialBalance, + 'app_balance': appBalance, + 'is_active': isActive ? 1 : 0, + 'updated_at': DateTime.now().toIso8601String(), + }; + } + + factory Account.fromDbMap(Map map) { + return Account( + id: map['id'] as int, + name: map['name'] as String, + type: map['type'] as String, + currency: map['currency'] as String? ?? 'MAD', + initialBalance: (map['initial_balance'] as num? ?? 0).toDouble(), + appBalance: (map['app_balance'] as num? ?? 0).toDouble(), + isActive: (map['is_active'] as int? ?? 1) == 1, + ); + } + + Account copyWith({ + int? id, + String? name, + String? type, + String? currency, + double? initialBalance, + double? appBalance, + bool? isActive, + }) { + return Account( + id: id ?? this.id, + name: name ?? this.name, + type: type ?? this.type, + currency: currency ?? this.currency, + initialBalance: initialBalance ?? this.initialBalance, + appBalance: appBalance ?? this.appBalance, + isActive: isActive ?? this.isActive, + ); + } +} diff --git a/lib/models/category.dart b/lib/models/category.dart new file mode 100644 index 0000000..bd9e653 --- /dev/null +++ b/lib/models/category.dart @@ -0,0 +1,50 @@ +class Category { + final int id; + final String name; + final String type; + final int? parentId; + + Category({ + required this.id, + required this.name, + required this.type, + this.parentId, + }); + + factory Category.fromJson(Map json) { + return Category( + id: json['id'] as int, + name: json['name'] as String, + type: json['type'] as String, + parentId: json['parent_id'] as int?, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'type': type, + 'parent_id': parentId, + }; + } + + Map toDbMap() { + return { + 'id': id, + 'name': name, + 'type': type, + 'parent_id': parentId, + 'updated_at': DateTime.now().toIso8601String(), + }; + } + + factory Category.fromDbMap(Map map) { + return Category( + id: map['id'] as int, + name: map['name'] as String, + type: map['type'] as String, + parentId: map['parent_id'] as int?, + ); + } +} diff --git a/lib/models/dashboard.dart b/lib/models/dashboard.dart new file mode 100644 index 0000000..6a6a3f2 --- /dev/null +++ b/lib/models/dashboard.dart @@ -0,0 +1,223 @@ +import 'account.dart'; + +class ReconciliationStatus { + final int accountId; + final String accountName; + final double appBalance; + final bool checkedToday; + final double? realBalance; + final double? difference; + + ReconciliationStatus({ + required this.accountId, + required this.accountName, + required this.appBalance, + required this.checkedToday, + this.realBalance, + this.difference, + }); + + factory ReconciliationStatus.fromJson(Map json) { + return ReconciliationStatus( + accountId: json['account_id'] as int, + accountName: json['account_name'] as String, + appBalance: (json['app_balance'] as num? ?? 0).toDouble(), + checkedToday: json['checked_today'] is int + ? (json['checked_today'] as int) == 1 + : json['checked_today'] as bool? ?? false, + realBalance: (json['real_balance'] as num?)?.toDouble(), + difference: (json['difference'] as num?)?.toDouble(), + ); + } + + Map toJson() { + return { + 'account_id': accountId, + 'account_name': accountName, + 'app_balance': appBalance, + 'checked_today': checkedToday, + 'real_balance': realBalance, + 'difference': difference, + }; + } + + ReconciliationStatus copyWith({ + double? appBalance, + bool? checkedToday, + double? realBalance, + double? difference, + }) { + return ReconciliationStatus( + accountId: accountId, + accountName: accountName, + appBalance: appBalance ?? this.appBalance, + checkedToday: checkedToday ?? this.checkedToday, + realBalance: realBalance ?? this.realBalance, + difference: difference ?? this.difference, + ); + } +} + +class DashboardData { + final String month; + final double totalBalance; + final double availableAfterReserves; + final double monthlyIncome; + final double monthlyExpenses; + final double monthlyBalance; + final double provisionsCurrentTotal; + final double provisionsTargetTotal; + final double monthlyChargesRemainingTotal; + final double monthlyTransferRemainingTotal; + final double monthlyProvisionOperationRemainingTotal; + + // Nouveaux champs backend : échéancier / opérations prévues ponctuelles. + final double scheduledExpensesRemainingTotal; + final double scheduledIncomeRemainingTotal; + final double scheduledTransferRemainingTotal; + final double scheduledProvisionRemainingTotal; + final double scheduledNetRemainingTotal; + final double projectedMonthBalance; + + final List accounts; + final List reconciliationsToday; + + DashboardData({ + required this.month, + required this.totalBalance, + required this.availableAfterReserves, + required this.monthlyIncome, + required this.monthlyExpenses, + required this.monthlyBalance, + required this.provisionsCurrentTotal, + required this.provisionsTargetTotal, + required this.monthlyChargesRemainingTotal, + required this.monthlyTransferRemainingTotal, + required this.monthlyProvisionOperationRemainingTotal, + required this.scheduledExpensesRemainingTotal, + required this.scheduledIncomeRemainingTotal, + required this.scheduledTransferRemainingTotal, + required this.scheduledProvisionRemainingTotal, + required this.scheduledNetRemainingTotal, + required this.projectedMonthBalance, + required this.accounts, + required this.reconciliationsToday, + }); + + double get plannedExpensesTotal => + monthlyChargesRemainingTotal + scheduledExpensesRemainingTotal; + + double get plannedTransfersTotal => + monthlyTransferRemainingTotal + scheduledTransferRemainingTotal; + + double get plannedProvisionsTotal => + monthlyProvisionOperationRemainingTotal + scheduledProvisionRemainingTotal; + + bool get hasScheduledInfo => + scheduledExpensesRemainingTotal != 0 || + scheduledIncomeRemainingTotal != 0 || + scheduledTransferRemainingTotal != 0 || + scheduledProvisionRemainingTotal != 0; + + factory DashboardData.fromJson(Map json) { + final availableRaw = json['available_after_reserves'] ?? json['total_balance'] ?? 0; + + final monthlyBalance = (json['monthly_balance'] as num? ?? 0).toDouble(); + final scheduledIncome = (json['scheduled_income_remaining_total'] as num? ?? 0).toDouble(); + final scheduledExpenses = (json['scheduled_expenses_remaining_total'] as num? ?? 0).toDouble(); + + return DashboardData( + month: json['month'] as String? ?? '', + totalBalance: (json['total_balance'] as num? ?? 0).toDouble(), + availableAfterReserves: (availableRaw as num).toDouble(), + monthlyIncome: (json['monthly_income'] as num? ?? 0).toDouble(), + monthlyExpenses: (json['monthly_expenses'] as num? ?? 0).toDouble(), + monthlyBalance: monthlyBalance, + provisionsCurrentTotal: (json['provisions_current_total'] as num? ?? 0).toDouble(), + provisionsTargetTotal: (json['provisions_target_total'] as num? ?? 0).toDouble(), + monthlyChargesRemainingTotal: (json['monthly_charges_remaining_total'] as num? ?? 0).toDouble(), + monthlyTransferRemainingTotal: (json['monthly_transfer_remaining_total'] as num? ?? 0).toDouble(), + monthlyProvisionOperationRemainingTotal: (json['monthly_provision_operation_remaining_total'] as num? ?? 0).toDouble(), + scheduledExpensesRemainingTotal: scheduledExpenses, + scheduledIncomeRemainingTotal: scheduledIncome, + scheduledTransferRemainingTotal: (json['scheduled_transfer_remaining_total'] as num? ?? 0).toDouble(), + scheduledProvisionRemainingTotal: (json['scheduled_provision_remaining_total'] as num? ?? 0).toDouble(), + scheduledNetRemainingTotal: (json['scheduled_net_remaining_total'] as num? ?? (scheduledIncome - scheduledExpenses)).toDouble(), + projectedMonthBalance: (json['projected_month_balance'] as num? ?? (monthlyBalance + scheduledIncome - scheduledExpenses)).toDouble(), + accounts: (json['accounts'] as List? ?? []) + .map((e) => Account.fromJson(e as Map)) + .toList(), + reconciliationsToday: (json['reconciliations_today'] as List? ?? []) + .map((e) => ReconciliationStatus.fromJson(e as Map)) + .toList(), + ); + } + + Map toJson() { + return { + 'month': month, + 'total_balance': totalBalance, + 'available_after_reserves': availableAfterReserves, + 'monthly_income': monthlyIncome, + 'monthly_expenses': monthlyExpenses, + 'monthly_balance': monthlyBalance, + 'provisions_current_total': provisionsCurrentTotal, + 'provisions_target_total': provisionsTargetTotal, + 'monthly_charges_remaining_total': monthlyChargesRemainingTotal, + 'monthly_transfer_remaining_total': monthlyTransferRemainingTotal, + 'monthly_provision_operation_remaining_total': monthlyProvisionOperationRemainingTotal, + 'scheduled_expenses_remaining_total': scheduledExpensesRemainingTotal, + 'scheduled_income_remaining_total': scheduledIncomeRemainingTotal, + 'scheduled_transfer_remaining_total': scheduledTransferRemainingTotal, + 'scheduled_provision_remaining_total': scheduledProvisionRemainingTotal, + 'scheduled_net_remaining_total': scheduledNetRemainingTotal, + 'projected_month_balance': projectedMonthBalance, + 'accounts': accounts.map((e) => e.toJson()).toList(), + 'reconciliations_today': reconciliationsToday.map((e) => e.toJson()).toList(), + }; + } + + DashboardData copyWith({ + String? month, + double? totalBalance, + double? availableAfterReserves, + double? monthlyIncome, + double? monthlyExpenses, + double? monthlyBalance, + double? provisionsCurrentTotal, + double? provisionsTargetTotal, + double? monthlyChargesRemainingTotal, + double? monthlyTransferRemainingTotal, + double? monthlyProvisionOperationRemainingTotal, + double? scheduledExpensesRemainingTotal, + double? scheduledIncomeRemainingTotal, + double? scheduledTransferRemainingTotal, + double? scheduledProvisionRemainingTotal, + double? scheduledNetRemainingTotal, + double? projectedMonthBalance, + List? accounts, + List? reconciliationsToday, + }) { + return DashboardData( + month: month ?? this.month, + totalBalance: totalBalance ?? this.totalBalance, + availableAfterReserves: availableAfterReserves ?? this.availableAfterReserves, + monthlyIncome: monthlyIncome ?? this.monthlyIncome, + monthlyExpenses: monthlyExpenses ?? this.monthlyExpenses, + monthlyBalance: monthlyBalance ?? this.monthlyBalance, + provisionsCurrentTotal: provisionsCurrentTotal ?? this.provisionsCurrentTotal, + provisionsTargetTotal: provisionsTargetTotal ?? this.provisionsTargetTotal, + monthlyChargesRemainingTotal: monthlyChargesRemainingTotal ?? this.monthlyChargesRemainingTotal, + monthlyTransferRemainingTotal: monthlyTransferRemainingTotal ?? this.monthlyTransferRemainingTotal, + monthlyProvisionOperationRemainingTotal: monthlyProvisionOperationRemainingTotal ?? this.monthlyProvisionOperationRemainingTotal, + scheduledExpensesRemainingTotal: scheduledExpensesRemainingTotal ?? this.scheduledExpensesRemainingTotal, + scheduledIncomeRemainingTotal: scheduledIncomeRemainingTotal ?? this.scheduledIncomeRemainingTotal, + scheduledTransferRemainingTotal: scheduledTransferRemainingTotal ?? this.scheduledTransferRemainingTotal, + scheduledProvisionRemainingTotal: scheduledProvisionRemainingTotal ?? this.scheduledProvisionRemainingTotal, + scheduledNetRemainingTotal: scheduledNetRemainingTotal ?? this.scheduledNetRemainingTotal, + projectedMonthBalance: projectedMonthBalance ?? this.projectedMonthBalance, + accounts: accounts ?? this.accounts, + reconciliationsToday: reconciliationsToday ?? this.reconciliationsToday, + ); + } +} diff --git a/lib/models/pending_operation.dart b/lib/models/pending_operation.dart new file mode 100644 index 0000000..e9ee193 --- /dev/null +++ b/lib/models/pending_operation.dart @@ -0,0 +1,30 @@ +import 'dart:convert'; + +class PendingOperation { + final int id; + final String operationType; + final Map payload; + final DateTime createdAt; + final String status; + final String? error; + + PendingOperation({ + required this.id, + required this.operationType, + required this.payload, + required this.createdAt, + required this.status, + this.error, + }); + + factory PendingOperation.fromDbMap(Map map) { + return PendingOperation( + id: map['id'] as int, + operationType: map['operation_type'] as String, + payload: jsonDecode(map['payload_json'] as String) as Map, + createdAt: DateTime.parse(map['created_at'] as String), + status: map['status'] as String? ?? 'pending', + error: map['error'] as String?, + ); + } +} diff --git a/lib/models/transaction_item.dart b/lib/models/transaction_item.dart new file mode 100644 index 0000000..ff75082 --- /dev/null +++ b/lib/models/transaction_item.dart @@ -0,0 +1,120 @@ +class TransactionItem { + final int id; + final String label; + final double amount; + final String type; + final int accountId; + final int? targetAccountId; + final int? categoryId; + final int? provisionId; + final DateTime date; + final String? note; + final bool isPending; + final int? localOperationId; + + TransactionItem({ + required this.id, + required this.label, + required this.amount, + required this.type, + required this.accountId, + required this.date, + this.targetAccountId, + this.categoryId, + this.provisionId, + this.note, + this.isPending = false, + this.localOperationId, + }); + + factory TransactionItem.fromJson(Map json) { + return TransactionItem( + id: json['id'] as int, + label: json['label'] as String, + amount: (json['amount'] as num? ?? 0).toDouble(), + type: json['type'] as String, + accountId: json['account_id'] as int, + targetAccountId: json['target_account_id'] as int?, + categoryId: json['category_id'] as int?, + provisionId: json['provision_id'] as int?, + date: DateTime.parse(json['date'] as String), + note: json['note'] as String?, + isPending: json['is_pending'] is int + ? (json['is_pending'] as int) == 1 + : json['is_pending'] as bool? ?? false, + localOperationId: json['local_operation_id'] as int?, + ); + } + + factory TransactionItem.fromPending({ + required int localOperationId, + required Map payload, + }) { + return TransactionItem( + id: -localOperationId, + label: payload['label'] as String? ?? 'Opération mobile', + amount: (payload['amount'] as num? ?? 0).toDouble(), + type: payload['type'] as String? ?? 'expense', + accountId: payload['account_id'] as int, + targetAccountId: payload['target_account_id'] as int?, + categoryId: payload['category_id'] as int?, + provisionId: payload['provision_id'] as int?, + date: DateTime.tryParse(payload['date'] as String? ?? '') ?? DateTime.now(), + note: payload['note'] as String?, + isPending: true, + localOperationId: localOperationId, + ); + } + + Map toJson() { + return { + 'id': id, + 'label': label, + 'amount': amount, + 'type': type, + 'account_id': accountId, + 'target_account_id': targetAccountId, + 'category_id': categoryId, + 'provision_id': provisionId, + 'date': date.toIso8601String(), + 'note': note, + 'is_pending': isPending, + 'local_operation_id': localOperationId, + }; + } + + Map toDbMap() { + return { + 'id': id, + 'label': label, + 'amount': amount, + 'type': type, + 'account_id': accountId, + 'target_account_id': targetAccountId, + 'category_id': categoryId, + 'provision_id': provisionId, + 'date': date.toIso8601String(), + 'note': note, + 'is_pending': isPending ? 1 : 0, + 'local_operation_id': localOperationId, + 'updated_at': DateTime.now().toIso8601String(), + }; + } + + factory TransactionItem.fromDbMap(Map map) { + return TransactionItem( + id: map['id'] as int, + label: map['label'] as String, + amount: (map['amount'] as num? ?? 0).toDouble(), + type: map['type'] as String, + accountId: map['account_id'] as int, + targetAccountId: map['target_account_id'] as int?, + categoryId: map['category_id'] as int?, + provisionId: map['provision_id'] as int?, + date: DateTime.parse(map['date'] as String), + note: map['note'] as String?, + isPending: (map['is_pending'] as int? ?? 0) == 1, + localOperationId: map['local_operation_id'] as int?, + ); + } +} diff --git a/lib/screens/app_lock_gate.dart b/lib/screens/app_lock_gate.dart new file mode 100644 index 0000000..c450735 --- /dev/null +++ b/lib/screens/app_lock_gate.dart @@ -0,0 +1,248 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../services/security_service.dart'; + +class AppLockGate extends StatefulWidget { + const AppLockGate({ + super.key, + required this.securityService, + required this.child, + }); + + final SecurityService securityService; + final Widget child; + + @override + State createState() => _AppLockGateState(); +} + +class _AppLockGateState extends State with WidgetsBindingObserver { + bool _checking = true; + bool _locked = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _loadLockState(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) { + _lockIfNeeded(); + } + } + + Future _loadLockState() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted) return; + setState(() { + _locked = enabled; + _checking = false; + }); + } + + Future _lockIfNeeded() async { + final enabled = await widget.securityService.isPinEnabled(); + if (!mounted || !enabled) return; + setState(() => _locked = true); + } + + void _unlock() { + setState(() => _locked = false); + } + + @override + Widget build(BuildContext context) { + if (_checking) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + if (_locked) { + return PinUnlockScreen( + securityService: widget.securityService, + onUnlocked: _unlock, + ); + } + + return widget.child; + } +} + +class PinUnlockScreen extends StatefulWidget { + const PinUnlockScreen({ + super.key, + required this.securityService, + required this.onUnlocked, + }); + + final SecurityService securityService; + final VoidCallback onUnlocked; + + @override + State createState() => _PinUnlockScreenState(); +} + +class _PinUnlockScreenState extends State { + final _pinController = TextEditingController(); + bool _checking = false; + bool _checkingBiometric = false; + bool _biometricEnabled = false; + bool _biometricAvailable = false; + String? _error; + + @override + void initState() { + super.initState(); + _loadBiometricState(); + } + + @override + void dispose() { + _pinController.dispose(); + super.dispose(); + } + + Future _loadBiometricState() async { + final enabled = await widget.securityService.isBiometricEnabled(); + final available = await widget.securityService.isBiometricAvailable(); + + if (!mounted) return; + setState(() { + _biometricEnabled = enabled; + _biometricAvailable = available; + }); + } + + Future _unlockWithBiometrics() async { + if (_checkingBiometric) return; + + setState(() { + _checkingBiometric = true; + _error = null; + }); + + final ok = await widget.securityService.authenticateWithBiometrics(); + + if (!mounted) return; + + if (ok) { + widget.onUnlocked(); + } else { + setState(() { + _checkingBiometric = false; + _error = 'Empreinte refusée ou annulée. Utilise le PIN.'; + }); + } + } + + Future _unlock() async { + if (_checking) return; + + setState(() { + _checking = true; + _error = null; + }); + + final ok = await widget.securityService.verifyPin(_pinController.text.trim()); + + if (!mounted) return; + + if (ok) { + _pinController.clear(); + widget.onUnlocked(); + } else { + HapticFeedback.vibrate(); + setState(() { + _checking = false; + _error = 'PIN incorrect.'; + }); + } + } + + @override + Widget build(BuildContext context) { + final showBiometric = _biometricEnabled && _biometricAvailable; + + return Scaffold( + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.all(24), + children: [ + Icon(showBiometric ? Icons.fingerprint : Icons.lock, size: 64), + const SizedBox(height: 16), + Text( + 'FIN65 verrouillé', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 8), + Text( + showBiometric + ? 'Déverrouille avec ton empreinte ou ton PIN.' + : 'Entre ton PIN pour accéder aux données locales.', + textAlign: TextAlign.center, + ), + if (showBiometric) ...[ + const SizedBox(height: 24), + FilledButton.icon( + onPressed: _checkingBiometric ? null : _unlockWithBiometrics, + icon: _checkingBiometric + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.fingerprint), + label: Text(_checkingBiometric ? 'Vérification...' : 'Utiliser l’empreinte'), + ), + ], + const SizedBox(height: 24), + TextField( + controller: _pinController, + autofocus: !showBiometric, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: 'PIN', + border: const OutlineInputBorder(), + errorText: _error, + counterText: '', + ), + onSubmitted: (_) => _checking ? null : _unlock(), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _checking ? null : _unlock, + icon: _checking + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.lock_open), + label: Text(_checking ? 'Vérification...' : 'Déverrouiller avec le PIN'), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart new file mode 100644 index 0000000..b1176d0 --- /dev/null +++ b/lib/screens/home_screen.dart @@ -0,0 +1,715 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/transaction_item.dart'; +import '../services/sync_service.dart'; +import 'quick_transaction_screen.dart'; +import 'settings_screen.dart'; +import 'sync_screen.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key, required this.syncService}); + + final SyncService syncService; + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + DashboardData? _dashboard; + List _accounts = []; + List _categories = []; + List _transactions = []; + int _pendingCount = 0; + DateTime? _lastSyncAt; + bool _isOnline = false; + bool _loading = true; + bool _syncing = false; + String? _message; + + final _money = NumberFormat.currency(locale: 'fr_FR', symbol: 'MAD ', decimalDigits: 2); + final _date = DateFormat('dd/MM/yyyy HH:mm', 'fr_FR'); + + @override + void initState() { + super.initState(); + _bootstrap(); + } + + Future _bootstrap() async { + try { + final local = await widget.syncService.loadLocalSnapshot( + isOnline: false, + message: 'Données locales chargées.', + ); + _applySnapshot(local, loading: false); + await _synchronize(); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _message = 'Erreur locale : $e'; + }); + } + } + + void _applySnapshot(SyncSnapshot snapshot, {bool? loading}) { + if (!mounted) return; + setState(() { + _dashboard = snapshot.dashboard; + _accounts = snapshot.accounts; + _categories = snapshot.categories; + _transactions = snapshot.transactions; + _pendingCount = snapshot.pendingCount; + _lastSyncAt = snapshot.lastSyncAt; + _isOnline = snapshot.isOnline; + _message = snapshot.message; + if (loading != null) _loading = loading; + }); + } + + Future _synchronize() async { + if (_syncing) return; + + setState(() { + _syncing = true; + _message = 'Synchronisation...'; + }); + + try { + final snapshot = await widget.syncService.synchronize(); + if (!mounted) return; + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Erreur de synchronisation : $e'; + _loading = false; + }); + } finally { + if (mounted) { + setState(() => _syncing = false); + } + } + } + + Future _reloadLocalAfterSave() async { + try { + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: _isOnline + ? 'Opération enregistrée.' + : 'Opération en attente de synchronisation.', + ); + _applySnapshot(snapshot, loading: false); + } catch (e) { + if (!mounted) return; + setState(() { + _message = 'Opération enregistrée localement, mais rechargement écran échoué : $e'; + _loading = false; + }); + } + } + + Future _openQuickAdd() async { + if (_accounts.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Crée d’abord au moins un compte dans la version web, puis synchronise.')), + ); + return; + } + + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => QuickTransactionScreen( + syncService: widget.syncService, + accounts: _accounts, + categories: _categories, + onSaved: _reloadLocalAfterSave, + ), + ), + ); + } + + +Future _openSyncScreen() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SyncScreen(syncService: widget.syncService), + ), + ); + + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: _isOnline, + message: null, + ); + _applySnapshot(snapshot, loading: false); +} + + Future _openSettings() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsScreen(apiService: widget.syncService.apiService), + ), + ); + await _synchronize(); + } + + @override + Widget build(BuildContext context) { + final dashboard = _dashboard; + + return Scaffold( + appBar: AppBar( + title: const Text('FIN65'), + actions: [ + IconButton( + tooltip: 'Page synchronisation', + onPressed: _openSyncScreen, + icon: Badge( + isLabelVisible: _pendingCount > 0, + label: Text('$_pendingCount'), + child: const Icon(Icons.cloud_sync), + ), + ), + IconButton( + tooltip: 'Synchroniser', + onPressed: _syncing ? null : _synchronize, + icon: _syncing + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + ), + IconButton(onPressed: _openSettings, icon: const Icon(Icons.settings)), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _openQuickAdd, + icon: const Icon(Icons.add), + label: const Text('Ajouter'), + ), + body: RefreshIndicator( + onRefresh: _synchronize, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ + _SyncBanner( + isOnline: _isOnline, + pendingCount: _pendingCount, + lastSyncAt: _lastSyncAt, + formatter: _date, + message: _message, + ), + const SizedBox(height: 12), + if (dashboard != null) ...[ + _DashboardCards( + dashboard: dashboard, + money: _money, + hasPending: _pendingCount > 0, + ), + const SizedBox(height: 16), + ] else + const _EmptyCacheCard(), + _SectionTitle(title: 'Comptes', action: _pendingCount > 0 ? 'Solde estimé' : 'Solde app'), + const SizedBox(height: 8), + if (_accounts.isEmpty) + const Card(child: ListTile(title: Text('Aucun compte en cache. Synchronise avec le backend.'))) + else + ..._accounts.map((a) => _AccountTile(account: a, money: _money)), + const SizedBox(height: 16), + _SectionTitle(title: 'Dernières transactions'), + const SizedBox(height: 8), + if (_transactions.isEmpty) + const Card(child: ListTile(title: Text('Aucune transaction en cache.'))) + else + ..._transactions.map( + (t) => _TransactionTile( + transaction: t, + accounts: _accounts, + categories: _categories, + money: _money, + ), + ), + const SizedBox(height: 90), + ], + ), + ), + ); + } +} + +class _SyncBanner extends StatelessWidget { + const _SyncBanner({ + required this.isOnline, + required this.pendingCount, + required this.lastSyncAt, + required this.formatter, + this.message, + }); + + final bool isOnline; + final int pendingCount; + final DateTime? lastSyncAt; + final DateFormat formatter; + final String? message; + + @override + Widget build(BuildContext context) { + final title = isOnline ? 'Connecté au backend' : 'Mode hors ligne'; + final subtitleParts = []; + + if (lastSyncAt != null) { + subtitleParts.add('Dernière synchro : ${formatter.format(lastSyncAt!.toLocal())}'); + } else { + subtitleParts.add('Aucune synchronisation réussie'); + } + + if (pendingCount > 0) { + subtitleParts.add('$pendingCount opération(s) en attente'); + } + + if (message != null && message!.isNotEmpty) { + subtitleParts.add(message!); + } + + return Card( + child: ListTile( + leading: Icon(isOnline ? Icons.cloud_done : Icons.cloud_off), + title: Text(title), + subtitle: Text(subtitleParts.join('\n')), + ), + ); + } +} + +class _EmptyCacheCard extends StatelessWidget { + const _EmptyCacheCard(); + + @override + Widget build(BuildContext context) { + return const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text( + 'Aucune donnée locale. Lance le backend PC une première fois, configure l’URL API, puis synchronise.', + ), + ), + ); + } +} + +class _DashboardCards extends StatelessWidget { + const _DashboardCards({ + required this.dashboard, + required this.money, + required this.hasPending, + }); + + final DashboardData dashboard; + final NumberFormat money; + final bool hasPending; + + @override + Widget build(BuildContext context) { + final labelSuffix = hasPending ? ' estimé' : ''; + + return Column( + children: [ + _MetricCard( + title: 'Disponible réel$labelSuffix', + value: money.format(dashboard.availableAfterReserves), + icon: Icons.account_balance_wallet, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + const SizedBox(height: 8), + _MetricCard( + title: 'Balance prévisionnelle du mois', + value: money.format(dashboard.projectedMonthBalance), + icon: Icons.insights, + backgroundColor: const Color(0xFFE3F2FD), + accentColor: const Color(0xFF1565C0), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Solde total$labelSuffix', + value: money.format(dashboard.totalBalance), + icon: Icons.savings, + compact: true, + backgroundColor: const Color(0xFFF3E5F5), + accentColor: const Color(0xFF6A1B9A), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Balance réelle', + value: money.format(dashboard.monthlyBalance), + icon: Icons.trending_up, + compact: true, + backgroundColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFFE8F5E9) + : const Color(0xFFFFEBEE), + accentColor: dashboard.monthlyBalance >= 0 + ? const Color(0xFF2E7D32) + : const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _MetricCard( + title: 'Revenus réels', + value: money.format(dashboard.monthlyIncome), + icon: Icons.arrow_downward, + compact: true, + backgroundColor: const Color(0xFFE8F5E9), + accentColor: const Color(0xFF2E7D32), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _MetricCard( + title: 'Dépenses réelles', + value: money.format(dashboard.monthlyExpenses), + icon: Icons.arrow_upward, + compact: true, + backgroundColor: const Color(0xFFFFEBEE), + accentColor: const Color(0xFFC62828), + ), + ), + ], + ), + const SizedBox(height: 8), + _PlannedInfoCard(dashboard: dashboard, money: money), + ], + ); + } +} + +class _PlannedInfoCard extends StatelessWidget { + const _PlannedInfoCard({ + required this.dashboard, + required this.money, + }); + + final DashboardData dashboard; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + final rows = <_InfoRow>[ + _InfoRow( + 'Dépenses prévues restantes', + dashboard.plannedExpensesTotal, + Icons.event_busy, + const Color(0xFFFFEBEE), + const Color(0xFFC62828), + ), + _InfoRow( + 'Revenus prévus échéancier', + dashboard.scheduledIncomeRemainingTotal, + Icons.event_available, + const Color(0xFFE8F5E9), + const Color(0xFF2E7D32), + ), + _InfoRow( + 'Dépenses échéancier', + dashboard.scheduledExpensesRemainingTotal, + Icons.calendar_month, + const Color(0xFFFFF3E0), + const Color(0xFFEF6C00), + ), + _InfoRow( + 'Transferts prévus', + dashboard.plannedTransfersTotal, + Icons.swap_horiz, + const Color(0xFFE3F2FD), + const Color(0xFF1565C0), + ), + _InfoRow( + 'Provisions prévues', + dashboard.plannedProvisionsTotal, + Icons.inventory_2, + const Color(0xFFF3E5F5), + const Color(0xFF6A1B9A), + ), + ]; + + return Card( + color: const Color(0xFFFAFAFA), + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: const Color(0xFFE3F2FD), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.event_note, color: Color(0xFF1565C0)), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Prévisionnel du mois', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w800, + ), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Inclut les opérations mensuelles et l’échéancier ponctuel du backend.', + style: Theme.of(context).textTheme.bodySmall, + ), + const Divider(height: 20), + ...rows.map( + (row) => Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9), + decoration: BoxDecoration( + color: row.backgroundColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: row.accentColor.withOpacity(0.22)), + ), + child: Row( + children: [ + Icon(row.icon, size: 20, color: row.accentColor), + const SizedBox(width: 10), + Expanded( + child: Text( + row.label, + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w700, + ), + ), + ), + Text( + money.format(row.value), + style: TextStyle( + color: row.accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _InfoRow { + const _InfoRow( + this.label, + this.value, + this.icon, + this.backgroundColor, + this.accentColor, + ); + + final String label; + final double value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; +} + +class _MetricCard extends StatelessWidget { + const _MetricCard({ + required this.title, + required this.value, + required this.icon, + required this.backgroundColor, + required this.accentColor, + this.compact = false, + }); + + final String title; + final String value; + final IconData icon; + final Color backgroundColor; + final Color accentColor; + final bool compact; + + @override + Widget build(BuildContext context) { + return Card( + color: backgroundColor, + elevation: 1, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: EdgeInsets.all(compact ? 12 : 16), + child: Row( + children: [ + Container( + width: compact ? 34 : 42, + height: compact ? 34 : 42, + decoration: BoxDecoration( + color: accentColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, size: compact ? 21 : 27, color: accentColor), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: accentColor, + fontWeight: FontWeight.w700, + ), + ), + Text( + value, + style: (compact + ? Theme.of(context).textTheme.titleMedium + : Theme.of(context).textTheme.headlineSmall) + ?.copyWith( + color: accentColor, + fontWeight: FontWeight.w900, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle({required this.title, this.action}); + + final String title; + final String? action; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(title, style: Theme.of(context).textTheme.titleLarge), + const Spacer(), + if (action != null) Text(action!, style: Theme.of(context).textTheme.bodySmall), + ], + ); + } +} + +class _AccountTile extends StatelessWidget { + const _AccountTile({required this.account, required this.money}); + + final Account account; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.account_balance), + title: Text(account.name), + subtitle: Text(account.type), + trailing: Text( + money.format(account.appBalance), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} + +class _TransactionTile extends StatelessWidget { + const _TransactionTile({ + required this.transaction, + required this.accounts, + required this.categories, + required this.money, + }); + + final TransactionItem transaction; + final List accounts; + final List categories; + final NumberFormat money; + + Account? _findAccount(int? id) { + if (id == null) return null; + for (final account in accounts) { + if (account.id == id) return account; + } + return null; + } + + Category? _findCategory(int? id) { + if (id == null) return null; + for (final category in categories) { + if (category.id == id) return category; + } + return null; + } + + @override + Widget build(BuildContext context) { + final account = _findAccount(transaction.accountId); + final target = _findAccount(transaction.targetAccountId); + final category = _findCategory(transaction.categoryId); + + final typeLabel = switch (transaction.type) { + 'expense' => 'Dépense', + 'income' => 'Recette', + 'transfer' => 'Transfert', + _ => transaction.type, + }; + + final accountLabel = transaction.type == 'transfer' + ? '${account?.name ?? transaction.accountId} → ${target?.name ?? transaction.targetAccountId}' + : account?.name ?? 'Compte ${transaction.accountId}'; + + return Card( + child: ListTile( + leading: Icon(transaction.isPending ? Icons.schedule_send : Icons.receipt_long), + title: Text(transaction.label), + subtitle: Text( + '${transaction.isPending ? 'EN ATTENTE • ' : ''}$typeLabel • $accountLabel${category == null ? '' : ' • ${category.name}'}', + ), + trailing: Text( + money.format(transaction.amount), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} diff --git a/lib/screens/quick_transaction_screen.dart b/lib/screens/quick_transaction_screen.dart new file mode 100644 index 0000000..d17c70c --- /dev/null +++ b/lib/screens/quick_transaction_screen.dart @@ -0,0 +1,452 @@ +import 'package:flutter/material.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../services/sync_service.dart'; + +class QuickTransactionScreen extends StatefulWidget { + const QuickTransactionScreen({ + super.key, + required this.syncService, + required this.accounts, + required this.categories, + required this.onSaved, + }); + + final SyncService syncService; + final List accounts; + final List categories; + + /// Important: this is async because the home screen must reload the local + /// SQLite snapshot before the quick form is closed. + final Future Function() onSaved; + + @override + State createState() => _QuickTransactionScreenState(); +} + +class _QuickTransactionScreenState extends State { + final _formKey = GlobalKey(); + final _amountController = TextEditingController(); + final _labelController = TextEditingController(); + final _noteController = TextEditingController(); + + String _type = 'expense'; + int? _accountId; + int? _targetAccountId; + int? _categoryId; + bool _saving = false; + + static const _quickAmounts = [10, 20, 50, 100, 200, 500, 1000]; + + static const _expenseTemplates = <_QuickTemplate>[ + _QuickTemplate(label: 'Courses', categoryHint: 'course'), + _QuickTemplate(label: 'Essence', categoryHint: 'essence'), + _QuickTemplate(label: 'Restaurant', categoryHint: 'restaurant'), + _QuickTemplate(label: 'Café', categoryHint: 'café'), + _QuickTemplate(label: 'Transport', categoryHint: 'transport'), + _QuickTemplate(label: 'Santé', categoryHint: 'santé'), + _QuickTemplate(label: 'Abonnement', categoryHint: 'abonnement'), + _QuickTemplate(label: 'Retrait cash', categoryHint: 'cash'), + ]; + + static const _incomeTemplates = <_QuickTemplate>[ + _QuickTemplate(label: 'Salaire', categoryHint: 'salaire'), + _QuickTemplate(label: 'Remboursement', categoryHint: 'remboursement'), + _QuickTemplate(label: 'Prime', categoryHint: 'prime'), + _QuickTemplate(label: 'Vente', categoryHint: 'vente'), + ]; + + static const _transferTemplates = <_QuickTemplate>[ + _QuickTemplate(label: 'Épargne'), + _QuickTemplate(label: 'Provision'), + _QuickTemplate(label: 'Banque → Cash'), + _QuickTemplate(label: 'Cash → Banque'), + ]; + + @override + void initState() { + super.initState(); + if (widget.accounts.isNotEmpty) { + _accountId = widget.accounts.first.id; + _targetAccountId = widget.accounts.length > 1 ? widget.accounts[1].id : null; + } + _setDefaultCategory(); + } + + @override + void dispose() { + _amountController.dispose(); + _labelController.dispose(); + _noteController.dispose(); + super.dispose(); + } + + List<_QuickTemplate> get _templates { + if (_type == 'income') return _incomeTemplates; + if (_type == 'transfer') return _transferTemplates; + return _expenseTemplates; + } + + void _setDefaultCategory({String? preferredHint}) { + final filtered = widget.categories.where((c) => c.type == _type).toList(); + + if (filtered.isEmpty) { + _categoryId = null; + return; + } + + if (preferredHint != null && preferredHint.trim().isNotEmpty) { + final normalizedHint = _normalize(preferredHint); + for (final category in filtered) { + final normalizedCategory = _normalize(category.name); + if (normalizedCategory.contains(normalizedHint) || + normalizedHint.contains(normalizedCategory)) { + _categoryId = category.id; + return; + } + } + } + + _categoryId = filtered.first.id; + } + + String _normalize(String value) { + return value + .toLowerCase() + .replaceAll('é', 'e') + .replaceAll('è', 'e') + .replaceAll('ê', 'e') + .replaceAll('à', 'a') + .replaceAll('â', 'a') + .replaceAll('ù', 'u') + .replaceAll('û', 'u') + .replaceAll('î', 'i') + .replaceAll('ï', 'i') + .replaceAll('ô', 'o') + .replaceAll('ç', 'c') + .trim(); + } + + List get _visibleCategories { + return widget.categories.where((c) => c.type == _type).toList(); + } + + void _applyTemplate(_QuickTemplate template) { + if (_saving) return; + + setState(() { + _labelController.text = template.label; + if (template.amount != null) { + _amountController.text = _formatAmount(template.amount!); + } + if (_type != 'transfer') { + _setDefaultCategory(preferredHint: template.categoryHint ?? template.label); + } + }); + } + + void _applyAmount(double amount) { + if (_saving) return; + setState(() { + _amountController.text = _formatAmount(amount); + }); + } + + String _formatAmount(double amount) { + if (amount == amount.roundToDouble()) return amount.toInt().toString(); + return amount.toStringAsFixed(2); + } + + + int? _firstOtherAccountId() { + for (final account in widget.accounts) { + if (account.id != _accountId) return account.id; + } + return null; + } + + Future _save() async { + if (!_formKey.currentState!.validate()) return; + + final accountId = _accountId; + if (accountId == null) { + _showSnack('Compte obligatoire.'); + return; + } + + final targetAccountId = _targetAccountId; + if (_type == 'transfer') { + if (targetAccountId == null) { + _showSnack('Compte cible obligatoire.'); + return; + } + if (targetAccountId == accountId) { + _showSnack('Source et cible doivent être différents.'); + return; + } + } + + setState(() => _saving = true); + + try { + final synced = await widget.syncService.createTransactionSmart( + label: _labelController.text.trim(), + amount: double.parse(_amountController.text.replaceAll(',', '.')), + type: _type, + accountId: accountId, + targetAccountId: _type == 'transfer' ? targetAccountId : null, + categoryId: _type == 'transfer' ? null : _categoryId, + note: _noteController.text.trim().isEmpty ? null : _noteController.text.trim(), + ); + + if (!mounted) return; + + await widget.onSaved(); + + if (!mounted) return; + _showSnack( + synced + ? 'Transaction synchronisée.' + : 'Backend absent : opération gardée localement.', + ); + + if (mounted) { + Navigator.of(context).pop(); + } + } catch (e) { + if (!mounted) return; + _showSnack('Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + void _showSnack(String text) { + final messenger = ScaffoldMessenger.maybeOf(context); + messenger?.clearSnackBars(); + messenger?.showSnackBar(SnackBar(content: Text(text))); + } + +Widget _buildSaveButton() { + return FilledButton.icon( + onPressed: _saving ? null : _save, + icon: _saving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.save), + label: Text(_saving ? 'Enregistrement...' : 'Enregistrer'), + ); +} + + @override + Widget build(BuildContext context) { + final categories = _visibleCategories; + + return Scaffold( + resizeToAvoidBottomInset: true, + appBar: AppBar( + title: const Text('Ajout rapide'), + ), + bottomNavigationBar: SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: _buildSaveButton(), + ), + body: Form( + key: _formKey, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + SegmentedButton( + segments: const [ + ButtonSegment(value: 'expense', label: Text('Dépense')), + ButtonSegment(value: 'income', label: Text('Recette')), + ButtonSegment(value: 'transfer', label: Text('Transfert')), + ], + selected: {_type}, + onSelectionChanged: _saving + ? null + : (values) { + setState(() { + _type = values.first; + _setDefaultCategory(); + if (_type == 'transfer' && _targetAccountId == _accountId) { + _targetAccountId = _firstOtherAccountId(); + } + }); + }, + ), + const SizedBox(height: 16), + _QuickChipsSection( + title: _type == 'transfer' + ? 'Transferts rapides' + : _type == 'income' + ? 'Recettes rapides' + : 'Dépenses rapides', + chips: _templates + .map((template) => ActionChip( + label: Text(template.label), + onPressed: _saving ? null : () => _applyTemplate(template), + )) + .toList(), + ), + const SizedBox(height: 16), + TextFormField( + controller: _amountController, + decoration: const InputDecoration( + labelText: 'Montant', + border: OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + validator: (value) { + final parsed = double.tryParse((value ?? '').replaceAll(',', '.')); + if (parsed == null || parsed <= 0) return 'Montant invalide'; + return null; + }, + ), + const SizedBox(height: 8), + _QuickChipsSection( + title: 'Montants rapides', + chips: _quickAmounts + .map((amount) => ChoiceChip( + label: Text(_formatAmount(amount)), + selected: _amountController.text == _formatAmount(amount), + onSelected: _saving ? null : (_) => _applyAmount(amount), + )) + .toList(), + dense: true, + ), + const SizedBox(height: 12), + TextFormField( + controller: _labelController, + decoration: const InputDecoration( + labelText: 'Libellé', + border: OutlineInputBorder(), + ), + validator: (value) { + if ((value ?? '').trim().isEmpty) return 'Libellé obligatoire'; + return null; + }, + ), + const SizedBox(height: 12), + DropdownButtonFormField( + value: _accountId, + decoration: const InputDecoration( + labelText: 'Compte source', + border: OutlineInputBorder(), + ), + items: widget.accounts + .map((a) => DropdownMenuItem(value: a.id, child: Text(a.name))) + .toList(), + onChanged: _saving + ? null + : (value) { + setState(() { + _accountId = value; + if (_type == 'transfer' && _targetAccountId == _accountId) { + _targetAccountId = _firstOtherAccountId(); + } + }); + }, + validator: (value) => value == null ? 'Compte obligatoire' : null, + ), + if (_type == 'transfer') ...[ + const SizedBox(height: 12), + DropdownButtonFormField( + value: _targetAccountId, + decoration: const InputDecoration( + labelText: 'Compte cible', + border: OutlineInputBorder(), + ), + items: widget.accounts + .map((a) => DropdownMenuItem(value: a.id, child: Text(a.name))) + .toList(), + onChanged: _saving ? null : (value) => setState(() => _targetAccountId = value), + validator: (value) { + if (value == null) return 'Compte cible obligatoire'; + if (value == _accountId) return 'Source et cible doivent être différents'; + return null; + }, + ), + ], + if (_type != 'transfer') ...[ + const SizedBox(height: 12), + DropdownButtonFormField( + value: _categoryId, + decoration: const InputDecoration( + labelText: 'Catégorie', + border: OutlineInputBorder(), + ), + items: categories + .map((c) => DropdownMenuItem(value: c.id, child: Text(c.name))) + .toList(), + onChanged: _saving ? null : (value) => setState(() => _categoryId = value), + ), + ], + const SizedBox(height: 12), + TextFormField( + controller: _noteController, + decoration: const InputDecoration( + labelText: 'Note', + border: OutlineInputBorder(), + ), + minLines: 2, + maxLines: 4, + ), + const SizedBox(height: 120), + ], + ), + ), + ); + } +} + +class _QuickTemplate { + const _QuickTemplate({ + required this.label, + this.categoryHint, + this.amount, + }); + + final String label; + final String? categoryHint; + final double? amount; +} + +class _QuickChipsSection extends StatelessWidget { + const _QuickChipsSection({ + required this.title, + required this.chips, + this.dense = false, + }); + + final String title; + final List chips; + final bool dense; + + @override + Widget build(BuildContext context) { + if (chips.isEmpty) return const SizedBox.shrink(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: dense + ? Theme.of(context).textTheme.bodyMedium + : Theme.of(context).textTheme.titleSmall, + ), + SizedBox(height: dense ? 4 : 8), + Wrap( + spacing: 8, + runSpacing: dense ? 4 : 8, + children: chips, + ), + ], + ); + } +} diff --git a/lib/screens/security_screen.dart b/lib/screens/security_screen.dart new file mode 100644 index 0000000..c3349fd --- /dev/null +++ b/lib/screens/security_screen.dart @@ -0,0 +1,311 @@ +import 'package:flutter/material.dart'; +import 'package:local_auth/local_auth.dart'; + +import '../services/security_service.dart'; + +class SecurityScreen extends StatefulWidget { + const SecurityScreen({ + super.key, + required this.securityService, + }); + + final SecurityService securityService; + + @override + State createState() => _SecurityScreenState(); +} + +class _SecurityScreenState extends State { + final _currentPinController = TextEditingController(); + final _newPinController = TextEditingController(); + final _confirmPinController = TextEditingController(); + + bool _loading = true; + bool _saving = false; + bool _enabled = false; + bool _biometricAvailable = false; + bool _biometricEnabled = false; + List _availableBiometrics = const []; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _currentPinController.dispose(); + _newPinController.dispose(); + _confirmPinController.dispose(); + super.dispose(); + } + + Future _load() async { + final enabled = await widget.securityService.isPinEnabled(); + final biometricAvailable = await widget.securityService.isBiometricAvailable(); + final biometricEnabled = await widget.securityService.isBiometricEnabled(); + final availableBiometrics = await widget.securityService.getAvailableBiometrics(); + + if (!mounted) return; + setState(() { + _enabled = enabled; + _biometricAvailable = biometricAvailable; + _biometricEnabled = biometricEnabled; + _availableBiometrics = availableBiometrics; + _loading = false; + }); + } + + Future _verifyCurrentPinFromField() async { + final current = _currentPinController.text.trim(); + final ok = await widget.securityService.verifyPin(current); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + return true; + } + + Future _savePin() async { + final newPin = _newPinController.text.trim(); + final confirm = _confirmPinController.text.trim(); + + if (newPin != confirm) { + setState(() => _message = 'Le nouveau PIN et la confirmation ne correspondent pas.'); + return; + } + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (_enabled) { + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + } + + await widget.securityService.setPin(newPin); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN activé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _disablePin() async { + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + + await widget.securityService.disablePin(); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN et biométrie désactivés.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _toggleBiometrics(bool value) async { + if (_saving) return; + + setState(() { + _saving = true; + _message = null; + }); + + try { + if (!_enabled) { + setState(() => _message = 'Active d’abord un PIN avant la biométrie.'); + return; + } + + if (value && !_biometricAvailable) { + setState(() => _message = 'Aucune empreinte/biométrie disponible sur ce téléphone.'); + return; + } + + final currentOk = await _verifyCurrentPinFromField(); + if (!currentOk) return; + + await widget.securityService.setBiometricEnabled(value); + _currentPinController.clear(); + + await _load(); + + setState(() { + _message = value + ? 'Déverrouillage par empreinte activé. Verrouille l’app puis teste avec le bouton empreinte.' + : 'Déverrouillage par empreinte désactivé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _biometricLabel() { + if (_availableBiometrics.isEmpty) return 'Aucune biométrie détectée.'; + + final labels = _availableBiometrics.map((type) { + return switch (type) { + BiometricType.fingerprint => 'empreinte', + BiometricType.face => 'visage', + BiometricType.iris => 'iris', + BiometricType.strong => 'biométrie forte', + BiometricType.weak => 'biométrie faible', + }; + }).toSet().join(', '); + + return 'Disponible : $labels.'; + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: const Center(child: CircularProgressIndicator()), + ); + } + + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: SwitchListTile( + value: _enabled, + onChanged: null, + secondary: Icon(_enabled ? Icons.lock : Icons.lock_open), + title: const Text('Verrouillage PIN'), + subtitle: Text( + _enabled + ? 'Activé. L’app se verrouille à la fermeture ou au changement d’application.' + : 'Désactivé. Tes données locales sont accessibles sans PIN.', + ), + ), + ), + if (_enabled) ...[ + const SizedBox(height: 12), + Card( + child: SwitchListTile( + value: _biometricEnabled, + onChanged: _saving || !_biometricAvailable ? null : _toggleBiometrics, + secondary: const Icon(Icons.fingerprint), + title: const Text('Déverrouillage par empreinte'), + subtitle: Text( + _biometricAvailable + ? '${_biometricLabel()} Entre le PIN actuel ci-dessous puis active l’interrupteur.' + : 'Aucune empreinte/biométrie disponible ou configurée sur ce téléphone.', + ), + ), + ), + ], + const SizedBox(height: 16), + if (_enabled) ...[ + TextField( + controller: _currentPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + helperText: 'Nécessaire pour changer le PIN, désactiver le PIN ou activer/désactiver l’empreinte.', + counterText: '', + ), + ), + const SizedBox(height: 12), + ], + TextField( + controller: _newPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: _enabled ? 'Nouveau PIN' : 'PIN', + border: const OutlineInputBorder(), + helperText: '4 à 8 chiffres.', + counterText: '', + ), + ), + const SizedBox(height: 12), + TextField( + controller: _confirmPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'Confirmer le PIN', + border: OutlineInputBorder(), + counterText: '', + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _saving ? null : _savePin, + icon: const Icon(Icons.save), + label: Text(_enabled ? 'Changer le PIN' : 'Activer le PIN'), + ), + if (_enabled) ...[ + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _saving ? null : _disablePin, + icon: const Icon(Icons.lock_open), + label: const Text('Désactiver le PIN'), + ), + ], + if (_message != null) ...[ + const SizedBox(height: 16), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 24), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Le PIN protège l’accès local à l’application. L’empreinte utilise la sécurité biométrique du téléphone. Le PIN reste le secours si l’empreinte échoue.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/security_screen.dart.before_biometric_ui_fix_072026_010339.73.bak b/lib/screens/security_screen.dart.before_biometric_ui_fix_072026_010339.73.bak new file mode 100644 index 0000000..eaa3cc8 --- /dev/null +++ b/lib/screens/security_screen.dart.before_biometric_ui_fix_072026_010339.73.bak @@ -0,0 +1,311 @@ +import 'package:flutter/material.dart'; +import 'package:local_auth/local_auth.dart'; + +import '../services/security_service.dart'; + +class SecurityScreen extends StatefulWidget { + const SecurityScreen({ + super.key, + required this.securityService, + }); + + final SecurityService securityService; + + @override + State createState() => _SecurityScreenState(); +} + +class _SecurityScreenState extends State { + final _currentPinController = TextEditingController(); + final _newPinController = TextEditingController(); + final _confirmPinController = TextEditingController(); + + bool _loading = true; + bool _saving = false; + bool _enabled = false; + bool _biometricAvailable = false; + bool _biometricEnabled = false; + List _availableBiometrics = const []; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _currentPinController.dispose(); + _newPinController.dispose(); + _confirmPinController.dispose(); + super.dispose(); + } + + Future _load() async { + final enabled = await widget.securityService.isPinEnabled(); + final biometricAvailable = await widget.securityService.isBiometricAvailable(); + final biometricEnabled = await widget.securityService.isBiometricEnabled(); + final availableBiometrics = await widget.securityService.getAvailableBiometrics(); + + if (!mounted) return; + setState(() { + _enabled = enabled; + _biometricAvailable = biometricAvailable; + _biometricEnabled = biometricEnabled; + _availableBiometrics = availableBiometrics; + _loading = false; + }); + } + + Future _verifyCurrentPinIfNeeded() async { + if (!_enabled) return true; + + final current = _currentPinController.text.trim(); + final ok = await widget.securityService.verifyPin(current); + if (!ok) { + setState(() => _message = 'PIN actuel incorrect.'); + return false; + } + return true; + } + + Future _savePin() async { + final newPin = _newPinController.text.trim(); + final confirm = _confirmPinController.text.trim(); + + if (newPin != confirm) { + setState(() => _message = 'Le nouveau PIN et la confirmation ne correspondent pas.'); + return; + } + + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinIfNeeded(); + if (!currentOk) return; + + await widget.securityService.setPin(newPin); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN activé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _disablePin() async { + setState(() { + _saving = true; + _message = null; + }); + + try { + final currentOk = await _verifyCurrentPinIfNeeded(); + if (!currentOk) return; + + await widget.securityService.disablePin(); + + _currentPinController.clear(); + _newPinController.clear(); + _confirmPinController.clear(); + + await _load(); + + setState(() { + _message = 'Verrouillage PIN et biométrie désactivés.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _toggleBiometrics(bool value) async { + setState(() { + _saving = true; + _message = null; + }); + + try { + if (value) { + final currentOk = await _verifyCurrentPinIfNeeded(); + if (!currentOk) return; + + final ok = await widget.securityService.authenticateWithBiometrics(); + + // If biometric was not enabled yet, authenticateWithBiometrics returns false by design. + // So enable first after checking availability, then immediately ask Android dialog. + if (!ok) { + await widget.securityService.setBiometricEnabled(true); + final check = await widget.securityService.authenticateWithBiometrics(); + if (!check) { + await widget.securityService.setBiometricEnabled(false); + setState(() => _message = 'Empreinte annulée ou refusée. Biométrie non activée.'); + return; + } + } else { + await widget.securityService.setBiometricEnabled(true); + } + } else { + await widget.securityService.setBiometricEnabled(false); + } + + await _load(); + setState(() { + _message = value ? 'Déverrouillage par empreinte activé.' : 'Déverrouillage par empreinte désactivé.'; + }); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _biometricLabel() { + if (_availableBiometrics.isEmpty) return 'Aucune biométrie détectée.'; + final labels = _availableBiometrics.map((type) { + return switch (type) { + BiometricType.fingerprint => 'empreinte', + BiometricType.face => 'visage', + BiometricType.iris => 'iris', + BiometricType.strong => 'biométrie forte', + BiometricType.weak => 'biométrie faible', + }; + }).toSet().join(', '); + return 'Disponible : $labels.'; + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: const Center(child: CircularProgressIndicator()), + ); + } + + return Scaffold( + appBar: AppBar(title: const Text('Sécurité')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: SwitchListTile( + value: _enabled, + onChanged: null, + secondary: Icon(_enabled ? Icons.lock : Icons.lock_open), + title: const Text('Verrouillage PIN'), + subtitle: Text( + _enabled + ? 'Activé. L’app se verrouille à la fermeture ou au changement d’application.' + : 'Désactivé. Tes données locales sont accessibles sans PIN.', + ), + ), + ), + if (_enabled) ...[ + const SizedBox(height: 12), + Card( + child: SwitchListTile( + value: _biometricEnabled, + onChanged: _saving || !_biometricAvailable ? null : _toggleBiometrics, + secondary: const Icon(Icons.fingerprint), + title: const Text('Déverrouillage par empreinte'), + subtitle: Text( + _biometricAvailable + ? '${_biometricLabel()} Le PIN reste disponible en secours.' + : 'Aucune empreinte/biométrie disponible ou configurée sur ce téléphone.', + ), + ), + ), + ], + const SizedBox(height: 16), + if (_enabled) ...[ + TextField( + controller: _currentPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'PIN actuel', + border: OutlineInputBorder(), + helperText: 'Demandé pour changer le PIN, désactiver ou activer l’empreinte.', + counterText: '', + ), + ), + const SizedBox(height: 12), + ], + TextField( + controller: _newPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: InputDecoration( + labelText: _enabled ? 'Nouveau PIN' : 'PIN', + border: const OutlineInputBorder(), + helperText: '4 à 8 chiffres.', + counterText: '', + ), + ), + const SizedBox(height: 12), + TextField( + controller: _confirmPinController, + obscureText: true, + keyboardType: TextInputType.number, + maxLength: 8, + decoration: const InputDecoration( + labelText: 'Confirmer le PIN', + border: OutlineInputBorder(), + counterText: '', + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _saving ? null : _savePin, + icon: const Icon(Icons.save), + label: Text(_enabled ? 'Changer le PIN' : 'Activer le PIN'), + ), + if (_enabled) ...[ + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: _saving ? null : _disablePin, + icon: const Icon(Icons.lock_open), + label: const Text('Désactiver le PIN'), + ), + ], + if (_message != null) ...[ + const SizedBox(height: 16), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 24), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Le PIN protège l’accès local à l’application. L’empreinte utilise la sécurité biométrique du téléphone. Le PIN reste le secours si l’empreinte échoue.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart new file mode 100644 index 0000000..a8433cc --- /dev/null +++ b/lib/screens/settings_screen.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; +import '../services/api_service.dart'; +import '../services/security_service.dart'; +import 'security_screen.dart'; + +class SettingsScreen extends StatefulWidget { + const SettingsScreen({super.key, required this.apiService}); + + final ApiService apiService; + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + final _controller = TextEditingController(); + bool _testing = false; + String? _message; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + _controller.text = await widget.apiService.getBaseUrl(); + if (mounted) setState(() {}); + } + + Future _save() async { + await widget.apiService.setBaseUrl(_controller.text); + if (mounted) { + setState(() => _message = 'URL enregistrée localement.'); + } + } + + Future _test() async { + setState(() { + _testing = true; + _message = null; + }); + + try { + await _save(); + final ok = await widget.apiService.healthCheck(); + setState(() => _message = ok ? 'Connexion OK.' : 'Réponse inattendue du serveur.'); + } catch (e) { + setState(() => _message = 'Erreur : $e'); + } finally { + if (mounted) setState(() => _testing = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Paramètres'), + ), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + const Text( + 'URL du backend FIN65', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 8), + const Text( + 'Émulateur Android : http://10.0.2.2:8000\nTéléphone réel : http://IP_DU_PC:8000', + ), + const SizedBox(height: 16), + TextField( + controller: _controller, + decoration: const InputDecoration( + labelText: 'URL API', + border: OutlineInputBorder(), + hintText: 'http://192.168.1.25:8000', + ), + keyboardType: TextInputType.url, + ), + const SizedBox(height: 12), + FilledButton( + onPressed: _testing ? null : _test, + child: Text(_testing ? 'Test...' : 'Enregistrer et tester'), + ), + if (_message != null) ...[ + const SizedBox(height: 16), + Text(_message!), + ], + const SizedBox(height: 24), + Card( + child: ListTile( + leading: const Icon(Icons.lock), + title: const Text('Sécurité'), + subtitle: const Text('Activer, changer ou désactiver le verrouillage PIN.'), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SecurityScreen( + securityService: SecurityService(), + ), + ), + ); + }, + ), + ), + const SizedBox(height: 12), + const Card( + child: Padding( + padding: EdgeInsets.all(12), + child: Text( + 'L’URL est stockée dans la base SQLite locale du mobile. ' + 'Elle reste donc disponible même sans backend.', + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/sync_screen.dart b/lib/screens/sync_screen.dart new file mode 100644 index 0000000..471910b --- /dev/null +++ b/lib/screens/sync_screen.dart @@ -0,0 +1,239 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/pending_operation.dart'; +import '../services/sync_service.dart'; + +class SyncScreen extends StatefulWidget { + const SyncScreen({ + super.key, + required this.syncService, + }); + + final SyncService syncService; + + @override + State createState() => _SyncScreenState(); +} + +class _SyncScreenState extends State { + final _date = DateFormat('dd/MM/yyyy HH:mm', 'fr_FR'); + final _money = NumberFormat.currency(locale: 'fr_FR', symbol: 'MAD ', decimalDigits: 2); + + bool _loading = true; + bool _syncing = false; + bool _isOnline = false; + String? _apiUrl; + String? _message; + DateTime? _lastSyncAt; + List _pending = []; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + setState(() { + _loading = true; + _message = null; + }); + + try { + final apiUrl = await widget.syncService.getApiUrl(); + final isOnline = await widget.syncService.testBackend(); + final snapshot = await widget.syncService.loadLocalSnapshot( + isOnline: isOnline, + message: null, + ); + final pending = await widget.syncService.loadPendingOperations(); + + if (!mounted) return; + setState(() { + _apiUrl = apiUrl; + _isOnline = isOnline; + _lastSyncAt = snapshot.lastSyncAt; + _pending = pending; + }); + } catch (e) { + if (!mounted) return; + setState(() => _message = 'Erreur locale : $e'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + Future _syncNow() async { + if (_syncing) return; + + setState(() { + _syncing = true; + _message = 'Synchronisation en cours...'; + }); + + try { + final snapshot = await widget.syncService.synchronize(); + final pending = await widget.syncService.loadPendingOperations(); + final apiUrl = await widget.syncService.getApiUrl(); + + if (!mounted) return; + + setState(() { + _apiUrl = apiUrl; + _isOnline = snapshot.isOnline; + _lastSyncAt = snapshot.lastSyncAt; + _pending = pending; + _message = snapshot.isOnline + ? 'Synchronisation terminée.' + : 'Backend indisponible. Les opérations restent en attente.'; + }); + } catch (e) { + if (!mounted) return; + setState(() => _message = 'Erreur de synchronisation : $e'); + } finally { + if (mounted) setState(() => _syncing = false); + } + } + + @override + Widget build(BuildContext context) { + final pendingCount = _pending.length; + + return Scaffold( + appBar: AppBar( + title: const Text('Synchronisation'), + actions: [ + IconButton( + onPressed: _loading || _syncing ? null : _load, + icon: const Icon(Icons.refresh), + ), + ], + ), + bottomNavigationBar: SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: FilledButton.icon( + onPressed: _syncing ? null : _syncNow, + icon: _syncing + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + label: Text(_syncing ? 'Synchronisation...' : 'Synchroniser maintenant'), + ), + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 110), + children: [ + Card( + child: ListTile( + leading: Icon(_isOnline ? Icons.cloud_done : Icons.cloud_off), + title: Text(_isOnline ? 'Backend joignable' : 'Backend indisponible'), + subtitle: Text(_apiUrl ?? 'URL API inconnue'), + ), + ), + Card( + child: ListTile( + leading: const Icon(Icons.schedule), + title: const Text('Dernière synchronisation réussie'), + subtitle: Text( + _lastSyncAt == null + ? 'Aucune synchronisation réussie' + : _date.format(_lastSyncAt!.toLocal()), + ), + ), + ), + Card( + child: ListTile( + leading: Icon(pendingCount == 0 ? Icons.check_circle : Icons.pending_actions), + title: Text('$pendingCount opération(s) en attente'), + subtitle: Text( + pendingCount == 0 + ? 'Aucune opération locale à envoyer.' + : 'Ces opérations seront envoyées quand le backend sera disponible.', + ), + ), + ), + if (_message != null && _message!.isNotEmpty) ...[ + const SizedBox(height: 8), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(_message!), + ), + ), + ], + const SizedBox(height: 16), + Text('File d’attente', style: Theme.of(context).textTheme.titleLarge), + const SizedBox(height: 8), + if (_pending.isEmpty) + const Card( + child: ListTile( + leading: Icon(Icons.inbox), + title: Text('Aucune opération en attente'), + ), + ) + else + ..._pending.map((operation) => _PendingOperationTile( + operation: operation, + date: _date, + money: _money, + )), + ], + ), + ); + } +} + +class _PendingOperationTile extends StatelessWidget { + const _PendingOperationTile({ + required this.operation, + required this.date, + required this.money, + }); + + final PendingOperation operation; + final DateFormat date; + final NumberFormat money; + + @override + Widget build(BuildContext context) { + final payload = operation.payload; + final label = payload['label']?.toString() ?? 'Opération mobile'; + final amount = (payload['amount'] as num? ?? 0).toDouble(); + final type = payload['type']?.toString() ?? operation.operationType; + final accountId = payload['account_id']?.toString() ?? '?'; + final targetAccountId = payload['target_account_id']?.toString(); + + final typeLabel = switch (type) { + 'expense' => 'Dépense', + 'income' => 'Recette', + 'transfer' => 'Transfert', + _ => type, + }; + + final accountLabel = type == 'transfer' && targetAccountId != null + ? 'Compte $accountId → compte $targetAccountId' + : 'Compte $accountId'; + + return Card( + child: ListTile( + leading: const Icon(Icons.schedule_send), + title: Text(label), + subtitle: Text( + '$typeLabel • $accountLabel\nCréée le ${date.format(operation.createdAt.toLocal())}' + '${operation.error == null ? '' : '\nDernière erreur : ${operation.error}'}', + ), + isThreeLine: true, + trailing: Text( + money.format(amount), + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + ); + } +} diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart new file mode 100644 index 0000000..cf13569 --- /dev/null +++ b/lib/services/api_service.dart @@ -0,0 +1,118 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +import '../config/app_config.dart'; +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/transaction_item.dart'; +import 'offline_store.dart'; + +class ApiService { + ApiService({OfflineStore? store}) : _store = store ?? OfflineStore.instance; + + final OfflineStore _store; + static const String _baseUrlKey = 'api_base_url'; + + Future getBaseUrl() async { + return await _store.getSetting(_baseUrlKey) ?? AppConfig.defaultApiBaseUrl; + } + + Future setBaseUrl(String value) async { + await _store.setSetting( + _baseUrlKey, + value.trim().replaceAll(RegExp(r'/$'), ''), + ); + } + + Future _uri(String path) async { + final baseUrl = await getBaseUrl(); + return Uri.parse('$baseUrl$path'); + } + + Future _getJson(String path) async { + final res = await http.get(await _uri(path)).timeout(const Duration(seconds: 5)); + return _handleResponse(res); + } + + Future _postJson(String path, Map body) async { + final res = await http + .post( + await _uri(path), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(body), + ) + .timeout(const Duration(seconds: 8)); + return _handleResponse(res); + } + + dynamic _handleResponse(http.Response res) { + if (res.statusCode >= 200 && res.statusCode < 300) { + if (res.body.isEmpty) return null; + return jsonDecode(utf8.decode(res.bodyBytes)); + } + + String message = 'Erreur HTTP ${res.statusCode}'; + try { + final body = jsonDecode(utf8.decode(res.bodyBytes)); + message = body['detail']?.toString() ?? body.toString(); + } catch (_) {} + throw Exception(message); + } + + Future healthCheck() async { + final data = await _getJson('/health'); + return data is Map && data['status'] == 'ok'; + } + + Future getDashboard() async { + final data = await _getJson('/dashboard'); + return DashboardData.fromJson(data as Map); + } + + Future> getAccounts() async { + final data = await _getJson('/accounts?active_only=true') as List; + return data.map((e) => Account.fromJson(e as Map)).toList(); + } + + Future> getCategories() async { + final data = await _getJson('/categories') as List; + return data.map((e) => Category.fromJson(e as Map)).toList(); + } + + Future> getTransactions({int limit = AppConfig.defaultTransactionLimit}) async { + final data = await _getJson('/transactions?limit=$limit') as List; + return data.map((e) => TransactionItem.fromJson(e as Map)).toList(); + } + + Future createTransactionFromPayload(Map payload) async { + final cleanPayload = Map.from(payload); + cleanPayload.removeWhere((_, value) => value == null); + + final data = await _postJson('/transactions', cleanPayload); + return TransactionItem.fromJson(data as Map); + } + + Future createTransaction({ + required String label, + required double amount, + required String type, + required int accountId, + int? targetAccountId, + int? categoryId, + String? note, + DateTime? date, + }) async { + return createTransactionFromPayload({ + 'date': (date ?? DateTime.now()).toIso8601String(), + 'label': label, + 'amount': amount, + 'type': type, + 'account_id': accountId, + 'target_account_id': targetAccountId, + 'category_id': categoryId, + 'created_from': 'android', + 'note': note, + }); + } +} diff --git a/lib/services/offline_store.dart b/lib/services/offline_store.dart new file mode 100644 index 0000000..ab760f8 --- /dev/null +++ b/lib/services/offline_store.dart @@ -0,0 +1,308 @@ +import 'dart:convert'; + +import 'package:path/path.dart' as p; +import 'package:sqflite/sqflite.dart'; + +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/pending_operation.dart'; +import '../models/transaction_item.dart'; + +class OfflineStore { + OfflineStore._(); + + static final OfflineStore instance = OfflineStore._(); + + Database? _database; + + Future get database async { + final existing = _database; + if (existing != null) return existing; + + final dbPath = await getDatabasesPath(); + final path = p.join(dbPath, 'fin65_mobile.db'); + + final db = await openDatabase( + path, + version: 1, + onCreate: _createSchema, + ); + + _database = db; + return db; + } + + Future _createSchema(Database db, int version) async { + await db.execute(''' + CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE sync_state ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE accounts_cache ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + currency TEXT NOT NULL, + initial_balance REAL NOT NULL, + app_balance REAL NOT NULL, + is_active INTEGER NOT NULL, + updated_at TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE categories_cache ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + parent_id INTEGER, + updated_at TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE transactions_cache ( + id INTEGER PRIMARY KEY, + label TEXT NOT NULL, + amount REAL NOT NULL, + type TEXT NOT NULL, + account_id INTEGER NOT NULL, + target_account_id INTEGER, + category_id INTEGER, + provision_id INTEGER, + date TEXT NOT NULL, + note TEXT, + is_pending INTEGER NOT NULL DEFAULT 0, + local_operation_id INTEGER, + updated_at TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE dashboard_cache ( + id INTEGER PRIMARY KEY CHECK (id = 1), + json TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE pending_operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + operation_type TEXT NOT NULL, + payload_json TEXT NOT NULL, + created_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + error TEXT + ) + '''); + } + + Future getSetting(String key) async { + final db = await database; + final rows = await db.query( + 'settings', + where: 'key = ?', + whereArgs: [key], + limit: 1, + ); + if (rows.isEmpty) return null; + return rows.first['value'] as String?; + } + + Future setSetting(String key, String value) async { + final db = await database; + await db.insert( + 'settings', + {'key': key, 'value': value}, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + Future getSyncState(String key) async { + final db = await database; + final rows = await db.query( + 'sync_state', + where: 'key = ?', + whereArgs: [key], + limit: 1, + ); + if (rows.isEmpty) return null; + return rows.first['value'] as String?; + } + + Future setSyncState(String key, String value) async { + final db = await database; + await db.insert( + 'sync_state', + {'key': key, 'value': value}, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + Future getLastSyncAt() async { + final value = await getSyncState('last_successful_sync_at'); + return value == null ? null : DateTime.tryParse(value); + } + + Future saveServerSnapshot({ + required DashboardData dashboard, + required List accounts, + required List categories, + required List transactions, + }) async { + final db = await database; + final now = DateTime.now().toIso8601String(); + + await db.transaction((txn) async { + await txn.delete('accounts_cache'); + await txn.delete('categories_cache'); + await txn.delete('transactions_cache'); + await txn.delete('dashboard_cache'); + + for (final account in accounts) { + await txn.insert( + 'accounts_cache', + account.toDbMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + for (final category in categories) { + await txn.insert( + 'categories_cache', + category.toDbMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + for (final transaction in transactions) { + await txn.insert( + 'transactions_cache', + transaction.toDbMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + await txn.insert( + 'dashboard_cache', + { + 'id': 1, + 'json': jsonEncode(dashboard.toJson()), + 'updated_at': now, + }, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + await txn.insert( + 'sync_state', + { + 'key': 'last_successful_sync_at', + 'value': now, + }, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + }); + } + + Future> loadAccounts() async { + final db = await database; + final rows = await db.query('accounts_cache', orderBy: 'name COLLATE NOCASE ASC'); + return rows.map(Account.fromDbMap).toList(); + } + + Future> loadCategories() async { + final db = await database; + final rows = await db.query('categories_cache', orderBy: 'type ASC, name COLLATE NOCASE ASC'); + return rows.map(Category.fromDbMap).toList(); + } + + Future> loadTransactions({int limit = 50}) async { + final db = await database; + final rows = await db.query( + 'transactions_cache', + orderBy: 'date DESC, id DESC', + limit: limit, + ); + return rows.map(TransactionItem.fromDbMap).toList(); + } + + Future loadDashboard() async { + final db = await database; + final rows = await db.query( + 'dashboard_cache', + where: 'id = 1', + limit: 1, + ); + if (rows.isEmpty) return null; + + final decoded = jsonDecode(rows.first['json'] as String) as Map; + return DashboardData.fromJson(decoded); + } + + Future enqueueCreateTransaction(Map payload) async { + final db = await database; + return db.insert( + 'pending_operations', + { + 'operation_type': 'create_transaction', + 'payload_json': jsonEncode(payload), + 'created_at': DateTime.now().toIso8601String(), + 'status': 'pending', + 'error': null, + }, + ); + } + + Future> loadPendingOperations() async { + final db = await database; + final rows = await db.query( + 'pending_operations', + where: 'status = ?', + whereArgs: ['pending'], + orderBy: 'created_at ASC, id ASC', + ); + return rows.map(PendingOperation.fromDbMap).toList(); + } + + Future pendingCount() async { + final db = await database; + final result = await db.rawQuery( + "SELECT COUNT(*) AS count FROM pending_operations WHERE status = 'pending'", + ); + return Sqflite.firstIntValue(result) ?? 0; + } + + Future deletePendingOperation(int id) async { + final db = await database; + await db.delete( + 'pending_operations', + where: 'id = ?', + whereArgs: [id], + ); + } + + Future markPendingError(int id, String error) async { + final db = await database; + await db.update( + 'pending_operations', + { + 'error': error, + 'status': 'pending', + }, + where: 'id = ?', + whereArgs: [id], + ); + } +} diff --git a/lib/services/security_service.dart b/lib/services/security_service.dart new file mode 100644 index 0000000..6af5277 --- /dev/null +++ b/lib/services/security_service.dart @@ -0,0 +1,118 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:local_auth/local_auth.dart'; + +import 'offline_store.dart'; + +class SecurityService { + SecurityService({ + OfflineStore? store, + LocalAuthentication? localAuth, + }) : _store = store ?? OfflineStore.instance, + _localAuth = localAuth ?? LocalAuthentication(); + + final OfflineStore _store; + final LocalAuthentication _localAuth; + + static const String _pinEnabledKey = 'security_pin_enabled'; + static const String _pinHashKey = 'security_pin_hash'; + static const String _biometricEnabledKey = 'security_biometric_enabled'; + static const String _salt = 'FIN65_LOCAL_PIN_V1'; + + Future isPinEnabled() async { + final enabled = await _store.getSetting(_pinEnabledKey); + final hash = await _store.getSetting(_pinHashKey); + return enabled == 'true' && hash != null && hash.isNotEmpty; + } + + Future setPin(String pin) async { + _validatePin(pin); + await _store.setSetting(_pinHashKey, _hashPin(pin)); + await _store.setSetting(_pinEnabledKey, 'true'); + } + + Future verifyPin(String pin) async { + if (!_isValidPinShape(pin)) return false; + final storedHash = await _store.getSetting(_pinHashKey); + if (storedHash == null || storedHash.isEmpty) return false; + return storedHash == _hashPin(pin); + } + + Future disablePin() async { + await _store.setSetting(_pinHashKey, ''); + await _store.setSetting(_pinEnabledKey, 'false'); + await setBiometricEnabled(false); + } + + Future isBiometricAvailable() async { + try { + final supported = await _localAuth.isDeviceSupported(); + final canCheck = await _localAuth.canCheckBiometrics; + final biometrics = await _localAuth.getAvailableBiometrics(); + return supported && canCheck && biometrics.isNotEmpty; + } catch (_) { + return false; + } + } + + Future> getAvailableBiometrics() async { + try { + return await _localAuth.getAvailableBiometrics(); + } catch (_) { + return const []; + } + } + + Future isBiometricEnabled() async { + final enabled = await _store.getSetting(_biometricEnabledKey); + final pinEnabled = await isPinEnabled(); + return pinEnabled && enabled == 'true'; + } + + Future setBiometricEnabled(bool enabled) async { + if (enabled) { + final pinEnabled = await isPinEnabled(); + if (!pinEnabled) { + throw Exception('Active d’abord un PIN avant la biométrie.'); + } + + final available = await isBiometricAvailable(); + if (!available) { + throw Exception('Aucune empreinte/biométrie disponible sur cet appareil.'); + } + } + + await _store.setSetting(_biometricEnabledKey, enabled ? 'true' : 'false'); + } + + Future authenticateWithBiometrics() async { + final enabled = await isBiometricEnabled(); + if (!enabled) return false; + + try { + return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + ); + } catch (_) { + return false; + } + } + + String _hashPin(String pin) { + return sha256.convert(utf8.encode('$_salt::$pin')).toString(); + } + + void _validatePin(String pin) { + if (!_isValidPinShape(pin)) { + throw Exception('Le PIN doit contenir 4 à 8 chiffres.'); + } + } + + bool _isValidPinShape(String pin) { + return RegExp(r'^\d{4,8}$').hasMatch(pin); + } +} + + diff --git a/lib/services/security_service.dart.before_local_auth_fix_20260709_004912.bak b/lib/services/security_service.dart.before_local_auth_fix_20260709_004912.bak new file mode 100644 index 0000000..843c92c --- /dev/null +++ b/lib/services/security_service.dart.before_local_auth_fix_20260709_004912.bak @@ -0,0 +1,120 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:local_auth/local_auth.dart'; + +import 'offline_store.dart'; + +class SecurityService { + SecurityService({ + OfflineStore? store, + LocalAuthentication? localAuth, + }) : _store = store ?? OfflineStore.instance, + _localAuth = localAuth ?? LocalAuthentication(); + + final OfflineStore _store; + final LocalAuthentication _localAuth; + + static const String _pinEnabledKey = 'security_pin_enabled'; + static const String _pinHashKey = 'security_pin_hash'; + static const String _biometricEnabledKey = 'security_biometric_enabled'; + static const String _salt = 'FIN65_LOCAL_PIN_V1'; + + Future isPinEnabled() async { + final enabled = await _store.getSetting(_pinEnabledKey); + final hash = await _store.getSetting(_pinHashKey); + return enabled == 'true' && hash != null && hash.isNotEmpty; + } + + Future setPin(String pin) async { + _validatePin(pin); + await _store.setSetting(_pinHashKey, _hashPin(pin)); + await _store.setSetting(_pinEnabledKey, 'true'); + } + + Future verifyPin(String pin) async { + if (!_isValidPinShape(pin)) return false; + final storedHash = await _store.getSetting(_pinHashKey); + if (storedHash == null || storedHash.isEmpty) return false; + return storedHash == _hashPin(pin); + } + + Future disablePin() async { + await _store.setSetting(_pinHashKey, ''); + await _store.setSetting(_pinEnabledKey, 'false'); + await setBiometricEnabled(false); + } + + Future isBiometricAvailable() async { + try { + final supported = await _localAuth.isDeviceSupported(); + final canCheck = await _localAuth.canCheckBiometrics; + final biometrics = await _localAuth.getAvailableBiometrics(); + return supported && canCheck && biometrics.isNotEmpty; + } catch (_) { + return false; + } + } + + Future> getAvailableBiometrics() async { + try { + return await _localAuth.getAvailableBiometrics(); + } catch (_) { + return const []; + } + } + + Future isBiometricEnabled() async { + final enabled = await _store.getSetting(_biometricEnabledKey); + final pinEnabled = await isPinEnabled(); + return pinEnabled && enabled == 'true'; + } + + Future setBiometricEnabled(bool enabled) async { + if (enabled) { + final pinEnabled = await isPinEnabled(); + if (!pinEnabled) { + throw Exception('Active d’abord un PIN avant la biométrie.'); + } + + final available = await isBiometricAvailable(); + if (!available) { + throw Exception('Aucune empreinte/biométrie disponible sur cet appareil.'); + } + } + + await _store.setSetting(_biometricEnabledKey, enabled ? 'true' : 'false'); + } + + Future authenticateWithBiometrics() async { + final enabled = await isBiometricEnabled(); + if (!enabled) return false; + + try { + return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + options: const AuthenticationOptions( + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, + ), + ); + } catch (_) { + return false; + } + } + + String _hashPin(String pin) { + return sha256.convert(utf8.encode('$_salt::$pin')).toString(); + } + + void _validatePin(String pin) { + if (!_isValidPinShape(pin)) { + throw Exception('Le PIN doit contenir 4 à 8 chiffres.'); + } + } + + bool _isValidPinShape(String pin) { + return RegExp(r'^\d{4,8}$').hasMatch(pin); + } +} diff --git a/lib/services/security_service.dart.before_local_auth_minimal_fix_20260709_005129.bak b/lib/services/security_service.dart.before_local_auth_minimal_fix_20260709_005129.bak new file mode 100644 index 0000000..08b595d --- /dev/null +++ b/lib/services/security_service.dart.before_local_auth_minimal_fix_20260709_005129.bak @@ -0,0 +1,119 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:local_auth/local_auth.dart'; + +import 'offline_store.dart'; + +class SecurityService { + SecurityService({ + OfflineStore? store, + LocalAuthentication? localAuth, + }) : _store = store ?? OfflineStore.instance, + _localAuth = localAuth ?? LocalAuthentication(); + + final OfflineStore _store; + final LocalAuthentication _localAuth; + + static const String _pinEnabledKey = 'security_pin_enabled'; + static const String _pinHashKey = 'security_pin_hash'; + static const String _biometricEnabledKey = 'security_biometric_enabled'; + static const String _salt = 'FIN65_LOCAL_PIN_V1'; + + Future isPinEnabled() async { + final enabled = await _store.getSetting(_pinEnabledKey); + final hash = await _store.getSetting(_pinHashKey); + return enabled == 'true' && hash != null && hash.isNotEmpty; + } + + Future setPin(String pin) async { + _validatePin(pin); + await _store.setSetting(_pinHashKey, _hashPin(pin)); + await _store.setSetting(_pinEnabledKey, 'true'); + } + + Future verifyPin(String pin) async { + if (!_isValidPinShape(pin)) return false; + final storedHash = await _store.getSetting(_pinHashKey); + if (storedHash == null || storedHash.isEmpty) return false; + return storedHash == _hashPin(pin); + } + + Future disablePin() async { + await _store.setSetting(_pinHashKey, ''); + await _store.setSetting(_pinEnabledKey, 'false'); + await setBiometricEnabled(false); + } + + Future isBiometricAvailable() async { + try { + final supported = await _localAuth.isDeviceSupported(); + final canCheck = await _localAuth.canCheckBiometrics; + final biometrics = await _localAuth.getAvailableBiometrics(); + return supported && canCheck && biometrics.isNotEmpty; + } catch (_) { + return false; + } + } + + Future> getAvailableBiometrics() async { + try { + return await _localAuth.getAvailableBiometrics(); + } catch (_) { + return const []; + } + } + + Future isBiometricEnabled() async { + final enabled = await _store.getSetting(_biometricEnabledKey); + final pinEnabled = await isPinEnabled(); + return pinEnabled && enabled == 'true'; + } + + Future setBiometricEnabled(bool enabled) async { + if (enabled) { + final pinEnabled = await isPinEnabled(); + if (!pinEnabled) { + throw Exception('Active d’abord un PIN avant la biométrie.'); + } + + final available = await isBiometricAvailable(); + if (!available) { + throw Exception('Aucune empreinte/biométrie disponible sur cet appareil.'); + } + } + + await _store.setSetting(_biometricEnabledKey, enabled ? 'true' : 'false'); + } + + Future authenticateWithBiometrics() async { + final enabled = await isBiometricEnabled(); + if (!enabled) return false; + + try { + return await _localAuth.authenticate( + localizedReason: 'Déverrouiller FIN65', + biometricOnly: true, + stickyAuth: true, + useErrorDialogs: true, + ); + } catch (_) { + return false; + } + } + + String _hashPin(String pin) { + return sha256.convert(utf8.encode('$_salt::$pin')).toString(); + } + + void _validatePin(String pin) { + if (!_isValidPinShape(pin)) { + throw Exception('Le PIN doit contenir 4 à 8 chiffres.'); + } + } + + bool _isValidPinShape(String pin) { + return RegExp(r'^\d{4,8}$').hasMatch(pin); + } +} + diff --git a/lib/services/sync_service.dart b/lib/services/sync_service.dart new file mode 100644 index 0000000..c286b93 --- /dev/null +++ b/lib/services/sync_service.dart @@ -0,0 +1,271 @@ +import '../config/app_config.dart'; +import '../models/account.dart'; +import '../models/category.dart'; +import '../models/dashboard.dart'; +import '../models/pending_operation.dart'; +import '../models/transaction_item.dart'; +import 'api_service.dart'; +import 'offline_store.dart'; + +class SyncSnapshot { + final DashboardData? dashboard; + final List accounts; + final List categories; + final List transactions; + final int pendingCount; + final DateTime? lastSyncAt; + final bool isOnline; + final String? message; + + SyncSnapshot({ + required this.dashboard, + required this.accounts, + required this.categories, + required this.transactions, + required this.pendingCount, + required this.lastSyncAt, + required this.isOnline, + this.message, + }); +} + +class SyncService { + SyncService({ + ApiService? apiService, + OfflineStore? offlineStore, + }) : store = offlineStore ?? OfflineStore.instance, + apiService = apiService ?? ApiService(store: offlineStore ?? OfflineStore.instance); + + final OfflineStore store; + final ApiService apiService; + +Future> loadPendingOperations() { + return store.loadPendingOperations(); +} + +Future getApiUrl() { + return apiService.getBaseUrl(); +} + +Future testBackend() async { + try { + return await apiService.healthCheck(); + } catch (_) { + return false; + } +} + + + Future loadLocalSnapshot({bool isOnline = false, String? message}) async { + final dashboard = await store.loadDashboard(); + final accounts = await store.loadAccounts(); + final categories = await store.loadCategories(); + final transactions = await store.loadTransactions(limit: AppConfig.defaultTransactionLimit); + final pending = await store.loadPendingOperations(); + final lastSyncAt = await store.getLastSyncAt(); + + return _applyPendingEstimates( + dashboard: dashboard, + accounts: accounts, + categories: categories, + transactions: transactions, + pending: pending, + lastSyncAt: lastSyncAt, + isOnline: isOnline, + message: message, + ); + } + + Future synchronize() async { + try { + await apiService.healthCheck(); + await _syncPendingOperations(); + + final accounts = await apiService.getAccounts(); + final categories = await apiService.getCategories(); + final dashboard = await apiService.getDashboard(); + final transactions = await apiService.getTransactions(limit: AppConfig.defaultTransactionLimit); + + await store.saveServerSnapshot( + dashboard: dashboard, + accounts: accounts, + categories: categories, + transactions: transactions, + ); + + return loadLocalSnapshot(isOnline: true, message: null); + } catch (e) { + return loadLocalSnapshot( + isOnline: false, + message: 'Backend indisponible. Données locales affichées.', + ); + } + } + + Future createTransactionSmart({ + required String label, + required double amount, + required String type, + required int accountId, + int? targetAccountId, + int? categoryId, + String? note, + }) async { + final payload = { + 'date': DateTime.now().toIso8601String(), + 'label': label, + 'amount': amount, + 'type': type, + 'account_id': accountId, + 'target_account_id': type == 'transfer' ? targetAccountId : null, + 'category_id': type == 'transfer' ? null : categoryId, + 'created_from': 'android', + 'note': note, + }; + + try { + await apiService.healthCheck(); + await apiService.createTransactionFromPayload(payload); + await synchronize(); + return true; + } catch (_) { + // Offline or backend unreachable: the operation is persisted locally in + // SQLite. The UI can then immediately reload an estimated snapshot. + await store.enqueueCreateTransaction(payload); + return false; + } + } + + Future _syncPendingOperations() async { + final pending = await store.loadPendingOperations(); + + for (final operation in pending) { + try { + if (operation.operationType == 'create_transaction') { + await apiService.createTransactionFromPayload(operation.payload); + await store.deletePendingOperation(operation.id); + } + } catch (e) { + await store.markPendingError(operation.id, e.toString()); + rethrow; + } + } + } + + SyncSnapshot _applyPendingEstimates({ + required DashboardData? dashboard, + required List accounts, + required List categories, + required List transactions, + required List pending, + required DateTime? lastSyncAt, + required bool isOnline, + String? message, + }) { + final accountMap = { + for (final account in accounts) account.id: account, + }; + + var adjustedDashboard = dashboard; + final pendingTransactions = []; + + for (final operation in pending) { + if (operation.operationType != 'create_transaction') continue; + + final item = TransactionItem.fromPending( + localOperationId: operation.id, + payload: operation.payload, + ); + pendingTransactions.add(item); + + final amount = item.amount; + final source = accountMap[item.accountId]; + + if (item.type == 'expense') { + if (source != null) { + accountMap[item.accountId] = source.copyWith( + appBalance: source.appBalance - amount, + ); + } + + adjustedDashboard = _adjustDashboard( + adjustedDashboard, + totalDelta: -amount, + availableDelta: -amount, + incomeDelta: 0, + expenseDelta: amount, + monthlyBalanceDelta: -amount, + ); + } else if (item.type == 'income') { + if (source != null) { + accountMap[item.accountId] = source.copyWith( + appBalance: source.appBalance + amount, + ); + } + + adjustedDashboard = _adjustDashboard( + adjustedDashboard, + totalDelta: amount, + availableDelta: amount, + incomeDelta: amount, + expenseDelta: 0, + monthlyBalanceDelta: amount, + ); + } else if (item.type == 'transfer') { + if (source != null) { + accountMap[item.accountId] = source.copyWith( + appBalance: source.appBalance - amount, + ); + } + + final targetId = item.targetAccountId; + if (targetId != null) { + final target = accountMap[targetId]; + if (target != null) { + accountMap[targetId] = target.copyWith( + appBalance: target.appBalance + amount, + ); + } + } + } + } + + final adjustedAccounts = accountMap.values.toList() + ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + + final allTransactions = [ + ...pendingTransactions.reversed, + ...transactions, + ]; + + return SyncSnapshot( + dashboard: adjustedDashboard, + accounts: adjustedAccounts, + categories: categories, + transactions: allTransactions, + pendingCount: pending.length, + lastSyncAt: lastSyncAt, + isOnline: isOnline, + message: message, + ); + } + + DashboardData? _adjustDashboard( + DashboardData? dashboard, { + required double totalDelta, + required double availableDelta, + required double incomeDelta, + required double expenseDelta, + required double monthlyBalanceDelta, + }) { + if (dashboard == null) return null; + + return dashboard.copyWith( + totalBalance: dashboard.totalBalance + totalDelta, + availableAfterReserves: dashboard.availableAfterReserves + availableDelta, + monthlyIncome: dashboard.monthlyIncome + incomeDelta, + monthlyExpenses: dashboard.monthlyExpenses + expenseDelta, + monthlyBalance: dashboard.monthlyBalance + monthlyBalanceDelta, + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..26f0799 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "fin65_mobile") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.fin65_mobile") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..2df1a03 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "fin65_mobile"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "fin65_mobile"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..5ad0735 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import local_auth_darwin +import sqflite_darwin + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + LocalAuthPlugin.register(with: registry.registrar(forPlugin: "LocalAuthPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..e984f67 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* fin65_mobile.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "fin65_mobile.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* fin65_mobile.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* fin65_mobile.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.fin65Mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/fin65_mobile.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/fin65_mobile"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.fin65Mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/fin65_mobile.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/fin65_mobile"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.fin65Mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/fin65_mobile.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/fin65_mobile"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* 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 = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..65ee402 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..b4406cb --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = fin65_mobile + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.fin65Mobile + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..db8acb2 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,365 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + 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" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" + url: "https://pub.dev" + source: hosted + version: "2.0.35" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + 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: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf + url: "https://pub.dev" + source: hosted + version: "0.19.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + local_auth: + dependency: "direct main" + description: + name: local_auth + sha256: ae6f382f638108c6becd134318d7c3f0a93875383a54010f61d7c97ac05d5137 + url: "https://pub.dev" + source: hosted + version: "3.0.1" + local_auth_android: + dependency: transitive + description: + name: local_auth_android + sha256: fdb936d59ab945c7af297defd67bd1ed87b11b6db1bc16d01e94677a8f1c38ec + url: "https://pub.dev" + source: hosted + version: "2.0.9" + local_auth_darwin: + dependency: transitive + description: + name: local_auth_darwin + sha256: a8c3d4e17454111f7fd31ff72a31222359f6059f7fe956c2dcfe0f88f49826d4 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + local_auth_platform_interface: + dependency: transitive + description: + name: local_auth_platform_interface + sha256: f98b8e388588583d3f781f6806e4f4c9f9e189d898d27f0c249b93a1973dd122 + url: "https://pub.dev" + source: hosted + version: "1.1.0" + local_auth_windows: + dependency: transitive + description: + name: local_auth_windows + sha256: be12c5b8ba5e64896983123655c5f67d2484ecfcc95e367952ad6e3bff94cb16 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + 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" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + 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" + 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" + sqflite: + dependency: "direct main" + description: + name: sqflite + sha256: "58a799e6ac17dd32fbab93813d39ed835a75ccc0f8f85b8955fe318c6712b082" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: d0548f9d7422a2dae99ec6f8b0a3074463b132d216fa5ba0d230eeefc901983b + url: "https://pub.dev" + source: hosted + version: "2.4.3" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "5bf6a55c166e73bf651ba7ec3ed486e577620e3dc8f3a9c6a258a8031b624590" + url: "https://pub.dev" + source: hosted + version: "2.5.11" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: c86ca18b8f666bbf903924687fe21cc16fc385d086005067e26619ca530bef9f + url: "https://pub.dev" + source: hosted + version: "2.4.3+1" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: f84939f84350d92d04416f8bc4dc52d3896aec7716cc9e80cf0146342139dc50 + url: "https://pub.dev" + source: hosted + version: "2.4.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "93b153dcb6a26dcddee6ca087dd634b53e38c10b5aa163e8e49501a776456153" + url: "https://pub.dev" + source: hosted + version: "3.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" +sdks: + dart: ">=3.12.0 <4.0.0" + flutter: ">=3.44.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..4c6472a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,26 @@ +name: fin65_mobile +description: FIN65 mobile app - offline-first avec SQLite local +publish_to: "none" + +version: 0.2.6+6 + +environment: + sdk: ">=3.4.0 <4.0.0" + +dependencies: + flutter: + sdk: flutter + http: ^1.2.2 + sqflite: ^2.4.2 + path: ^1.9.1 + intl: ^0.19.0 + crypto: ^3.0.6 + local_auth: ^3.0.1 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^4.0.0 + +flutter: + uses-material-design: true diff --git a/remove_icon_config_only.bat b/remove_icon_config_only.bat new file mode 100644 index 0000000..f72acb4 --- /dev/null +++ b/remove_icon_config_only.bat @@ -0,0 +1,17 @@ +@echo off +setlocal + +set "ROOT_DIR=D:\07-Logiciels\20-FIN65" +set "MOBILE_DIR=%ROOT_DIR%\fin65_mobile" +set "PUB_CACHE=%ROOT_DIR%\.pub-cache" + +cd /d "%MOBILE_DIR%" || ( + echo Dossier mobile introuvable. + pause + exit /b 1 +) + +del "flutter_launcher_icons.yaml" >nul 2>&1 +echo Configuration flutter_launcher_icons supprimee. +echo Les fichiers Android generes restent en place. +pause diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..cab368d --- /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:fin65_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); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..5239546 --- /dev/null +++ b/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + fin65_mobile + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..5d3b919 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "fin65_mobile", + "short_name": "fin65_mobile", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..b75cd4f --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(fin65_mobile LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "fin65_mobile") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..7407ddd --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + LocalAuthPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("LocalAuthPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..ef187dc --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + local_auth_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..322aa53 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "fin65_mobile" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "fin65_mobile" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "fin65_mobile.exe" "\0" + VALUE "ProductName", "fin65_mobile" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..b2c4987 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"fin65_mobile", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_