Compare commits
133 Commits
41402e1b2c
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e665dea82a | ||
|
|
b511ec5df0 | ||
|
|
c0e53cd3f6 | ||
|
|
4fc7abc5b4 | ||
|
|
e04bf6f405 | ||
|
|
bed761401f | ||
|
|
55463649b2 | ||
|
|
62d2aa17be | ||
|
|
acfb2259cc | ||
|
|
d1d2194861 | ||
|
|
b542f98a91 | ||
|
|
f983b869ba | ||
|
|
ead346bb1b | ||
|
|
8d27e771a7 | ||
|
|
31fe3a4260 | ||
|
|
a2c6cd1d4f | ||
|
|
5fe9f371b2 | ||
|
|
b27fb7ed4c | ||
|
|
919ef611bc | ||
|
|
3eeed888b5 | ||
|
|
322f611522 | ||
|
|
a7d2634c5f | ||
|
|
ae125f1144 | ||
|
|
d66907f636 | ||
|
|
508d69a4f4 | ||
|
|
ee00415d23 | ||
|
|
576b86fbbb | ||
|
|
918742293b | ||
|
|
19c06c71f8 | ||
|
|
3e5f3a7ece | ||
|
|
12fdd6da62 | ||
|
|
15a7319239 | ||
|
|
911fb86611 | ||
|
|
8b4c66ba0d | ||
|
|
1352dc49cc | ||
|
|
51ffe2031d | ||
|
|
c70ed9c504 | ||
|
|
67d798f590 | ||
|
|
d60cce83c9 | ||
|
|
c03d2b969c | ||
|
|
4af4450b94 | ||
|
|
6be4bed2e0 | ||
|
|
d13094c662 | ||
|
|
a9c3087f53 | ||
|
|
1b6d40627d | ||
|
|
67a7d1ad2a | ||
|
|
4ef550f48b | ||
|
|
993a5870c5 | ||
|
|
5a682bb6d7 | ||
|
|
bb5a89a06d | ||
|
|
3036eec3af | ||
|
|
63fc18ea74 | ||
|
|
ca3f62c709 | ||
|
|
b13f0b87a3 | ||
|
|
8ec8f35a31 | ||
|
|
230b7abf8b | ||
|
|
2abb080c09 | ||
|
|
a34c1e5a3d | ||
|
|
68605dea78 | ||
|
|
59b708a160 | ||
|
|
2849dfaade | ||
|
|
b08f9164e6 | ||
|
|
5fb9fbaf2b | ||
|
|
520c38782f | ||
|
|
5b21fb12e3 | ||
|
|
a49aa198f4 | ||
|
|
ef895ff892 | ||
|
|
06c8d2c589 | ||
|
|
20be1ab64c | ||
|
|
795f0e8853 | ||
|
|
d3f2cc6eb0 | ||
|
|
e34780c9a7 | ||
|
|
495b0dc98f | ||
|
|
7b03381f7c | ||
|
|
800a402046 | ||
|
|
50101d1196 | ||
|
|
ae25ea73a8 | ||
|
|
407425a2b9 | ||
|
|
088f4a2833 | ||
|
|
c63124b16b | ||
|
|
329708fe6c | ||
|
|
e5b2be5245 | ||
|
|
0fb1634a91 | ||
|
|
8634edc916 | ||
|
|
1211569078 | ||
|
|
26b970982c | ||
|
|
e77393dd13 | ||
|
|
020fa8823d | ||
|
|
959fc33fe4 | ||
|
|
a57fc811d8 | ||
|
|
a96084ba17 | ||
|
|
b96c988e80 | ||
|
|
14d2761832 | ||
|
|
bd3fd28d3c | ||
|
|
e8ef20d046 | ||
|
|
9fc8d5d1de | ||
|
|
73db84896a | ||
|
|
9734532491 | ||
|
|
7d38f54123 | ||
|
|
d02a627b86 | ||
|
|
6ce40dd2d6 | ||
|
|
00ffdcf10b | ||
|
|
e4d38692fe | ||
|
|
1f93a4e42d | ||
|
|
bf48971dc4 | ||
|
|
13933fc56c | ||
|
|
ca28e0a780 | ||
|
|
34b5efb1fc | ||
|
|
f96a51c7cf | ||
|
|
cac0770467 | ||
|
|
9b11836409 | ||
|
|
9f2bfcaa55 | ||
|
|
e174c1274d | ||
|
|
cf4c6447dd | ||
|
|
a74d76b485 | ||
|
|
fd19b88eef | ||
|
|
f3ae91ccf9 | ||
|
|
6757cb013a | ||
|
|
1e70b9e09f | ||
|
|
b4bcc8f498 | ||
|
|
68f546d0e8 | ||
|
|
0668fcad57 | ||
|
|
b1f86b1c6a | ||
|
|
bf796a661c | ||
|
|
272fce2e59 | ||
|
|
fd710b8cb8 | ||
|
|
cad9d42128 | ||
|
|
9198493dd5 | ||
|
|
f7eeb7c6f1 | ||
|
|
258f10b42b | ||
|
|
79cf3f4655 | ||
|
|
c322bc079a | ||
|
|
9101a94691 |
@@ -1,82 +0,0 @@
|
||||
# Details
|
||||
|
||||
Date : 2025-10-14 11:10:48
|
||||
|
||||
Directory c:\\Users\\dayro\\Documents\\coding\\travel_mate
|
||||
|
||||
Total : 67 files, 5159 codes, 328 comments, 739 blanks, all 6226 lines
|
||||
|
||||
[Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
|
||||
|
||||
## Files
|
||||
| filename | language | code | comment | blank | total |
|
||||
| :--- | :--- | ---: | ---: | ---: | ---: |
|
||||
| [README.md](/README.md) | Markdown | 45 | 0 | 16 | 61 |
|
||||
| [analysis\_options.yaml](/analysis_options.yaml) | YAML | 3 | 22 | 4 | 29 |
|
||||
| [android/app/google-services.json](/android/app/google-services.json) | JSON | 54 | 0 | 0 | 54 |
|
||||
| [android/app/src/debug/AndroidManifest.xml](/android/app/src/debug/AndroidManifest.xml) | XML | 3 | 4 | 1 | 8 |
|
||||
| [android/app/src/main/AndroidManifest.xml](/android/app/src/main/AndroidManifest.xml) | XML | 40 | 11 | 1 | 52 |
|
||||
| [android/app/src/main/res/drawable-v21/launch\_background.xml](/android/app/src/main/res/drawable-v21/launch_background.xml) | XML | 4 | 7 | 2 | 13 |
|
||||
| [android/app/src/main/res/drawable/launch\_background.xml](/android/app/src/main/res/drawable/launch_background.xml) | XML | 4 | 7 | 2 | 13 |
|
||||
| [android/app/src/main/res/values-night/styles.xml](/android/app/src/main/res/values-night/styles.xml) | XML | 9 | 9 | 1 | 19 |
|
||||
| [android/app/src/main/res/values/styles.xml](/android/app/src/main/res/values/styles.xml) | XML | 9 | 9 | 1 | 19 |
|
||||
| [android/app/src/profile/AndroidManifest.xml](/android/app/src/profile/AndroidManifest.xml) | XML | 3 | 4 | 1 | 8 |
|
||||
| [android/build/reports/problems/problems-report.html](/android/build/reports/problems/problems-report.html) | HTML | 548 | 2 | 114 | 664 |
|
||||
| [android/gradle.properties](/android/gradle.properties) | Properties | 3 | 0 | 1 | 4 |
|
||||
| [android/gradle/wrapper/gradle-wrapper.properties](/android/gradle/wrapper/gradle-wrapper.properties) | Properties | 5 | 0 | 1 | 6 |
|
||||
| [firebase.json](/firebase.json) | JSON | 1 | 0 | 0 | 1 |
|
||||
| [ios/Podfile](/ios/Podfile) | Ruby | 32 | 2 | 10 | 44 |
|
||||
| [ios/RunnerTests/RunnerTests.swift](/ios/RunnerTests/RunnerTests.swift) | Swift | 7 | 2 | 4 | 13 |
|
||||
| [ios/Runner/AppDelegate.swift](/ios/Runner/AppDelegate.swift) | Swift | 14 | 0 | 2 | 16 |
|
||||
| [ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json](/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json) | JSON | 122 | 0 | 1 | 123 |
|
||||
| [ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json](/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json) | JSON | 23 | 0 | 1 | 24 |
|
||||
| [ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md](/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md) | Markdown | 3 | 0 | 2 | 5 |
|
||||
| [ios/Runner/Base.lproj/LaunchScreen.storyboard](/ios/Runner/Base.lproj/LaunchScreen.storyboard) | XML | 36 | 1 | 1 | 38 |
|
||||
| [ios/Runner/Base.lproj/Main.storyboard](/ios/Runner/Base.lproj/Main.storyboard) | XML | 25 | 1 | 1 | 27 |
|
||||
| [ios/Runner/Runner-Bridging-Header.h](/ios/Runner/Runner-Bridging-Header.h) | C++ | 1 | 0 | 1 | 2 |
|
||||
| [lib/blocs/auth/auth\_bloc.dart](/lib/blocs/auth/auth_bloc.dart) | Dart | 129 | 1 | 20 | 150 |
|
||||
| [lib/blocs/auth/auth\_event.dart](/lib/blocs/auth/auth_event.dart) | Dart | 40 | 0 | 15 | 55 |
|
||||
| [lib/blocs/auth/auth\_state.dart](/lib/blocs/auth/auth_state.dart) | Dart | 28 | 0 | 14 | 42 |
|
||||
| [lib/blocs/theme/theme\_bloc.dart](/lib/blocs/theme/theme_bloc.dart) | Dart | 40 | 1 | 5 | 46 |
|
||||
| [lib/blocs/theme/theme\_event.dart](/lib/blocs/theme/theme_event.dart) | Dart | 14 | 0 | 6 | 20 |
|
||||
| [lib/blocs/theme/theme\_state.dart](/lib/blocs/theme/theme_state.dart) | Dart | 16 | 0 | 5 | 21 |
|
||||
| [lib/blocs/trip/trip\_bloc.dart](/lib/blocs/trip/trip_bloc.dart) | Dart | 103 | 1 | 14 | 118 |
|
||||
| [lib/blocs/trip/trip\_event.dart](/lib/blocs/trip/trip_event.dart) | Dart | 51 | 0 | 20 | 71 |
|
||||
| [lib/blocs/trip/trip\_state.dart](/lib/blocs/trip/trip_state.dart) | Dart | 27 | 0 | 13 | 40 |
|
||||
| [lib/blocs/user/user\_bloc.dart](/lib/blocs/user/user_bloc.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/blocs/user/user\_event.dart](/lib/blocs/user/user_event.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/blocs/user/user\_state.dart](/lib/blocs/user/user_state.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/components/count/count\_content.dart](/lib/components/count/count_content.dart) | Dart | 25 | 0 | 3 | 28 |
|
||||
| [lib/components/group/group\_content.dart](/lib/components/group/group_content.dart) | Dart | 115 | 2 | 12 | 129 |
|
||||
| [lib/components/home/create\_trip\_content.dart](/lib/components/home/create_trip_content.dart) | Dart | 481 | 21 | 63 | 565 |
|
||||
| [lib/components/home/home\_content.dart](/lib/components/home/home_content.dart) | Dart | 366 | 12 | 30 | 408 |
|
||||
| [lib/components/home/show\_trip\_details\_content.dart](/lib/components/home/show_trip_details_content.dart) | Dart | 106 | 2 | 4 | 112 |
|
||||
| [lib/components/map/map\_content.dart](/lib/components/map/map_content.dart) | Dart | 100 | 4 | 11 | 115 |
|
||||
| [lib/components/profile/profile\_content.dart](/lib/components/profile/profile_content.dart) | Dart | 328 | 6 | 29 | 363 |
|
||||
| [lib/components/settings/settings\_content.dart](/lib/components/settings/settings_content.dart) | Dart | 60 | 2 | 10 | 72 |
|
||||
| [lib/components/settings/settings\_theme\_content.dart](/lib/components/settings/settings_theme_content.dart) | Dart | 123 | 4 | 10 | 137 |
|
||||
| [lib/data/data\_sources/firestore\_data\_source.dart](/lib/data/data_sources/firestore_data_source.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/data/data\_sources/local\_data\_source.dart](/lib/data/data_sources/local_data_source.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/data/models/group.dart](/lib/data/models/group.dart) | Dart | 23 | 0 | 3 | 26 |
|
||||
| [lib/data/models/message.dart](/lib/data/models/message.dart) | Dart | 14 | 0 | 1 | 15 |
|
||||
| [lib/data/models/trip.dart](/lib/data/models/trip.dart) | Dart | 176 | 16 | 24 | 216 |
|
||||
| [lib/data/models/user.dart](/lib/data/models/user.dart) | Dart | 61 | 6 | 13 | 80 |
|
||||
| [lib/firebase\_options.dart](/lib/firebase_options.dart) | Dart | 60 | 12 | 5 | 77 |
|
||||
| [lib/main.dart](/lib/main.dart) | Dart | 89 | 0 | 5 | 94 |
|
||||
| [lib/pages/home.dart](/lib/pages/home.dart) | Dart | 147 | 6 | 13 | 166 |
|
||||
| [lib/pages/login.dart](/lib/pages/login.dart) | Dart | 285 | 9 | 28 | 322 |
|
||||
| [lib/pages/resetpswd.dart](/lib/pages/resetpswd.dart) | Dart | 92 | 2 | 13 | 107 |
|
||||
| [lib/pages/signup.dart](/lib/pages/signup.dart) | Dart | 256 | 7 | 20 | 283 |
|
||||
| [lib/providers/theme\_provider.dart](/lib/providers/theme_provider.dart) | Dart | 41 | 1 | 9 | 51 |
|
||||
| [lib/providers/user\_provider.dart](/lib/providers/user_provider.dart) | Dart | 94 | 9 | 18 | 121 |
|
||||
| [lib/repositories/auth\_repository.dart](/lib/repositories/auth_repository.dart) | Dart | 115 | 11 | 22 | 148 |
|
||||
| [lib/repositories/trip\_repository.dart](/lib/repositories/trip_repository.dart) | Dart | 92 | 9 | 12 | 113 |
|
||||
| [lib/repositories/user\_repository.dart](/lib/repositories/user_repository.dart) | Dart | 77 | 7 | 11 | 95 |
|
||||
| [lib/services/auth\_service.dart](/lib/services/auth_service.dart) | Dart | 84 | 6 | 18 | 108 |
|
||||
| [lib/services/group\_service.dart](/lib/services/group_service.dart) | Dart | 53 | 1 | 6 | 60 |
|
||||
| [lib/services/message\_service.dart](/lib/services/message_service.dart) | Dart | 0 | 0 | 1 | 1 |
|
||||
| [lib/services/trip\_service.dart](/lib/services/trip_service.dart) | Dart | 209 | 21 | 39 | 269 |
|
||||
| [pubspec.yaml](/pubspec.yaml) | YAML | 31 | 58 | 14 | 103 |
|
||||
| [test/widget\_test.dart](/test/widget_test.dart) | Dart | 14 | 10 | 7 | 31 |
|
||||
|
||||
[Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
|
||||
@@ -1,15 +0,0 @@
|
||||
# Diff Details
|
||||
|
||||
Date : 2025-10-14 11:10:48
|
||||
|
||||
Directory c:\\Users\\dayro\\Documents\\coding\\travel_mate
|
||||
|
||||
Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines
|
||||
|
||||
[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details
|
||||
|
||||
## Files
|
||||
| filename | language | code | comment | blank | total |
|
||||
| :--- | :--- | ---: | ---: | ---: | ---: |
|
||||
|
||||
[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details
|
||||
@@ -1,2 +0,0 @@
|
||||
"filename", "language", "", "comment", "blank", "total"
|
||||
"Total", "-", , 0, 0, 0
|
||||
|
@@ -1,19 +0,0 @@
|
||||
# Diff Summary
|
||||
|
||||
Date : 2025-10-14 11:10:48
|
||||
|
||||
Directory c:\\Users\\dayro\\Documents\\coding\\travel_mate
|
||||
|
||||
Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines
|
||||
|
||||
[Summary](results.md) / [Details](details.md) / Diff Summary / [Diff Details](diff-details.md)
|
||||
|
||||
## Languages
|
||||
| language | files | code | comment | blank | total |
|
||||
| :--- | ---: | ---: | ---: | ---: | ---: |
|
||||
|
||||
## Directories
|
||||
| path | files | code | comment | blank | total |
|
||||
| :--- | ---: | ---: | ---: | ---: | ---: |
|
||||
|
||||
[Summary](results.md) / [Details](details.md) / Diff Summary / [Diff Details](diff-details.md)
|
||||
@@ -1,22 +0,0 @@
|
||||
Date : 2025-10-14 11:10:48
|
||||
Directory : c:\Users\dayro\Documents\coding\travel_mate
|
||||
Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines
|
||||
|
||||
Languages
|
||||
+----------+------------+------------+------------+------------+------------+
|
||||
| language | files | code | comment | blank | total |
|
||||
+----------+------------+------------+------------+------------+------------+
|
||||
+----------+------------+------------+------------+------------+------------+
|
||||
|
||||
Directories
|
||||
+------+------------+------------+------------+------------+------------+
|
||||
| path | files | code | comment | blank | total |
|
||||
+------+------------+------------+------------+------------+------------+
|
||||
+------+------------+------------+------------+------------+------------+
|
||||
|
||||
Files
|
||||
+----------+----------+------------+------------+------------+------------+
|
||||
| filename | language | code | comment | blank | total |
|
||||
+----------+----------+------------+------------+------------+------------+
|
||||
| Total | | 0 | 0 | 0 | 0 |
|
||||
+----------+----------+------------+------------+------------+------------+
|
||||
@@ -1,69 +0,0 @@
|
||||
"filename", "language", "YAML", "Markdown", "Dart", "JSON", "Swift", "C++", "XML", "Ruby", "Properties", "HTML", "comment", "blank", "total"
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\README.md", "Markdown", 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 61
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\analysis_options.yaml", "YAML", 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 4, 29
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\google-services.json", "JSON", 0, 0, 0, 54, 0, 0, 0, 0, 0, 0, 0, 0, 54
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\debug\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4, 1, 8
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 11, 1, 52
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\drawable-v21\launch_background.xml", "XML", 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 7, 2, 13
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\drawable\launch_background.xml", "XML", 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 7, 2, 13
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\values-night\styles.xml", "XML", 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 9, 1, 19
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\values\styles.xml", "XML", 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 9, 1, 19
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\app\src\profile\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4, 1, 8
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\build\reports\problems\problems-report.html", "HTML", 0, 0, 0, 0, 0, 0, 0, 0, 0, 548, 2, 114, 664
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\gradle.properties", "Properties", 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 4
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\android\gradle\wrapper\gradle-wrapper.properties", "Properties", 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 1, 6
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\firebase.json", "JSON", 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Podfile", "Ruby", 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 2, 10, 44
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\RunnerTests\RunnerTests.swift", "Swift", 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 4, 13
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\AppDelegate.swift", "Swift", 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 2, 16
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json", "JSON", 0, 0, 0, 122, 0, 0, 0, 0, 0, 0, 0, 1, 123
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\LaunchImage.imageset\Contents.json", "JSON", 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 1, 24
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\LaunchImage.imageset\README.md", "Markdown", 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Base.lproj\LaunchScreen.storyboard", "XML", 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 1, 1, 38
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Base.lproj\Main.storyboard", "XML", 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 1, 1, 27
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Runner-Bridging-Header.h", "C++", 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 2
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_bloc.dart", "Dart", 0, 0, 129, 0, 0, 0, 0, 0, 0, 0, 1, 20, 150
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_event.dart", "Dart", 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 15, 55
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_state.dart", "Dart", 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 14, 42
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_bloc.dart", "Dart", 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 1, 5, 46
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_event.dart", "Dart", 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 6, 20
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_state.dart", "Dart", 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 5, 21
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_bloc.dart", "Dart", 0, 0, 103, 0, 0, 0, 0, 0, 0, 0, 1, 14, 118
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_event.dart", "Dart", 0, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 20, 71
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_state.dart", "Dart", 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 13, 40
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_bloc.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_event.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_state.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\count\count_content.dart", "Dart", 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 3, 28
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\group\group_content.dart", "Dart", 0, 0, 115, 0, 0, 0, 0, 0, 0, 0, 2, 12, 129
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\create_trip_content.dart", "Dart", 0, 0, 481, 0, 0, 0, 0, 0, 0, 0, 21, 63, 565
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\home_content.dart", "Dart", 0, 0, 366, 0, 0, 0, 0, 0, 0, 0, 12, 30, 408
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\show_trip_details_content.dart", "Dart", 0, 0, 106, 0, 0, 0, 0, 0, 0, 0, 2, 4, 112
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\map\map_content.dart", "Dart", 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 4, 11, 115
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\profile\profile_content.dart", "Dart", 0, 0, 328, 0, 0, 0, 0, 0, 0, 0, 6, 29, 363
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\settings\settings_content.dart", "Dart", 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 2, 10, 72
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\components\settings\settings_theme_content.dart", "Dart", 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 4, 10, 137
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\data_sources\firestore_data_source.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\data_sources\local_data_source.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\group.dart", "Dart", 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 3, 26
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\message.dart", "Dart", 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 1, 15
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\trip.dart", "Dart", 0, 0, 176, 0, 0, 0, 0, 0, 0, 0, 16, 24, 216
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\user.dart", "Dart", 0, 0, 61, 0, 0, 0, 0, 0, 0, 0, 6, 13, 80
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\firebase_options.dart", "Dart", 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 12, 5, 77
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\main.dart", "Dart", 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 0, 5, 94
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\pages\home.dart", "Dart", 0, 0, 147, 0, 0, 0, 0, 0, 0, 0, 6, 13, 166
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\pages\login.dart", "Dart", 0, 0, 285, 0, 0, 0, 0, 0, 0, 0, 9, 28, 322
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\pages\resetpswd.dart", "Dart", 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 2, 13, 107
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\pages\signup.dart", "Dart", 0, 0, 256, 0, 0, 0, 0, 0, 0, 0, 7, 20, 283
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\providers\theme_provider.dart", "Dart", 0, 0, 41, 0, 0, 0, 0, 0, 0, 0, 1, 9, 51
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\providers\user_provider.dart", "Dart", 0, 0, 94, 0, 0, 0, 0, 0, 0, 0, 9, 18, 121
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\auth_repository.dart", "Dart", 0, 0, 115, 0, 0, 0, 0, 0, 0, 0, 11, 22, 148
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\trip_repository.dart", "Dart", 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 9, 12, 113
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\user_repository.dart", "Dart", 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 7, 11, 95
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\services\auth_service.dart", "Dart", 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 6, 18, 108
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\services\group_service.dart", "Dart", 0, 0, 53, 0, 0, 0, 0, 0, 0, 0, 1, 6, 60
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\services\message_service.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\lib\services\trip_service.dart", "Dart", 0, 0, 209, 0, 0, 0, 0, 0, 0, 0, 21, 39, 269
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\pubspec.yaml", "YAML", 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 14, 103
|
||||
"c:\Users\dayro\Documents\coding\travel_mate\test\widget_test.dart", "Dart", 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 10, 7, 31
|
||||
"Total", "-", 34, 48, 4134, 200, 21, 1, 133, 32, 8, 548, 328, 739, 6226
|
||||
|
File diff suppressed because one or more lines are too long
@@ -1,81 +0,0 @@
|
||||
# Summary
|
||||
|
||||
Date : 2025-10-14 11:10:48
|
||||
|
||||
Directory c:\\Users\\dayro\\Documents\\coding\\travel_mate
|
||||
|
||||
Total : 67 files, 5159 codes, 328 comments, 739 blanks, all 6226 lines
|
||||
|
||||
Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
|
||||
|
||||
## Languages
|
||||
| language | files | code | comment | blank | total |
|
||||
| :--- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Dart | 43 | 4,134 | 189 | 557 | 4,880 |
|
||||
| HTML | 1 | 548 | 2 | 114 | 664 |
|
||||
| JSON | 4 | 200 | 0 | 2 | 202 |
|
||||
| XML | 9 | 133 | 53 | 11 | 197 |
|
||||
| Markdown | 2 | 48 | 0 | 18 | 66 |
|
||||
| YAML | 2 | 34 | 80 | 18 | 132 |
|
||||
| Ruby | 1 | 32 | 2 | 10 | 44 |
|
||||
| Swift | 2 | 21 | 2 | 6 | 29 |
|
||||
| Properties | 2 | 8 | 0 | 2 | 10 |
|
||||
| C++ | 1 | 1 | 0 | 1 | 2 |
|
||||
|
||||
## Directories
|
||||
| path | files | code | comment | blank | total |
|
||||
| :--- | ---: | ---: | ---: | ---: | ---: |
|
||||
| . | 67 | 5,159 | 328 | 739 | 6,226 |
|
||||
| . (Files) | 4 | 80 | 80 | 34 | 194 |
|
||||
| android | 11 | 682 | 53 | 125 | 860 |
|
||||
| android (Files) | 1 | 3 | 0 | 1 | 4 |
|
||||
| android\\app | 8 | 126 | 51 | 9 | 186 |
|
||||
| android\\app (Files) | 1 | 54 | 0 | 0 | 54 |
|
||||
| android\\app\\src | 7 | 72 | 51 | 9 | 132 |
|
||||
| android\\app\\src\\debug | 1 | 3 | 4 | 1 | 8 |
|
||||
| android\\app\\src\\main | 5 | 66 | 43 | 7 | 116 |
|
||||
| android\\app\\src\\main (Files) | 1 | 40 | 11 | 1 | 52 |
|
||||
| android\\app\\src\\main\\res | 4 | 26 | 32 | 6 | 64 |
|
||||
| android\\app\\src\\main\\res\\drawable | 1 | 4 | 7 | 2 | 13 |
|
||||
| android\\app\\src\\main\\res\\drawable-v21 | 1 | 4 | 7 | 2 | 13 |
|
||||
| android\\app\\src\\main\\res\\values | 1 | 9 | 9 | 1 | 19 |
|
||||
| android\\app\\src\\main\\res\\values-night | 1 | 9 | 9 | 1 | 19 |
|
||||
| android\\app\\src\\profile | 1 | 3 | 4 | 1 | 8 |
|
||||
| android\\build | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\\build\\reports | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\\build\\reports\\problems | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\\gradle | 1 | 5 | 0 | 1 | 6 |
|
||||
| android\\gradle\\wrapper | 1 | 5 | 0 | 1 | 6 |
|
||||
| ios | 9 | 263 | 6 | 23 | 292 |
|
||||
| ios (Files) | 1 | 32 | 2 | 10 | 44 |
|
||||
| ios\\Runner | 7 | 224 | 2 | 9 | 235 |
|
||||
| ios\\Runner (Files) | 2 | 15 | 0 | 3 | 18 |
|
||||
| ios\\RunnerTests | 1 | 7 | 2 | 4 | 13 |
|
||||
| ios\\Runner\\Assets.xcassets | 3 | 148 | 0 | 4 | 152 |
|
||||
| ios\\Runner\\Assets.xcassets\\AppIcon.appiconset | 1 | 122 | 0 | 1 | 123 |
|
||||
| ios\\Runner\\Assets.xcassets\\LaunchImage.imageset | 2 | 26 | 0 | 3 | 29 |
|
||||
| ios\\Runner\\Base.lproj | 2 | 61 | 2 | 2 | 65 |
|
||||
| lib | 42 | 4,120 | 179 | 550 | 4,849 |
|
||||
| lib (Files) | 2 | 149 | 12 | 10 | 171 |
|
||||
| lib\\blocs | 12 | 448 | 3 | 115 | 566 |
|
||||
| lib\\blocs\\auth | 3 | 197 | 1 | 49 | 247 |
|
||||
| lib\\blocs\\theme | 3 | 70 | 1 | 16 | 87 |
|
||||
| lib\\blocs\\trip | 3 | 181 | 1 | 47 | 229 |
|
||||
| lib\\blocs\\user | 3 | 0 | 0 | 3 | 3 |
|
||||
| lib\\components | 9 | 1,704 | 53 | 172 | 1,929 |
|
||||
| lib\\components\\count | 1 | 25 | 0 | 3 | 28 |
|
||||
| lib\\components\\group | 1 | 115 | 2 | 12 | 129 |
|
||||
| lib\\components\\home | 3 | 953 | 35 | 97 | 1,085 |
|
||||
| lib\\components\\map | 1 | 100 | 4 | 11 | 115 |
|
||||
| lib\\components\\profile | 1 | 328 | 6 | 29 | 363 |
|
||||
| lib\\components\\settings | 2 | 183 | 6 | 20 | 209 |
|
||||
| lib\\data | 6 | 274 | 22 | 43 | 339 |
|
||||
| lib\\data\\data_sources | 2 | 0 | 0 | 2 | 2 |
|
||||
| lib\\data\\models | 4 | 274 | 22 | 41 | 337 |
|
||||
| lib\\pages | 4 | 780 | 24 | 74 | 878 |
|
||||
| lib\\providers | 2 | 135 | 10 | 27 | 172 |
|
||||
| lib\\repositories | 3 | 284 | 27 | 45 | 356 |
|
||||
| lib\\services | 4 | 346 | 28 | 64 | 438 |
|
||||
| test | 1 | 14 | 10 | 7 | 31 |
|
||||
|
||||
Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
|
||||
@@ -1,151 +0,0 @@
|
||||
Date : 2025-10-14 11:10:48
|
||||
Directory : c:\Users\dayro\Documents\coding\travel_mate
|
||||
Total : 67 files, 5159 codes, 328 comments, 739 blanks, all 6226 lines
|
||||
|
||||
Languages
|
||||
+------------+------------+------------+------------+------------+------------+
|
||||
| language | files | code | comment | blank | total |
|
||||
+------------+------------+------------+------------+------------+------------+
|
||||
| Dart | 43 | 4,134 | 189 | 557 | 4,880 |
|
||||
| HTML | 1 | 548 | 2 | 114 | 664 |
|
||||
| JSON | 4 | 200 | 0 | 2 | 202 |
|
||||
| XML | 9 | 133 | 53 | 11 | 197 |
|
||||
| Markdown | 2 | 48 | 0 | 18 | 66 |
|
||||
| YAML | 2 | 34 | 80 | 18 | 132 |
|
||||
| Ruby | 1 | 32 | 2 | 10 | 44 |
|
||||
| Swift | 2 | 21 | 2 | 6 | 29 |
|
||||
| Properties | 2 | 8 | 0 | 2 | 10 |
|
||||
| C++ | 1 | 1 | 0 | 1 | 2 |
|
||||
+------------+------------+------------+------------+------------+------------+
|
||||
|
||||
Directories
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
| path | files | code | comment | blank | total |
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
| . | 67 | 5,159 | 328 | 739 | 6,226 |
|
||||
| . (Files) | 4 | 80 | 80 | 34 | 194 |
|
||||
| android | 11 | 682 | 53 | 125 | 860 |
|
||||
| android (Files) | 1 | 3 | 0 | 1 | 4 |
|
||||
| android\app | 8 | 126 | 51 | 9 | 186 |
|
||||
| android\app (Files) | 1 | 54 | 0 | 0 | 54 |
|
||||
| android\app\src | 7 | 72 | 51 | 9 | 132 |
|
||||
| android\app\src\debug | 1 | 3 | 4 | 1 | 8 |
|
||||
| android\app\src\main | 5 | 66 | 43 | 7 | 116 |
|
||||
| android\app\src\main (Files) | 1 | 40 | 11 | 1 | 52 |
|
||||
| android\app\src\main\res | 4 | 26 | 32 | 6 | 64 |
|
||||
| android\app\src\main\res\drawable | 1 | 4 | 7 | 2 | 13 |
|
||||
| android\app\src\main\res\drawable-v21 | 1 | 4 | 7 | 2 | 13 |
|
||||
| android\app\src\main\res\values | 1 | 9 | 9 | 1 | 19 |
|
||||
| android\app\src\main\res\values-night | 1 | 9 | 9 | 1 | 19 |
|
||||
| android\app\src\profile | 1 | 3 | 4 | 1 | 8 |
|
||||
| android\build | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\build\reports | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\build\reports\problems | 1 | 548 | 2 | 114 | 664 |
|
||||
| android\gradle | 1 | 5 | 0 | 1 | 6 |
|
||||
| android\gradle\wrapper | 1 | 5 | 0 | 1 | 6 |
|
||||
| ios | 9 | 263 | 6 | 23 | 292 |
|
||||
| ios (Files) | 1 | 32 | 2 | 10 | 44 |
|
||||
| ios\Runner | 7 | 224 | 2 | 9 | 235 |
|
||||
| ios\Runner (Files) | 2 | 15 | 0 | 3 | 18 |
|
||||
| ios\RunnerTests | 1 | 7 | 2 | 4 | 13 |
|
||||
| ios\Runner\Assets.xcassets | 3 | 148 | 0 | 4 | 152 |
|
||||
| ios\Runner\Assets.xcassets\AppIcon.appiconset | 1 | 122 | 0 | 1 | 123 |
|
||||
| ios\Runner\Assets.xcassets\LaunchImage.imageset | 2 | 26 | 0 | 3 | 29 |
|
||||
| ios\Runner\Base.lproj | 2 | 61 | 2 | 2 | 65 |
|
||||
| lib | 42 | 4,120 | 179 | 550 | 4,849 |
|
||||
| lib (Files) | 2 | 149 | 12 | 10 | 171 |
|
||||
| lib\blocs | 12 | 448 | 3 | 115 | 566 |
|
||||
| lib\blocs\auth | 3 | 197 | 1 | 49 | 247 |
|
||||
| lib\blocs\theme | 3 | 70 | 1 | 16 | 87 |
|
||||
| lib\blocs\trip | 3 | 181 | 1 | 47 | 229 |
|
||||
| lib\blocs\user | 3 | 0 | 0 | 3 | 3 |
|
||||
| lib\components | 9 | 1,704 | 53 | 172 | 1,929 |
|
||||
| lib\components\count | 1 | 25 | 0 | 3 | 28 |
|
||||
| lib\components\group | 1 | 115 | 2 | 12 | 129 |
|
||||
| lib\components\home | 3 | 953 | 35 | 97 | 1,085 |
|
||||
| lib\components\map | 1 | 100 | 4 | 11 | 115 |
|
||||
| lib\components\profile | 1 | 328 | 6 | 29 | 363 |
|
||||
| lib\components\settings | 2 | 183 | 6 | 20 | 209 |
|
||||
| lib\data | 6 | 274 | 22 | 43 | 339 |
|
||||
| lib\data\data_sources | 2 | 0 | 0 | 2 | 2 |
|
||||
| lib\data\models | 4 | 274 | 22 | 41 | 337 |
|
||||
| lib\pages | 4 | 780 | 24 | 74 | 878 |
|
||||
| lib\providers | 2 | 135 | 10 | 27 | 172 |
|
||||
| lib\repositories | 3 | 284 | 27 | 45 | 356 |
|
||||
| lib\services | 4 | 346 | 28 | 64 | 438 |
|
||||
| test | 1 | 14 | 10 | 7 | 31 |
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
|
||||
Files
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
| filename | language | code | comment | blank | total |
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\README.md | Markdown | 45 | 0 | 16 | 61 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\analysis_options.yaml | YAML | 3 | 22 | 4 | 29 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\google-services.json | JSON | 54 | 0 | 0 | 54 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\debug\AndroidManifest.xml | XML | 3 | 4 | 1 | 8 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\AndroidManifest.xml | XML | 40 | 11 | 1 | 52 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\drawable-v21\launch_background.xml | XML | 4 | 7 | 2 | 13 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\drawable\launch_background.xml | XML | 4 | 7 | 2 | 13 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\values-night\styles.xml | XML | 9 | 9 | 1 | 19 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\main\res\values\styles.xml | XML | 9 | 9 | 1 | 19 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\app\src\profile\AndroidManifest.xml | XML | 3 | 4 | 1 | 8 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\build\reports\problems\problems-report.html | HTML | 548 | 2 | 114 | 664 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\gradle.properties | Properties | 3 | 0 | 1 | 4 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\android\gradle\wrapper\gradle-wrapper.properties | Properties | 5 | 0 | 1 | 6 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\firebase.json | JSON | 1 | 0 | 0 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Podfile | Ruby | 32 | 2 | 10 | 44 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\RunnerTests\RunnerTests.swift | Swift | 7 | 2 | 4 | 13 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\AppDelegate.swift | Swift | 14 | 0 | 2 | 16 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json | JSON | 122 | 0 | 1 | 123 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\LaunchImage.imageset\Contents.json | JSON | 23 | 0 | 1 | 24 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Assets.xcassets\LaunchImage.imageset\README.md | Markdown | 3 | 0 | 2 | 5 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Base.lproj\LaunchScreen.storyboard | XML | 36 | 1 | 1 | 38 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Base.lproj\Main.storyboard | XML | 25 | 1 | 1 | 27 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\ios\Runner\Runner-Bridging-Header.h | C++ | 1 | 0 | 1 | 2 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_bloc.dart | Dart | 129 | 1 | 20 | 150 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_event.dart | Dart | 40 | 0 | 15 | 55 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\auth\auth_state.dart | Dart | 28 | 0 | 14 | 42 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_bloc.dart | Dart | 40 | 1 | 5 | 46 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_event.dart | Dart | 14 | 0 | 6 | 20 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\theme\theme_state.dart | Dart | 16 | 0 | 5 | 21 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_bloc.dart | Dart | 103 | 1 | 14 | 118 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_event.dart | Dart | 51 | 0 | 20 | 71 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\trip\trip_state.dart | Dart | 27 | 0 | 13 | 40 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_bloc.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_event.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\blocs\user\user_state.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\count\count_content.dart | Dart | 25 | 0 | 3 | 28 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\group\group_content.dart | Dart | 115 | 2 | 12 | 129 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\create_trip_content.dart | Dart | 481 | 21 | 63 | 565 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\home_content.dart | Dart | 366 | 12 | 30 | 408 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\home\show_trip_details_content.dart | Dart | 106 | 2 | 4 | 112 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\map\map_content.dart | Dart | 100 | 4 | 11 | 115 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\profile\profile_content.dart | Dart | 328 | 6 | 29 | 363 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\settings\settings_content.dart | Dart | 60 | 2 | 10 | 72 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\components\settings\settings_theme_content.dart | Dart | 123 | 4 | 10 | 137 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\data_sources\firestore_data_source.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\data_sources\local_data_source.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\group.dart | Dart | 23 | 0 | 3 | 26 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\message.dart | Dart | 14 | 0 | 1 | 15 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\trip.dart | Dart | 176 | 16 | 24 | 216 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\data\models\user.dart | Dart | 61 | 6 | 13 | 80 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\firebase_options.dart | Dart | 60 | 12 | 5 | 77 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\main.dart | Dart | 89 | 0 | 5 | 94 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\pages\home.dart | Dart | 147 | 6 | 13 | 166 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\pages\login.dart | Dart | 285 | 9 | 28 | 322 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\pages\resetpswd.dart | Dart | 92 | 2 | 13 | 107 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\pages\signup.dart | Dart | 256 | 7 | 20 | 283 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\providers\theme_provider.dart | Dart | 41 | 1 | 9 | 51 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\providers\user_provider.dart | Dart | 94 | 9 | 18 | 121 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\auth_repository.dart | Dart | 115 | 11 | 22 | 148 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\trip_repository.dart | Dart | 92 | 9 | 12 | 113 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\repositories\user_repository.dart | Dart | 77 | 7 | 11 | 95 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\services\auth_service.dart | Dart | 84 | 6 | 18 | 108 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\services\group_service.dart | Dart | 53 | 1 | 6 | 60 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\services\message_service.dart | Dart | 0 | 0 | 1 | 1 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\lib\services\trip_service.dart | Dart | 209 | 21 | 39 | 269 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\pubspec.yaml | YAML | 31 | 58 | 14 | 103 |
|
||||
| c:\Users\dayro\Documents\coding\travel_mate\test\widget_test.dart | Dart | 14 | 10 | 7 | 31 |
|
||||
| Total | | 5,159 | 328 | 739 | 6,226 |
|
||||
+-----------------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+
|
||||
5
.firebaserc
Normal file
5
.firebaserc
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"projects": {
|
||||
"default": "travelmate-a47f5"
|
||||
}
|
||||
}
|
||||
226
.gitea/workflows/deploy.yaml
Normal file
226
.gitea/workflows/deploy.yaml
Normal file
@@ -0,0 +1,226 @@
|
||||
name: Deploy TravelMate (Full Mobile)
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- release
|
||||
|
||||
jobs:
|
||||
# --- JOB 1 : ANDROID (Génération APK) ---
|
||||
deploy-android:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Configuration Flutter & Secrets
|
||||
run: |
|
||||
flutter pub get
|
||||
echo "${{ secrets.ENV_FILE }}" > .env
|
||||
printf '%s' '${{ secrets.FIREBASE_CREDENTIALS }}' > ./android/firebase_credentials.json
|
||||
|
||||
- name: Build & Deploy Android
|
||||
working-directory: ./android
|
||||
env:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
RAW_PROPERTIES: ${{ secrets.ANDROID_KEY_PROPERTIES }}
|
||||
FIREBASE_ANDROID_APP_ID: ${{ secrets.FIREBASE_ANDROID_APP_ID }}
|
||||
run: |
|
||||
# 1. Keystore
|
||||
echo "$ANDROID_KEYSTORE_BASE64" | base64 -D > keystore.jks
|
||||
echo "$RAW_PROPERTIES" > temp_props.txt
|
||||
echo "storePassword=$(grep 'storePassword' temp_props.txt | cut -d'=' -f2 | tr -d '\r')" > key.properties
|
||||
echo "keyPassword=$(grep 'keyPassword' temp_props.txt | cut -d'=' -f2 | tr -d '\r')" >> key.properties
|
||||
echo "keyAlias=$(grep 'keyAlias' temp_props.txt | cut -d'=' -f2 | tr -d '\r')" >> key.properties
|
||||
echo "storeFile=$(pwd)/keystore.jks" >> key.properties
|
||||
|
||||
# 2. Gemfile (Correctifs Ruby 3.4 inclus)
|
||||
echo "source 'https://rubygems.org'" > Gemfile
|
||||
echo "gem 'fastlane', '>= 2.230.0'" >> Gemfile
|
||||
echo "gem 'fastlane-plugin-firebase_app_distribution'" >> Gemfile
|
||||
for g in abbrev ostruct mutex_m base64 csv bigdecimal drb nkf reline logger; do echo "gem '$g'" >> Gemfile; done
|
||||
|
||||
gem install bundler -v 2.7.2 --no-document
|
||||
bundle _2.7.2_ update
|
||||
|
||||
# 3. Build & Envoi
|
||||
cd .. && flutter build apk --release && cd android
|
||||
bundle _2.7.2_ exec fastlane run firebase_app_distribution \
|
||||
app:"$FIREBASE_ANDROID_APP_ID" \
|
||||
android_artifact_path:"../build/app/outputs/flutter-apk/app-release.apk" \
|
||||
service_credentials_file:"firebase_credentials.json"
|
||||
|
||||
# --- JOB 2 : IOS (Génération IPA) ---
|
||||
deploy-ios:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Dépendances iOS & Secrets
|
||||
run: |
|
||||
flutter pub get
|
||||
echo "${{ secrets.ENV_FILE }}" > .env
|
||||
printf '%s' '${{ secrets.FIREBASE_CREDENTIALS }}' > ./ios/firebase_credentials.json
|
||||
cd ios && (pod install --repo-update || pod update)
|
||||
|
||||
- name: Préparer le Code Signing
|
||||
env:
|
||||
P12_BASE: ${{ secrets.IOS_P12_BASE64 }}
|
||||
P12_PASS: ${{ secrets.IOS_P12_PASSWORD }}
|
||||
PROV_BASE: ${{ secrets.IOS_PROVISION_BASE64 }}
|
||||
TEAM_ID: ${{ secrets.IOS_TEAM_ID }}
|
||||
run: |
|
||||
# Créer et configurer le keychain
|
||||
security delete-keychain build.keychain || true
|
||||
security create-keychain -p "" build.keychain
|
||||
security unlock-keychain -p "" build.keychain
|
||||
security list-keychains -d user -s build.keychain $(security list-keychains -d user | xargs)
|
||||
security set-keychain-settings -lut 21600 build.keychain
|
||||
|
||||
# Importer le certificat
|
||||
echo "$P12_BASE" | base64 -D -o cert.p12
|
||||
security import cert.p12 -k build.keychain -P "$P12_PASS" -T /usr/bin/codesign
|
||||
security set-key-partition-list -S apple-tool:,apple: -s -k "" build.keychain
|
||||
|
||||
# Installer le profil de provisioning
|
||||
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
|
||||
PROFILE_PATH=~/Library/MobileDevice/Provisioning\ Profiles/distribution.mobileprovision
|
||||
echo "$PROV_BASE" | base64 -D -o "$PROFILE_PATH"
|
||||
|
||||
# Extraire l'UUID du profil
|
||||
PROFILE_UUID=$(/usr/libexec/PlistBuddy -c "Print UUID" /dev/stdin <<< $(/usr/bin/security cms -D -i "$PROFILE_PATH"))
|
||||
echo "Profile UUID: $PROFILE_UUID"
|
||||
|
||||
# Copier avec l'UUID correct
|
||||
cp "$PROFILE_PATH" ~/Library/MobileDevice/Provisioning\ Profiles/$PROFILE_UUID.mobileprovision
|
||||
|
||||
- name: Configurer le projet Xcode
|
||||
env:
|
||||
TEAM_ID: ${{ secrets.IOS_TEAM_ID }}
|
||||
BUNDLE_ID: ${{ secrets.IOS_BUNDLE_ID }}
|
||||
run: |
|
||||
cd ios
|
||||
|
||||
# Extraire le nom du profil de provisioning
|
||||
PROV_NAME=$(/usr/libexec/PlistBuddy -c "Print Name" /dev/stdin <<< $(/usr/bin/security cms -D -i ~/Library/MobileDevice/Provisioning\ Profiles/distribution.mobileprovision))
|
||||
echo "📝 Provisioning Profile Name: $PROV_NAME"
|
||||
|
||||
# Obtenir l'UUID du profil
|
||||
PROFILE_UUID=$(/usr/libexec/PlistBuddy -c "Print UUID" /dev/stdin <<< $(/usr/bin/security cms -D -i ~/Library/MobileDevice/Provisioning\ Profiles/distribution.mobileprovision))
|
||||
echo "🔑 Profile UUID: $PROFILE_UUID"
|
||||
|
||||
# Sauvegarder les variables pour la prochaine étape
|
||||
echo "$PROV_NAME" > /tmp/prov_name.txt
|
||||
echo "$TEAM_ID" > /tmp/team_id.txt
|
||||
echo "$BUNDLE_ID" > /tmp/bundle_id.txt
|
||||
|
||||
echo "✅ Configuration des paramètres de signing prête"
|
||||
|
||||
- name: Créer exportOptions.plist
|
||||
env:
|
||||
TEAM_ID: ${{ secrets.IOS_TEAM_ID }}
|
||||
BUNDLE_ID: ${{ secrets.IOS_BUNDLE_ID }}
|
||||
run: |
|
||||
# Extraire le nom du profil
|
||||
PROV_NAME=$(/usr/libexec/PlistBuddy -c "Print Name" /dev/stdin <<< $(/usr/bin/security cms -D -i ~/Library/MobileDevice/Provisioning\ Profiles/distribution.mobileprovision))
|
||||
|
||||
cat > ios/exportOptions.plist <<EOF
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>method</key>
|
||||
<string>ad-hoc</string>
|
||||
<key>teamID</key>
|
||||
<string>$TEAM_ID</string>
|
||||
<key>signingStyle</key>
|
||||
<string>manual</string>
|
||||
<key>provisioningProfiles</key>
|
||||
<dict>
|
||||
<key>$BUNDLE_ID</key>
|
||||
<string>$PROV_NAME</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
EOF
|
||||
|
||||
- name: Build IPA avec Flutter
|
||||
run: |
|
||||
# Récupérer les variables sauvegardées
|
||||
PROV_NAME=$(cat /tmp/prov_name.txt)
|
||||
TEAM_ID=$(cat /tmp/team_id.txt)
|
||||
BUNDLE_ID=$(cat /tmp/bundle_id.txt)
|
||||
|
||||
echo "📝 Provisioning Profile: $PROV_NAME"
|
||||
echo "🔑 Team ID: $TEAM_ID"
|
||||
echo "📦 Bundle ID: $BUNDLE_ID"
|
||||
|
||||
# Clean
|
||||
flutter clean
|
||||
flutter pub get
|
||||
|
||||
echo "🔨 Build de l'IPA avec Flutter..."
|
||||
|
||||
# Flutter build ipa gère automatiquement le signing des Pods
|
||||
# On utilise SEULEMENT --export-options-plist (pas --export-method)
|
||||
flutter build ipa \
|
||||
--release \
|
||||
--export-options-plist=ios/exportOptions.plist
|
||||
|
||||
echo "✅ Build terminé"
|
||||
echo "📂 Recherche de l'IPA..."
|
||||
|
||||
# L'IPA devrait être dans build/ios/ipa/
|
||||
find build/ios -name "*.ipa" -type f
|
||||
|
||||
IPA_FILE=$(find build/ios/ipa -name "*.ipa" | head -n 1)
|
||||
|
||||
if [ -z "$IPA_FILE" ]; then
|
||||
echo "❌ ERREUR: Aucun fichier IPA trouvé !"
|
||||
echo "📂 Contenu de build/ios/ :"
|
||||
ls -R build/ios/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ IPA trouvée : $IPA_FILE"
|
||||
echo "📊 Taille : $(du -h "$IPA_FILE" | cut -f1)"
|
||||
|
||||
- name: Vérification et Upload Firebase
|
||||
env:
|
||||
FIREBASE_IOS_APP_ID: ${{ secrets.FIREBASE_IOS_APP_ID }}
|
||||
run: |
|
||||
cd ios
|
||||
|
||||
# Configuration Fastlane
|
||||
echo "source 'https://rubygems.org'" > Gemfile
|
||||
echo "gem 'fastlane', '>= 2.230.0'" >> Gemfile
|
||||
echo "gem 'fastlane-plugin-firebase_app_distribution'" >> Gemfile
|
||||
for g in abbrev ostruct mutex_m base64 csv bigdecimal drb nkf reline logger; do echo "gem '$g'" >> Gemfile; done
|
||||
|
||||
gem install bundler -v 2.7.2 --no-document
|
||||
bundle _2.7.2_ update
|
||||
|
||||
# Recherche de l'IPA
|
||||
IPA_FILE=$(find ../build/ios/ipa -name "*.ipa" | head -n 1)
|
||||
|
||||
if [ -z "$IPA_FILE" ]; then
|
||||
echo "❌ ERREUR : Aucun fichier IPA trouvé !"
|
||||
echo "📂 Structure complète du dossier build :"
|
||||
ls -R ../build/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ IPA trouvée : $IPA_FILE"
|
||||
echo "📊 Taille : $(du -h "$IPA_FILE" | cut -f1)"
|
||||
|
||||
# Upload vers Firebase
|
||||
bundle _2.7.2_ exec fastlane run firebase_app_distribution \
|
||||
app:"$FIREBASE_IOS_APP_ID" \
|
||||
ipa_path:"$IPA_FILE" \
|
||||
service_credentials_file:"firebase_credentials.json"
|
||||
|
||||
- name: Nettoyage Final
|
||||
if: always()
|
||||
run: |
|
||||
security list-keychains -d user -s login.keychain
|
||||
security delete-keychain build.keychain || true
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -44,7 +44,15 @@ app.*.map.json
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
.vscode
|
||||
.VSCodeCounter
|
||||
.VSCodeCounter/*
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.env.*.local
|
||||
firestore.rules
|
||||
storage.rules
|
||||
/functions/node_modules
|
||||
|
||||
.idea
|
||||
.vscode
|
||||
.VSCodeCounter
|
||||
|
||||
|
||||
@@ -56,3 +56,7 @@ Travel Mate est une application mobile conçue pour simplifier l'organisation de
|
||||
- **Google Places API** - Recherche de lieux et points d'intérêt
|
||||
- **Google Maps API** - Cartes et navigation
|
||||
- **Google Directions API** - Calcul d'itinéraires
|
||||
|
||||
## 🚀 CI/CD & Déploiement
|
||||
|
||||
Les versions de test interne Android et IOS sont automatiquement distribuées via **Firebase App Distribution**.
|
||||
|
||||
6
android/Gemfile
Normal file
6
android/Gemfile
Normal file
@@ -0,0 +1,6 @@
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem "fastlane"
|
||||
|
||||
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||
@@ -1,21 +1,28 @@
|
||||
import java.util.Properties
|
||||
import java.io.FileInputStream
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services")
|
||||
// END: FlutterFire Configuration
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
val keystoreProperties = Properties()
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.travel_mate"
|
||||
namespace = "be.devdayronvl.travel_mate"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
isCoreLibraryDesugaringEnabled = true
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
@@ -23,25 +30,39 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.example.travel_mate"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
applicationId = "be.devdayronvl.travel_mate"
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties["keyAlias"] as String?
|
||||
keyPassword = keystoreProperties["keyPassword"] as String?
|
||||
storeFile = if (keystoreProperties["storeFile"] != null) {
|
||||
rootProject.file(keystoreProperties["storeFile"] as String)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
storePassword = keystoreProperties["storePassword"] as String?
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
// Applique la configuration de signature définie au-dessus
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,42 @@
|
||||
"storage_bucket": "travelmate-a47f5.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:521527250907:android:56c632e98c7826347da1fe",
|
||||
"android_client_info": {
|
||||
"package_name": "be.devdayronvl.travel_mate"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "521527250907-j0kt1hc8hc7qc2kedp4akehau754cn5d.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyAON_ol0Jr34tKbETvdDK9JCQdKNawxBeQ"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "521527250907-j0kt1hc8hc7qc2kedp4akehau754cn5d.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
},
|
||||
{
|
||||
"client_id": "521527250907-196i04qgm4talrosgi0ne0q8en90hkkh.apps.googleusercontent.com",
|
||||
"client_type": 2,
|
||||
"ios_info": {
|
||||
"bundle_id": "be.devdayronvl.TravelMate"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:521527250907:android:be3db7fc84f053ec7da1fe",
|
||||
@@ -13,6 +49,22 @@
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "521527250907-19lrclc10eb0p8li1qutepctfqdohn0b.apps.googleusercontent.com",
|
||||
"client_type": 1,
|
||||
"android_info": {
|
||||
"package_name": "com.example.travel_mate",
|
||||
"certificate_hash": "2374761dc92a30812608c072638510002041eca8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_id": "521527250907-5v8l011nod30a6c52nkmk69d00h0ma0q.apps.googleusercontent.com",
|
||||
"client_type": 1,
|
||||
"android_info": {
|
||||
"package_name": "com.example.travel_mate",
|
||||
"certificate_hash": "c98141ab89d42b16c273e611054e7c87aa773d83"
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_id": "521527250907-lqgj1lmfcsjusm2be9r6kpuanq3jvjcd.apps.googleusercontent.com",
|
||||
"client_type": 1,
|
||||
@@ -39,10 +91,10 @@
|
||||
"client_type": 3
|
||||
},
|
||||
{
|
||||
"client_id": "521527250907-3i1qe2656eojs8k9hjdi573j09i9p41m.apps.googleusercontent.com",
|
||||
"client_id": "521527250907-196i04qgm4talrosgi0ne0q8en90hkkh.apps.googleusercontent.com",
|
||||
"client_type": 2,
|
||||
"ios_info": {
|
||||
"bundle_id": "com.example.travelMate"
|
||||
"bundle_id": "be.devdayronvl.TravelMate"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -13,13 +13,15 @@
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
|
||||
<!-- Permissions pour écrire dans le stockage -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<application
|
||||
android:label="travel_mate"
|
||||
android:label="Travel Mate"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:screenOrientation="portrait"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
@@ -40,6 +42,20 @@
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Apple Sign In Callback Activity -->
|
||||
<activity
|
||||
android:name="com.aboutyou.dart_packages.sign_in_with_apple.SignInWithAppleCallback"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="signinwithapple" />
|
||||
<data android:path="/" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
@@ -47,7 +63,10 @@
|
||||
android:value="2" />
|
||||
<meta-data
|
||||
android:name="com.google.android.geo.API_KEY"
|
||||
android:value="AIzaSyCAtz1_d5K0ANwxAA_T84iq7Ac_gsUs_oM"/>
|
||||
android:value="AIzaSyAON_ol0Jr34tKbETvdDK9JCQdKNawxBeQ"/>
|
||||
<meta-data
|
||||
android:name="com.google.firebase.messaging.default_notification_channel_id"
|
||||
android:value="high_importance_channel" />
|
||||
</application>
|
||||
<!-- Required to query activities that can process text, see:
|
||||
https://developer.android.com/training/package-visibility and
|
||||
@@ -59,5 +78,23 @@
|
||||
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent>
|
||||
<!-- Waze -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="waze" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="https" android:host="www.waze.com" />
|
||||
</intent>
|
||||
<!-- Google Maps -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="google.navigation" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="https" android:host="www.google.com" />
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.example.travel_mate
|
||||
package be.devdayronvl.travel_mate
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
|
||||
File diff suppressed because one or more lines are too long
2
android/fastlane/Appfile
Normal file
2
android/fastlane/Appfile
Normal file
@@ -0,0 +1,2 @@
|
||||
json_key_file("'/Users/dayronvanleemput/Documents/Coding/clé/travelmate-a47f5-1e4759031f2d.json'") # Path to the json secret file - Follow https://docs.fastlane.tools/actions/supply/#setup to get one
|
||||
package_name("be.devdayronvl.travel_mate") # e.g. com.krausefx.app
|
||||
28
android/fastlane/Fastfile
Normal file
28
android/fastlane/Fastfile
Normal file
@@ -0,0 +1,28 @@
|
||||
default_platform(:android)
|
||||
|
||||
platform :android do
|
||||
desc "Deploy to Firebase from Mac"
|
||||
lane :deploy_firebase do
|
||||
|
||||
# 1. Création du Keystore depuis le secret Gitea
|
||||
if ENV['ANDROID_KEYSTORE_BASE64']
|
||||
File.open("upload-keystore.jks", "wb") do |f|
|
||||
f.write(Base64.decode64(ENV['ANDROID_KEYSTORE_BASE64']))
|
||||
end
|
||||
else
|
||||
UI.error("Secret Keystore manquant !")
|
||||
end
|
||||
|
||||
# 2. Build de l'App Bundle (AAB)
|
||||
sh("flutter build appbundle --release")
|
||||
|
||||
# 3. Envoi vers Firebase App Distribution
|
||||
firebase_app_distribution(
|
||||
app: ENV["FIREBASE_ANDROID_APP_ID"],
|
||||
service_credentials_file: "firebase_credentials.json",
|
||||
groups: "testers",
|
||||
android_artifact_path: "../build/app/outputs/bundle/release/app-release.aab",
|
||||
release_notes: "Build depuis Mac M1/M2. Commit: #{ENV['GITHUB_SHA']}"
|
||||
)
|
||||
end
|
||||
end
|
||||
5
android/fastlane/Pluginfile
Normal file
5
android/fastlane/Pluginfile
Normal file
@@ -0,0 +1,5 @@
|
||||
# Autogenerated by fastlane
|
||||
#
|
||||
# Ensure this file is checked in to source control!
|
||||
|
||||
gem 'fastlane-plugin-firebase_app_distribution'
|
||||
BIN
assets/icons/Icône de l'application.png
Normal file
BIN
assets/icons/Icône de l'application.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 137 KiB |
BIN
assets/icons/presentation_image.jpg
Normal file
BIN
assets/icons/presentation_image.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 182 KiB |
@@ -1 +1,37 @@
|
||||
{"flutter":{"platforms":{"android":{"default":{"projectId":"travelmate-a47f5","appId":"1:521527250907:android:be3db7fc84f053ec7da1fe","fileOutput":"android/app/google-services.json"}},"dart":{"lib/firebase_options.dart":{"projectId":"travelmate-a47f5","configurations":{"android":"1:521527250907:android:be3db7fc84f053ec7da1fe","ios":"1:521527250907:ios:64b41be39c54db1c7da1fe","windows":"1:521527250907:web:53ff98bcdb8c218f7da1fe"}}}}}}
|
||||
{
|
||||
"flutter": {
|
||||
"platforms": {
|
||||
"android": {
|
||||
"default": {
|
||||
"projectId": "travelmate-a47f5",
|
||||
"appId": "1:521527250907:android:be3db7fc84f053ec7da1fe",
|
||||
"fileOutput": "android/app/google-services.json"
|
||||
}
|
||||
},
|
||||
"dart": {
|
||||
"lib/firebase_options.dart": {
|
||||
"projectId": "travelmate-a47f5",
|
||||
"configurations": {
|
||||
"android": "1:521527250907:android:be3db7fc84f053ec7da1fe",
|
||||
"ios": "1:521527250907:ios:64b41be39c54db1c7da1fe",
|
||||
"windows": "1:521527250907:web:53ff98bcdb8c218f7da1fe"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"functions": [
|
||||
{
|
||||
"source": "functions",
|
||||
"codebase": "default",
|
||||
"disallowLegacyRuntimeConfig": true,
|
||||
"ignore": [
|
||||
"node_modules",
|
||||
".git",
|
||||
"firebase-debug.log",
|
||||
"firebase-debug.*.log",
|
||||
"*.local"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
2
functions/.gitignore
vendored
Normal file
2
functions/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
*.local
|
||||
196
functions/index.js
Normal file
196
functions/index.js
Normal file
@@ -0,0 +1,196 @@
|
||||
const functions = require("firebase-functions/v1");
|
||||
const admin = require("firebase-admin");
|
||||
|
||||
admin.initializeApp();
|
||||
|
||||
// Helper function to send notifications to a list of users
|
||||
async function sendNotificationToUsers(userIds, title, body, excludeUserId, data = {}) {
|
||||
console.log(`Starting sendNotificationToUsers. Total users: ${userIds.length}, Exclude: ${excludeUserId}`);
|
||||
try {
|
||||
const tokens = [];
|
||||
|
||||
for (const userId of userIds) {
|
||||
if (userId === excludeUserId) {
|
||||
console.log(`Skipping user ${userId} (sender)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const userDoc = await admin.firestore().collection("users").doc(userId).get();
|
||||
if (userDoc.exists) {
|
||||
const userData = userDoc.data();
|
||||
if (userData.fcmToken) {
|
||||
console.log(`Found token for user ${userId}`);
|
||||
tokens.push(userData.fcmToken);
|
||||
} else {
|
||||
console.log(`No FCM token found for user ${userId}`);
|
||||
}
|
||||
} else {
|
||||
console.log(`User document not found for ${userId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// De-duplicate tokens
|
||||
const uniqueTokens = [...new Set(tokens)];
|
||||
console.log(`Total unique tokens to send: ${uniqueTokens.length} (from ${tokens.length} found)`);
|
||||
|
||||
if (uniqueTokens.length > 0) {
|
||||
const message = {
|
||||
notification: {
|
||||
title: title,
|
||||
body: body,
|
||||
},
|
||||
tokens: uniqueTokens,
|
||||
data: {
|
||||
click_action: "FLUTTER_NOTIFICATION_CLICK",
|
||||
...data
|
||||
},
|
||||
android: {
|
||||
priority: "high",
|
||||
notification: {
|
||||
channelId: "high_importance_channel",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const response = await admin.messaging().sendEachForMulticast(message);
|
||||
console.log(`${response.successCount} messages were sent successfully`);
|
||||
if (response.failureCount > 0) {
|
||||
console.log('Failed notifications:', response.responses.filter(r => !r.success));
|
||||
}
|
||||
} else {
|
||||
console.log("No tokens found, skipping notification send.");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error sending notification:", error);
|
||||
}
|
||||
}
|
||||
|
||||
exports.onActivityCreated = functions.firestore
|
||||
.document("activities/{activityId}")
|
||||
.onCreate(async (snapshot, context) => {
|
||||
console.log(`onActivityCreated triggered for ${context.params.activityId}`);
|
||||
const activity = snapshot.data();
|
||||
const tripId = activity.tripId;
|
||||
const createdBy = activity.createdBy || "Unknown";
|
||||
|
||||
if (!tripId) {
|
||||
console.log("No tripId found in activity");
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch trip to get participants
|
||||
const tripDoc = await admin.firestore().collection("trips").doc(tripId).get();
|
||||
if (!tripDoc.exists) {
|
||||
console.log(`Trip ${tripId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
const trip = tripDoc.data();
|
||||
const participants = trip.participants || [];
|
||||
if (trip.createdBy && !participants.includes(trip.createdBy)) {
|
||||
participants.push(trip.createdBy);
|
||||
}
|
||||
|
||||
console.log(`Found trip participants: ${JSON.stringify(participants)}`);
|
||||
|
||||
// Fetch creator name
|
||||
let creatorName = "Quelqu'un";
|
||||
if (createdBy !== "Unknown") {
|
||||
const userDoc = await admin.firestore().collection("users").doc(createdBy).get();
|
||||
if (userDoc.exists) {
|
||||
creatorName = userDoc.data().prenom || "Quelqu'un";
|
||||
}
|
||||
}
|
||||
|
||||
await sendNotificationToUsers(
|
||||
participants,
|
||||
"Nouvelle activité !",
|
||||
`${creatorName} a ajouté une nouvelle activité : ${activity.name || activity.title}`,
|
||||
createdBy,
|
||||
{ tripId: tripId }
|
||||
);
|
||||
});
|
||||
|
||||
exports.onMessageCreated = functions.firestore
|
||||
.document("groups/{groupId}/messages/{messageId}")
|
||||
.onCreate(async (snapshot, context) => {
|
||||
console.log(`onMessageCreated triggered for ${context.params.messageId} in group ${context.params.groupId}`);
|
||||
const message = snapshot.data();
|
||||
const groupId = context.params.groupId;
|
||||
const senderId = message.senderId;
|
||||
|
||||
// Fetch group to get members
|
||||
const groupDoc = await admin.firestore().collection("groups").doc(groupId).get();
|
||||
if (!groupDoc.exists) {
|
||||
console.log(`Group ${groupId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
const group = groupDoc.data();
|
||||
const memberIds = group.memberIds || [];
|
||||
console.log(`Found group members: ${JSON.stringify(memberIds)}`);
|
||||
|
||||
let senderName = message.senderName || "Quelqu'un";
|
||||
|
||||
await sendNotificationToUsers(
|
||||
memberIds,
|
||||
"Nouveau message",
|
||||
`${senderName} : ${message.text}`,
|
||||
senderId,
|
||||
{ groupId: groupId }
|
||||
);
|
||||
});
|
||||
|
||||
exports.onExpenseCreated = functions.firestore
|
||||
.document("expenses/{expenseId}")
|
||||
.onCreate(async (snapshot, context) => {
|
||||
console.log(`onExpenseCreated triggered for ${context.params.expenseId}`);
|
||||
const expense = snapshot.data();
|
||||
const groupId = expense.groupId;
|
||||
const paidBy = expense.paidById || expense.paidBy;
|
||||
|
||||
if (!groupId) {
|
||||
console.log("No groupId found in expense");
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch group to get members
|
||||
const groupDoc = await admin.firestore().collection("groups").doc(groupId).get();
|
||||
if (!groupDoc.exists) {
|
||||
console.log(`Group ${groupId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
const group = groupDoc.data();
|
||||
const memberIds = group.memberIds || [];
|
||||
console.log(`Found group members: ${JSON.stringify(memberIds)}`);
|
||||
|
||||
let payerName = expense.paidByName || "Quelqu'un";
|
||||
|
||||
await sendNotificationToUsers(
|
||||
memberIds,
|
||||
"Nouvelle dépense",
|
||||
`${payerName} a ajouté une dépense : ${expense.amount} ${expense.currency || '€'}`,
|
||||
paidBy,
|
||||
{ groupId: groupId }
|
||||
);
|
||||
});
|
||||
|
||||
exports.callbacks_signInWithApple = functions.https.onRequest((req, res) => {
|
||||
const code = req.body.code;
|
||||
const state = req.body.state;
|
||||
const id_token = req.body.id_token;
|
||||
const user = req.body.user;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (code) params.append('code', code);
|
||||
if (state) params.append('state', state);
|
||||
if (id_token) params.append('id_token', id_token);
|
||||
if (user) params.append('user', user);
|
||||
|
||||
const qs = params.toString();
|
||||
const packageName = 'be.devdayronvl.travel_mate';
|
||||
const redirectUrl = `intent://callback?${qs}#Intent;package=${packageName};scheme=signinwithapple;end`;
|
||||
|
||||
res.redirect(302, redirectUrl);
|
||||
});
|
||||
6823
functions/package-lock.json
generated
Normal file
6823
functions/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
23
functions/package.json
Normal file
23
functions/package.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "functions",
|
||||
"description": "Cloud Functions for Firebase",
|
||||
"scripts": {
|
||||
"serve": "firebase emulators:start --only functions",
|
||||
"shell": "firebase functions:shell",
|
||||
"start": "npm run shell",
|
||||
"deploy": "firebase deploy --only functions",
|
||||
"logs": "firebase functions:log"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20"
|
||||
},
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"firebase-admin": "^13.6.0",
|
||||
"firebase-functions": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"firebase-functions-test": "^3.4.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
214
ios/Podfile.lock
214
ios/Podfile.lock
@@ -1205,56 +1205,85 @@ PODS:
|
||||
- BoringSSL-GRPC/Interface (= 0.0.37)
|
||||
- BoringSSL-GRPC/Interface (0.0.37)
|
||||
- cloud_firestore (6.0.3):
|
||||
- Firebase/Firestore (= 12.4.0)
|
||||
- Firebase/Firestore (= 12.6.0)
|
||||
- firebase_core
|
||||
- Flutter
|
||||
- Firebase/Auth (12.4.0):
|
||||
- Firebase/Auth (12.6.0):
|
||||
- Firebase/CoreOnly
|
||||
- FirebaseAuth (~> 12.4.0)
|
||||
- Firebase/CoreOnly (12.4.0):
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- Firebase/Firestore (12.4.0):
|
||||
- FirebaseAuth (~> 12.6.0)
|
||||
- Firebase/CoreOnly (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- Firebase/Firestore (12.6.0):
|
||||
- Firebase/CoreOnly
|
||||
- FirebaseFirestore (~> 12.4.0)
|
||||
- Firebase/Storage (12.4.0):
|
||||
- FirebaseFirestore (~> 12.6.0)
|
||||
- Firebase/Messaging (12.6.0):
|
||||
- Firebase/CoreOnly
|
||||
- FirebaseStorage (~> 12.4.0)
|
||||
- FirebaseMessaging (~> 12.6.0)
|
||||
- Firebase/Storage (12.6.0):
|
||||
- Firebase/CoreOnly
|
||||
- FirebaseStorage (~> 12.6.0)
|
||||
- firebase_analytics (12.1.0):
|
||||
- firebase_core
|
||||
- FirebaseAnalytics (= 12.6.0)
|
||||
- Flutter
|
||||
- firebase_auth (6.1.1):
|
||||
- Firebase/Auth (= 12.4.0)
|
||||
- Firebase/Auth (= 12.6.0)
|
||||
- firebase_core
|
||||
- Flutter
|
||||
- firebase_core (4.2.0):
|
||||
- Firebase/CoreOnly (= 12.4.0)
|
||||
- firebase_core (4.3.0):
|
||||
- Firebase/CoreOnly (= 12.6.0)
|
||||
- Flutter
|
||||
- firebase_messaging (16.0.4):
|
||||
- Firebase/Messaging (= 12.6.0)
|
||||
- firebase_core
|
||||
- Flutter
|
||||
- firebase_storage (13.0.3):
|
||||
- Firebase/Storage (= 12.4.0)
|
||||
- Firebase/Storage (= 12.6.0)
|
||||
- firebase_core
|
||||
- Flutter
|
||||
- FirebaseAppCheckInterop (12.4.0)
|
||||
- FirebaseAuth (12.4.0):
|
||||
- FirebaseAppCheckInterop (~> 12.4.0)
|
||||
- FirebaseAuthInterop (~> 12.4.0)
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- FirebaseCoreExtension (~> 12.4.0)
|
||||
- FirebaseAnalytics (12.6.0):
|
||||
- FirebaseAnalytics/Default (= 12.6.0)
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseInstallations (~> 12.6.0)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/MethodSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- nanopb (~> 3.30910.0)
|
||||
- FirebaseAnalytics/Default (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseInstallations (~> 12.6.0)
|
||||
- GoogleAppMeasurement/Default (= 12.6.0)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/MethodSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- nanopb (~> 3.30910.0)
|
||||
- FirebaseAppCheckInterop (12.6.0)
|
||||
- FirebaseAuth (12.6.0):
|
||||
- FirebaseAppCheckInterop (~> 12.6.0)
|
||||
- FirebaseAuthInterop (~> 12.6.0)
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseCoreExtension (~> 12.6.0)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GTMSessionFetcher/Core (< 6.0, >= 3.4)
|
||||
- RecaptchaInterop (~> 101.0)
|
||||
- FirebaseAuthInterop (12.4.0)
|
||||
- FirebaseCore (12.4.0):
|
||||
- FirebaseCoreInternal (~> 12.4.0)
|
||||
- FirebaseAuthInterop (12.6.0)
|
||||
- FirebaseCore (12.6.0):
|
||||
- FirebaseCoreInternal (~> 12.6.0)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/Logger (~> 8.1)
|
||||
- FirebaseCoreExtension (12.4.0):
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- FirebaseCoreInternal (12.4.0):
|
||||
- FirebaseCoreExtension (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseCoreInternal (12.6.0):
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- FirebaseFirestore (12.4.0):
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- FirebaseCoreExtension (~> 12.4.0)
|
||||
- FirebaseFirestoreInternal (~> 12.4.0)
|
||||
- FirebaseSharedSwift (~> 12.4.0)
|
||||
- FirebaseFirestoreInternal (12.4.0):
|
||||
- FirebaseFirestore (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseCoreExtension (~> 12.6.0)
|
||||
- FirebaseFirestoreInternal (~> 12.6.0)
|
||||
- FirebaseSharedSwift (~> 12.6.0)
|
||||
- FirebaseFirestoreInternal (12.6.0):
|
||||
- abseil/algorithm (~> 1.20240722.0)
|
||||
- abseil/base (~> 1.20240722.0)
|
||||
- abseil/container/flat_hash_map (~> 1.20240722.0)
|
||||
@@ -1263,21 +1292,37 @@ PODS:
|
||||
- abseil/strings/strings (~> 1.20240722.0)
|
||||
- abseil/time (~> 1.20240722.0)
|
||||
- abseil/types (~> 1.20240722.0)
|
||||
- FirebaseAppCheckInterop (~> 12.4.0)
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- FirebaseAppCheckInterop (~> 12.6.0)
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- "gRPC-C++ (~> 1.69.0)"
|
||||
- gRPC-Core (~> 1.69.0)
|
||||
- leveldb-library (~> 1.22)
|
||||
- nanopb (~> 3.30910.0)
|
||||
- FirebaseSharedSwift (12.4.0)
|
||||
- FirebaseStorage (12.4.0):
|
||||
- FirebaseAppCheckInterop (~> 12.4.0)
|
||||
- FirebaseAuthInterop (~> 12.4.0)
|
||||
- FirebaseCore (~> 12.4.0)
|
||||
- FirebaseCoreExtension (~> 12.4.0)
|
||||
- FirebaseInstallations (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/UserDefaults (~> 8.1)
|
||||
- PromisesObjC (~> 2.4)
|
||||
- FirebaseMessaging (12.6.0):
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseInstallations (~> 12.6.0)
|
||||
- GoogleDataTransport (~> 10.1)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/Reachability (~> 8.1)
|
||||
- GoogleUtilities/UserDefaults (~> 8.1)
|
||||
- nanopb (~> 3.30910.0)
|
||||
- FirebaseSharedSwift (12.6.0)
|
||||
- FirebaseStorage (12.6.0):
|
||||
- FirebaseAppCheckInterop (~> 12.6.0)
|
||||
- FirebaseAuthInterop (~> 12.6.0)
|
||||
- FirebaseCore (~> 12.6.0)
|
||||
- FirebaseCoreExtension (~> 12.6.0)
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GTMSessionFetcher/Core (< 6.0, >= 3.4)
|
||||
- Flutter (1.0.0)
|
||||
- flutter_local_notifications (0.0.1):
|
||||
- Flutter
|
||||
- geolocator_apple (1.2.0):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
@@ -1292,10 +1337,40 @@ PODS:
|
||||
- FlutterMacOS
|
||||
- GoogleSignIn (~> 9.0)
|
||||
- GTMSessionFetcher (>= 3.4.0)
|
||||
- GoogleAdsOnDeviceConversion (3.2.0):
|
||||
- GoogleUtilities/Environment (~> 8.1)
|
||||
- GoogleUtilities/Logger (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- nanopb (~> 3.30910.0)
|
||||
- GoogleAppMeasurement/Core (12.6.0):
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/MethodSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- nanopb (~> 3.30910.0)
|
||||
- GoogleAppMeasurement/Default (12.6.0):
|
||||
- GoogleAdsOnDeviceConversion (~> 3.2.0)
|
||||
- GoogleAppMeasurement/Core (= 12.6.0)
|
||||
- GoogleAppMeasurement/IdentitySupport (= 12.6.0)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/MethodSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- nanopb (~> 3.30910.0)
|
||||
- GoogleAppMeasurement/IdentitySupport (12.6.0):
|
||||
- GoogleAppMeasurement/Core (= 12.6.0)
|
||||
- GoogleUtilities/AppDelegateSwizzler (~> 8.1)
|
||||
- GoogleUtilities/MethodSwizzler (~> 8.1)
|
||||
- GoogleUtilities/Network (~> 8.1)
|
||||
- "GoogleUtilities/NSData+zlib (~> 8.1)"
|
||||
- nanopb (~> 3.30910.0)
|
||||
- GoogleDataTransport (10.1.0):
|
||||
- nanopb (~> 3.30910.0)
|
||||
- PromisesObjC (~> 2.4)
|
||||
- GoogleMaps (9.4.0):
|
||||
- GoogleMaps/Maps (= 9.4.0)
|
||||
- GoogleMaps/Maps (9.4.0)
|
||||
- GoogleSignIn (9.0.0):
|
||||
- GoogleSignIn (9.1.0):
|
||||
- AppAuth (~> 2.0)
|
||||
- AppCheckCore (~> 11.0)
|
||||
- GTMAppAuth (~> 5.0)
|
||||
@@ -1310,6 +1385,9 @@ PODS:
|
||||
- GoogleUtilities/Logger (8.1.0):
|
||||
- GoogleUtilities/Environment
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/MethodSwizzler (8.1.0):
|
||||
- GoogleUtilities/Logger
|
||||
- GoogleUtilities/Privacy
|
||||
- GoogleUtilities/Network (8.1.0):
|
||||
- GoogleUtilities/Logger
|
||||
- "GoogleUtilities/NSData+zlib"
|
||||
@@ -1454,10 +1532,13 @@ PODS:
|
||||
|
||||
DEPENDENCIES:
|
||||
- cloud_firestore (from `.symlinks/plugins/cloud_firestore/ios`)
|
||||
- firebase_analytics (from `.symlinks/plugins/firebase_analytics/ios`)
|
||||
- firebase_auth (from `.symlinks/plugins/firebase_auth/ios`)
|
||||
- firebase_core (from `.symlinks/plugins/firebase_core/ios`)
|
||||
- firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`)
|
||||
- firebase_storage (from `.symlinks/plugins/firebase_storage/ios`)
|
||||
- Flutter (from `Flutter`)
|
||||
- flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`)
|
||||
- geolocator_apple (from `.symlinks/plugins/geolocator_apple/darwin`)
|
||||
- google_maps_flutter_ios (from `.symlinks/plugins/google_maps_flutter_ios/ios`)
|
||||
- google_sign_in_ios (from `.symlinks/plugins/google_sign_in_ios/darwin`)
|
||||
@@ -1477,6 +1558,7 @@ SPEC REPOS:
|
||||
- AppCheckCore
|
||||
- BoringSSL-GRPC
|
||||
- Firebase
|
||||
- FirebaseAnalytics
|
||||
- FirebaseAppCheckInterop
|
||||
- FirebaseAuth
|
||||
- FirebaseAuthInterop
|
||||
@@ -1485,9 +1567,14 @@ SPEC REPOS:
|
||||
- FirebaseCoreInternal
|
||||
- FirebaseFirestore
|
||||
- FirebaseFirestoreInternal
|
||||
- FirebaseInstallations
|
||||
- FirebaseMessaging
|
||||
- FirebaseSharedSwift
|
||||
- FirebaseStorage
|
||||
- Google-Maps-iOS-Utils
|
||||
- GoogleAdsOnDeviceConversion
|
||||
- GoogleAppMeasurement
|
||||
- GoogleDataTransport
|
||||
- GoogleMaps
|
||||
- GoogleSignIn
|
||||
- GoogleUtilities
|
||||
@@ -1503,14 +1590,20 @@ SPEC REPOS:
|
||||
EXTERNAL SOURCES:
|
||||
cloud_firestore:
|
||||
:path: ".symlinks/plugins/cloud_firestore/ios"
|
||||
firebase_analytics:
|
||||
:path: ".symlinks/plugins/firebase_analytics/ios"
|
||||
firebase_auth:
|
||||
:path: ".symlinks/plugins/firebase_auth/ios"
|
||||
firebase_core:
|
||||
:path: ".symlinks/plugins/firebase_core/ios"
|
||||
firebase_messaging:
|
||||
:path: ".symlinks/plugins/firebase_messaging/ios"
|
||||
firebase_storage:
|
||||
:path: ".symlinks/plugins/firebase_storage/ios"
|
||||
Flutter:
|
||||
:path: Flutter
|
||||
flutter_local_notifications:
|
||||
:path: ".symlinks/plugins/flutter_local_notifications/ios"
|
||||
geolocator_apple:
|
||||
:path: ".symlinks/plugins/geolocator_apple/darwin"
|
||||
google_maps_flutter_ios:
|
||||
@@ -1539,28 +1632,37 @@ SPEC CHECKSUMS:
|
||||
AppAuth: 1c1a8afa7e12f2ec3a294d9882dfa5ab7d3cb063
|
||||
AppCheckCore: cc8fd0a3a230ddd401f326489c99990b013f0c4f
|
||||
BoringSSL-GRPC: dded2a44897e45f28f08ae87a55ee4bcd19bc508
|
||||
cloud_firestore: 79014bb3b303d451717ed5fe69fded8a2b2e8dc2
|
||||
Firebase: f07b15ae5a6ec0f93713e30b923d9970d144af3e
|
||||
firebase_auth: c2b8be95d602d4e8a9148fae72333ef78e69cc20
|
||||
firebase_core: 744984dbbed8b3036abf34f0b98d80f130a7e464
|
||||
firebase_storage: 0ba617a05b24aec050395e4d5d3773c0d7518a15
|
||||
FirebaseAppCheckInterop: f734c802f21fe1da0837708f0f9a27218c8a4ed0
|
||||
FirebaseAuth: 4a2aed737c84114a9d9b33d11ae1b147d6b94889
|
||||
FirebaseAuthInterop: 858e6b754966e70740a4370dd1503dfffe6dbb49
|
||||
FirebaseCore: bb595f3114953664e3c1dc032f008a244147cfd3
|
||||
FirebaseCoreExtension: 7e1f7118ee970e001a8013719fb90950ee5e0018
|
||||
FirebaseCoreInternal: d7f5a043c2cd01a08103ab586587c1468047bca6
|
||||
FirebaseFirestore: 2a6183381cf7679b1bb000eb76a8e3178e25dee2
|
||||
FirebaseFirestoreInternal: 6577a27cd5dc3722b900042527f86d4ea1626134
|
||||
FirebaseSharedSwift: 93426a1de92f19e1199fac5295a4f8df16458daa
|
||||
FirebaseStorage: 20d6b56fb8a40ebaa03d6a2889fe33dac64adb73
|
||||
cloud_firestore: d7598ff2b1b2064e810f839dbdde2765c0f2052a
|
||||
Firebase: a451a7b61536298fd5cbfe3a746fd40443a50679
|
||||
firebase_analytics: 4f9cca09e65f6c2944a862c6dc86f6bed9fb769c
|
||||
firebase_auth: cfb7237c0d01e87360cb3bf61e02a417c36e19e8
|
||||
firebase_core: ba00a168e719694f38960502ceb560285603d073
|
||||
firebase_messaging: 752f1df5294ead9d72091d4974362d00d4aec201
|
||||
firebase_storage: 5716627614e95c75e243134f65c1b0d6f66a4315
|
||||
FirebaseAnalytics: d0a97a0db6425e5a5d966340b87f92ca7b13a557
|
||||
FirebaseAppCheckInterop: e2178171b4145013c7c1a3cc464d1d446d3a1896
|
||||
FirebaseAuth: 613c463cb43545a7fd2cd99ade09b78ac472c544
|
||||
FirebaseAuthInterop: db06756ef028006d034b6004dc0c37c24f7828d4
|
||||
FirebaseCore: 0e38ad5d62d980a47a64b8e9301ffa311457be04
|
||||
FirebaseCoreExtension: 032fd6f8509e591fda8cb76f6651f20d926b121f
|
||||
FirebaseCoreInternal: 69bf1306a05b8ac43004f6cc1f804bb7b05b229e
|
||||
FirebaseFirestore: 51ce079b9ddcaa481644164eda649d362c2a6396
|
||||
FirebaseFirestoreInternal: 8b1d2b0a1b859b2ddbd63f448c416c5be7367405
|
||||
FirebaseInstallations: 631b38da2e11a83daa4bfb482f79d286a5dfa7ad
|
||||
FirebaseMessaging: a61bc42dcab3f7a346d94bbb54dab2c9435b18b2
|
||||
FirebaseSharedSwift: 79f27fff0addd15c3de19b87fba426f3cc2c964f
|
||||
FirebaseStorage: 550349b1e8f7315834ea08308696e9469d77135d
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
flutter_local_notifications: a5a732f069baa862e728d839dd2ebb904737effb
|
||||
geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e
|
||||
Google-Maps-iOS-Utils: 0a484b05ed21d88c9f9ebbacb007956edd508a96
|
||||
google_maps_flutter_ios: 0291eb2aa252298a769b04d075e4a9d747ff7264
|
||||
google_sign_in_ios: 205742c688aea0e64db9da03c33121694a365109
|
||||
GoogleAdsOnDeviceConversion: d68c69dd9581a0f5da02617b6f377e5be483970f
|
||||
GoogleAppMeasurement: 3bf40aff49a601af5da1c3345702fcb4991d35ee
|
||||
GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7
|
||||
GoogleMaps: 0608099d4870cac8754bdba9b6953db543432438
|
||||
GoogleSignIn: c7f09cfbc85a1abf69187be091997c317cc33b77
|
||||
GoogleSignIn: fcee2257188d5eda57a5e2b6a715550ffff9206d
|
||||
GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1
|
||||
"gRPC-C++": cc207623316fb041a7a3e774c252cf68a058b9e8
|
||||
gRPC-Core: 860978b7db482de8b4f5e10677216309b5ff6330
|
||||
|
||||
@@ -490,7 +490,11 @@
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 456VVYXDFN;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -499,6 +503,8 @@
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = be.devdayronvl.TravelMate;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = myiphone;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
@@ -673,7 +679,11 @@
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 456VVYXDFN;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -682,6 +692,8 @@
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = be.devdayronvl.TravelMate;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = myiphone;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
@@ -696,7 +708,11 @@
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 456VVYXDFN;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -705,6 +721,8 @@
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = be.devdayronvl.TravelMate;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = myiphone;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
|
||||
@@ -32,6 +32,14 @@
|
||||
<string>com.googleusercontent.apps.521527250907-3i1qe2656eojs8k9hjdi573j09i9p41m</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>Apple Sign-In</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(FLUTTER_BUILD_NUMBER)</string>
|
||||
@@ -39,6 +47,11 @@
|
||||
<string>521527250907-3i1qe2656eojs8k9hjdi573j09i9p41m.apps.googleusercontent.com</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>UIBackgroundModes</key>
|
||||
<array>
|
||||
<string>fetch</string>
|
||||
<string>remote-notification</string>
|
||||
</array>
|
||||
<key>NSLocationAlwaysUsageDescription</key>
|
||||
<string>Cette application a besoin de votre position pour afficher votre localisation sur la carte</string>
|
||||
<key>NSLocationWhenInUseUsageDescription</key>
|
||||
@@ -52,27 +65,18 @@
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>Apple Sign-In</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
|
||||
<key>LSApplicationQueriesSchemes</key>
|
||||
<array>
|
||||
<string>comgooglemaps</string>
|
||||
<string>waze</string>
|
||||
</array>
|
||||
<!-- Permission Caméra -->
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>L'application a besoin d'accéder à votre caméra pour prendre des photos de profil.</string>
|
||||
|
||||
@@ -6,5 +6,7 @@
|
||||
<array>
|
||||
<string>Default</string>
|
||||
</array>
|
||||
<key>aps-environment</key>
|
||||
<string>development</string>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
/// accountBloc.close();
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
@@ -30,7 +31,7 @@ import 'account_state.dart';
|
||||
import '../../repositories/account_repository.dart';
|
||||
import '../../models/account.dart';
|
||||
|
||||
class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
final AccountRepository _repository;
|
||||
StreamSubscription? _accountsSubscription;
|
||||
final _errorService = ErrorService();
|
||||
@@ -40,26 +41,34 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
on<_AccountsUpdated>(_onAccountsUpdated);
|
||||
on<CreateAccount>(_onCreateAccount);
|
||||
on<CreateAccountWithMembers>(_onCreateAccountWithMembers);
|
||||
on<AddMemberToAccount>(_onAddMemberToAccount);
|
||||
on<RemoveMemberFromAccount>(_onRemoveMemberFromAccount);
|
||||
}
|
||||
|
||||
Future<void> _onLoadAccountsByUserId(
|
||||
LoadAccountsByUserId event,
|
||||
Emitter<AccountState> emit,
|
||||
) async {
|
||||
) async {
|
||||
try {
|
||||
emit(AccountLoading());
|
||||
await _accountsSubscription?.cancel();
|
||||
_accountsSubscription = _repository.getAccountByUserId(event.userId).listen(
|
||||
(accounts) {
|
||||
add(_AccountsUpdated(accounts));
|
||||
},
|
||||
onError: (error) {
|
||||
add(_AccountsUpdated([], error: error.toString()));
|
||||
},
|
||||
);
|
||||
_accountsSubscription = _repository
|
||||
.getAccountByUserId(event.userId)
|
||||
.listen(
|
||||
(accounts) {
|
||||
add(_AccountsUpdated(accounts));
|
||||
},
|
||||
onError: (error) {
|
||||
add(_AccountsUpdated([], error: error.toString()));
|
||||
},
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
emit(AccountError(e.toString()));
|
||||
_errorService.logError(
|
||||
'AccountBloc',
|
||||
'Error loading accounts: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const AccountError('Impossible de charger les comptes'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,8 +96,12 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
);
|
||||
emit(AccountOperationSuccess('Compte créé avec succès. ID: $accountId'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
emit(AccountError('Erreur lors de la création du compte: ${e.toString()}'));
|
||||
_errorService.logError(
|
||||
'AccountBloc',
|
||||
'Error creating account: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const AccountError('Impossible de créer le compte'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +109,7 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
CreateAccountWithMembers event,
|
||||
Emitter<AccountState> emit,
|
||||
) async {
|
||||
try{
|
||||
try {
|
||||
emit(AccountLoading());
|
||||
final accountId = await _repository.createAccountWithMembers(
|
||||
account: event.account,
|
||||
@@ -104,8 +117,51 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
);
|
||||
emit(AccountOperationSuccess('Compte créé avec succès. ID: $accountId'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
emit(AccountError('Erreur lors de la création du compte: ${e.toString()}'));
|
||||
_errorService.logError(
|
||||
'AccountBloc',
|
||||
'Error creating account with members: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const AccountError('Impossible de créer le compte'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onAddMemberToAccount(
|
||||
AddMemberToAccount event,
|
||||
Emitter<AccountState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(AccountLoading());
|
||||
await _repository.addMemberToAccount(event.accountId, event.member);
|
||||
emit(AccountOperationSuccess('Membre ajouté avec succès'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AccountBloc',
|
||||
'Error adding member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const AccountError('Impossible d\'ajouter le membre'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onRemoveMemberFromAccount(
|
||||
RemoveMemberFromAccount event,
|
||||
Emitter<AccountState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(AccountLoading());
|
||||
await _repository.removeMemberFromAccount(
|
||||
event.accountId,
|
||||
event.memberId,
|
||||
);
|
||||
emit(AccountOperationSuccess('Membre supprimé avec succès'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AccountBloc',
|
||||
'Error removing member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const AccountError('Impossible de supprimer le membre'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,4 +180,4 @@ class _AccountsUpdated extends AccountEvent {
|
||||
|
||||
@override
|
||||
List<Object?> get props => [accounts, error];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,4 +85,32 @@ class CreateAccountWithMembers extends AccountEvent {
|
||||
|
||||
@override
|
||||
List<Object?> get props => [account, members];
|
||||
}
|
||||
|
||||
/// Event to add a member to an existing account.
|
||||
///
|
||||
/// This event is dispatched when a new member needs to be added to
|
||||
/// an account, typically when editing a trip and adding new participants.
|
||||
class AddMemberToAccount extends AccountEvent {
|
||||
final String accountId;
|
||||
final GroupMember member;
|
||||
|
||||
const AddMemberToAccount(this.accountId, this.member);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [accountId, member];
|
||||
}
|
||||
|
||||
/// Event to remove a member from an existing account.
|
||||
///
|
||||
/// This event is dispatched when a member needs to be removed from
|
||||
/// an account, typically when editing a trip and removing participants.
|
||||
class RemoveMemberFromAccount extends AccountEvent {
|
||||
final String accountId;
|
||||
final String memberId;
|
||||
|
||||
const RemoveMemberFromAccount(this.accountId, this.memberId);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [accountId, memberId];
|
||||
}
|
||||
@@ -17,13 +17,14 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
required ActivityRepository repository,
|
||||
required ActivityPlacesService placesService,
|
||||
required ErrorService errorService,
|
||||
}) : _repository = repository,
|
||||
_placesService = placesService,
|
||||
_errorService = errorService,
|
||||
super(const ActivityInitial()) {
|
||||
|
||||
}) : _repository = repository,
|
||||
_placesService = placesService,
|
||||
_errorService = errorService,
|
||||
super(const ActivityInitial()) {
|
||||
on<LoadActivities>(_onLoadActivities);
|
||||
on<LoadTripActivitiesPreservingSearch>(_onLoadTripActivitiesPreservingSearch);
|
||||
on<LoadTripActivitiesPreservingSearch>(
|
||||
_onLoadTripActivitiesPreservingSearch,
|
||||
);
|
||||
on<SearchActivities>(_onSearchActivities);
|
||||
on<SearchActivitiesWithCoordinates>(_onSearchActivitiesWithCoordinates);
|
||||
on<SearchActivitiesByText>(_onSearchActivitiesByText);
|
||||
@@ -39,6 +40,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
on<RestoreCachedSearchResults>(_onRestoreCachedSearchResults);
|
||||
on<RemoveFromSearchResults>(_onRemoveFromSearchResults);
|
||||
on<AddActivityAndRemoveFromSearch>(_onAddActivityAndRemoveFromSearch);
|
||||
on<UpdateActivityDate>(_onUpdateActivityDate);
|
||||
}
|
||||
|
||||
/// Handles loading activities for a trip
|
||||
@@ -48,15 +50,18 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
) async {
|
||||
try {
|
||||
emit(const ActivityLoading());
|
||||
|
||||
|
||||
final activities = await _repository.getActivitiesByTrip(event.tripId);
|
||||
|
||||
emit(ActivityLoaded(
|
||||
activities: activities,
|
||||
filteredActivities: activities,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur chargement activités: $e');
|
||||
|
||||
emit(
|
||||
ActivityLoaded(activities: activities, filteredActivities: activities),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur chargement activités: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de charger les activités'));
|
||||
}
|
||||
}
|
||||
@@ -68,24 +73,57 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
) async {
|
||||
try {
|
||||
final activities = await _repository.getActivitiesByTrip(event.tripId);
|
||||
|
||||
|
||||
// Si on a un état de recherche actif, on le préserve
|
||||
if (state is ActivitySearchResults) {
|
||||
// On garde l'état de recherche inchangé, pas besoin d'émettre
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Sinon, on charge normalement
|
||||
emit(ActivityLoaded(
|
||||
activities: activities,
|
||||
filteredActivities: activities,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur chargement activités: $e');
|
||||
emit(
|
||||
ActivityLoaded(activities: activities, filteredActivities: activities),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur chargement activités: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de charger les activités'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onUpdateActivityDate(
|
||||
UpdateActivityDate event,
|
||||
Emitter<ActivityState> emit,
|
||||
) async {
|
||||
try {
|
||||
final activity = await _repository.getActivity(
|
||||
event.tripId,
|
||||
event.activityId,
|
||||
);
|
||||
|
||||
if (activity != null) {
|
||||
final updatedActivity = activity.copyWith(
|
||||
date: event.date,
|
||||
clearDate: event.date == null,
|
||||
);
|
||||
await _repository.updateActivity(updatedActivity);
|
||||
|
||||
// Recharger les activités pour mettre à jour l'UI
|
||||
add(LoadActivities(event.tripId));
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur mise à jour date: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de mettre à jour la date'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles searching activities using Google Places API
|
||||
Future<void> _onSearchActivities(
|
||||
SearchActivities event,
|
||||
@@ -99,17 +137,19 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
} else {
|
||||
emit(const ActivitySearching());
|
||||
}
|
||||
|
||||
|
||||
final searchResults = await _placesService.searchActivities(
|
||||
destination: event.destination,
|
||||
tripId: event.tripId,
|
||||
category: event.category,
|
||||
maxResults: event.maxResults ?? 20, // Par défaut 20, ou utiliser la valeur spécifiée
|
||||
maxResults:
|
||||
event.maxResults ??
|
||||
20, // Par défaut 20, ou utiliser la valeur spécifiée
|
||||
offset: event.offset ?? 0, // Par défaut 0
|
||||
);
|
||||
|
||||
|
||||
List<Activity> finalResults;
|
||||
|
||||
|
||||
// Si on doit ajouter aux résultats existants
|
||||
if (event.appendToExisting && state is ActivitySearchResults) {
|
||||
final currentState = state as ActivitySearchResults;
|
||||
@@ -117,18 +157,28 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
} else {
|
||||
finalResults = searchResults;
|
||||
}
|
||||
|
||||
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, finalResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: finalResults,
|
||||
query: event.category?.displayName ?? 'Toutes les activités',
|
||||
isLoading: false,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur recherche activités: $e');
|
||||
emit(const ActivityError('Impossible de rechercher les activités'));
|
||||
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: finalResults,
|
||||
query: event.category?.displayName ?? 'Toutes les activités',
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur recherche activités: $e',
|
||||
stackTrace,
|
||||
);
|
||||
// Extraire le message d'erreur si disponible
|
||||
final errorMessage = e.toString().replaceAll('Exception: ', '');
|
||||
emit(
|
||||
ActivityError('Impossible de rechercher les activités: $errorMessage'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +195,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
} else {
|
||||
emit(const ActivitySearching());
|
||||
}
|
||||
|
||||
|
||||
final searchResults = await _placesService.searchActivitiesPaginated(
|
||||
latitude: event.latitude,
|
||||
longitude: event.longitude,
|
||||
@@ -153,10 +203,10 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
category: event.category,
|
||||
pageSize: event.maxResults ?? 20,
|
||||
);
|
||||
|
||||
|
||||
final activities = searchResults['activities'] as List<Activity>;
|
||||
List<Activity> finalResults;
|
||||
|
||||
|
||||
// Si on doit ajouter aux résultats existants
|
||||
if (event.appendToExisting && state is ActivitySearchResults) {
|
||||
final currentState = state as ActivitySearchResults;
|
||||
@@ -164,17 +214,23 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
} else {
|
||||
finalResults = activities;
|
||||
}
|
||||
|
||||
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, finalResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: finalResults,
|
||||
query: event.category?.displayName ?? 'Toutes les activités',
|
||||
isLoading: false,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur recherche activités avec coordonnées: $e');
|
||||
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: finalResults,
|
||||
query: event.category?.displayName ?? 'Toutes les activités',
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur recherche activités avec coordonnées: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de rechercher les activités'));
|
||||
}
|
||||
}
|
||||
@@ -186,22 +242,25 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
) async {
|
||||
try {
|
||||
emit(const ActivitySearching());
|
||||
|
||||
|
||||
final searchResults = await _placesService.searchActivitiesByText(
|
||||
query: event.query,
|
||||
destination: event.destination,
|
||||
tripId: event.tripId,
|
||||
);
|
||||
|
||||
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, searchResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: searchResults,
|
||||
query: event.query,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur recherche textuelle: $e');
|
||||
|
||||
emit(
|
||||
ActivitySearchResults(searchResults: searchResults, query: event.query),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur recherche textuelle: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de rechercher les activités'));
|
||||
}
|
||||
}
|
||||
@@ -218,7 +277,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
event.activity.tripId,
|
||||
event.activity.placeId!,
|
||||
);
|
||||
|
||||
|
||||
if (existing != null) {
|
||||
emit(const ActivityError('Cette activité a déjà été ajoutée'));
|
||||
return;
|
||||
@@ -226,27 +285,38 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
}
|
||||
|
||||
final activityId = await _repository.addActivity(event.activity);
|
||||
|
||||
|
||||
if (activityId != null) {
|
||||
// Si on est en état de recherche (suggestions Google), préserver cet état
|
||||
if (state is ActivitySearchResults) {
|
||||
// On ne change rien à l'état de recherche, on le garde tel quel
|
||||
// La suppression de l'activité des résultats se fait dans _onRemoveFromSearchResults
|
||||
final currentState = state as ActivitySearchResults;
|
||||
// On garde l'état de recherche inchangé mais on ajoute l'info de l'activité ajoutée
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
newlyAddedActivity: event.activity.copyWith(id: activityId),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Sinon, émettre l'état d'ajout réussi
|
||||
emit(ActivityAdded(
|
||||
activity: event.activity.copyWith(id: activityId),
|
||||
message: 'Activité ajoutée avec succès',
|
||||
));
|
||||
emit(
|
||||
ActivityAdded(
|
||||
activity: event.activity.copyWith(id: activityId),
|
||||
message: 'Activité ajoutée avec succès',
|
||||
),
|
||||
);
|
||||
// Reload activities while preserving search results
|
||||
add(LoadTripActivitiesPreservingSearch(event.activity.tripId));
|
||||
} else {
|
||||
emit(const ActivityError('Impossible d\'ajouter l\'activité'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur ajout activité: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur ajout activité: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible d\'ajouter l\'activité'));
|
||||
}
|
||||
}
|
||||
@@ -263,7 +333,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
event.activity.tripId,
|
||||
event.activity.placeId!,
|
||||
);
|
||||
|
||||
|
||||
if (existing != null) {
|
||||
emit(const ActivityError('Cette activité a déjà été ajoutée'));
|
||||
return;
|
||||
@@ -271,7 +341,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
}
|
||||
|
||||
final activityId = await _repository.addActivity(event.activity);
|
||||
|
||||
|
||||
if (activityId != null) {
|
||||
// Si on est en état de recherche (suggestions Google), préserver cet état
|
||||
// en supprimant l'activité des résultats
|
||||
@@ -280,27 +350,35 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
final updatedResults = currentState.searchResults
|
||||
.where((activity) => activity.id != event.googleActivityId)
|
||||
.toList();
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
));
|
||||
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Sinon, émettre l'état d'ajout réussi
|
||||
emit(ActivityAdded(
|
||||
activity: event.activity.copyWith(id: activityId),
|
||||
message: 'Activité ajoutée avec succès',
|
||||
));
|
||||
emit(
|
||||
ActivityAdded(
|
||||
activity: event.activity.copyWith(id: activityId),
|
||||
message: 'Activité ajoutée avec succès',
|
||||
),
|
||||
);
|
||||
// Reload activities while preserving search results
|
||||
add(LoadTripActivitiesPreservingSearch(event.activity.tripId));
|
||||
} else {
|
||||
emit(const ActivityError('Impossible d\'ajouter l\'activité'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur ajout activité: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur ajout activité: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible d\'ajouter l\'activité'));
|
||||
}
|
||||
}
|
||||
@@ -313,35 +391,39 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
try {
|
||||
// Filter out existing activities
|
||||
final filteredActivities = <Activity>[];
|
||||
|
||||
emit(ActivityBatchAdding(
|
||||
activitiesToAdd: event.activities,
|
||||
progress: 0,
|
||||
total: event.activities.length,
|
||||
));
|
||||
|
||||
|
||||
emit(
|
||||
ActivityBatchAdding(
|
||||
activitiesToAdd: event.activities,
|
||||
progress: 0,
|
||||
total: event.activities.length,
|
||||
),
|
||||
);
|
||||
|
||||
for (int i = 0; i < event.activities.length; i++) {
|
||||
final activity = event.activities[i];
|
||||
|
||||
|
||||
if (activity.placeId != null) {
|
||||
final existing = await _repository.findExistingActivity(
|
||||
activity.tripId,
|
||||
activity.placeId!,
|
||||
);
|
||||
|
||||
|
||||
if (existing == null) {
|
||||
filteredActivities.add(activity);
|
||||
}
|
||||
} else {
|
||||
filteredActivities.add(activity);
|
||||
}
|
||||
|
||||
|
||||
// Update progress
|
||||
emit(ActivityBatchAdding(
|
||||
activitiesToAdd: event.activities,
|
||||
progress: i + 1,
|
||||
total: event.activities.length,
|
||||
));
|
||||
emit(
|
||||
ActivityBatchAdding(
|
||||
activitiesToAdd: event.activities,
|
||||
progress: i + 1,
|
||||
total: event.activities.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (filteredActivities.isEmpty) {
|
||||
@@ -350,19 +432,25 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
}
|
||||
|
||||
final addedIds = await _repository.addActivitiesBatch(filteredActivities);
|
||||
|
||||
|
||||
if (addedIds.isNotEmpty) {
|
||||
emit(ActivityOperationSuccess(
|
||||
'${addedIds.length} activité(s) ajoutée(s) avec succès',
|
||||
operationType: 'batch_add',
|
||||
));
|
||||
emit(
|
||||
ActivityOperationSuccess(
|
||||
'${addedIds.length} activité(s) ajoutée(s) avec succès',
|
||||
operationType: 'batch_add',
|
||||
),
|
||||
);
|
||||
// Reload activities
|
||||
add(LoadActivities(event.activities.first.tripId));
|
||||
} else {
|
||||
emit(const ActivityError('Impossible d\'ajouter les activités'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur ajout en lot: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur ajout en lot: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible d\'ajouter les activités'));
|
||||
}
|
||||
}
|
||||
@@ -376,10 +464,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Show voting state
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
emit(ActivityVoting(
|
||||
activityId: event.activityId,
|
||||
activities: currentState.activities,
|
||||
));
|
||||
emit(
|
||||
ActivityVoting(
|
||||
activityId: event.activityId,
|
||||
activities: currentState.activities,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final success = await _repository.voteForActivity(
|
||||
@@ -387,37 +477,41 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
event.userId,
|
||||
event.vote,
|
||||
);
|
||||
|
||||
|
||||
if (success) {
|
||||
emit(ActivityVoteRecorded(
|
||||
activityId: event.activityId,
|
||||
vote: event.vote,
|
||||
userId: event.userId,
|
||||
));
|
||||
|
||||
emit(
|
||||
ActivityVoteRecorded(
|
||||
activityId: event.activityId,
|
||||
vote: event.vote,
|
||||
userId: event.userId,
|
||||
),
|
||||
);
|
||||
|
||||
// Reload activities to reflect the new vote
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
final activities = await _repository.getActivitiesByTrip(
|
||||
currentState.activities.first.tripId,
|
||||
);
|
||||
|
||||
emit(currentState.copyWith(
|
||||
activities: activities,
|
||||
filteredActivities: _applyFilters(
|
||||
activities,
|
||||
currentState.activeFilter,
|
||||
currentState.minRating,
|
||||
currentState.showVotedOnly,
|
||||
event.userId,
|
||||
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
activities: activities,
|
||||
filteredActivities: _applyFilters(
|
||||
activities,
|
||||
currentState.activeFilter,
|
||||
currentState.minRating,
|
||||
currentState.showVotedOnly,
|
||||
event.userId,
|
||||
),
|
||||
),
|
||||
));
|
||||
);
|
||||
}
|
||||
} else {
|
||||
emit(const ActivityError('Impossible d\'enregistrer le vote'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur vote: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('activity_bloc', 'Erreur vote: $e', stackTrace);
|
||||
emit(const ActivityError('Impossible d\'enregistrer le vote'));
|
||||
}
|
||||
}
|
||||
@@ -429,13 +523,15 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
) async {
|
||||
try {
|
||||
final success = await _repository.deleteActivity(event.activityId);
|
||||
|
||||
|
||||
if (success) {
|
||||
emit(ActivityDeleted(
|
||||
activityId: event.activityId,
|
||||
message: 'Activité supprimée avec succès',
|
||||
));
|
||||
|
||||
emit(
|
||||
ActivityDeleted(
|
||||
activityId: event.activityId,
|
||||
message: 'Activité supprimée avec succès',
|
||||
),
|
||||
);
|
||||
|
||||
// Reload if we're on the activity list
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
@@ -446,8 +542,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
} else {
|
||||
emit(const ActivityError('Impossible de supprimer l\'activité'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur suppression: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur suppression: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de supprimer l\'activité'));
|
||||
}
|
||||
}
|
||||
@@ -459,7 +559,7 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
) async {
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
|
||||
|
||||
final filteredActivities = _applyFilters(
|
||||
currentState.activities,
|
||||
event.category,
|
||||
@@ -467,13 +567,15 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
event.showVotedOnly ?? false,
|
||||
'', // UserId would be needed for showVotedOnly filter
|
||||
);
|
||||
|
||||
emit(currentState.copyWith(
|
||||
filteredActivities: filteredActivities,
|
||||
activeFilter: event.category,
|
||||
minRating: event.minRating,
|
||||
showVotedOnly: event.showVotedOnly ?? false,
|
||||
));
|
||||
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
filteredActivities: filteredActivities,
|
||||
activeFilter: event.category,
|
||||
minRating: event.minRating,
|
||||
showVotedOnly: event.showVotedOnly ?? false,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,27 +605,35 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
try {
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
emit(ActivityUpdating(
|
||||
activityId: event.activity.id,
|
||||
activities: currentState.activities,
|
||||
));
|
||||
emit(
|
||||
ActivityUpdating(
|
||||
activityId: event.activity.id,
|
||||
activities: currentState.activities,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final success = await _repository.updateActivity(event.activity);
|
||||
|
||||
|
||||
if (success) {
|
||||
emit(const ActivityOperationSuccess(
|
||||
'Activité mise à jour avec succès',
|
||||
operationType: 'update',
|
||||
));
|
||||
|
||||
emit(
|
||||
const ActivityOperationSuccess(
|
||||
'Activité mise à jour avec succès',
|
||||
operationType: 'update',
|
||||
),
|
||||
);
|
||||
|
||||
// Reload activities
|
||||
add(LoadActivities(event.activity.tripId));
|
||||
} else {
|
||||
emit(const ActivityError('Impossible de mettre à jour l\'activité'));
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur mise à jour: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur mise à jour: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const ActivityError('Impossible de mettre à jour l\'activité'));
|
||||
}
|
||||
}
|
||||
@@ -536,13 +646,15 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
try {
|
||||
// This would require extending the Activity model to include favorites
|
||||
// For now, we'll use the voting system as a favorite system
|
||||
add(VoteForActivity(
|
||||
activityId: event.activityId,
|
||||
userId: event.userId,
|
||||
vote: 1,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur favori: $e');
|
||||
add(
|
||||
VoteForActivity(
|
||||
activityId: event.activityId,
|
||||
userId: event.userId,
|
||||
vote: 1,
|
||||
),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('activity_bloc', 'Erreur favori: $e', stackTrace);
|
||||
emit(const ActivityError('Impossible de modifier les favoris'));
|
||||
}
|
||||
}
|
||||
@@ -558,7 +670,25 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
var filtered = activities;
|
||||
|
||||
if (category != null) {
|
||||
filtered = filtered.where((a) => a.category == category).toList();
|
||||
filtered = filtered.where((a) {
|
||||
// Check exact match (internal value)
|
||||
if (a.category == category) return true;
|
||||
|
||||
// Check display name match
|
||||
// Find the enum that matches the filter category (which is a display name)
|
||||
try {
|
||||
final categoryEnum = ActivityCategory.values.firstWhere(
|
||||
(e) => e.displayName == category,
|
||||
);
|
||||
// Check if activity category matches the enum's google type or display name
|
||||
return a.category == categoryEnum.googlePlaceType ||
|
||||
a.category == categoryEnum.displayName ||
|
||||
a.category.toLowerCase() == categoryEnum.name.toLowerCase();
|
||||
} catch (_) {
|
||||
// If no matching enum found, fallback to simple string comparison
|
||||
return a.category.toLowerCase() == category.toLowerCase();
|
||||
}
|
||||
}).toList();
|
||||
}
|
||||
|
||||
if (minRating != null) {
|
||||
@@ -580,18 +710,20 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Si on est actuellement dans un état de résultats de recherche
|
||||
if (state is ActivitySearchResults) {
|
||||
final currentState = state as ActivitySearchResults;
|
||||
|
||||
|
||||
// Filtrer l'activité à retirer
|
||||
final updatedResults = currentState.searchResults
|
||||
.where((activity) => activity.id != event.activityId)
|
||||
.toList();
|
||||
|
||||
|
||||
// Émettre le nouvel état avec l'activité retirée
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
));
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,10 +732,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
RestoreCachedSearchResults event,
|
||||
Emitter<ActivityState> emit,
|
||||
) async {
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: event.searchResults,
|
||||
query: 'cached',
|
||||
isLoading: false,
|
||||
));
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: event.searchResults,
|
||||
query: 'cached',
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,15 @@ class SearchActivities extends ActivityEvent {
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [tripId, destination, category, maxResults, offset, reset, appendToExisting];
|
||||
List<Object?> get props => [
|
||||
tripId,
|
||||
destination,
|
||||
category,
|
||||
maxResults,
|
||||
offset,
|
||||
reset,
|
||||
appendToExisting,
|
||||
];
|
||||
}
|
||||
|
||||
/// Event to search activities using coordinates directly (bypasses geocoding)
|
||||
@@ -76,7 +84,16 @@ class SearchActivitiesWithCoordinates extends ActivityEvent {
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [tripId, latitude, longitude, category, maxResults, offset, reset, appendToExisting];
|
||||
List<Object?> get props => [
|
||||
tripId,
|
||||
latitude,
|
||||
longitude,
|
||||
category,
|
||||
maxResults,
|
||||
offset,
|
||||
reset,
|
||||
appendToExisting,
|
||||
];
|
||||
}
|
||||
|
||||
/// Event to search activities by text query
|
||||
@@ -95,6 +112,21 @@ class SearchActivitiesByText extends ActivityEvent {
|
||||
List<Object> get props => [tripId, destination, query];
|
||||
}
|
||||
|
||||
class UpdateActivityDate extends ActivityEvent {
|
||||
final String tripId;
|
||||
final String activityId;
|
||||
final DateTime? date;
|
||||
|
||||
const UpdateActivityDate({
|
||||
required this.tripId,
|
||||
required this.activityId,
|
||||
this.date,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [tripId, activityId, date];
|
||||
}
|
||||
|
||||
/// Event to add a single activity to the trip
|
||||
class AddActivity extends ActivityEvent {
|
||||
final Activity activity;
|
||||
@@ -147,11 +179,7 @@ class FilterActivities extends ActivityEvent {
|
||||
final double? minRating;
|
||||
final bool? showVotedOnly;
|
||||
|
||||
const FilterActivities({
|
||||
this.category,
|
||||
this.minRating,
|
||||
this.showVotedOnly,
|
||||
});
|
||||
const FilterActivities({this.category, this.minRating, this.showVotedOnly});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [category, minRating, showVotedOnly];
|
||||
@@ -228,4 +256,4 @@ class AddActivityAndRemoveFromSearch extends ActivityEvent {
|
||||
|
||||
@override
|
||||
List<Object> get props => [activity, googleActivityId];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,9 @@ class ActivityLoaded extends ActivityState {
|
||||
|
||||
/// Gets activities by category
|
||||
List<Activity> getActivitiesByCategory(String category) {
|
||||
return activities.where((activity) => activity.category == category).toList();
|
||||
return activities
|
||||
.where((activity) => activity.category == category)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Gets top rated activities
|
||||
@@ -77,14 +79,14 @@ class ActivityLoaded extends ActivityState {
|
||||
sorted.sort((a, b) {
|
||||
final aScore = a.totalVotes;
|
||||
final bScore = b.totalVotes;
|
||||
|
||||
|
||||
if (aScore != bScore) {
|
||||
return bScore.compareTo(aScore);
|
||||
}
|
||||
|
||||
|
||||
return (b.rating ?? 0).compareTo(a.rating ?? 0);
|
||||
});
|
||||
|
||||
|
||||
return sorted.take(limit).toList();
|
||||
}
|
||||
}
|
||||
@@ -94,26 +96,35 @@ class ActivitySearchResults extends ActivityState {
|
||||
final List<Activity> searchResults;
|
||||
final String query;
|
||||
final bool isLoading;
|
||||
final Activity? newlyAddedActivity;
|
||||
|
||||
const ActivitySearchResults({
|
||||
required this.searchResults,
|
||||
required this.query,
|
||||
this.isLoading = false,
|
||||
this.newlyAddedActivity,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object> get props => [searchResults, query, isLoading];
|
||||
List<Object?> get props => [
|
||||
searchResults,
|
||||
query,
|
||||
isLoading,
|
||||
newlyAddedActivity,
|
||||
];
|
||||
|
||||
/// Creates a copy with optional modifications
|
||||
ActivitySearchResults copyWith({
|
||||
List<Activity>? searchResults,
|
||||
String? query,
|
||||
bool? isLoading,
|
||||
Activity? newlyAddedActivity,
|
||||
}) {
|
||||
return ActivitySearchResults(
|
||||
searchResults: searchResults ?? this.searchResults,
|
||||
query: query ?? this.query,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
newlyAddedActivity: newlyAddedActivity ?? this.newlyAddedActivity,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -123,10 +134,7 @@ class ActivityOperationSuccess extends ActivityState {
|
||||
final String message;
|
||||
final String? operationType;
|
||||
|
||||
const ActivityOperationSuccess(
|
||||
this.message, {
|
||||
this.operationType,
|
||||
});
|
||||
const ActivityOperationSuccess(this.message, {this.operationType});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [message, operationType];
|
||||
@@ -138,11 +146,7 @@ class ActivityError extends ActivityState {
|
||||
final String? errorCode;
|
||||
final dynamic error;
|
||||
|
||||
const ActivityError(
|
||||
this.message, {
|
||||
this.errorCode,
|
||||
this.error,
|
||||
});
|
||||
const ActivityError(this.message, {this.errorCode, this.error});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [message, errorCode, error];
|
||||
@@ -153,10 +157,7 @@ class ActivityVoting extends ActivityState {
|
||||
final String activityId;
|
||||
final List<Activity> activities;
|
||||
|
||||
const ActivityVoting({
|
||||
required this.activityId,
|
||||
required this.activities,
|
||||
});
|
||||
const ActivityVoting({required this.activityId, required this.activities});
|
||||
|
||||
@override
|
||||
List<Object> get props => [activityId, activities];
|
||||
@@ -167,10 +168,7 @@ class ActivityUpdating extends ActivityState {
|
||||
final String activityId;
|
||||
final List<Activity> activities;
|
||||
|
||||
const ActivityUpdating({
|
||||
required this.activityId,
|
||||
required this.activities,
|
||||
});
|
||||
const ActivityUpdating({required this.activityId, required this.activities});
|
||||
|
||||
@override
|
||||
List<Object> get props => [activityId, activities];
|
||||
@@ -200,10 +198,7 @@ class ActivityAdded extends ActivityState {
|
||||
final Activity activity;
|
||||
final String message;
|
||||
|
||||
const ActivityAdded({
|
||||
required this.activity,
|
||||
required this.message,
|
||||
});
|
||||
const ActivityAdded({required this.activity, required this.message});
|
||||
|
||||
@override
|
||||
List<Object> get props => [activity, message];
|
||||
@@ -214,10 +209,7 @@ class ActivityDeleted extends ActivityState {
|
||||
final String activityId;
|
||||
final String message;
|
||||
|
||||
const ActivityDeleted({
|
||||
required this.activityId,
|
||||
required this.message,
|
||||
});
|
||||
const ActivityDeleted({required this.activityId, required this.message});
|
||||
|
||||
@override
|
||||
List<Object> get props => [activityId, message];
|
||||
@@ -237,4 +229,4 @@ class ActivityVoteRecorded extends ActivityState {
|
||||
|
||||
@override
|
||||
List<Object> get props => [activityId, vote, userId];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,19 +25,28 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../repositories/auth_repository.dart';
|
||||
import 'auth_event.dart';
|
||||
import 'auth_state.dart';
|
||||
import '../../services/notification_service.dart';
|
||||
import '../../services/analytics_service.dart';
|
||||
|
||||
/// BLoC for managing authentication state and operations.
|
||||
class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
/// Repository for authentication operations.
|
||||
final AuthRepository _authRepository;
|
||||
final NotificationService _notificationService;
|
||||
final AnalyticsService _analyticsService;
|
||||
|
||||
/// Creates an [AuthBloc] with the provided [authRepository].
|
||||
///
|
||||
/// The bloc starts in the [AuthInitial] state and registers event handlers
|
||||
/// for all supported authentication events.
|
||||
AuthBloc({required AuthRepository authRepository})
|
||||
: _authRepository = authRepository,
|
||||
super(AuthInitial()) {
|
||||
AuthBloc({
|
||||
required AuthRepository authRepository,
|
||||
NotificationService? notificationService,
|
||||
AnalyticsService? analyticsService,
|
||||
}) : _authRepository = authRepository,
|
||||
_notificationService = notificationService ?? NotificationService(),
|
||||
_analyticsService = analyticsService ?? AnalyticsService(),
|
||||
super(AuthInitial()) {
|
||||
on<AuthCheckRequested>(_onAuthCheckRequested);
|
||||
on<AuthSignInRequested>(_onSignInRequested);
|
||||
on<AuthSignUpRequested>(_onSignUpRequested);
|
||||
@@ -69,6 +78,9 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
|
||||
if (user != null) {
|
||||
// Save FCM Token on auto-login
|
||||
await _notificationService.saveTokenToFirestore(user.id!);
|
||||
await _analyticsService.setUserId(user.id);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(AuthUnauthenticated());
|
||||
@@ -77,7 +89,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
emit(AuthUnauthenticated());
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,12 +110,19 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
|
||||
if (user != null) {
|
||||
// Save FCM Token
|
||||
await NotificationService().saveTokenToFirestore(user.id!);
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'login',
|
||||
parameters: {'method': 'email'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(const AuthError(message: 'Invalid email or password'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,12 +146,19 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
|
||||
if (user != null) {
|
||||
// Save FCM Token
|
||||
await NotificationService().saveTokenToFirestore(user.id!);
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'sign_up',
|
||||
parameters: {'method': 'email'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(const AuthError(message: 'Failed to create account'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +176,13 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
final user = await _authRepository.signInWithGoogle();
|
||||
|
||||
if (user != null) {
|
||||
// Save FCM Token
|
||||
await NotificationService().saveTokenToFirestore(user.id!);
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'login',
|
||||
parameters: {'method': 'google'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(
|
||||
@@ -160,7 +193,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,12 +211,17 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
|
||||
if (user != null) {
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'sign_up',
|
||||
parameters: {'method': 'google'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(const AuthError(message: 'Failed to create account with Google'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,12 +239,17 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
|
||||
if (user != null) {
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'sign_up',
|
||||
parameters: {'method': 'apple'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(const AuthError(message: 'Failed to create account with Apple'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,6 +267,13 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
final user = await _authRepository.signInWithApple();
|
||||
|
||||
if (user != null) {
|
||||
// Save FCM Token
|
||||
await NotificationService().saveTokenToFirestore(user.id!);
|
||||
await _analyticsService.setUserId(user.id);
|
||||
await _analyticsService.logEvent(
|
||||
name: 'login',
|
||||
parameters: {'method': 'apple'},
|
||||
);
|
||||
emit(AuthAuthenticated(user: user));
|
||||
} else {
|
||||
emit(
|
||||
@@ -234,7 +284,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +296,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
Emitter<AuthState> emit,
|
||||
) async {
|
||||
await _authRepository.signOut();
|
||||
await _analyticsService.setUserId(null); // Clear user ID
|
||||
emit(AuthUnauthenticated());
|
||||
}
|
||||
|
||||
@@ -261,7 +312,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
await _authRepository.resetPassword(event.email);
|
||||
emit(AuthPasswordResetSent(email: event.email));
|
||||
} catch (e) {
|
||||
emit(AuthError(message: e.toString()));
|
||||
emit(AuthError(message: e.toString().replaceAll('Exception: ', '')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
/// balanceRepository: balanceRepository,
|
||||
/// expenseRepository: expenseRepository,
|
||||
/// );
|
||||
///
|
||||
///
|
||||
/// // Load balances for a group
|
||||
/// balanceBloc.add(LoadGroupBalances('groupId123'));
|
||||
///
|
||||
///
|
||||
/// // Mark a settlement as completed
|
||||
/// balanceBloc.add(MarkSettlementAsCompleted(
|
||||
/// groupId: 'groupId123',
|
||||
@@ -32,6 +32,7 @@
|
||||
/// ));
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../repositories/balance_repository.dart';
|
||||
import '../../repositories/expense_repository.dart';
|
||||
@@ -46,10 +47,10 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
final ErrorService _errorService;
|
||||
|
||||
/// Constructor for BalanceBloc.
|
||||
///
|
||||
///
|
||||
/// Initializes the bloc with required repositories and optional services.
|
||||
/// Sets up event handlers for balance-related operations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [balanceRepository]: Repository for balance data operations
|
||||
/// [expenseRepository]: Repository for expense data operations
|
||||
@@ -61,7 +62,12 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
BalanceService? balanceService,
|
||||
ErrorService? errorService,
|
||||
}) : _balanceRepository = balanceRepository,
|
||||
_balanceService = balanceService ?? BalanceService(balanceRepository: balanceRepository, expenseRepository: expenseRepository),
|
||||
_balanceService =
|
||||
balanceService ??
|
||||
BalanceService(
|
||||
balanceRepository: balanceRepository,
|
||||
expenseRepository: expenseRepository,
|
||||
),
|
||||
_errorService = errorService ?? ErrorService(),
|
||||
super(BalanceInitial()) {
|
||||
on<LoadGroupBalances>(_onLoadGroupBalance);
|
||||
@@ -70,11 +76,11 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadGroupBalances] events.
|
||||
///
|
||||
///
|
||||
/// Loads and calculates user balances for a specific group along with
|
||||
/// optimal settlement recommendations. This provides a complete overview
|
||||
/// of who owes money to whom and the most efficient payment strategy.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The LoadGroupBalances event containing the group ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -83,30 +89,38 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
Emitter<BalanceState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(BalanceLoading());
|
||||
|
||||
// Emit empty state initially to avoid infinite spinner
|
||||
emit(const GroupBalancesLoaded(balances: [], settlements: []));
|
||||
|
||||
// Calculate group user balances
|
||||
final userBalances = await _balanceRepository.calculateGroupUserBalances(event.groupId);
|
||||
|
||||
final userBalances = await _balanceRepository.calculateGroupUserBalances(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
// Calculate optimal settlements
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(event.groupId);
|
||||
|
||||
emit(GroupBalancesLoaded(
|
||||
balances: userBalances,
|
||||
settlements: settlements,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceBloc', 'Error loading balance: $e');
|
||||
emit(BalanceError(e.toString()));
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
emit(
|
||||
GroupBalancesLoaded(balances: userBalances, settlements: settlements),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'BalanceBloc',
|
||||
'Error loading balance: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const BalanceError('Impossible de charger la balance'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [RefreshBalance] events.
|
||||
///
|
||||
///
|
||||
/// Refreshes the balance data for a group while trying to maintain the current
|
||||
/// state when possible to provide a smoother user experience. Only shows loading
|
||||
/// state if there's no existing balance data.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The RefreshBalance event containing the group ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -119,29 +133,36 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
if (state is! GroupBalancesLoaded) {
|
||||
emit(BalanceLoading());
|
||||
}
|
||||
|
||||
|
||||
// Calculate group user balances
|
||||
final userBalances = await _balanceRepository.calculateGroupUserBalances(event.groupId);
|
||||
|
||||
final userBalances = await _balanceRepository.calculateGroupUserBalances(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
// Calculate optimal settlements
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(event.groupId);
|
||||
|
||||
emit(GroupBalancesLoaded(
|
||||
balances: userBalances,
|
||||
settlements: settlements,
|
||||
));
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceBloc', 'Error refreshing balance: $e');
|
||||
emit(BalanceError(e.toString()));
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
emit(
|
||||
GroupBalancesLoaded(balances: userBalances, settlements: settlements),
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'BalanceBloc',
|
||||
'Error refreshing balance: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const BalanceError('Impossible de rafraîchir la balance'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [MarkSettlementAsCompleted] events.
|
||||
///
|
||||
///
|
||||
/// Records a settlement transaction between two users, marking that
|
||||
/// a debt has been paid. This updates the balance calculations and
|
||||
/// automatically refreshes the group balance data to reflect the change.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The MarkSettlementAsCompleted event containing settlement details
|
||||
/// [emit]: State emitter function
|
||||
@@ -156,14 +177,20 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
toUserId: event.toUserId,
|
||||
amount: event.amount,
|
||||
);
|
||||
|
||||
|
||||
emit(const BalanceOperationSuccess('Settlement marked as completed'));
|
||||
|
||||
|
||||
// Reload balance after settlement
|
||||
add(RefreshBalance(event.groupId));
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceBloc', 'Error marking settlement: $e');
|
||||
emit(BalanceError(e.toString()));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'BalanceBloc',
|
||||
'Error marking settlement: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(
|
||||
const BalanceError('Impossible de marquer le règlement comme terminé'),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'expense_event.dart';
|
||||
import 'expense_state.dart';
|
||||
|
||||
/// BLoC for managing expense operations and state.
|
||||
///
|
||||
///
|
||||
/// This BLoC handles expense-related operations including loading expenses,
|
||||
/// creating new expenses, updating existing ones, deleting expenses, and
|
||||
/// managing expense splits. It coordinates with the expense repository and
|
||||
@@ -15,18 +15,18 @@ import 'expense_state.dart';
|
||||
class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
/// Repository for expense data operations.
|
||||
final ExpenseRepository _expenseRepository;
|
||||
|
||||
|
||||
/// Service for expense business logic and validation.
|
||||
final ExpenseService _expenseService;
|
||||
|
||||
|
||||
/// Service for error handling and logging.
|
||||
final ErrorService _errorService;
|
||||
|
||||
|
||||
/// Subscription to the expenses stream for real-time updates.
|
||||
StreamSubscription? _expensesSubscription;
|
||||
|
||||
/// Creates a new [ExpenseBloc] with required dependencies.
|
||||
///
|
||||
///
|
||||
/// [expenseRepository] is required for data operations.
|
||||
/// [expenseService] and [errorService] have default implementations if not provided.
|
||||
ExpenseBloc({
|
||||
@@ -34,10 +34,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
ExpenseService? expenseService,
|
||||
ErrorService? errorService,
|
||||
}) : _expenseRepository = expenseRepository,
|
||||
_expenseService = expenseService ?? ExpenseService(expenseRepository: expenseRepository),
|
||||
_expenseService =
|
||||
expenseService ??
|
||||
ExpenseService(expenseRepository: expenseRepository),
|
||||
_errorService = errorService ?? ErrorService(),
|
||||
super(ExpenseInitial()) {
|
||||
|
||||
on<LoadExpensesByGroup>(_onLoadExpensesByGroup);
|
||||
on<ExpensesUpdated>(_onExpensesUpdated);
|
||||
on<CreateExpense>(_onCreateExpense);
|
||||
@@ -48,7 +49,7 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadExpensesByGroup] events.
|
||||
///
|
||||
///
|
||||
/// Sets up a stream subscription to receive real-time updates for expenses
|
||||
/// in the specified group. Cancels any existing subscription before creating a new one.
|
||||
Future<void> _onLoadExpensesByGroup(
|
||||
@@ -56,27 +57,30 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
Emitter<ExpenseState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(ExpenseLoading());
|
||||
|
||||
// Emit empty state initially to avoid infinite spinner
|
||||
// The stream will update with actual data when available
|
||||
emit(const ExpensesLoaded(expenses: []));
|
||||
|
||||
await _expensesSubscription?.cancel();
|
||||
|
||||
|
||||
_expensesSubscription = _expenseRepository
|
||||
.getExpensesStream(event.groupId)
|
||||
.listen(
|
||||
(expenses) => add(ExpensesUpdated(expenses)),
|
||||
onError: (error) => add(ExpensesUpdated([], error: error.toString())),
|
||||
onError: (error) =>
|
||||
add(ExpensesUpdated([], error: error.toString())),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error loading expenses: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible de charger les dépenses'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [ExpensesUpdated] events.
|
||||
///
|
||||
///
|
||||
/// Processes real-time updates from the expense stream, either emitting
|
||||
/// the updated expense list or an error state if the stream encountered an error.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The ExpensesUpdated event containing expenses or error information
|
||||
/// [emit]: State emitter function
|
||||
@@ -92,11 +96,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
}
|
||||
|
||||
/// Handles [CreateExpense] events.
|
||||
///
|
||||
///
|
||||
/// Creates a new expense with validation and optional receipt image upload.
|
||||
/// Uses the expense service to handle business logic and validation,
|
||||
/// including currency conversion and split calculations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The CreateExpense event containing expense data and optional receipt
|
||||
/// [emit]: State emitter function
|
||||
@@ -105,20 +109,23 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
Emitter<ExpenseState> emit,
|
||||
) async {
|
||||
try {
|
||||
await _expenseService.createExpenseWithValidation(event.expense, event.receiptImage);
|
||||
await _expenseService.createExpenseWithValidation(
|
||||
event.expense,
|
||||
event.receiptImage,
|
||||
);
|
||||
emit(const ExpenseOperationSuccess('Expense created successfully'));
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error creating expense: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible de créer la dépense'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [UpdateExpense] events.
|
||||
///
|
||||
///
|
||||
/// Updates an existing expense with validation and optional new receipt image.
|
||||
/// Uses the expense service to handle business logic, validation, and
|
||||
/// recalculation of splits if expense details change.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The UpdateExpense event containing updated expense data and optional new receipt
|
||||
/// [emit]: State emitter function
|
||||
@@ -127,19 +134,22 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
Emitter<ExpenseState> emit,
|
||||
) async {
|
||||
try {
|
||||
await _expenseService.updateExpenseWithValidation(event.expense, event.newReceiptImage);
|
||||
await _expenseService.updateExpenseWithValidation(
|
||||
event.expense,
|
||||
event.newReceiptImage,
|
||||
);
|
||||
emit(const ExpenseOperationSuccess('Expense updated successfully'));
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error updating expense: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible de mettre à jour la dépense'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [DeleteExpense] events.
|
||||
///
|
||||
///
|
||||
/// Permanently deletes an expense from the database. This action
|
||||
/// cannot be undone and will affect group balance calculations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The DeleteExpense event containing the expense ID to delete
|
||||
/// [emit]: State emitter function
|
||||
@@ -152,16 +162,16 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
emit(const ExpenseOperationSuccess('Expense deleted successfully'));
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error deleting expense: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible de supprimer la dépense'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [MarkSplitAsPaid] events.
|
||||
///
|
||||
///
|
||||
/// Marks a user's portion of an expense split as paid, updating the
|
||||
/// expense's split information and affecting balance calculations.
|
||||
/// This helps track who has settled their portion of shared expenses.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The MarkSplitAsPaid event containing expense ID and user ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -174,16 +184,16 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
emit(const ExpenseOperationSuccess('Payment marked as completed'));
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error marking split as paid: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible de marquer comme payé'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [ArchiveExpense] events.
|
||||
///
|
||||
///
|
||||
/// Archives an expense, moving it out of the active expense list
|
||||
/// while preserving it for historical records and audit purposes.
|
||||
/// Archived expenses are not included in current balance calculations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The ArchiveExpense event containing the expense ID to archive
|
||||
/// [emit]: State emitter function
|
||||
@@ -196,12 +206,12 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
emit(const ExpenseOperationSuccess('Expense archived successfully'));
|
||||
} catch (e) {
|
||||
_errorService.logError('ExpenseBloc', 'Error archiving expense: $e');
|
||||
emit(ExpenseError(e.toString()));
|
||||
emit(const ExpenseError('Impossible d\'archiver la dépense'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans up resources when the bloc is closed.
|
||||
///
|
||||
///
|
||||
/// Cancels the expense stream subscription to prevent memory leaks
|
||||
/// and ensure proper disposal of resources.
|
||||
@override
|
||||
@@ -209,4 +219,4 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
_expensesSubscription?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,10 @@
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final groupBloc = GroupBloc(groupRepository);
|
||||
///
|
||||
///
|
||||
/// // Load groups for a user
|
||||
/// groupBloc.add(LoadGroupsByUserId('userId123'));
|
||||
///
|
||||
///
|
||||
/// // Create a new group with members
|
||||
/// groupBloc.add(CreateGroupWithMembers(
|
||||
/// group: newGroup,
|
||||
@@ -32,6 +32,7 @@
|
||||
/// ));
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
@@ -44,18 +45,18 @@ import '../../models/group.dart';
|
||||
class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
/// Repository for group data operations
|
||||
final GroupRepository _repository;
|
||||
|
||||
|
||||
/// Subscription to group stream for real-time updates
|
||||
StreamSubscription? _groupsSubscription;
|
||||
|
||||
|
||||
/// Service for error handling and logging
|
||||
final _errorService = ErrorService();
|
||||
|
||||
/// Constructor for GroupBloc.
|
||||
///
|
||||
///
|
||||
/// Initializes the bloc with the group repository and sets up event handlers
|
||||
/// for all group-related operations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [_repository]: Repository for group data operations
|
||||
GroupBloc(this._repository) : super(GroupInitial()) {
|
||||
@@ -71,39 +72,45 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadGroupsByUserId] events.
|
||||
///
|
||||
///
|
||||
/// Loads all groups for a specific user with real-time updates via stream subscription.
|
||||
/// Cancels any existing subscription before creating a new one to prevent memory leaks.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The LoadGroupsByUserId event containing the user ID
|
||||
/// [emit]: State emitter function
|
||||
Future<void> _onLoadGroupsByUserId(
|
||||
LoadGroupsByUserId event,
|
||||
Emitter<GroupState> emit,
|
||||
) async {
|
||||
) async {
|
||||
try {
|
||||
emit(GroupLoading());
|
||||
await _groupsSubscription?.cancel();
|
||||
_groupsSubscription = _repository.getGroupsByUserId(event.userId).listen(
|
||||
(groups) {
|
||||
add(_GroupsUpdated(groups));
|
||||
},
|
||||
onError: (error) {
|
||||
add(_GroupsUpdated([], error: error.toString()));
|
||||
},
|
||||
);
|
||||
_groupsSubscription = _repository
|
||||
.getGroupsByUserId(event.userId)
|
||||
.listen(
|
||||
(groups) {
|
||||
add(_GroupsUpdated(groups));
|
||||
},
|
||||
onError: (error) {
|
||||
add(_GroupsUpdated([], error: error.toString()));
|
||||
},
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
emit(GroupError(e.toString()));
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error loading groups: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de charger les groupes'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [_GroupsUpdated] events.
|
||||
///
|
||||
///
|
||||
/// Processes real-time updates from the group stream, either emitting
|
||||
/// the updated group list or an error state if the stream encountered an error.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The _GroupsUpdated event containing groups or error information
|
||||
/// [emit]: State emitter function
|
||||
@@ -120,10 +127,10 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadGroupsByTrip] events.
|
||||
///
|
||||
///
|
||||
/// Loads the group associated with a specific trip. Since each trip typically
|
||||
/// has one primary group, this returns a single group or an empty list.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The LoadGroupsByTrip event containing the trip ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -139,16 +146,21 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
} else {
|
||||
emit(const GroupsLoaded([]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(GroupError(e.toString()));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error loading group by trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de charger le groupe du voyage'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [CreateGroup] events.
|
||||
///
|
||||
///
|
||||
/// Creates a new group without any initial members. The group creator
|
||||
/// can add members later using AddMemberToGroup events.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The CreateGroup event containing the group data
|
||||
/// [emit]: State emitter function
|
||||
@@ -164,17 +176,22 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
);
|
||||
emit(GroupCreated(groupId: groupId));
|
||||
emit(const GroupOperationSuccess('Group created successfully'));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during creation: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error creating group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de créer le groupe'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [CreateGroupWithMembers] events.
|
||||
///
|
||||
///
|
||||
/// Creates a new group with an initial set of members. This is useful
|
||||
/// for setting up complete groups in one operation, such as when
|
||||
/// planning a trip with known participants.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The CreateGroupWithMembers event containing group data and member list
|
||||
/// [emit]: State emitter function
|
||||
@@ -189,16 +206,21 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
members: event.members,
|
||||
);
|
||||
emit(GroupCreated(groupId: groupId));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during creation: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error creating group with members: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de créer le groupe'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [AddMemberToGroup] events.
|
||||
///
|
||||
///
|
||||
/// Adds a new member to an existing group. The member will be able to
|
||||
/// participate in group expenses and access group features.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The AddMemberToGroup event containing group ID and member data
|
||||
/// [emit]: State emitter function
|
||||
@@ -209,16 +231,21 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
try {
|
||||
await _repository.addMember(event.groupId, event.member);
|
||||
emit(const GroupOperationSuccess('Member added'));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during addition: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error adding member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible d\'ajouter le membre'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [RemoveMemberFromGroup] events.
|
||||
///
|
||||
///
|
||||
/// Removes a member from a group. This will affect expense calculations
|
||||
/// and the member will no longer have access to group features.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The RemoveMemberFromGroup event containing group ID and user ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -229,16 +256,21 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
try {
|
||||
await _repository.removeMember(event.groupId, event.userId);
|
||||
emit(const GroupOperationSuccess('Member removed'));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during removal: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error removing member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de supprimer le membre'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [UpdateGroup] events.
|
||||
///
|
||||
///
|
||||
/// Updates group information such as name, description, or settings.
|
||||
/// Member lists are managed through separate add/remove member events.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The UpdateGroup event containing group ID and updated group data
|
||||
/// [emit]: State emitter function
|
||||
@@ -249,16 +281,21 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
try {
|
||||
await _repository.updateGroup(event.groupId, event.group);
|
||||
emit(const GroupOperationSuccess('Group updated'));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during update: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error updating group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de mettre à jour le groupe'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [DeleteGroup] events.
|
||||
///
|
||||
///
|
||||
/// Permanently deletes a group and all associated data. This action
|
||||
/// cannot be undone and will affect all group members and expenses.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The DeleteGroup event containing the trip ID to delete
|
||||
/// [emit]: State emitter function
|
||||
@@ -269,13 +306,18 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
try {
|
||||
await _repository.deleteGroup(event.tripId);
|
||||
emit(const GroupOperationSuccess('Group deleted'));
|
||||
} catch (e) {
|
||||
emit(GroupError('Error during deletion: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupBloc',
|
||||
'Error deleting group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(const GroupError('Impossible de supprimer le groupe'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans up resources when the bloc is closed.
|
||||
///
|
||||
///
|
||||
/// Cancels the group stream subscription to prevent memory leaks
|
||||
/// and ensure proper disposal of resources.
|
||||
@override
|
||||
@@ -286,18 +328,18 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
|
||||
}
|
||||
|
||||
/// Private event for handling real-time group updates from streams.
|
||||
///
|
||||
///
|
||||
/// This internal event is used to process updates from the group stream
|
||||
/// subscription and emit appropriate states based on the received data.
|
||||
class _GroupsUpdated extends GroupEvent {
|
||||
/// List of groups received from the stream
|
||||
final List<Group> groups;
|
||||
|
||||
|
||||
/// Error message if the stream encountered an error
|
||||
final String? error;
|
||||
|
||||
/// Creates a _GroupsUpdated event.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [groups]: List of groups from the stream update
|
||||
/// [error]: Optional error message if stream failed
|
||||
@@ -305,4 +347,4 @@ class _GroupsUpdated extends GroupEvent {
|
||||
|
||||
@override
|
||||
List<Object?> get props => [groups, error];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final messageBloc = MessageBloc();
|
||||
///
|
||||
///
|
||||
/// // Load messages for a group
|
||||
/// messageBloc.add(LoadMessages('groupId123'));
|
||||
///
|
||||
///
|
||||
/// // Send a message
|
||||
/// messageBloc.add(SendMessage(
|
||||
/// groupId: 'groupId123',
|
||||
@@ -30,7 +30,7 @@
|
||||
/// senderId: 'userId123',
|
||||
/// senderName: 'John Doe',
|
||||
/// ));
|
||||
///
|
||||
///
|
||||
/// // React to a message
|
||||
/// messageBloc.add(ReactToMessage(
|
||||
/// groupId: 'groupId123',
|
||||
@@ -40,6 +40,7 @@
|
||||
/// ));
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../models/message.dart';
|
||||
@@ -52,23 +53,23 @@ import 'message_state.dart';
|
||||
class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
/// Service for message operations and business logic
|
||||
final MessageService _messageService;
|
||||
|
||||
|
||||
/// Subscription to message stream for real-time updates
|
||||
StreamSubscription<List<Message>>? _messagesSubscription;
|
||||
|
||||
/// Constructor for MessageBloc.
|
||||
///
|
||||
///
|
||||
/// Initializes the bloc with an optional message service. If no service is provided,
|
||||
/// creates a default MessageService with MessageRepository. Sets up event handlers
|
||||
/// for all message-related operations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [messageService]: Optional service for message operations (auto-created if null)
|
||||
MessageBloc({MessageService? messageService})
|
||||
: _messageService = messageService ?? MessageService(
|
||||
messageRepository: MessageRepository(),
|
||||
),
|
||||
super(MessageInitial()) {
|
||||
: _messageService =
|
||||
messageService ??
|
||||
MessageService(messageRepository: MessageRepository()),
|
||||
super(MessageInitial()) {
|
||||
on<LoadMessages>(_onLoadMessages);
|
||||
on<SendMessage>(_onSendMessage);
|
||||
on<DeleteMessage>(_onDeleteMessage);
|
||||
@@ -79,10 +80,10 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadMessages] events.
|
||||
///
|
||||
///
|
||||
/// Loads messages for a specific group with real-time updates via stream subscription.
|
||||
/// Cancels any existing subscription before creating a new one to prevent memory leaks.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The LoadMessages event containing the group ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -101,31 +102,28 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
add(_MessagesUpdated(messages: messages, groupId: event.groupId));
|
||||
},
|
||||
onError: (error) {
|
||||
add(_MessagesError('Error loading messages: $error'));
|
||||
add(const _MessagesError('Impossible de charger les messages'));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Handles [_MessagesUpdated] events.
|
||||
///
|
||||
///
|
||||
/// Processes real-time updates from the message stream, emitting the
|
||||
/// updated message list with the associated group ID.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The _MessagesUpdated event containing messages and group ID
|
||||
/// [emit]: State emitter function
|
||||
void _onMessagesUpdated(
|
||||
_MessagesUpdated event,
|
||||
Emitter<MessageState> emit,
|
||||
) {
|
||||
void _onMessagesUpdated(_MessagesUpdated event, Emitter<MessageState> emit) {
|
||||
emit(MessagesLoaded(messages: event.messages, groupId: event.groupId));
|
||||
}
|
||||
|
||||
/// Handles [SendMessage] events.
|
||||
///
|
||||
///
|
||||
/// Sends a new message to a group chat. The stream subscription will
|
||||
/// automatically update the UI with the new message, so no state is emitted here.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The SendMessage event containing message details
|
||||
/// [emit]: State emitter function
|
||||
@@ -142,15 +140,15 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
senderName: event.senderName,
|
||||
);
|
||||
} catch (e) {
|
||||
emit(MessageError('Error sending message: $e'));
|
||||
emit(const MessageError('Impossible d\'envoyer le message'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [DeleteMessage] events.
|
||||
///
|
||||
///
|
||||
/// Deletes a message from the group chat. The Firestore stream will
|
||||
/// automatically update the UI, so no state is emitted here unless there's an error.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The DeleteMessage event containing group ID and message ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -166,15 +164,15 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
messageId: event.messageId,
|
||||
);
|
||||
} catch (e) {
|
||||
emit(MessageError('Error deleting message: $e'));
|
||||
emit(const MessageError('Impossible de supprimer le message'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [UpdateMessage] events.
|
||||
///
|
||||
///
|
||||
/// Updates/edits an existing message in the group chat. The Firestore stream will
|
||||
/// automatically update the UI with the edited message, so no state is emitted here.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The UpdateMessage event containing message ID and new text
|
||||
/// [emit]: State emitter function
|
||||
@@ -191,15 +189,15 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
newText: event.newText,
|
||||
);
|
||||
} catch (e) {
|
||||
emit(MessageError('Error updating message: $e'));
|
||||
emit(const MessageError('Impossible de modifier le message'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [ReactToMessage] events.
|
||||
///
|
||||
///
|
||||
/// Adds an emoji reaction to a message. The Firestore stream will
|
||||
/// automatically update the UI with the new reaction, so no state is emitted here.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The ReactToMessage event containing message ID, user ID, and reaction
|
||||
/// [emit]: State emitter function
|
||||
@@ -217,15 +215,15 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
reaction: event.reaction,
|
||||
);
|
||||
} catch (e) {
|
||||
emit(MessageError('Error adding reaction: $e'));
|
||||
emit(const MessageError('Impossible d\'ajouter la réaction'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [RemoveReaction] events.
|
||||
///
|
||||
///
|
||||
/// Removes a user's reaction from a message. The Firestore stream will
|
||||
/// automatically update the UI with the removed reaction, so no state is emitted here.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The RemoveReaction event containing message ID and user ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -242,12 +240,12 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
userId: event.userId,
|
||||
);
|
||||
} catch (e) {
|
||||
emit(MessageError('Error removing reaction: $e'));
|
||||
emit(const MessageError('Impossible de supprimer la réaction'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans up resources when the bloc is closed.
|
||||
///
|
||||
///
|
||||
/// Cancels the message stream subscription to prevent memory leaks
|
||||
/// and ensure proper disposal of resources.
|
||||
@override
|
||||
@@ -258,32 +256,29 @@ class MessageBloc extends Bloc<MessageEvent, MessageState> {
|
||||
}
|
||||
|
||||
/// Private event for handling real-time message updates from streams.
|
||||
///
|
||||
///
|
||||
/// This internal event is used to process updates from the message stream
|
||||
/// subscription and emit appropriate states based on the received data.
|
||||
class _MessagesUpdated extends MessageEvent {
|
||||
/// List of messages received from the stream
|
||||
final List<Message> messages;
|
||||
|
||||
|
||||
/// Group ID associated with the messages
|
||||
final String groupId;
|
||||
|
||||
/// Creates a _MessagesUpdated event.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [messages]: List of messages from the stream update
|
||||
/// [groupId]: ID of the group these messages belong to
|
||||
const _MessagesUpdated({
|
||||
required this.messages,
|
||||
required this.groupId,
|
||||
});
|
||||
const _MessagesUpdated({required this.messages, required this.groupId});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [messages, groupId];
|
||||
}
|
||||
|
||||
/// Private event for handling message stream errors.
|
||||
///
|
||||
///
|
||||
/// This internal event is used to process errors from the message stream
|
||||
/// subscription and emit appropriate error states.
|
||||
class _MessagesError extends MessageEvent {
|
||||
@@ -291,7 +286,7 @@ class _MessagesError extends MessageEvent {
|
||||
final String error;
|
||||
|
||||
/// Creates a _MessagesError event.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [error]: Error message from the stream failure
|
||||
const _MessagesError(this.error);
|
||||
|
||||
@@ -22,43 +22,46 @@
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final tripBloc = TripBloc(tripRepository);
|
||||
///
|
||||
///
|
||||
/// // Load trips for a user
|
||||
/// tripBloc.add(LoadTripsByUserId(userId: 'userId123'));
|
||||
///
|
||||
///
|
||||
/// // Create a new trip
|
||||
/// tripBloc.add(TripCreateRequested(trip: newTrip));
|
||||
///
|
||||
///
|
||||
/// // Update a trip
|
||||
/// tripBloc.add(TripUpdateRequested(trip: updatedTrip));
|
||||
///
|
||||
///
|
||||
/// // Delete a trip
|
||||
/// tripBloc.add(TripDeleteRequested(tripId: 'tripId456'));
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/models/trip.dart';
|
||||
import 'trip_event.dart';
|
||||
import 'trip_state.dart';
|
||||
import '../../repositories/trip_repository.dart';
|
||||
import '../../services/error_service.dart';
|
||||
|
||||
/// BLoC that manages trip-related operations and state.
|
||||
class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
/// Repository for trip data operations
|
||||
final TripRepository _repository;
|
||||
|
||||
final _errorService = ErrorService();
|
||||
|
||||
/// Subscription to trip stream for real-time updates
|
||||
StreamSubscription? _tripsSubscription;
|
||||
|
||||
|
||||
/// Current user ID for automatic list refreshing after operations
|
||||
String? _currentUserId;
|
||||
|
||||
/// Constructor for TripBloc.
|
||||
///
|
||||
///
|
||||
/// Initializes the bloc with the trip repository and sets up event handlers
|
||||
/// for all trip-related operations.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [_repository]: Repository for trip data operations
|
||||
TripBloc(this._repository) : super(TripInitial()) {
|
||||
@@ -71,11 +74,11 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
}
|
||||
|
||||
/// Handles [LoadTripsByUserId] events.
|
||||
///
|
||||
///
|
||||
/// Loads all trips for a specific user with real-time updates via stream subscription.
|
||||
/// Stores the user ID for future automatic refreshing after operations and cancels
|
||||
/// any existing subscription to prevent memory leaks.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The LoadTripsByUserId event containing the user ID
|
||||
/// [emit]: State emitter function
|
||||
@@ -84,41 +87,54 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
Emitter<TripState> emit,
|
||||
) async {
|
||||
emit(TripLoading());
|
||||
|
||||
|
||||
_currentUserId = event.userId;
|
||||
await _tripsSubscription?.cancel();
|
||||
|
||||
_tripsSubscription = _repository.getTripsByUserId(event.userId).listen(
|
||||
(trips) {
|
||||
add(_TripsUpdated(trips));
|
||||
},
|
||||
onError: (error) {
|
||||
emit(TripError(error.toString()));
|
||||
},
|
||||
);
|
||||
_tripsSubscription = _repository
|
||||
.getTripsByUserId(event.userId)
|
||||
.listen(
|
||||
(trips) {
|
||||
add(_TripsUpdated(trips));
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripBloc',
|
||||
'Error loading trips: $error',
|
||||
stackTrace,
|
||||
);
|
||||
add(
|
||||
const _TripsUpdated(
|
||||
[],
|
||||
error: 'Impossible de charger les voyages',
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Handles [_TripsUpdated] events.
|
||||
///
|
||||
///
|
||||
/// Processes real-time updates from the trip stream and emits the
|
||||
/// updated trip list to the UI.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The _TripsUpdated event containing the updated trip list
|
||||
/// [emit]: State emitter function
|
||||
void _onTripsUpdated(
|
||||
_TripsUpdated event,
|
||||
Emitter<TripState> emit,
|
||||
) {
|
||||
emit(TripLoaded(event.trips));
|
||||
void _onTripsUpdated(_TripsUpdated event, Emitter<TripState> emit) {
|
||||
if (event.error != null) {
|
||||
emit(TripError(event.error!));
|
||||
} else {
|
||||
emit(TripLoaded(event.trips));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [TripCreateRequested] events.
|
||||
///
|
||||
///
|
||||
/// Creates a new trip and automatically refreshes the user's trip list
|
||||
/// to show the newly created trip. Includes a delay to allow the creation
|
||||
/// to complete before refreshing.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The TripCreateRequested event containing the trip data
|
||||
/// [emit]: State emitter function
|
||||
@@ -128,27 +144,27 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
) async {
|
||||
try {
|
||||
emit(TripLoading());
|
||||
|
||||
|
||||
final tripId = await _repository.createTrip(event.trip);
|
||||
|
||||
|
||||
emit(TripCreated(tripId: tripId));
|
||||
|
||||
|
||||
await Future.delayed(const Duration(milliseconds: 800));
|
||||
if (_currentUserId != null) {
|
||||
add(LoadTripsByUserId(userId: _currentUserId!));
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
emit(TripError('Error during creation: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('TripBloc', 'Error creating trip: $e', stackTrace);
|
||||
emit(const TripError('Impossible de créer le voyage'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [TripUpdateRequested] events.
|
||||
///
|
||||
///
|
||||
/// Updates an existing trip and automatically refreshes the user's trip list
|
||||
/// to show the updated information. Includes a delay to allow the update
|
||||
/// to complete before refreshing.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The TripUpdateRequested event containing the updated trip data
|
||||
/// [emit]: State emitter function
|
||||
@@ -163,18 +179,18 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
if (_currentUserId != null) {
|
||||
add(LoadTripsByUserId(userId: _currentUserId!));
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
emit(TripError('Error during update: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('TripBloc', 'Error updating trip: $e', stackTrace);
|
||||
emit(const TripError('Impossible de mettre à jour le voyage'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [TripDeleteRequested] events.
|
||||
///
|
||||
///
|
||||
/// Deletes a trip and automatically refreshes the user's trip list
|
||||
/// to remove the deleted trip from the UI. Includes a delay to allow
|
||||
/// the deletion to complete before refreshing.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The TripDeleteRequested event containing the trip ID to delete
|
||||
/// [emit]: State emitter function
|
||||
@@ -184,39 +200,36 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
) async {
|
||||
try {
|
||||
await _repository.deleteTrip(event.tripId);
|
||||
|
||||
|
||||
emit(const TripOperationSuccess('Trip deleted successfully'));
|
||||
|
||||
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
if (_currentUserId != null) {
|
||||
add(LoadTripsByUserId(userId: _currentUserId!));
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
emit(TripError('Error during deletion: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('TripBloc', 'Error deleting trip: $e', stackTrace);
|
||||
emit(const TripError('Impossible de supprimer le voyage'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles [ResetTrips] events.
|
||||
///
|
||||
///
|
||||
/// Resets the trip state to initial and cleans up resources.
|
||||
/// Cancels the trip stream subscription and clears the current user ID.
|
||||
/// This is useful for user logout or when switching contexts.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [event]: The ResetTrips event
|
||||
/// [emit]: State emitter function
|
||||
Future<void> _onResetTrips(
|
||||
ResetTrips event,
|
||||
Emitter<TripState> emit,
|
||||
) async {
|
||||
Future<void> _onResetTrips(ResetTrips event, Emitter<TripState> emit) async {
|
||||
await _tripsSubscription?.cancel();
|
||||
_currentUserId = null;
|
||||
emit(TripInitial());
|
||||
}
|
||||
|
||||
/// Cleans up resources when the bloc is closed.
|
||||
///
|
||||
///
|
||||
/// Cancels the trip stream subscription to prevent memory leaks
|
||||
/// and ensure proper disposal of resources.
|
||||
@override
|
||||
@@ -227,19 +240,14 @@ class TripBloc extends Bloc<TripEvent, TripState> {
|
||||
}
|
||||
|
||||
/// Private event for handling real-time trip updates from streams.
|
||||
///
|
||||
///
|
||||
/// This internal event is used to process updates from the trip stream
|
||||
/// subscription and emit appropriate states based on the received data.
|
||||
/// internal event
|
||||
class _TripsUpdated extends TripEvent {
|
||||
/// List of trips received from the stream
|
||||
final List<Trip> trips;
|
||||
|
||||
/// Creates a _TripsUpdated event.
|
||||
///
|
||||
/// Args:
|
||||
/// [trips]: List of trips from the stream update
|
||||
const _TripsUpdated(this.trips);
|
||||
|
||||
final String? error;
|
||||
const _TripsUpdated(this.trips, {this.error});
|
||||
@override
|
||||
List<Object?> get props => [trips];
|
||||
}
|
||||
List<Object?> get props => [trips, error];
|
||||
}
|
||||
|
||||
@@ -1,23 +1,32 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
|
||||
import 'package:travel_mate/repositories/group_repository.dart';
|
||||
import 'package:travel_mate/services/notification_service.dart';
|
||||
import 'package:travel_mate/services/logger_service.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
import 'user_event.dart' as event;
|
||||
import 'user_state.dart' as state;
|
||||
|
||||
/// BLoC for managing user data and operations.
|
||||
///
|
||||
///
|
||||
/// This BLoC handles user-related operations including loading user data,
|
||||
/// updating user information, and managing user state throughout the application.
|
||||
/// It coordinates with Firebase Auth and Firestore to manage user data persistence.
|
||||
class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
/// Firebase Auth instance for authentication operations.
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
|
||||
|
||||
/// Firestore instance for user data operations.
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
|
||||
|
||||
final GroupRepository _groupRepository = GroupRepository();
|
||||
|
||||
final _errorService = ErrorService();
|
||||
|
||||
/// Creates a new [UserBloc] with initial state.
|
||||
///
|
||||
///
|
||||
/// Registers event handlers for all user-related events.
|
||||
UserBloc() : super(state.UserInitial()) {
|
||||
on<event.UserInitialized>(_onUserInitialized);
|
||||
@@ -25,9 +34,9 @@ class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
on<event.UserUpdated>(_onUserUpdated);
|
||||
on<event.UserLoggedOut>(_onUserLoggedOut);
|
||||
}
|
||||
|
||||
|
||||
/// Handles [UserInitialized] events.
|
||||
///
|
||||
///
|
||||
/// Initializes the current authenticated user's data by fetching it from Firestore.
|
||||
/// If the user doesn't exist in Firestore, creates a default user document.
|
||||
/// This is typically called when the app starts or after successful authentication.
|
||||
@@ -36,49 +45,71 @@ class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
Emitter<state.UserState> emit,
|
||||
) async {
|
||||
emit(state.UserLoading());
|
||||
|
||||
|
||||
try {
|
||||
final currentUser = _auth.currentUser;
|
||||
|
||||
|
||||
if (currentUser == null) {
|
||||
emit(state.UserError('No user currently authenticated'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Initialize notifications and update token
|
||||
final notificationService = NotificationService();
|
||||
await notificationService.initialize();
|
||||
final fcmToken = await notificationService.getFCMToken();
|
||||
LoggerService.info('UserBloc - FCM Token retrieved: $fcmToken');
|
||||
|
||||
// Fetch user data from Firestore
|
||||
final userDoc = await _firestore
|
||||
.collection('users')
|
||||
.doc(currentUser.uid)
|
||||
.get();
|
||||
|
||||
|
||||
if (!userDoc.exists) {
|
||||
// Create a default user if it doesn't exist
|
||||
final defaultUser = state.UserModel(
|
||||
id: currentUser.uid,
|
||||
email: currentUser.email ?? '',
|
||||
prenom: currentUser.displayName ?? 'Voyageur',
|
||||
fcmToken: fcmToken,
|
||||
);
|
||||
|
||||
|
||||
await _firestore
|
||||
.collection('users')
|
||||
.doc(currentUser.uid)
|
||||
.set(defaultUser.toJson());
|
||||
|
||||
|
||||
emit(state.UserLoaded(defaultUser));
|
||||
} else {
|
||||
final user = state.UserModel.fromJson({
|
||||
'id': currentUser.uid,
|
||||
...userDoc.data()!,
|
||||
});
|
||||
|
||||
// Update FCM token if it changed
|
||||
if (fcmToken != null && user.fcmToken != fcmToken) {
|
||||
LoggerService.info('UserBloc - Updating FCM token in Firestore');
|
||||
await _firestore.collection('users').doc(currentUser.uid).set({
|
||||
'fcmToken': fcmToken,
|
||||
}, SetOptions(merge: true));
|
||||
LoggerService.info('UserBloc - FCM token updated');
|
||||
} else {
|
||||
LoggerService.info(
|
||||
'UserBloc - FCM token not updated. Local: $fcmToken, Firestore: ${user.fcmToken}',
|
||||
);
|
||||
}
|
||||
|
||||
emit(state.UserLoaded(user));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(state.UserError('Error loading user: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('UserBloc', 'Error loading user: $e', stackTrace);
|
||||
emit(state.UserError('Impossible de charger l\'utilisateur'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Handles [LoadUser] events.
|
||||
///
|
||||
///
|
||||
/// Loads a specific user's data from Firestore by their user ID.
|
||||
/// This is useful when you need to display information about other users.
|
||||
Future<void> _onLoadUser(
|
||||
@@ -86,13 +117,13 @@ class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
Emitter<state.UserState> emit,
|
||||
) async {
|
||||
emit(state.UserLoading());
|
||||
|
||||
|
||||
try {
|
||||
final userDoc = await _firestore
|
||||
.collection('users')
|
||||
.doc(event.userId)
|
||||
.get();
|
||||
|
||||
|
||||
if (userDoc.exists) {
|
||||
final user = state.UserModel.fromJson({
|
||||
'id': event.userId,
|
||||
@@ -102,13 +133,14 @@ class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
} else {
|
||||
emit(state.UserError('User not found'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(state.UserError('Error loading user: $e'));
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('UserBloc', 'Error loading user: $e', stackTrace);
|
||||
emit(state.UserError('Impossible de charger l\'utilisateur'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Handles [UserUpdated] events.
|
||||
///
|
||||
///
|
||||
/// Updates the current user's data in Firestore with the provided information.
|
||||
/// Only updates the fields specified in the userData map, allowing for partial updates.
|
||||
/// After successful update, reloads the user data to reflect changes.
|
||||
@@ -118,32 +150,47 @@ class UserBloc extends Bloc<event.UserEvent, state.UserState> {
|
||||
) async {
|
||||
if (this.state is state.UserLoaded) {
|
||||
final currentUser = (this.state as state.UserLoaded).user;
|
||||
|
||||
|
||||
try {
|
||||
await _firestore
|
||||
.collection('users')
|
||||
.doc(currentUser.id)
|
||||
.update(event.userData);
|
||||
|
||||
|
||||
final updatedDoc = await _firestore
|
||||
.collection('users')
|
||||
.doc(currentUser.id)
|
||||
.get();
|
||||
|
||||
|
||||
final updatedUser = state.UserModel.fromJson({
|
||||
'id': currentUser.id,
|
||||
...updatedDoc.data()!,
|
||||
});
|
||||
|
||||
|
||||
emit(state.UserLoaded(updatedUser));
|
||||
} catch (e) {
|
||||
emit(state.UserError('Error updating user: $e'));
|
||||
|
||||
// Propager les changements aux groupes
|
||||
await _groupRepository.updateMemberDetails(
|
||||
userId: currentUser.id,
|
||||
firstName: event
|
||||
.userData['prenom'], // 'prenom' dans Firestore map map to firstName usually? Wait, UserModel has prenom/nom.
|
||||
lastName: event.userData['nom'],
|
||||
profilePictureUrl: event
|
||||
.userData['profilePictureUrl'], // Key was 'profilePictureUrl' in ProfileContent
|
||||
);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserBloc',
|
||||
'Error updating user: $e',
|
||||
stackTrace,
|
||||
);
|
||||
emit(state.UserError('Impossible de mettre à jour l\'utilisateur'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Handles [UserLoggedOut] events.
|
||||
///
|
||||
///
|
||||
/// Resets the user bloc state to initial when the user logs out.
|
||||
/// This clears any cached user data from the application state.
|
||||
Future<void> _onUserLoggedOut(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// Abstract base class for all user-related states.
|
||||
///
|
||||
///
|
||||
/// This class extends [Equatable] to enable value equality for state comparison.
|
||||
/// All user states in the application should inherit from this class.
|
||||
abstract class UserState extends Equatable {
|
||||
@@ -10,79 +10,82 @@ abstract class UserState extends Equatable {
|
||||
}
|
||||
|
||||
/// Initial state of the user bloc.
|
||||
///
|
||||
///
|
||||
/// This state represents the initial state before any user operations
|
||||
/// have been performed or when the user has logged out.
|
||||
class UserInitial extends UserState {}
|
||||
|
||||
/// State indicating that a user operation is in progress.
|
||||
///
|
||||
///
|
||||
/// This state is used to show loading indicators during user data
|
||||
/// operations like loading, updating, or initializing user information.
|
||||
class UserLoading extends UserState {}
|
||||
|
||||
/// State indicating that user data has been successfully loaded.
|
||||
///
|
||||
///
|
||||
/// This state contains the loaded user information and is used
|
||||
/// throughout the app to access current user data.
|
||||
class UserLoaded extends UserState {
|
||||
/// The loaded user data.
|
||||
final UserModel user;
|
||||
|
||||
|
||||
/// Creates a [UserLoaded] state with the given [user] data.
|
||||
UserLoaded(this.user);
|
||||
|
||||
|
||||
@override
|
||||
List<Object?> get props => [user];
|
||||
}
|
||||
|
||||
/// State indicating that a user operation has failed.
|
||||
///
|
||||
///
|
||||
/// This state contains an error message that can be displayed to the user
|
||||
/// when user operations fail.
|
||||
class UserError extends UserState {
|
||||
/// The error message describing what went wrong.
|
||||
final String message;
|
||||
|
||||
|
||||
/// Creates a [UserError] state with the given error [message].
|
||||
UserError(this.message);
|
||||
|
||||
|
||||
@override
|
||||
List<Object?> get props => [message];
|
||||
}
|
||||
|
||||
/// Simple user model for representing user data in the application.
|
||||
///
|
||||
///
|
||||
/// This model contains basic user information and provides methods for
|
||||
/// serialization/deserialization with Firestore operations.
|
||||
/// Simple user model for representing user data in the application.
|
||||
///
|
||||
///
|
||||
/// This model contains basic user information and provides methods for
|
||||
/// serialization/deserialization with Firestore operations.
|
||||
class UserModel {
|
||||
/// Unique identifier for the user (Firebase UID).
|
||||
final String id;
|
||||
|
||||
|
||||
/// User's email address.
|
||||
final String email;
|
||||
|
||||
|
||||
/// User's first name.
|
||||
final String prenom;
|
||||
|
||||
|
||||
/// User's last name (optional).
|
||||
final String? nom;
|
||||
|
||||
|
||||
/// Platform used for authentication (e.g., 'google', 'apple', 'email').
|
||||
final String? authMethod;
|
||||
|
||||
|
||||
/// User's phone number (optional).
|
||||
final String? phoneNumber;
|
||||
|
||||
|
||||
/// User's profile picture URL (optional).
|
||||
final String? profilePictureUrl;
|
||||
|
||||
|
||||
/// Firebase Cloud Messaging token for push notifications.
|
||||
final String? fcmToken;
|
||||
|
||||
/// Creates a new [UserModel] instance.
|
||||
///
|
||||
///
|
||||
/// [id], [email], and [prenom] are required fields.
|
||||
/// [nom], [authMethod], [phoneNumber], and [profilePictureUrl] are optional and can be null.
|
||||
UserModel({
|
||||
@@ -93,10 +96,11 @@ class UserModel {
|
||||
this.authMethod,
|
||||
this.phoneNumber,
|
||||
this.profilePictureUrl,
|
||||
this.fcmToken,
|
||||
});
|
||||
|
||||
|
||||
/// Creates a [UserModel] instance from a JSON map.
|
||||
///
|
||||
///
|
||||
/// Handles null values gracefully by providing default values.
|
||||
/// [prenom] defaults to 'Voyageur' (Traveler) if not provided.
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) {
|
||||
@@ -108,11 +112,12 @@ class UserModel {
|
||||
authMethod: json['authMethod'] ?? json['platform'],
|
||||
phoneNumber: json['phoneNumber'],
|
||||
profilePictureUrl: json['profilePictureUrl'],
|
||||
fcmToken: json['fcmToken'],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Converts the [UserModel] instance to a JSON map.
|
||||
///
|
||||
///
|
||||
/// Useful for storing user data in Firestore or other JSON-based operations.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
@@ -123,6 +128,7 @@ class UserModel {
|
||||
'authMethod': authMethod,
|
||||
'phoneNumber': phoneNumber,
|
||||
'profilePictureUrl': profilePictureUrl,
|
||||
'fcmToken': fcmToken,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
///
|
||||
/// The component automatically loads account data when initialized and
|
||||
/// provides a clean interface for managing group-based expenses.
|
||||
///
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../services/error_service.dart';
|
||||
import 'package:travel_mate/blocs/user/user_bloc.dart';
|
||||
import '../../models/account.dart';
|
||||
import '../../blocs/account/account_bloc.dart';
|
||||
@@ -28,8 +31,9 @@ import '../../blocs/account/account_state.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/components/error/error_content.dart';
|
||||
import '../../blocs/user/user_state.dart' as user_state;
|
||||
import '../../repositories/group_repository.dart'; // Ajouter cet import
|
||||
import 'group_expenses_page.dart'; // Ajouter cet import
|
||||
import '../../repositories/group_repository.dart';
|
||||
import '../widgets/user_state_widget.dart';
|
||||
import 'group_expenses_page.dart';
|
||||
|
||||
/// Widget that displays the account content page with account management functionality.
|
||||
class AccountContent extends StatefulWidget {
|
||||
@@ -44,10 +48,10 @@ class _AccountContentState extends State<AccountContent> {
|
||||
/// Repository for group data operations used for navigation
|
||||
final _groupRepository = GroupRepository(); // Ajouter cette ligne
|
||||
|
||||
@override
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
|
||||
// Load immediately without waiting for the next frame
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_loadInitialData();
|
||||
@@ -55,13 +59,13 @@ class _AccountContentState extends State<AccountContent> {
|
||||
}
|
||||
|
||||
/// Loads the initial account data for the current user.
|
||||
///
|
||||
///
|
||||
/// Retrieves the current user from UserBloc and loads their accounts
|
||||
/// using the AccountBloc. Handles errors gracefully with error display.
|
||||
void _loadInitialData() {
|
||||
try {
|
||||
final userState = context.read<UserBloc>().state;
|
||||
|
||||
|
||||
if (userState is user_state.UserLoaded) {
|
||||
final userId = userState.user.id;
|
||||
context.read<AccountBloc>().add(LoadAccountsByUserId(userId));
|
||||
@@ -69,123 +73,98 @@ class _AccountContentState extends State<AccountContent> {
|
||||
throw Exception('User not connected');
|
||||
}
|
||||
} catch (e) {
|
||||
ErrorContent(
|
||||
message: 'Error loading accounts: $e',
|
||||
onRetry: () {},
|
||||
);
|
||||
ErrorContent(message: 'Error loading accounts: $e', onRetry: () {});
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigates to the group expenses page for a specific account.
|
||||
///
|
||||
///
|
||||
/// Retrieves the group associated with the account and navigates to
|
||||
/// the group expenses management page. Shows error messages if the
|
||||
/// group cannot be found or if navigation fails.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [account]: The account to navigate to for expense management
|
||||
Future<void> _navigateToGroupExpenses(Account account) async {
|
||||
try {
|
||||
// Retrieve the group associated with the account
|
||||
final group = await _groupRepository.getGroupByTripId(account.tripId);
|
||||
|
||||
|
||||
if (group != null && mounted) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => GroupExpensesPage(
|
||||
account: account,
|
||||
group: group,
|
||||
),
|
||||
builder: (context) =>
|
||||
GroupExpensesPage(account: account, group: group),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Group not found for this account'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: 'Group not found for this account');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Error loading group: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: 'Error loading group: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the main widget for the account content page.
|
||||
///
|
||||
///
|
||||
/// Creates a responsive UI that handles different user and account states:
|
||||
/// - Shows loading indicator for user authentication
|
||||
/// - Displays error content for user errors
|
||||
/// - Builds account content based on account loading states
|
||||
///
|
||||
///
|
||||
/// Returns:
|
||||
/// Widget representing the complete account page UI
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<UserBloc, user_state.UserState>(
|
||||
builder: (context, userState) {
|
||||
if (userState is user_state.UserLoading) {
|
||||
return const Scaffold(
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
if (userState is user_state.UserError) {
|
||||
return ErrorContent(
|
||||
message: 'User error: ${userState.message}',
|
||||
onRetry: () {},
|
||||
);
|
||||
}
|
||||
|
||||
if (userState is! user_state.UserLoaded) {
|
||||
return const Scaffold(
|
||||
body: Center(child: Text('User not connected')),
|
||||
);
|
||||
}
|
||||
final user = userState.user;
|
||||
|
||||
return UserStateWrapper(
|
||||
builder: (context, user) {
|
||||
return BlocConsumer<AccountBloc, AccountState>(
|
||||
listener: (context, accountState) {
|
||||
if (accountState is AccountError) {
|
||||
ErrorContent(
|
||||
message: 'Account loading error: ${accountState.message}',
|
||||
message:
|
||||
'Erreur de chargement des comptes : ${accountState.message}',
|
||||
onRetry: () {
|
||||
context.read<AccountBloc>().add(LoadAccountsByUserId(user.id));
|
||||
context.read<AccountBloc>().add(
|
||||
LoadAccountsByUserId(user.id),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, accountState) {
|
||||
return Scaffold(
|
||||
body: SafeArea(child: _buildContent(accountState, user.id))
|
||||
);
|
||||
body: SafeArea(child: _buildContent(accountState, user.id)),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
loadingWidget: const Scaffold(
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
errorWidget: ErrorContent(message: 'User error', onRetry: () {}),
|
||||
noUserWidget: const Scaffold(
|
||||
body: Center(child: Text('Utilisateur non connecté')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the main content based on the current account state.
|
||||
///
|
||||
///
|
||||
/// Handles different account loading states and renders appropriate UI:
|
||||
/// - Loading: Shows circular progress indicator with loading message
|
||||
/// - Error: Displays error content with retry functionality
|
||||
/// - Loaded: Renders the accounts list or empty state message
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [accountState]: Current state of account loading
|
||||
/// [userId]: ID of the current user for reload operations
|
||||
///
|
||||
///
|
||||
/// Returns:
|
||||
/// Widget representing the account content UI
|
||||
Widget _buildContent(AccountState accountState, String userId) {
|
||||
@@ -196,15 +175,15 @@ class _AccountContentState extends State<AccountContent> {
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text('Loading accounts...'),
|
||||
],
|
||||
),
|
||||
Text('Chargement des comptes...'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (accountState is AccountError) {
|
||||
return ErrorContent(
|
||||
message: 'Account loading error...',
|
||||
message: 'Erreur de chargement des comptes...',
|
||||
onRetry: () {
|
||||
context.read<AccountBloc>().add(LoadAccountsByUserId(userId));
|
||||
},
|
||||
@@ -222,25 +201,25 @@ class _AccountContentState extends State<AccountContent> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text('Unknown state'),
|
||||
const Text('État inconnu'),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.read<AccountBloc>().add(LoadAccountsByUserId(userId));
|
||||
},
|
||||
child: const Text('Load accounts'),
|
||||
child: const Text('Charger les comptes'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the empty state widget when no accounts are found.
|
||||
///
|
||||
///
|
||||
/// Displays a user-friendly message explaining that accounts are
|
||||
/// automatically created when trips are created. Shows an icon
|
||||
/// and informative text to guide the user.
|
||||
///
|
||||
///
|
||||
/// Returns:
|
||||
/// Widget representing the empty accounts state
|
||||
Widget _buildEmptyState() {
|
||||
@@ -250,7 +229,11 @@ class _AccountContentState extends State<AccountContent> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.account_balance_wallet, size: 80, color: Colors.grey),
|
||||
const Icon(
|
||||
Icons.account_balance_wallet,
|
||||
size: 80,
|
||||
color: Colors.grey,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Text(
|
||||
'No accounts found',
|
||||
@@ -258,7 +241,7 @@ class _AccountContentState extends State<AccountContent> {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Accounts are automatically created when you create a trip',
|
||||
'Les comptes sont créés automatiquement lorsque vous créez des voyages.',
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
@@ -269,15 +252,15 @@ class _AccountContentState extends State<AccountContent> {
|
||||
}
|
||||
|
||||
/// Builds a scrollable list of user accounts with pull-to-refresh functionality.
|
||||
///
|
||||
///
|
||||
/// Creates a RefreshIndicator-wrapped ListView that displays all user accounts
|
||||
/// in card format. Includes a header with title and description, and renders
|
||||
/// each account using the _buildSimpleAccountCard method.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [accounts]: List of accounts to display
|
||||
/// [userId]: Current user ID for refresh operations
|
||||
///
|
||||
///
|
||||
/// Returns:
|
||||
/// Widget containing the accounts list with pull-to-refresh capability
|
||||
Widget _buildAccountsList(List<Account> accounts, String userId) {
|
||||
@@ -289,39 +272,28 @@ class _AccountContentState extends State<AccountContent> {
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const Text(
|
||||
'My accounts',
|
||||
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Manage your travel accounts',
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[600]),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
...accounts.map((account) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: _buildSimpleAccountCard(account),
|
||||
);
|
||||
})
|
||||
}),
|
||||
],
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Builds an individual account card with account information.
|
||||
///
|
||||
///
|
||||
/// Creates a Material Design card displaying account details including:
|
||||
/// - Account name with color-coded avatar
|
||||
/// - Member count and member names (up to 2 displayed)
|
||||
/// - Navigation capability to group expenses
|
||||
/// - Error handling for card rendering issues
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [account]: Account object containing account details
|
||||
///
|
||||
///
|
||||
/// Returns:
|
||||
/// Widget representing a single account card
|
||||
Widget _buildSimpleAccountCard(Account account) {
|
||||
@@ -329,9 +301,10 @@ class _AccountContentState extends State<AccountContent> {
|
||||
final colors = [Colors.blue, Colors.purple, Colors.green, Colors.orange];
|
||||
final color = colors[account.name.hashCode.abs() % colors.length];
|
||||
|
||||
String memberInfo = '${account.members.length} member${account.members.length > 1 ? 's' : ''}';
|
||||
String memberInfo =
|
||||
'${account.members.length} member${account.members.length > 1 ? 's' : ''}';
|
||||
|
||||
if(account.members.isNotEmpty){
|
||||
if (account.members.isNotEmpty) {
|
||||
final names = account.members
|
||||
.take(2)
|
||||
.map((m) => m.pseudo.isNotEmpty ? m.pseudo : m.firstName)
|
||||
@@ -344,15 +317,19 @@ class _AccountContentState extends State<AccountContent> {
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: color,
|
||||
child: const Icon(Icons.account_balance_wallet, color: Colors.white),
|
||||
child: const Icon(
|
||||
Icons.account_balance_wallet,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
account.name,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
subtitle: Text(memberInfo),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _navigateToGroupExpenses(account), // Navigate to group expenses
|
||||
onTap: () =>
|
||||
_navigateToGroupExpenses(account), // Navigate to group expenses
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
@@ -361,8 +338,8 @@ class _AccountContentState extends State<AccountContent> {
|
||||
child: const ListTile(
|
||||
leading: Icon(Icons.error, color: Colors.red),
|
||||
title: Text('Display error'),
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,12 +56,14 @@
|
||||
/// - Group
|
||||
/// - ExpenseBloc
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:travel_mate/models/expense_split.dart';
|
||||
import '../../services/error_service.dart';
|
||||
import '../../blocs/expense/expense_bloc.dart';
|
||||
import '../../blocs/expense/expense_event.dart';
|
||||
import '../../blocs/expense/expense_state.dart';
|
||||
@@ -76,11 +78,25 @@ import '../../models/expense.dart';
|
||||
class AddExpenseDialog extends StatefulWidget {
|
||||
/// The group to which the expense belongs.
|
||||
final Group group;
|
||||
|
||||
/// The user creating or editing the expense.
|
||||
final user_state.UserModel currentUser;
|
||||
|
||||
/// The expense to edit (null for new expense).
|
||||
final Expense? expenseToEdit;
|
||||
|
||||
/// Optional initial category for a new expense.
|
||||
final ExpenseCategory? initialCategory;
|
||||
|
||||
/// Optional initial amount for a new expense.
|
||||
final double? initialAmount;
|
||||
|
||||
/// Optional initial splits (userId -> amount) for a new expense.
|
||||
final Map<String, double>? initialSplits;
|
||||
|
||||
/// Optional initial description for a new expense.
|
||||
final String? initialDescription;
|
||||
|
||||
/// Creates an AddExpenseDialog.
|
||||
///
|
||||
/// [group] is the group for the expense.
|
||||
@@ -91,6 +107,10 @@ class AddExpenseDialog extends StatefulWidget {
|
||||
required this.group,
|
||||
required this.currentUser,
|
||||
this.expenseToEdit,
|
||||
this.initialCategory,
|
||||
this.initialAmount,
|
||||
this.initialSplits,
|
||||
this.initialDescription,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -103,33 +123,49 @@ class AddExpenseDialog extends StatefulWidget {
|
||||
class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
/// Form key for validating the expense form.
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
/// Controller for the expense description field.
|
||||
final _descriptionController = TextEditingController();
|
||||
|
||||
/// Controller for the expense amount field.
|
||||
final _amountController = TextEditingController();
|
||||
|
||||
/// The selected date for the expense.
|
||||
late DateTime _selectedDate;
|
||||
|
||||
/// The selected category for the expense.
|
||||
late ExpenseCategory _selectedCategory;
|
||||
|
||||
/// The selected currency for the expense.
|
||||
late ExpenseCurrency _selectedCurrency;
|
||||
|
||||
/// The user ID of the payer.
|
||||
late String _paidById;
|
||||
|
||||
/// Map of userId to split amount for each participant.
|
||||
final Map<String, double> _splits = {};
|
||||
|
||||
/// The selected receipt image file, if any.
|
||||
File? _receiptImage;
|
||||
|
||||
/// Whether the dialog is currently submitting data.
|
||||
bool _isLoading = false;
|
||||
|
||||
/// Whether the expense is split equally among participants.
|
||||
bool _splitEqually = true;
|
||||
|
||||
/// Whether the existing receipt has been removed.
|
||||
bool _receiptRemoved = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Initialize form fields and splits based on whether editing or creating
|
||||
_selectedDate = widget.expenseToEdit?.date ?? DateTime.now();
|
||||
_selectedCategory = widget.expenseToEdit?.category ?? ExpenseCategory.other;
|
||||
_selectedCategory =
|
||||
widget.expenseToEdit?.category ??
|
||||
widget.initialCategory ??
|
||||
ExpenseCategory.other;
|
||||
_selectedCurrency = widget.expenseToEdit?.currency ?? ExpenseCurrency.eur;
|
||||
_paidById = widget.expenseToEdit?.paidById ?? widget.currentUser.id;
|
||||
|
||||
@@ -142,9 +178,32 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
}
|
||||
_splitEqually = false;
|
||||
} else {
|
||||
// Creating: initialize splits for all group members
|
||||
for (final member in widget.group.members) {
|
||||
_splits[member.userId] = 0;
|
||||
// Creating: initialize splits
|
||||
if (widget.initialDescription != null) {
|
||||
_descriptionController.text = widget.initialDescription!;
|
||||
}
|
||||
|
||||
if (widget.initialAmount != null) {
|
||||
_amountController.text = widget.initialAmount.toString();
|
||||
}
|
||||
|
||||
if (widget.initialSplits != null) {
|
||||
_splits.addAll(widget.initialSplits!);
|
||||
// Fill remaining members with 0 if not in initialSplits
|
||||
for (final member in widget.group.members) {
|
||||
if (!_splits.containsKey(member.userId)) {
|
||||
_splits[member.userId] = 0;
|
||||
} else {
|
||||
// If we have specific splits, we probably aren't splitting equally by default logic
|
||||
// unless we want to force it. For reimbursement, we likely set exact amounts.
|
||||
_splitEqually = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Default behavior: initialize splits for all group members
|
||||
for (final member in widget.group.members) {
|
||||
_splits[member.userId] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,14 +231,11 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
if (pickedFile != null) {
|
||||
final file = File(pickedFile.path);
|
||||
final fileSize = await file.length();
|
||||
|
||||
|
||||
if (fileSize > 5 * 1024 * 1024) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('L\'image ne doit pas dépasser 5 Mo'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
ErrorService().showError(
|
||||
message: 'L\'image ne doit pas dépasser 5 Mo',
|
||||
);
|
||||
}
|
||||
return;
|
||||
@@ -199,11 +255,11 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
|
||||
final amount = double.tryParse(_amountController.text) ?? 0;
|
||||
final selectedMembers = _splits.entries.where((e) => e.value >= 0).toList();
|
||||
|
||||
|
||||
if (selectedMembers.isEmpty) return;
|
||||
|
||||
final splitAmount = amount / selectedMembers.length;
|
||||
|
||||
|
||||
setState(() {
|
||||
for (final entry in selectedMembers) {
|
||||
_splits[entry.key] = splitAmount;
|
||||
@@ -221,24 +277,18 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
final amount = double.parse(_amountController.text);
|
||||
final selectedSplits = _splits.entries
|
||||
.where((e) => e.value > 0)
|
||||
.map((e) {
|
||||
final member = widget.group.members.firstWhere((m) => m.userId == e.key);
|
||||
return ExpenseSplit(
|
||||
userId: e.key,
|
||||
userName: member.firstName,
|
||||
amount: e.value,
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
final selectedSplits = _splits.entries.where((e) => e.value > 0).map((e) {
|
||||
final member = widget.group.members.firstWhere((m) => m.userId == e.key);
|
||||
return ExpenseSplit(
|
||||
userId: e.key,
|
||||
userName: member.firstName,
|
||||
amount: e.value,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
if (selectedSplits.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Veuillez sélectionner au moins un participant'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
ErrorService().showError(
|
||||
message: 'Veuillez sélectionner au moins un participant',
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -248,11 +298,15 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
try {
|
||||
// Convertir en EUR
|
||||
final amountInEur = context.read<ExpenseBloc>().state is ExpensesLoaded
|
||||
? (context.read<ExpenseBloc>().state as ExpensesLoaded)
|
||||
.exchangeRates[_selectedCurrency]! * amount
|
||||
? ((context.read<ExpenseBloc>().state as ExpensesLoaded)
|
||||
.exchangeRates[_selectedCurrency.code] ??
|
||||
1.0) *
|
||||
amount
|
||||
: amount;
|
||||
|
||||
final payer = widget.group.members.firstWhere((m) => m.userId == _paidById);
|
||||
final payer = widget.group.members.firstWhere(
|
||||
(m) => m.userId == _paidById,
|
||||
);
|
||||
|
||||
final expense = Expense(
|
||||
id: widget.expenseToEdit?.id ?? '',
|
||||
@@ -266,41 +320,32 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
paidByName: payer.firstName,
|
||||
splits: selectedSplits,
|
||||
date: _selectedDate,
|
||||
receiptUrl: widget.expenseToEdit?.receiptUrl,
|
||||
receiptUrl: _receiptRemoved ? null : widget.expenseToEdit?.receiptUrl,
|
||||
createdAt: widget.expenseToEdit?.createdAt ?? DateTime.now(),
|
||||
);
|
||||
|
||||
if (widget.expenseToEdit == null) {
|
||||
context.read<ExpenseBloc>().add(CreateExpense(
|
||||
expense: expense,
|
||||
receiptImage: _receiptImage,
|
||||
));
|
||||
context.read<ExpenseBloc>().add(
|
||||
CreateExpense(expense: expense, receiptImage: _receiptImage),
|
||||
);
|
||||
} else {
|
||||
context.read<ExpenseBloc>().add(UpdateExpense(
|
||||
expense: expense,
|
||||
newReceiptImage: _receiptImage,
|
||||
));
|
||||
context.read<ExpenseBloc>().add(
|
||||
UpdateExpense(expense: expense, newReceiptImage: _receiptImage),
|
||||
);
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(widget.expenseToEdit == null
|
||||
? 'Dépense ajoutée'
|
||||
: 'Dépense modifiée'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
ErrorService().showSnackbar(
|
||||
message: widget.expenseToEdit == null
|
||||
? 'Dépense ajoutée'
|
||||
: 'Dépense modifiée',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: 'Erreur: $e');
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
@@ -314,284 +359,425 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
/// Returns a Dialog widget containing the expense form.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isDark = theme.brightness == Brightness.dark;
|
||||
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
backgroundColor: isDark ? theme.scaffoldBackgroundColor : Colors.white,
|
||||
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 700),
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.expenseToEdit == null
|
||||
? 'Nouvelle dépense'
|
||||
: 'Modifier la dépense'),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
constraints: const BoxConstraints(maxWidth: 500, maxHeight: 800),
|
||||
child: Column(
|
||||
children: [
|
||||
// Header
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 24, 16, 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.expenseToEdit == null
|
||||
? 'Nouvelle dépense'
|
||||
: 'Modifier la dépense',
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Form(
|
||||
key: _formKey,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
// Description
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Description',
|
||||
hintText: 'Ex: Restaurant, Essence...',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.description),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Veuillez entrer une description';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
|
||||
// Montant et devise
|
||||
Row(
|
||||
// Form Content
|
||||
Expanded(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextFormField(
|
||||
controller: _amountController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Montant',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.euro),
|
||||
// Description
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Description',
|
||||
hintText: 'Ex: Restaurant, Essence...',
|
||||
prefixIcon: const Icon(Icons.description_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
onChanged: (_) => _calculateSplits(),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Requis';
|
||||
}
|
||||
if (double.tryParse(value) == null || double.parse(value) <= 0) {
|
||||
return 'Montant invalide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<ExpenseCurrency>(
|
||||
initialValue: _selectedCurrency,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Devise',
|
||||
border: OutlineInputBorder(),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
items: ExpenseCurrency.values.map((currency) {
|
||||
return DropdownMenuItem(
|
||||
value: currency,
|
||||
child: Text(currency.code),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _selectedCurrency = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Requis';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Catégorie
|
||||
DropdownButtonFormField<ExpenseCategory>(
|
||||
initialValue: _selectedCategory,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Catégorie',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.category),
|
||||
),
|
||||
items: ExpenseCategory.values.map((category) {
|
||||
return DropdownMenuItem(
|
||||
value: category,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(category.icon, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text(category.displayName),
|
||||
],
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _selectedCategory = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date
|
||||
ListTile(
|
||||
leading: const Icon(Icons.calendar_today),
|
||||
title: const Text('Date'),
|
||||
subtitle: Text(DateFormat('dd/MM/yyyy').format(_selectedDate)),
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(color: Colors.grey[300]!),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(const Duration(days: 365)),
|
||||
);
|
||||
if (date != null) {
|
||||
setState(() => _selectedDate = date);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Payé par
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _paidById,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Payé par',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person),
|
||||
),
|
||||
items: widget.group.members.map((member) {
|
||||
return DropdownMenuItem(
|
||||
value: member.userId,
|
||||
child: Text(member.firstName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _paidById = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Division
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
// Montant et Devise
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Text(
|
||||
'Division',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextFormField(
|
||||
controller: _amountController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Montant',
|
||||
prefixIcon: const Icon(Icons.euro_symbol),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
onChanged: (_) => _calculateSplits(),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Requis';
|
||||
}
|
||||
if (double.tryParse(value) == null ||
|
||||
double.parse(value) <= 0) {
|
||||
return 'Invalide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<ExpenseCurrency>(
|
||||
initialValue: _selectedCurrency,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Devise',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
items: ExpenseCurrency.values.map((currency) {
|
||||
return DropdownMenuItem(
|
||||
value: currency,
|
||||
child: Text(currency.code),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _selectedCurrency = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Catégorie
|
||||
DropdownButtonFormField<ExpenseCategory>(
|
||||
initialValue: _selectedCategory,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Catégorie',
|
||||
prefixIcon: Icon(_selectedCategory.icon),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
items: ExpenseCategory.values.map((category) {
|
||||
return DropdownMenuItem(
|
||||
value: category,
|
||||
child: Text(category.displayName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _selectedCategory = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date
|
||||
InkWell(
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(
|
||||
const Duration(days: 365),
|
||||
),
|
||||
);
|
||||
if (date != null) setState(() => _selectedDate = date);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: InputDecorator(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Date',
|
||||
prefixIcon: const Icon(Icons.calendar_today_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
DateFormat('dd/MM/yyyy').format(_selectedDate),
|
||||
style: theme.textTheme.bodyLarge,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Payé par
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _paidById,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Payé par',
|
||||
prefixIcon: const Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
items: widget.group.members.map((member) {
|
||||
return DropdownMenuItem(
|
||||
value: member.userId,
|
||||
child: Text(member.firstName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) setState(() => _paidById = value);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Division Section
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: isDark ? Colors.grey[800] : Colors.grey[50],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: theme.dividerColor),
|
||||
),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Text(
|
||||
'Division',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'Égale',
|
||||
style: TextStyle(
|
||||
color: isDark
|
||||
? Colors.grey[400]
|
||||
: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Switch(
|
||||
value: _splitEqually,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_splitEqually = value;
|
||||
if (value) _calculateSplits();
|
||||
});
|
||||
},
|
||||
activeThumbColor: theme.colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(),
|
||||
...widget.group.members.map((member) {
|
||||
final isSelected =
|
||||
_splits.containsKey(member.userId) &&
|
||||
_splits[member.userId]! >= 0;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
member.firstName,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
if (!_splitEqually && isSelected)
|
||||
SizedBox(
|
||||
width: 100,
|
||||
child: TextFormField(
|
||||
initialValue: _splits[member.userId]
|
||||
?.toStringAsFixed(2),
|
||||
decoration: const InputDecoration(
|
||||
isDense: true,
|
||||
contentPadding: EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 8,
|
||||
),
|
||||
border: OutlineInputBorder(),
|
||||
suffixText: '€',
|
||||
),
|
||||
keyboardType:
|
||||
const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
onChanged: (value) {
|
||||
final amount =
|
||||
double.tryParse(value) ?? 0;
|
||||
setState(
|
||||
() =>
|
||||
_splits[member.userId] = amount,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Checkbox(
|
||||
value: isSelected,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
if (value == true) {
|
||||
_splits[member.userId] = 0;
|
||||
if (_splitEqually) _calculateSplits();
|
||||
} else {
|
||||
_splits[member.userId] = -1;
|
||||
}
|
||||
});
|
||||
},
|
||||
activeColor: theme.colorScheme.primary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Reçu (Optional - keeping simple for now as per design focus)
|
||||
if (_receiptImage != null ||
|
||||
(widget.expenseToEdit?.receiptUrl != null &&
|
||||
!_receiptRemoved))
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: theme.dividerColor),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.receipt_long, color: Colors.green),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Reçu joint'),
|
||||
const Spacer(),
|
||||
Text(_splitEqually ? 'Égale' : 'Personnalisée'),
|
||||
Switch(
|
||||
value: _splitEqually,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_splitEqually = value;
|
||||
if (value) _calculateSplits();
|
||||
});
|
||||
},
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => setState(() {
|
||||
_receiptImage = null;
|
||||
_receiptRemoved = true;
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(),
|
||||
...widget.group.members.map((member) {
|
||||
final isSelected = _splits.containsKey(member.userId) &&
|
||||
_splits[member.userId]! >= 0;
|
||||
|
||||
return CheckboxListTile(
|
||||
title: Text(member.firstName),
|
||||
subtitle: _splitEqually || !isSelected
|
||||
? null
|
||||
: TextFormField(
|
||||
initialValue: _splits[member.userId]?.toStringAsFixed(2),
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Montant',
|
||||
isDense: true,
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
onChanged: (value) {
|
||||
final amount = double.tryParse(value) ?? 0;
|
||||
setState(() => _splits[member.userId] = amount);
|
||||
},
|
||||
),
|
||||
value: isSelected,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
if (value == true) {
|
||||
_splits[member.userId] = 0;
|
||||
if (_splitEqually) _calculateSplits();
|
||||
} else {
|
||||
_splits[member.userId] = -1;
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Reçu
|
||||
ListTile(
|
||||
leading: const Icon(Icons.receipt),
|
||||
title: Text(_receiptImage != null || widget.expenseToEdit?.receiptUrl != null
|
||||
? 'Reçu ajouté'
|
||||
: 'Ajouter un reçu'),
|
||||
subtitle: _receiptImage != null
|
||||
? const Text('Nouveau reçu sélectionné')
|
||||
: null,
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.add_photo_alternate),
|
||||
onPressed: _pickImage,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(color: Colors.grey[300]!),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Boutons
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Annuler'),
|
||||
)
|
||||
else
|
||||
OutlinedButton.icon(
|
||||
onPressed: _pickImage,
|
||||
icon: const Icon(Icons.camera_alt_outlined),
|
||||
label: const Text('Ajouter un reçu'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
onPressed: _isLoading ? null : _submit,
|
||||
child: _isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(widget.expenseToEdit == null ? 'Ajouter' : 'Modifier'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Bottom Button
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: _isLoading ? null : _submit,
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
backgroundColor: theme.colorScheme.primary,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
),
|
||||
child: _isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
widget.expenseToEdit == null
|
||||
? 'Ajouter'
|
||||
: 'Enregistrer',
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -6,7 +6,13 @@
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../blocs/user/user_bloc.dart';
|
||||
import '../../blocs/user/user_state.dart' as user_state;
|
||||
import '../../models/expense.dart';
|
||||
import '../../models/group.dart';
|
||||
import '../../models/user_balance.dart';
|
||||
import 'add_expense_dialog.dart';
|
||||
|
||||
/// A stateless widget that displays a list of user balances in a group.
|
||||
///
|
||||
@@ -18,21 +24,19 @@ class BalancesTab extends StatelessWidget {
|
||||
/// The list of user balances to display.
|
||||
final List<UserBalance> balances;
|
||||
|
||||
/// The group associated with these balances.
|
||||
final Group group;
|
||||
|
||||
/// Creates a `BalancesTab` widget.
|
||||
///
|
||||
/// The [balances] parameter must not be null.
|
||||
const BalancesTab({
|
||||
super.key,
|
||||
required this.balances,
|
||||
});
|
||||
const BalancesTab({super.key, required this.balances, required this.group});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Check if the balances list is empty and display a placeholder message if true.
|
||||
if (balances.isEmpty) {
|
||||
return const Center(
|
||||
child: Text('Aucune balance à afficher'),
|
||||
);
|
||||
return const Center(child: Text('Aucune balance à afficher'));
|
||||
}
|
||||
|
||||
// Render the list of balances as a scrollable list.
|
||||
@@ -79,81 +83,149 @@ class BalancesTab extends StatelessWidget {
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
child: Column(
|
||||
children: [
|
||||
// Display the user's initial in a circular avatar.
|
||||
CircleAvatar(
|
||||
radius: 24,
|
||||
backgroundColor: isDark ? Colors.grey[800] : Colors.grey[200],
|
||||
child: Text(
|
||||
balance.userName.isNotEmpty
|
||||
? balance.userName[0].toUpperCase()
|
||||
: '?',
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// Display the user's name and financial details.
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// User's name.
|
||||
Text(
|
||||
balance.userName,
|
||||
Row(
|
||||
children: [
|
||||
// Display the user's initial in a circular avatar.
|
||||
CircleAvatar(
|
||||
radius: 24,
|
||||
backgroundColor: isDark ? Colors.grey[800] : Colors.grey[200],
|
||||
child: Text(
|
||||
balance.userName.isNotEmpty
|
||||
? balance.userName[0].toUpperCase()
|
||||
: '?',
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// User's total paid and owed amounts.
|
||||
Text(
|
||||
'Payé: ${balance.totalPaid.toStringAsFixed(2)} € • Doit: ${balance.totalOwed.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Display the user's balance status and amount.
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// Icon indicating the balance status.
|
||||
Icon(balanceIcon, size: 16, color: balanceColor),
|
||||
const SizedBox(width: 4),
|
||||
// User's absolute balance amount.
|
||||
Text(
|
||||
'${balance.absoluteBalance.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: balanceColor,
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// Display the user's name and financial details.
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// User's name.
|
||||
Text(
|
||||
balance.userName,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
// User's total paid and owed amounts.
|
||||
Text(
|
||||
'Payé: ${balance.totalPaid.toStringAsFixed(2)} € • Doit: ${balance.totalOwed.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Display the user's balance status and amount.
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// Icon indicating the balance status.
|
||||
Icon(balanceIcon, size: 16, color: balanceColor),
|
||||
const SizedBox(width: 4),
|
||||
// User's absolute balance amount.
|
||||
Text(
|
||||
'${balance.absoluteBalance.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: balanceColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Text indicating the balance status (e.g., "À recevoir").
|
||||
Text(
|
||||
balanceText,
|
||||
style: TextStyle(fontSize: 12, color: balanceColor),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Text indicating the balance status (e.g., "À recevoir").
|
||||
Text(
|
||||
balanceText,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: balanceColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
// "Rembourser" button (Only show if this user is owed money and current user is looking at list?
|
||||
// Wait, this list shows balances of everyone.
|
||||
// Requirement: "Il faut un bouton dans la page qui permet de régler l'argent qu'on doit à une certaine personne"
|
||||
// So if I look at "Alice", and Alice "shouldReceive" (is green), it implies the group owes Alice.
|
||||
// But does it mean *I* owe Alice?
|
||||
// The BalancesTab shows the *Group's* balances.
|
||||
// However, usually settlement is 1-on-1. The requirement says: "régler l'argent qu'on doit à une certaine personne".
|
||||
// If the user displayed here 'shouldReceive' money, it means they are owed money.
|
||||
// If I click 'Rembourser', it implies *I* am paying them.
|
||||
// This button should probably be available if the user on the card is POSITIVE (shouldReceive)
|
||||
// AND I am not that user.
|
||||
if (balance.shouldReceive) ...[
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () => _showReimbursementDialog(context, balance),
|
||||
icon: const Icon(Icons.monetization_on_outlined),
|
||||
label: Text('Rembourser ${balance.userName}'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: Colors.green,
|
||||
side: const BorderSide(color: Colors.green),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showReimbursementDialog(
|
||||
BuildContext context,
|
||||
UserBalance payeeBalance,
|
||||
) {
|
||||
final userState = context.read<UserBloc>().state;
|
||||
|
||||
if (userState is! user_state.UserLoaded) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Erreur: utilisateur non connecté')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final currentUser = userState.user;
|
||||
|
||||
// Prevent reimbursing yourself
|
||||
if (payeeBalance.userId == currentUser.id) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Vous ne pouvez pas vous rembourser vous-même'),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AddExpenseDialog(
|
||||
group: group,
|
||||
currentUser: currentUser,
|
||||
initialCategory: ExpenseCategory.reimbursement,
|
||||
initialDescription: 'Remboursement',
|
||||
initialAmount: payeeBalance.absoluteBalance,
|
||||
initialSplits: {
|
||||
payeeBalance.userId: payeeBalance
|
||||
.absoluteBalance, // The payee receives the full amount (as split)
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,185 +42,351 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Formatters for displaying dates and times.
|
||||
final dateFormat = DateFormat('dd MMMM yyyy');
|
||||
final timeFormat = DateFormat('HH:mm');
|
||||
final dateFormat = DateFormat('dd MMMM yyyy', 'fr_FR');
|
||||
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return BlocBuilder<UserBloc, user_state.UserState>(
|
||||
builder: (context, userState) {
|
||||
// Determine the current user and their permissions.
|
||||
final currentUser = userState is user_state.UserLoaded ? userState.user : null;
|
||||
final currentUser = userState is user_state.UserLoaded
|
||||
? userState.user
|
||||
: null;
|
||||
final canEdit = currentUser?.id == expense.paidById;
|
||||
|
||||
return Dialog(
|
||||
backgroundColor: Colors.transparent,
|
||||
insetPadding: const EdgeInsets.all(16),
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 500, maxHeight: 700),
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Détails de la dépense'),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
if (canEdit) ...[
|
||||
// Edit button.
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
_showEditDialog(context, currentUser!);
|
||||
},
|
||||
),
|
||||
// Delete button.
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.red),
|
||||
onPressed: () => _confirmDelete(context),
|
||||
),
|
||||
],
|
||||
// Close button.
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
// Header with icon and description.
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
width: 80,
|
||||
height: 80,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.withValues(alpha: 0.1),
|
||||
shape: BoxShape.circle,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.2),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Header with actions
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 20, 16, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'Détails',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (canEdit) ...[
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
tooltip: 'Modifier',
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
_showEditDialog(context, currentUser!);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.delete_outline,
|
||||
color: Colors.red,
|
||||
),
|
||||
child: Icon(
|
||||
expense.category.icon,
|
||||
size: 40,
|
||||
color: Colors.blue,
|
||||
tooltip: 'Supprimer',
|
||||
onPressed: () => _confirmDelete(context),
|
||||
),
|
||||
],
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(24, 10, 24, 24),
|
||||
children: [
|
||||
// Icon and Category
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
width: 80,
|
||||
height: 80,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer
|
||||
.withValues(alpha: 0.3),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
expense.category.icon,
|
||||
size: 36,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
expense.description,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
expense.category.displayName,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Amount Display
|
||||
Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest
|
||||
.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.outline.withValues(
|
||||
alpha: 0.1,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'Montant total',
|
||||
style: theme.textTheme.labelLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'${expense.amount.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: theme.textTheme.displaySmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
if (expense.currency != ExpenseCurrency.eur)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
'≈ ${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Info Grid
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildInfoCard(
|
||||
context,
|
||||
Icons.person_outline,
|
||||
'Payé par',
|
||||
expense.paidByName,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _buildInfoCard(
|
||||
context,
|
||||
Icons.calendar_today_outlined,
|
||||
'Date',
|
||||
dateFormat.format(expense.date),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Splits Section
|
||||
Text(
|
||||
'Répartition',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.outline.withValues(
|
||||
alpha: 0.1,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
children: expense.splits.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final split = entry.value;
|
||||
final isLast = index == expense.splits.length - 1;
|
||||
return Column(
|
||||
children: [
|
||||
_buildSplitTile(context, split),
|
||||
if (!isLast)
|
||||
Divider(
|
||||
height: 1,
|
||||
indent: 16,
|
||||
endIndent: 16,
|
||||
color: theme.colorScheme.outline.withValues(
|
||||
alpha: 0.1,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
|
||||
// Receipt Section
|
||||
if (expense.receiptUrl != null) ...[
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
expense.description,
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
'Reçu',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
expense.category.displayName,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey[600],
|
||||
const SizedBox(height: 12),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Image.network(
|
||||
expense.receiptUrl!,
|
||||
width: double.infinity,
|
||||
height: 200,
|
||||
fit: BoxFit.cover,
|
||||
loadingBuilder:
|
||||
(context, child, loadingProgress) {
|
||||
if (loadingProgress == null) return child;
|
||||
return Container(
|
||||
height: 200,
|
||||
color: theme
|
||||
.colorScheme
|
||||
.surfaceContainerHighest,
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
},
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
return Container(
|
||||
height: 200,
|
||||
color: theme
|
||||
.colorScheme
|
||||
.surfaceContainerHighest,
|
||||
child: const Center(
|
||||
child: Icon(Icons.broken_image_outlined),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Positioned.fill(
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => Dialog(
|
||||
backgroundColor: Colors.transparent,
|
||||
insetPadding: EdgeInsets.zero,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
InteractiveViewer(
|
||||
minScale: 0.5,
|
||||
maxScale: 4.0,
|
||||
child: Image.network(
|
||||
expense.receiptUrl!,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 40,
|
||||
right: 20,
|
||||
child: IconButton(
|
||||
icon: const Icon(
|
||||
Icons.close,
|
||||
color: Colors.white,
|
||||
size: 30,
|
||||
),
|
||||
onPressed: () => Navigator.of(
|
||||
context,
|
||||
).pop(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Amount card.
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'${expense.amount.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: const TextStyle(
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.green,
|
||||
),
|
||||
),
|
||||
if (expense.currency != ExpenseCurrency.eur)
|
||||
Text(
|
||||
'≈ ${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Colors.grey[600],
|
||||
// Archive Button
|
||||
if (!expense.isArchived && canEdit) ...[
|
||||
const SizedBox(height: 32),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () => _confirmArchive(context),
|
||||
icon: const Icon(Icons.archive_outlined),
|
||||
label: const Text('Archiver cette dépense'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Information rows.
|
||||
_buildInfoRow(Icons.person, 'Payé par', expense.paidByName),
|
||||
_buildInfoRow(Icons.calendar_today, 'Date', dateFormat.format(expense.date)),
|
||||
_buildInfoRow(Icons.access_time, 'Heure', timeFormat.format(expense.createdAt)),
|
||||
|
||||
if (expense.isEdited && expense.editedAt != null)
|
||||
_buildInfoRow(
|
||||
Icons.edit,
|
||||
'Modifié le',
|
||||
dateFormat.format(expense.editedAt!),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// Splits section.
|
||||
const Text(
|
||||
'Répartition',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...expense.splits.map((split) => _buildSplitTile(context, split)),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Receipt section.
|
||||
if (expense.receiptUrl != null) ...[
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Reçu',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Image.network(
|
||||
expense.receiptUrl!,
|
||||
fit: BoxFit.cover,
|
||||
loadingBuilder: (context, child, loadingProgress) {
|
||||
if (loadingProgress == null) return child;
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
},
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
return const Center(
|
||||
child: Text('Erreur de chargement de l\'image'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Archive button.
|
||||
if (!expense.isArchived && canEdit)
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => _confirmArchive(context),
|
||||
icon: const Icon(Icons.archive),
|
||||
label: const Text('Archiver cette dépense'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -228,83 +394,135 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds a row displaying an icon, a label, and a value.
|
||||
Widget _buildInfoRow(IconData icon, String label, String value) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(
|
||||
Widget _buildInfoCard(
|
||||
BuildContext context,
|
||||
IconData icon,
|
||||
String label,
|
||||
String value,
|
||||
) {
|
||||
final theme = Theme.of(context);
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.outline.withValues(alpha: 0.1),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(icon, size: 20, color: Colors.grey[600]),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Icon(icon, size: 16, color: theme.colorScheme.onSurfaceVariant),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
label,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds a tile displaying details about a split in the expense.
|
||||
///
|
||||
/// The tile shows the user's name, the split amount, and whether the split is paid. If the current user
|
||||
/// is responsible for the split and it is unpaid, a button is provided to mark it as paid.
|
||||
Widget _buildSplitTile(BuildContext context, ExpenseSplit split) {
|
||||
return BlocBuilder<UserBloc, user_state.UserState>(
|
||||
builder: (context, userState) {
|
||||
final currentUser = userState is user_state.UserLoaded ? userState.user : null;
|
||||
final currentUser = userState is user_state.UserLoaded
|
||||
? userState.user
|
||||
: null;
|
||||
final isCurrentUser = currentUser?.id == split.userId;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: split.isPaid ? Colors.green : Colors.orange,
|
||||
child: Icon(
|
||||
split.isPaid ? Icons.check : Icons.pending,
|
||||
color: Colors.white,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
split.userName,
|
||||
style: TextStyle(
|
||||
fontWeight: isCurrentUser ? FontWeight.bold : FontWeight.normal,
|
||||
),
|
||||
),
|
||||
subtitle: Text(split.isPaid ? 'Payé' : 'En attente'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'${split.amount.toStringAsFixed(2)} €',
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: split.isPaid
|
||||
? Colors.green.withValues(alpha: 0.1)
|
||||
: Colors.orange.withValues(alpha: 0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
split.isPaid ? Icons.check : Icons.access_time_rounded,
|
||||
color: split.isPaid ? Colors.green : Colors.orange,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
if (!split.isPaid && isCurrentUser) ...[
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.check_circle, color: Colors.green),
|
||||
onPressed: () {
|
||||
context.read<ExpenseBloc>().add(MarkSplitAsPaid(
|
||||
expenseId: expense.id,
|
||||
userId: split.userId,
|
||||
));
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
isCurrentUser ? 'Moi' : split.userName,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
fontWeight: isCurrentUser
|
||||
? FontWeight.bold
|
||||
: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
split.isPaid ? 'Payé' : 'En attente',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: split.isPaid ? Colors.green : Colors.orange,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
'${split.amount.toStringAsFixed(2)} €',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (!split.isPaid && isCurrentUser)
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
context.read<ExpenseBloc>().add(
|
||||
MarkSplitAsPaid(
|
||||
expenseId: expense.id,
|
||||
userId: split.userId,
|
||||
),
|
||||
);
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
'Marquer payé',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -312,7 +530,6 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows a dialog for editing the expense.
|
||||
void _showEditDialog(BuildContext context, user_state.UserModel currentUser) {
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -327,13 +544,14 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows a confirmation dialog for deleting the expense.
|
||||
void _confirmDelete(BuildContext context) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Supprimer la dépense'),
|
||||
content: const Text('Êtes-vous sûr de vouloir supprimer cette dépense ?'),
|
||||
content: const Text(
|
||||
'Êtes-vous sûr de vouloir supprimer cette dépense ?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
@@ -341,9 +559,7 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
context.read<ExpenseBloc>().add(DeleteExpense(
|
||||
expense.id,
|
||||
));
|
||||
context.read<ExpenseBloc>().add(DeleteExpense(expense.id));
|
||||
Navigator.of(dialogContext).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
@@ -355,13 +571,14 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows a confirmation dialog for archiving the expense.
|
||||
void _confirmArchive(BuildContext context) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Archiver la dépense'),
|
||||
content: const Text('Cette dépense sera archivée et n\'apparaîtra plus dans les calculs de balance.'),
|
||||
content: const Text(
|
||||
'Cette dépense sera archivée et n\'apparaîtra plus dans les calculs de balance.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
@@ -369,9 +586,7 @@ class ExpenseDetailDialog extends StatelessWidget {
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
context.read<ExpenseBloc>().add(ArchiveExpense(
|
||||
expense.id,
|
||||
));
|
||||
context.read<ExpenseBloc>().add(ArchiveExpense(expense.id));
|
||||
Navigator.of(dialogContext).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
|
||||
@@ -7,11 +7,13 @@ import 'expense_detail_dialog.dart';
|
||||
class ExpensesTab extends StatelessWidget {
|
||||
final List<Expense> expenses;
|
||||
final Group group;
|
||||
final String currentUserId;
|
||||
|
||||
const ExpensesTab({
|
||||
super.key,
|
||||
required this.expenses,
|
||||
required this.group,
|
||||
required this.currentUserId,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -48,95 +50,159 @@ class ExpensesTab extends StatelessWidget {
|
||||
}
|
||||
|
||||
Widget _buildExpenseCard(BuildContext context, Expense expense) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final dateFormat = DateFormat('dd/MM/yyyy');
|
||||
final theme = Theme.of(context);
|
||||
final isDark = theme.brightness == Brightness.dark;
|
||||
final dateFormat = DateFormat('dd/MM');
|
||||
|
||||
return Card(
|
||||
// Logique pour déterminer l'impact sur l'utilisateur
|
||||
bool isPayer = expense.paidById == currentUserId;
|
||||
double amountToDisplay = expense.amount;
|
||||
bool isPositive = isPayer;
|
||||
|
||||
// Si je suis le payeur, je suis en positif (on me doit de l'argent)
|
||||
// Si je ne suis pas le payeur, je suis en négatif (je dois de l'argent)
|
||||
// Note: Pour être précis, il faudrait calculer ma part exacte, mais pour l'instant
|
||||
// on affiche le total avec la couleur indiquant si j'ai payé ou non.
|
||||
|
||||
final amountColor = isPositive ? Colors.green : Colors.red;
|
||||
final prefix = isPositive ? '+' : '-';
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: InkWell(
|
||||
onTap: () => _showExpenseDetail(context, expense),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: isDark ? Colors.blue[900] : Colors.blue[100],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
decoration: BoxDecoration(
|
||||
color: isDark ? theme.cardColor : Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.05),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: () => _showExpenseDetail(context, expense),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
// Icone circulaire
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: _getCategoryColor(
|
||||
expense.category,
|
||||
).withValues(alpha: 0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
expense.category.icon,
|
||||
color: _getCategoryColor(expense.category),
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
expense.category.icon,
|
||||
color: Colors.blue,
|
||||
const SizedBox(width: 16),
|
||||
|
||||
// Détails
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
expense.description,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
isPayer
|
||||
? 'Payé par vous'
|
||||
: 'Payé par ${expense.paidByName}',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: isDark
|
||||
? Colors.grey[400]
|
||||
: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
' • ${dateFormat.format(expense.date)}',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: isDark
|
||||
? Colors.grey[500]
|
||||
: Colors.grey[500],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
// Montant
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
expense.description,
|
||||
style: const TextStyle(
|
||||
'$prefix${amountToDisplay.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: amountColor,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Payé par ${expense.paidByName}',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
if (expense.currency != ExpenseCurrency.eur)
|
||||
Text(
|
||||
'Total ${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: isDark ? Colors.grey[500] : Colors.grey[400],
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
dateFormat.format(expense.date),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[500] : Colors.grey[500],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
'${expense.amount.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.green,
|
||||
),
|
||||
),
|
||||
if (expense.currency != ExpenseCurrency.eur)
|
||||
Text(
|
||||
'${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _getCategoryColor(ExpenseCategory category) {
|
||||
switch (category) {
|
||||
case ExpenseCategory.restaurant:
|
||||
return Colors.orange;
|
||||
case ExpenseCategory.transport:
|
||||
return Colors.blue;
|
||||
case ExpenseCategory.accommodation:
|
||||
return Colors.purple;
|
||||
case ExpenseCategory.entertainment:
|
||||
return Colors.pink;
|
||||
case ExpenseCategory.shopping:
|
||||
return Colors.teal;
|
||||
case ExpenseCategory.other:
|
||||
return Colors.grey;
|
||||
case ExpenseCategory.reimbursement:
|
||||
return Colors.green;
|
||||
}
|
||||
}
|
||||
|
||||
void _showExpenseDetail(BuildContext context, Expense expense) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => ExpenseDetailDialog(
|
||||
expense: expense,
|
||||
group: group,
|
||||
),
|
||||
builder: (context) => ExpenseDetailDialog(expense: expense, group: group),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ import '../../models/group.dart';
|
||||
import 'add_expense_dialog.dart';
|
||||
import 'balances_tab.dart';
|
||||
import 'expenses_tab.dart';
|
||||
import 'settlements_tab.dart';
|
||||
import '../../models/user_balance.dart';
|
||||
import '../../models/expense.dart';
|
||||
import '../../services/error_service.dart';
|
||||
|
||||
class GroupExpensesPage extends StatefulWidget {
|
||||
final Account account;
|
||||
@@ -31,13 +33,14 @@ class GroupExpensesPage extends StatefulWidget {
|
||||
|
||||
class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
|
||||
late TabController _tabController;
|
||||
|
||||
ExpenseCategory? _selectedCategory;
|
||||
String? _selectedPayerId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: 3, vsync: this);
|
||||
_tabController = TabController(length: 2, vsync: this);
|
||||
_loadData();
|
||||
}
|
||||
|
||||
@@ -50,118 +53,261 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
void _loadData() {
|
||||
// Charger les dépenses du groupe
|
||||
context.read<ExpenseBloc>().add(LoadExpensesByGroup(widget.group.id));
|
||||
|
||||
|
||||
// Charger les balances du groupe
|
||||
context.read<BalanceBloc>().add(LoadGroupBalances(widget.group.id));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: isDarkMode
|
||||
? theme.scaffoldBackgroundColor
|
||||
: Colors.grey[50],
|
||||
appBar: AppBar(
|
||||
title: Text(widget.account.name),
|
||||
backgroundColor: Theme.of(context).primaryColor,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
bottom: TabBar(
|
||||
controller: _tabController,
|
||||
indicatorColor: Colors.white,
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: Colors.white70,
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(Icons.balance),
|
||||
text: 'Balances',
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.receipt_long),
|
||||
text: 'Dépenses',
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.payment),
|
||||
text: 'Règlements',
|
||||
),
|
||||
],
|
||||
title: const Text(
|
||||
'Dépenses du voyage',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
centerTitle: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
actions: [],
|
||||
),
|
||||
body: MultiBlocListener(
|
||||
listeners: [
|
||||
BlocListener<ExpenseBloc, ExpenseState>(
|
||||
listener: (context, state) {
|
||||
if (state is ExpenseOperationSuccess) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.message),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
ErrorService().showSnackbar(
|
||||
message: state.message,
|
||||
isError: false,
|
||||
);
|
||||
_loadData(); // Recharger les données après une opération
|
||||
} else if (state is ExpenseError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.message),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
ErrorService().showError(message: state.message);
|
||||
} else if (state is ExpensesLoaded) {
|
||||
// Rafraîchir les balances quand les dépenses changent (ex: via stream)
|
||||
context.read<BalanceBloc>().add(
|
||||
RefreshBalance(widget.group.id),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
child: Column(
|
||||
children: [
|
||||
// Onglet Balances
|
||||
// Summary Card
|
||||
BlocBuilder<BalanceBloc, BalanceState>(
|
||||
builder: (context, state) {
|
||||
if (state is BalanceLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (state is GroupBalancesLoaded) {
|
||||
return BalancesTab(balances: state.balances);
|
||||
} else if (state is BalanceError) {
|
||||
return _buildErrorState('Erreur lors du chargement des balances: ${state.message}');
|
||||
if (state is GroupBalancesLoaded) {
|
||||
return _buildSummaryCard(state.balances, isDarkMode);
|
||||
}
|
||||
return _buildEmptyState('Aucune balance disponible');
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
|
||||
// Onglet Dépenses
|
||||
BlocBuilder<ExpenseBloc, ExpenseState>(
|
||||
builder: (context, state) {
|
||||
if (state is ExpenseLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (state is ExpensesLoaded) {
|
||||
return ExpensesTab(
|
||||
expenses: state.expenses,
|
||||
group: widget.group,
|
||||
);
|
||||
} else if (state is ExpenseError) {
|
||||
return _buildErrorState('Erreur lors du chargement des dépenses: ${state.message}');
|
||||
}
|
||||
return _buildEmptyState('Aucune dépense trouvée');
|
||||
},
|
||||
|
||||
// Tabs
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
bottom: BorderSide(color: theme.dividerColor, width: 1),
|
||||
),
|
||||
),
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
labelColor: theme.colorScheme.primary,
|
||||
unselectedLabelColor: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.6,
|
||||
),
|
||||
indicatorColor: theme.colorScheme.primary,
|
||||
indicatorWeight: 3,
|
||||
labelStyle: const TextStyle(fontWeight: FontWeight.bold),
|
||||
tabs: const [
|
||||
Tab(text: 'Toutes les dépenses'),
|
||||
Tab(text: 'Mes soldes'),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Onglet Règlements
|
||||
BlocBuilder<BalanceBloc, BalanceState>(
|
||||
builder: (context, state) {
|
||||
if (state is BalanceLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (state is GroupBalancesLoaded) {
|
||||
return SettlementsTab(settlements: state.settlements);
|
||||
} else if (state is BalanceError) {
|
||||
return _buildErrorState('Erreur lors du chargement des règlements: ${state.message}');
|
||||
}
|
||||
return _buildEmptyState('Aucun règlement nécessaire');
|
||||
},
|
||||
|
||||
// Tab View
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
// Onglet Dépenses
|
||||
BlocBuilder<ExpenseBloc, ExpenseState>(
|
||||
builder: (context, state) {
|
||||
if (state is ExpenseLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (state is ExpensesLoaded) {
|
||||
final userState = context.read<UserBloc>().state;
|
||||
final currentUserId = userState is user_state.UserLoaded
|
||||
? userState.user.id
|
||||
: '';
|
||||
|
||||
var filteredExpenses = state.expenses;
|
||||
|
||||
if (_selectedCategory != null) {
|
||||
filteredExpenses = filteredExpenses
|
||||
.where((e) => e.category == _selectedCategory)
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (_selectedPayerId != null) {
|
||||
filteredExpenses = filteredExpenses
|
||||
.where((e) => e.paidById == _selectedPayerId)
|
||||
.toList();
|
||||
}
|
||||
|
||||
return ExpensesTab(
|
||||
expenses: filteredExpenses,
|
||||
group: widget.group,
|
||||
currentUserId: currentUserId,
|
||||
);
|
||||
} else if (state is ExpenseError) {
|
||||
return _buildErrorState('Erreur: ${state.message}');
|
||||
}
|
||||
return _buildEmptyState('Aucune dépense trouvée');
|
||||
},
|
||||
),
|
||||
|
||||
// Onglet Balances (Combiné)
|
||||
BlocBuilder<BalanceBloc, BalanceState>(
|
||||
builder: (context, state) {
|
||||
if (state is BalanceLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (state is GroupBalancesLoaded) {
|
||||
return BalancesTab(
|
||||
balances: state.balances,
|
||||
group: widget.group,
|
||||
);
|
||||
} else if (state is BalanceError) {
|
||||
return _buildErrorState('Erreur: ${state.message}');
|
||||
}
|
||||
return _buildEmptyState('Aucune balance disponible');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
heroTag: 'group_expenses_fab',
|
||||
onPressed: _showAddExpenseDialog,
|
||||
heroTag: "add_expense_fab",
|
||||
backgroundColor: Colors.blue,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 4,
|
||||
shape: const CircleBorder(),
|
||||
tooltip: 'Ajouter une dépense',
|
||||
child: const Icon(Icons.add),
|
||||
child: const Icon(Icons.add, size: 32),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSummaryCard(List<UserBalance> balances, bool isDarkMode) {
|
||||
// Trouver la balance de l'utilisateur courant
|
||||
final userState = context.read<UserBloc>().state;
|
||||
double myBalance = 0;
|
||||
|
||||
if (userState is user_state.UserLoaded) {
|
||||
final myBalanceObj = balances.firstWhere(
|
||||
(b) => b.userId == userState.user.id,
|
||||
orElse: () => const UserBalance(
|
||||
userId: '',
|
||||
userName: '',
|
||||
totalPaid: 0,
|
||||
totalOwed: 0,
|
||||
balance: 0,
|
||||
),
|
||||
);
|
||||
myBalance = myBalanceObj.balance;
|
||||
}
|
||||
|
||||
final isPositive = myBalance >= 0;
|
||||
final color = isPositive ? Colors.green : Colors.red;
|
||||
final amountStr = '${myBalance.abs().toStringAsFixed(2)} €';
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.all(16),
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: isDarkMode ? Colors.grey[800] : Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.05),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Votre solde total',
|
||||
style: TextStyle(
|
||||
color: isDarkMode ? Colors.grey[400] : Colors.grey[600],
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
isPositive ? 'On vous doit ' : 'Vous devez ',
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
amountStr,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
isPositive
|
||||
? 'Vous êtes en positif sur ce voyage.'
|
||||
: 'Vous êtes en négatif sur ce voyage.',
|
||||
style: TextStyle(
|
||||
color: isDarkMode ? Colors.grey[400] : Colors.grey[600],
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
_tabController.animateTo(1); // Aller à l'onglet Balances
|
||||
},
|
||||
child: Text(
|
||||
'Voir le détail des soldes',
|
||||
style: TextStyle(
|
||||
color: Colors.blue[400],
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -171,11 +317,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 80,
|
||||
color: Colors.red[300],
|
||||
),
|
||||
Icon(Icons.error_outline, size: 80, color: Colors.red[300]),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Erreur',
|
||||
@@ -190,10 +332,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32),
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
@@ -213,11 +352,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 80,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
Icon(Icons.info_outline, size: 80, color: Colors.grey[400]),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Aucune donnée',
|
||||
@@ -230,10 +365,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
message,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Colors.grey[500],
|
||||
),
|
||||
style: TextStyle(fontSize: 16, color: Colors.grey[500]),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
@@ -243,22 +375,15 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
|
||||
void _showAddExpenseDialog() {
|
||||
final userState = context.read<UserBloc>().state;
|
||||
|
||||
|
||||
if (userState is user_state.UserLoaded) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AddExpenseDialog(
|
||||
group: widget.group,
|
||||
currentUser: userState.user,
|
||||
),
|
||||
builder: (context) =>
|
||||
AddExpenseDialog(group: widget.group, currentUser: userState.user),
|
||||
);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Erreur: utilisateur non connecté'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: 'Erreur: utilisateur non connecté');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
322
lib/components/activities/activity_detail_dialog.dart
Normal file
322
lib/components/activities/activity_detail_dialog.dart
Normal file
@@ -0,0 +1,322 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../services/map_navigation_service.dart';
|
||||
import '../../models/activity.dart';
|
||||
|
||||
class ActivityDetailDialog extends StatelessWidget {
|
||||
final Activity activity;
|
||||
|
||||
const ActivityDetailDialog({super.key, required this.activity});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
// final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
// Traduction de la catégorie
|
||||
String categoryDisplay = activity.category;
|
||||
final categoryEnum = ActivityCategory.values.firstWhere(
|
||||
(e) => e.name == activity.category,
|
||||
orElse: () => ActivityCategory.attraction, // Fallback
|
||||
);
|
||||
categoryDisplay = categoryEnum.displayName;
|
||||
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
backgroundColor: theme.scaffoldBackgroundColor,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Image header
|
||||
if (activity.imageUrl != null && activity.imageUrl!.isNotEmpty)
|
||||
ClipRRect(
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(16),
|
||||
),
|
||||
child: Image.network(
|
||||
activity.imageUrl!,
|
||||
height: 200,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => Container(
|
||||
height: 100,
|
||||
color: Colors.grey[300],
|
||||
child: const Icon(Icons.image_not_supported, size: 50),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Titre et Catégorie
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
activity.name,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
vertical: 5,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(
|
||||
alpha: 0.1,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
categoryDisplay,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date
|
||||
if (activity.date != null) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.calendar_today,
|
||||
size: 20,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
DateFormat(
|
||||
'EEEE d MMMM yyyy',
|
||||
'fr_FR',
|
||||
).format(activity.date!),
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Heures d'ouverture
|
||||
if (activity.openingHours.isNotEmpty) ...[
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.access_time,
|
||||
size: 20,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: activity.openingHours
|
||||
.map(
|
||||
(hour) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(
|
||||
hour,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Adresse
|
||||
if (activity.address != null) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.location_on,
|
||||
size: 20,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
activity.address!,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Description
|
||||
if (activity.description.isNotEmpty) ...[
|
||||
Text(
|
||||
'Description',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
activity.description,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Votes
|
||||
if (activity.votes.isNotEmpty) ...[
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
_buildVoteStat(
|
||||
Icons.thumb_up,
|
||||
Colors.green,
|
||||
activity.positiveVotes,
|
||||
'Pour',
|
||||
),
|
||||
_buildVoteStat(
|
||||
Icons.thumb_down,
|
||||
Colors.red,
|
||||
activity.negativeVotes,
|
||||
'Contre',
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Boutons
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
if (activity.latitude != null && activity.longitude != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: () {
|
||||
// Déclencher la navigation
|
||||
context
|
||||
.read<MapNavigationService>()
|
||||
.navigateToLocation(
|
||||
activity.latitude!,
|
||||
activity.longitude!,
|
||||
name: activity.name,
|
||||
);
|
||||
|
||||
// Revenir à la page d'accueil (fermer le dialog et les pages empilées comme ActivitiesPage)
|
||||
Navigator.of(
|
||||
context,
|
||||
).popUntil((route) => route.isFirst);
|
||||
},
|
||||
icon: const Icon(Icons.map_outlined),
|
||||
label: const Text('Voir sur la carte de l\'app'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 12,
|
||||
horizontal: 24,
|
||||
),
|
||||
backgroundColor:
|
||||
theme.colorScheme.secondaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.onSecondaryContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(
|
||||
'https://www.google.com/maps/search/?api=1&query=${activity.latitude},${activity.longitude}',
|
||||
);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(
|
||||
url,
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.map),
|
||||
label: const Text('Voir sur Google Maps'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 12,
|
||||
horizontal: 24,
|
||||
),
|
||||
backgroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
minimumSize: const Size(double.infinity, 45),
|
||||
),
|
||||
child: const Text('Fermer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildVoteStat(IconData icon, Color color, int count, String label) {
|
||||
return Column(
|
||||
children: [
|
||||
Icon(icon, color: color),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'$count',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
Text(label, style: const TextStyle(fontSize: 12, color: Colors.grey)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'dart:math' as math;
|
||||
import '../../blocs/activity/activity_bloc.dart';
|
||||
import '../../blocs/activity/activity_event.dart';
|
||||
@@ -25,6 +26,7 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
|
||||
final ErrorService _errorService = ErrorService();
|
||||
|
||||
ActivityCategory _selectedCategory = ActivityCategory.attraction;
|
||||
DateTime? _selectedDate;
|
||||
bool _isLoading = false;
|
||||
|
||||
@override
|
||||
@@ -57,7 +59,7 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
|
||||
height: 4,
|
||||
margin: const EdgeInsets.symmetric(vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.3),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
@@ -149,6 +151,13 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
|
||||
icon: Icons.location_on,
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Date et heure (optionnel)
|
||||
_buildSectionTitle('Date et heure (optionnel)'),
|
||||
const SizedBox(height: 8),
|
||||
_buildDateTimePicker(),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// Boutons d'action
|
||||
@@ -368,6 +377,8 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
|
||||
votes: {},
|
||||
createdAt: DateTime.now(),
|
||||
updatedAt: DateTime.now(),
|
||||
date: _selectedDate,
|
||||
createdBy: FirebaseAuth.instance.currentUser?.uid,
|
||||
);
|
||||
|
||||
context.read<ActivityBloc>().add(AddActivity(activity));
|
||||
@@ -412,4 +423,92 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
|
||||
return Icons.spa;
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildDateTimePicker() {
|
||||
final theme = Theme.of(context);
|
||||
final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
return InkWell(
|
||||
onTap: _pickDateTime,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isDarkMode
|
||||
? Colors.white.withValues(alpha: 0.2)
|
||||
: Colors.black.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.calendar_today,
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
_selectedDate != null
|
||||
? '${_selectedDate!.day}/${_selectedDate!.month}/${_selectedDate!.year} à ${_selectedDate!.hour}:${_selectedDate!.minute.toString().padLeft(2, '0')}'
|
||||
: 'Choisir une date et une heure',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: _selectedDate != null
|
||||
? theme.colorScheme.onSurface
|
||||
: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (_selectedDate != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.clear, size: 20),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_selectedDate = null;
|
||||
});
|
||||
},
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickDateTime() async {
|
||||
final now = DateTime.now();
|
||||
final initialDate = widget.trip.startDate.isAfter(now)
|
||||
? widget.trip.startDate
|
||||
: now;
|
||||
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate ?? initialDate,
|
||||
firstDate: now.subtract(const Duration(days: 365)),
|
||||
lastDate: now.add(const Duration(days: 365 * 2)),
|
||||
);
|
||||
|
||||
if (date == null) return;
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
final time = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay.fromDateTime(_selectedDate ?? now),
|
||||
);
|
||||
|
||||
if (time == null) return;
|
||||
|
||||
setState(() {
|
||||
_selectedDate = DateTime(
|
||||
date.year,
|
||||
date.month,
|
||||
date.day,
|
||||
time.hour,
|
||||
time.minute,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A reusable error display component.
|
||||
///
|
||||
///
|
||||
/// This widget provides a consistent way to display error messages throughout
|
||||
/// the application. It supports customizable titles, messages, icons, and
|
||||
/// action buttons for retry and close operations.
|
||||
class ErrorContent extends StatelessWidget {
|
||||
/// The error title to display
|
||||
final String title;
|
||||
|
||||
|
||||
/// The error message to display
|
||||
final String message;
|
||||
|
||||
|
||||
/// Optional callback for retry action
|
||||
final VoidCallback? onRetry;
|
||||
|
||||
|
||||
/// Optional callback for close action
|
||||
final VoidCallback? onClose;
|
||||
|
||||
|
||||
/// Icon to display with the error
|
||||
final IconData icon;
|
||||
|
||||
|
||||
/// Color of the error icon
|
||||
final Color? iconColor;
|
||||
|
||||
/// Creates a new [ErrorContent] widget.
|
||||
///
|
||||
///
|
||||
/// [message] is required, other parameters are optional with sensible defaults.
|
||||
const ErrorContent({
|
||||
super.key,
|
||||
@@ -79,11 +79,7 @@ class ErrorContent extends StatelessWidget {
|
||||
color: defaultIconColor?.withValues(alpha: 0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
size: 48,
|
||||
color: defaultIconColor,
|
||||
),
|
||||
child: Icon(icon, size: 48, color: defaultIconColor),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
@@ -167,9 +163,7 @@ void showErrorDialog(
|
||||
barrierDismissible: barrierDismissible,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: ErrorContent(
|
||||
title: title,
|
||||
message: message,
|
||||
@@ -187,70 +181,3 @@ void showErrorDialog(
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Fonction helper pour afficher l'erreur en bottom sheet
|
||||
void showErrorBottomSheet(
|
||||
BuildContext context, {
|
||||
String title = 'Une erreur est survenue',
|
||||
required String message,
|
||||
VoidCallback? onRetry,
|
||||
IconData icon = Icons.error_outline,
|
||||
Color? iconColor,
|
||||
bool isDismissible = true,
|
||||
}) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isDismissible: isDismissible,
|
||||
enableDrag: isDismissible,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (BuildContext sheetContext) {
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: ErrorContent(
|
||||
title: title,
|
||||
message: message,
|
||||
icon: icon,
|
||||
iconColor: iconColor,
|
||||
onRetry: onRetry != null
|
||||
? () {
|
||||
Navigator.of(sheetContext).pop();
|
||||
onRetry();
|
||||
}
|
||||
: null,
|
||||
onClose: () => Navigator.of(sheetContext).pop(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Fonction helper pour afficher en SnackBar (pour erreurs mineures)
|
||||
void showErrorSnackBar(
|
||||
BuildContext context, {
|
||||
required String message,
|
||||
VoidCallback? onRetry,
|
||||
Duration duration = const Duration(seconds: 4),
|
||||
}) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(message),
|
||||
backgroundColor: Colors.red[400],
|
||||
duration: duration,
|
||||
action: onRetry != null
|
||||
? SnackBarAction(
|
||||
label: 'Réessayer',
|
||||
textColor: Colors.white,
|
||||
onPressed: onRetry,
|
||||
)
|
||||
: null,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'dart:async';
|
||||
import '../../blocs/user/user_bloc.dart';
|
||||
import '../../blocs/user/user_state.dart' as user_state;
|
||||
import '../../blocs/message/message_bloc.dart';
|
||||
import '../../blocs/message/message_event.dart';
|
||||
import '../../blocs/message/message_state.dart';
|
||||
import '../../models/group.dart';
|
||||
import '../../models/group_member.dart';
|
||||
import '../../models/message.dart';
|
||||
import '../../repositories/group_repository.dart';
|
||||
import '../../services/error_service.dart';
|
||||
|
||||
/// Chat group content widget for group messaging functionality.
|
||||
///
|
||||
///
|
||||
/// This widget provides a complete chat interface for group members to
|
||||
/// communicate within a travel group. Features include:
|
||||
/// - Real-time message loading and sending
|
||||
@@ -17,7 +21,7 @@ import '../../models/message.dart';
|
||||
/// - Message reactions (like/unlike)
|
||||
/// - Scroll-to-bottom functionality
|
||||
/// - Message status indicators
|
||||
///
|
||||
///
|
||||
/// The widget integrates with MessageBloc for state management and
|
||||
/// handles various message operations through the bloc pattern.
|
||||
class ChatGroupContent extends StatefulWidget {
|
||||
@@ -25,13 +29,10 @@ class ChatGroupContent extends StatefulWidget {
|
||||
final Group group;
|
||||
|
||||
/// Creates a chat group content widget.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [group]: The group object containing group details and ID
|
||||
const ChatGroupContent({
|
||||
super.key,
|
||||
required this.group,
|
||||
});
|
||||
const ChatGroupContent({super.key, required this.group});
|
||||
|
||||
@override
|
||||
State<ChatGroupContent> createState() => _ChatGroupContentState();
|
||||
@@ -40,33 +41,52 @@ class ChatGroupContent extends StatefulWidget {
|
||||
class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
/// Controller for the message input field
|
||||
final _messageController = TextEditingController();
|
||||
|
||||
|
||||
/// Controller for managing scroll position in the message list
|
||||
final _scrollController = ScrollController();
|
||||
|
||||
|
||||
/// Currently selected message for editing (null if not editing)
|
||||
Message? _editingMessage;
|
||||
|
||||
/// Repository pour gérer les groupes
|
||||
final _groupRepository = GroupRepository();
|
||||
|
||||
/// Subscription pour écouter les changements des membres du groupe
|
||||
late StreamSubscription<List<GroupMember>> _membersSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Load messages when the widget initializes
|
||||
context.read<MessageBloc>().add(LoadMessages(widget.group.id));
|
||||
|
||||
// Écouter les changements des membres du groupe
|
||||
_membersSubscription = _groupRepository
|
||||
.watchGroupMembers(widget.group.id)
|
||||
.listen((updatedMembers) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
widget.group.members.clear();
|
||||
widget.group.members.addAll(updatedMembers);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_messageController.dispose();
|
||||
_scrollController.dispose();
|
||||
_membersSubscription.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Sends a new message or updates an existing message.
|
||||
///
|
||||
///
|
||||
/// Handles both sending new messages and editing existing ones based
|
||||
/// on the current editing state. Validates input and clears the input
|
||||
/// field after successful submission.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [currentUser]: The user sending or editing the message
|
||||
void _sendMessage(user_state.UserModel currentUser) {
|
||||
@@ -76,33 +96,33 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
if (_editingMessage != null) {
|
||||
// Edit mode - update existing message
|
||||
context.read<MessageBloc>().add(
|
||||
UpdateMessage(
|
||||
groupId: widget.group.id,
|
||||
messageId: _editingMessage!.id,
|
||||
newText: messageText,
|
||||
),
|
||||
);
|
||||
UpdateMessage(
|
||||
groupId: widget.group.id,
|
||||
messageId: _editingMessage!.id,
|
||||
newText: messageText,
|
||||
),
|
||||
);
|
||||
_cancelEdit();
|
||||
} else {
|
||||
// Send mode - create new message
|
||||
context.read<MessageBloc>().add(
|
||||
SendMessage(
|
||||
groupId: widget.group.id,
|
||||
text: messageText,
|
||||
senderId: currentUser.id,
|
||||
senderName: currentUser.prenom,
|
||||
),
|
||||
);
|
||||
SendMessage(
|
||||
groupId: widget.group.id,
|
||||
text: messageText,
|
||||
senderId: currentUser.id,
|
||||
senderName: currentUser.prenom,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
_messageController.clear();
|
||||
}
|
||||
|
||||
/// Initiates editing mode for a selected message.
|
||||
///
|
||||
///
|
||||
/// Sets the message as the currently editing message and populates
|
||||
/// the input field with the message text for modification.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [message]: The message to edit
|
||||
void _editMessage(Message message) {
|
||||
@@ -113,7 +133,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
}
|
||||
|
||||
/// Cancels the current editing operation.
|
||||
///
|
||||
///
|
||||
/// Resets the editing state and clears the input field,
|
||||
/// returning to normal message sending mode.
|
||||
void _cancelEdit() {
|
||||
@@ -124,46 +144,43 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
}
|
||||
|
||||
/// Deletes a message from the group chat.
|
||||
///
|
||||
///
|
||||
/// Sends a delete event to the MessageBloc to remove the specified
|
||||
/// message from the group's message history.
|
||||
///
|
||||
///
|
||||
/// Args:
|
||||
/// [messageId]: The ID of the message to delete
|
||||
void _deleteMessage(String messageId) {
|
||||
context.read<MessageBloc>().add(
|
||||
DeleteMessage(
|
||||
groupId: widget.group.id,
|
||||
messageId: messageId,
|
||||
),
|
||||
);
|
||||
DeleteMessage(groupId: widget.group.id, messageId: messageId),
|
||||
);
|
||||
}
|
||||
|
||||
void _reactToMessage(String messageId, String userId, String reaction) {
|
||||
context.read<MessageBloc>().add(
|
||||
ReactToMessage(
|
||||
groupId: widget.group.id,
|
||||
messageId: messageId,
|
||||
userId: userId,
|
||||
reaction: reaction,
|
||||
),
|
||||
);
|
||||
ReactToMessage(
|
||||
groupId: widget.group.id,
|
||||
messageId: messageId,
|
||||
userId: userId,
|
||||
reaction: reaction,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _removeReaction(String messageId, String userId) {
|
||||
context.read<MessageBloc>().add(
|
||||
RemoveReaction(
|
||||
groupId: widget.group.id,
|
||||
messageId: messageId,
|
||||
userId: userId,
|
||||
),
|
||||
);
|
||||
RemoveReaction(
|
||||
groupId: widget.group.id,
|
||||
messageId: messageId,
|
||||
userId: userId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
|
||||
return BlocBuilder<UserBloc, user_state.UserState>(
|
||||
builder: (context, userState) {
|
||||
if (userState is! user_state.UserLoaded) {
|
||||
@@ -183,7 +200,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
Text(widget.group.name, style: const TextStyle(fontSize: 18)),
|
||||
Text(
|
||||
'${widget.group.members.length} membre${widget.group.members.length > 1 ? 's' : ''}',
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.normal),
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -201,12 +221,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
child: BlocConsumer<MessageBloc, MessageState>(
|
||||
listener: (context, state) {
|
||||
if (state is MessageError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.message),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: state.message);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
@@ -235,7 +250,8 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
itemBuilder: (context, index) {
|
||||
final message = state.messages[index];
|
||||
final isMe = message.senderId == currentUser.id;
|
||||
final showDate = index == 0 ||
|
||||
final showDate =
|
||||
index == 0 ||
|
||||
!_isSameDay(
|
||||
state.messages[index - 1].timestamp,
|
||||
message.timestamp,
|
||||
@@ -243,8 +259,14 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
if (showDate) _buildDateSeparator(message.timestamp),
|
||||
_buildMessageBubble(message, isMe, isDark, currentUser.id),
|
||||
if (showDate)
|
||||
_buildDateSeparator(message.timestamp),
|
||||
_buildMessageBubble(
|
||||
message,
|
||||
isMe,
|
||||
isDark,
|
||||
currentUser.id,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
@@ -260,14 +282,15 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
if (_editingMessage != null)
|
||||
Container(
|
||||
color: isDark ? Colors.blue[900] : Colors.blue[100],
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.edit, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
const Expanded(
|
||||
child: Text('Modification du message'),
|
||||
),
|
||||
const Expanded(child: Text('Modification du message')),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: _cancelEdit,
|
||||
@@ -295,11 +318,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
child: TextField(
|
||||
controller: _messageController,
|
||||
decoration: InputDecoration(
|
||||
hintText: _editingMessage != null
|
||||
? 'Modifier le message...'
|
||||
hintText: _editingMessage != null
|
||||
? 'Modifier le message...'
|
||||
: 'Écrire un message...',
|
||||
filled: true,
|
||||
fillColor: isDark ? Colors.grey[850] : Colors.grey[100],
|
||||
fillColor: isDark
|
||||
? Colors.grey[850]
|
||||
: Colors.grey[100],
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
borderSide: BorderSide.none,
|
||||
@@ -309,16 +334,21 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
maxLines: null,
|
||||
maxLines: 5,
|
||||
minLines: 1,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
onPressed: () => _sendMessage(currentUser),
|
||||
icon: Icon(_editingMessage != null ? Icons.check : Icons.send),
|
||||
icon: Icon(
|
||||
_editingMessage != null ? Icons.check : Icons.send,
|
||||
),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.all(12),
|
||||
),
|
||||
@@ -341,27 +371,17 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.chat_bubble_outline,
|
||||
size: 80,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
Icon(Icons.chat_bubble_outline, size: 80, color: Colors.grey[400]),
|
||||
const SizedBox(height: 16),
|
||||
const Text(
|
||||
'Aucun message',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Commencez la conversation !',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -369,10 +389,15 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMessageBubble(Message message, bool isMe, bool isDark, String currentUserId) {
|
||||
Widget _buildMessageBubble(
|
||||
Message message,
|
||||
bool isMe,
|
||||
bool isDark,
|
||||
String currentUserId,
|
||||
) {
|
||||
final Color bubbleColor;
|
||||
final Color textColor;
|
||||
|
||||
|
||||
if (isMe) {
|
||||
bubbleColor = isDark ? const Color(0xFF1E3A5F) : const Color(0xFF90CAF9);
|
||||
textColor = isDark ? Colors.white : Colors.black87;
|
||||
@@ -380,77 +405,140 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
bubbleColor = isDark ? Colors.grey[800]! : Colors.grey[200]!;
|
||||
textColor = isDark ? Colors.white : Colors.black87;
|
||||
}
|
||||
|
||||
|
||||
// Trouver le membre qui a envoyé le message pour récupérer son pseudo actuel
|
||||
final senderMember = widget.group.members.cast<GroupMember?>().firstWhere(
|
||||
(m) => m?.userId == message.senderId,
|
||||
orElse: () => null,
|
||||
);
|
||||
|
||||
// Utiliser le pseudo actuel du membre, ou le senderName en fallback
|
||||
final displayName = senderMember != null
|
||||
? senderMember.pseudo
|
||||
: message.senderName;
|
||||
|
||||
return Align(
|
||||
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: GestureDetector(
|
||||
onLongPress: () => _showMessageOptions(context, message, isMe, currentUserId),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: MediaQuery.of(context).size.width * 0.7,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: bubbleColor,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(16),
|
||||
topRight: const Radius.circular(16),
|
||||
bottomLeft: Radius.circular(isMe ? 16 : 4),
|
||||
bottomRight: Radius.circular(isMe ? 4 : 16),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
||||
onLongPress: () =>
|
||||
_showMessageOptions(context, message, isMe, currentUserId),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: Row(
|
||||
mainAxisAlignment: isMe
|
||||
? MainAxisAlignment.end
|
||||
: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// Avatar du sender (seulement pour les autres messages)
|
||||
if (!isMe) ...[
|
||||
Text(
|
||||
message.senderName,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[700],
|
||||
CircleAvatar(
|
||||
radius: 16,
|
||||
backgroundImage:
|
||||
(senderMember != null &&
|
||||
senderMember.profilePictureUrl != null &&
|
||||
senderMember.profilePictureUrl!.isNotEmpty)
|
||||
? NetworkImage(senderMember.profilePictureUrl!)
|
||||
: null,
|
||||
child:
|
||||
(senderMember == null ||
|
||||
senderMember.profilePictureUrl == null ||
|
||||
senderMember.profilePictureUrl!.isEmpty)
|
||||
? Text(
|
||||
displayName.isNotEmpty
|
||||
? displayName[0].toUpperCase()
|
||||
: '?',
|
||||
style: const TextStyle(fontSize: 12),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
|
||||
Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 10,
|
||||
),
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: MediaQuery.of(context).size.width * 0.65,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: bubbleColor,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(16),
|
||||
topRight: const Radius.circular(16),
|
||||
bottomLeft: Radius.circular(isMe ? 16 : 4),
|
||||
bottomRight: Radius.circular(isMe ? 4 : 16),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
Text(
|
||||
message.text,
|
||||
style: TextStyle(fontSize: 15, color: textColor),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_formatTime(message.timestamp),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: textColor.withValues(alpha: 0.7),
|
||||
),
|
||||
),
|
||||
if (message.isEdited) ...[
|
||||
const SizedBox(width: 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: isMe
|
||||
? CrossAxisAlignment.end
|
||||
: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!isMe) ...[
|
||||
Text(
|
||||
displayName,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[700],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
Text(
|
||||
'(modifié)',
|
||||
message.isDeleted
|
||||
? 'a supprimé un message'
|
||||
: message.text,
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: textColor.withValues(alpha: 0.6),
|
||||
fontSize: 15,
|
||||
color: message.isDeleted
|
||||
? textColor.withValues(alpha: 0.5)
|
||||
: textColor,
|
||||
fontStyle: message.isDeleted
|
||||
? FontStyle.italic
|
||||
: FontStyle.normal,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_formatTime(message.timestamp),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: textColor.withValues(alpha: 0.7),
|
||||
),
|
||||
),
|
||||
if (message.isEdited) ...[
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'(modifié)',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: textColor.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
// Afficher les réactions
|
||||
if (message.reactions.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Wrap(
|
||||
spacing: 4,
|
||||
children: _buildReactionChips(message, currentUserId),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
// Afficher les réactions
|
||||
if (message.reactions.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Wrap(
|
||||
spacing: 4,
|
||||
children: _buildReactionChips(message, currentUserId),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -460,7 +548,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
|
||||
List<Widget> _buildReactionChips(Message message, String currentUserId) {
|
||||
final reactionCounts = <String, List<String>>{};
|
||||
|
||||
|
||||
// Grouper les réactions par emoji
|
||||
message.reactions.forEach((userId, emoji) {
|
||||
reactionCounts.putIfAbsent(emoji, () => []).add(userId);
|
||||
@@ -482,7 +570,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: hasReacted
|
||||
color: hasReacted
|
||||
? Colors.blue.withValues(alpha: 0.3)
|
||||
: Colors.grey.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -497,7 +585,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
const SizedBox(width: 2),
|
||||
Text(
|
||||
'${userIds.length}',
|
||||
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
|
||||
style: const TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -506,7 +597,12 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
}).toList();
|
||||
}
|
||||
|
||||
void _showMessageOptions(BuildContext context, Message message, bool isMe, String currentUserId) {
|
||||
void _showMessageOptions(
|
||||
BuildContext context,
|
||||
Message message,
|
||||
bool isMe,
|
||||
String currentUserId,
|
||||
) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
@@ -541,7 +637,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.delete, color: Colors.red),
|
||||
title: const Text('Supprimer', style: TextStyle(color: Colors.red)),
|
||||
title: const Text(
|
||||
'Supprimer',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_showDeleteConfirmation(context, message.id);
|
||||
@@ -642,11 +741,55 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
itemCount: widget.group.members.length,
|
||||
itemBuilder: (context, index) {
|
||||
final member = widget.group.members[index];
|
||||
final initials = member.pseudo.isNotEmpty
|
||||
? member.pseudo[0].toUpperCase()
|
||||
: (member.firstName.isNotEmpty
|
||||
? member.firstName[0].toUpperCase()
|
||||
: '?');
|
||||
|
||||
// Construire le nom complet
|
||||
final fullName = '${member.firstName} ${member.lastName}'.trim();
|
||||
|
||||
return ListTile(
|
||||
leading: CircleAvatar(
|
||||
child: Text(member.pseudo.substring(0, 1).toUpperCase()),
|
||||
backgroundImage:
|
||||
(member.profilePictureUrl != null &&
|
||||
member.profilePictureUrl!.isNotEmpty)
|
||||
? NetworkImage(member.profilePictureUrl!)
|
||||
: null,
|
||||
child:
|
||||
(member.profilePictureUrl == null ||
|
||||
member.profilePictureUrl!.isEmpty)
|
||||
? Text(initials)
|
||||
: null,
|
||||
),
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(member.pseudo),
|
||||
if (fullName.isNotEmpty)
|
||||
Text(
|
||||
fullName,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: member.role == 'admin'
|
||||
? const Text(
|
||||
'Administrateur',
|
||||
style: TextStyle(fontSize: 12),
|
||||
)
|
||||
: null,
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.edit, size: 18),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
_showChangePseudoDialog(member);
|
||||
},
|
||||
),
|
||||
title: Text(member.pseudo),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -660,4 +803,80 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _showChangePseudoDialog(dynamic member) {
|
||||
final pseudoController = TextEditingController(text: member.pseudo);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor:
|
||||
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
|
||||
title: Text(
|
||||
'Changer le pseudo',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
content: TextField(
|
||||
controller: pseudoController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Nouveau pseudo',
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
style: TextStyle(color: theme.colorScheme.onSurface),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(
|
||||
'Annuler',
|
||||
style: TextStyle(color: theme.colorScheme.primary),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
final newPseudo = pseudoController.text.trim();
|
||||
if (newPseudo.isNotEmpty) {
|
||||
_updateMemberPseudo(member, newPseudo);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
},
|
||||
child: Text(
|
||||
'Valider',
|
||||
style: TextStyle(color: theme.colorScheme.primary),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _updateMemberPseudo(dynamic member, String newPseudo) async {
|
||||
try {
|
||||
final updatedMember = member.copyWith(pseudo: newPseudo);
|
||||
await _groupRepository.addMember(widget.group.id, updatedMember);
|
||||
|
||||
if (mounted) {
|
||||
// Le stream listener va automatiquement mettre à jour les membres
|
||||
// Pas besoin de fermer le dialog ou de faire un refresh manuel
|
||||
|
||||
ErrorService().showSnackbar(
|
||||
message: 'Pseudo modifié en "$newPseudo"',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ErrorService().showError(
|
||||
message: 'Erreur lors de la modification du pseudo: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/components/error/error_content.dart';
|
||||
import '../../services/error_service.dart';
|
||||
import 'package:travel_mate/components/group/chat_group_content.dart';
|
||||
import 'package:travel_mate/components/widgets/user_state_widget.dart';
|
||||
import '../../blocs/user/user_bloc.dart';
|
||||
@@ -50,19 +50,12 @@ class _GroupContentState extends State<GroupContent> {
|
||||
return BlocConsumer<GroupBloc, GroupState>(
|
||||
listener: (context, groupState) {
|
||||
if (groupState is GroupOperationSuccess) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(groupState.message),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
ErrorService().showSnackbar(
|
||||
message: groupState.message,
|
||||
isError: false,
|
||||
);
|
||||
} else if (groupState is GroupError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(groupState.message),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: groupState.message);
|
||||
}
|
||||
},
|
||||
builder: (context, groupState) {
|
||||
@@ -127,17 +120,6 @@ class _GroupContentState extends State<GroupContent> {
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const Text(
|
||||
'Mes groupes',
|
||||
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Discutez avec les participants',
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[600]),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
...groups.map((group) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
@@ -155,12 +137,9 @@ class _GroupContentState extends State<GroupContent> {
|
||||
final color = colors[group.name.hashCode.abs() % colors.length];
|
||||
|
||||
// Membres de manière simple
|
||||
String memberInfo = '${group.members.length} membre(s)';
|
||||
String memberInfo = '${group.memberIds.length} membre(s)';
|
||||
if (group.members.isNotEmpty) {
|
||||
final names = group.members
|
||||
.take(2)
|
||||
.map((m) => m.pseudo.isNotEmpty ? m.pseudo : m.firstName)
|
||||
.join(', ');
|
||||
final names = group.members.take(2).map((m) => m.firstName).join(', ');
|
||||
memberInfo += '\n$names';
|
||||
}
|
||||
|
||||
@@ -223,8 +202,7 @@ class _GroupContentState extends State<GroupContent> {
|
||||
if (mounted) {
|
||||
if (retry) {
|
||||
if (userId == '') {
|
||||
showErrorDialog(
|
||||
context,
|
||||
ErrorService().showError(
|
||||
title: 'Erreur utilisateur',
|
||||
message: 'Utilisateur non connecté. Veuillez vous reconnecter.',
|
||||
icon: Icons.error,
|
||||
@@ -234,8 +212,7 @@ class _GroupContentState extends State<GroupContent> {
|
||||
},
|
||||
);
|
||||
} else {
|
||||
showErrorDialog(
|
||||
context,
|
||||
ErrorService().showError(
|
||||
title: 'Erreur de chargement',
|
||||
message: error,
|
||||
icon: Icons.cloud_off,
|
||||
@@ -246,8 +223,7 @@ class _GroupContentState extends State<GroupContent> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
showErrorDialog(
|
||||
context,
|
||||
ErrorService().showError(
|
||||
title: 'Erreur',
|
||||
message: error,
|
||||
icon: Icons.error,
|
||||
|
||||
487
lib/components/home/calendar/calendar_page.dart
Normal file
487
lib/components/home/calendar/calendar_page.dart
Normal file
@@ -0,0 +1,487 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../models/trip.dart';
|
||||
import '../../../models/activity.dart';
|
||||
import '../../../blocs/activity/activity_bloc.dart';
|
||||
import '../../../blocs/activity/activity_state.dart';
|
||||
import '../../../blocs/activity/activity_event.dart';
|
||||
import '../../../repositories/user_repository.dart';
|
||||
import '../../../models/user.dart';
|
||||
|
||||
class CalendarPage extends StatefulWidget {
|
||||
final Trip trip;
|
||||
|
||||
const CalendarPage({super.key, required this.trip});
|
||||
|
||||
@override
|
||||
State<CalendarPage> createState() => _CalendarPageState();
|
||||
}
|
||||
|
||||
class _CalendarPageState extends State<CalendarPage> {
|
||||
late DateTime _focusedDay;
|
||||
DateTime? _selectedDay;
|
||||
final CalendarFormat _calendarFormat = CalendarFormat.week;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focusedDay = widget.trip.startDate;
|
||||
_selectedDay = _focusedDay;
|
||||
}
|
||||
|
||||
List<Activity> _getActivitiesForDay(DateTime day, List<Activity> activities) {
|
||||
return activities.where((activity) {
|
||||
if (activity.date == null) return false;
|
||||
return isSameDay(activity.date, day);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
Future<void> _selectTimeAndSchedule(Activity activity, DateTime date) async {
|
||||
final TimeOfDay? pickedTime = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay.now(),
|
||||
builder: (BuildContext context, Widget? child) {
|
||||
return MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
|
||||
child: child!,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (pickedTime != null && mounted) {
|
||||
final scheduledDate = DateTime(
|
||||
date.year,
|
||||
date.month,
|
||||
date.day,
|
||||
pickedTime.hour,
|
||||
pickedTime.minute,
|
||||
);
|
||||
|
||||
context.read<ActivityBloc>().add(
|
||||
UpdateActivityDate(
|
||||
tripId: widget.trip.id!,
|
||||
activityId: activity.id,
|
||||
date: scheduledDate,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: isDarkMode
|
||||
? theme.scaffoldBackgroundColor
|
||||
: Colors.white,
|
||||
appBar: AppBar(
|
||||
title: Text(
|
||||
widget.trip.title,
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
centerTitle: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: Icon(Icons.arrow_back_ios, color: theme.colorScheme.onSurface),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.people, color: theme.colorScheme.onSurface),
|
||||
onPressed: () => _showParticipantsDialog(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: BlocBuilder<ActivityBloc, ActivityState>(
|
||||
builder: (context, state) {
|
||||
if (state is ActivityLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
List<Activity> allActivities = [];
|
||||
if (state is ActivityLoaded) {
|
||||
allActivities = state.activities;
|
||||
} else if (state is ActivitySearchResults) {
|
||||
// Fallback if we are in search state
|
||||
}
|
||||
|
||||
// Filter approved activities
|
||||
final approvedActivities = allActivities.where((a) {
|
||||
return a.isApprovedByAllParticipants([
|
||||
...widget.trip.participants,
|
||||
widget.trip.createdBy,
|
||||
]);
|
||||
}).toList();
|
||||
|
||||
final scheduledActivities = approvedActivities
|
||||
.where((a) => a.date != null)
|
||||
.toList();
|
||||
|
||||
final unscheduledActivities = approvedActivities
|
||||
.where((a) => a.date == null)
|
||||
.toList();
|
||||
|
||||
final selectedActivities = _getActivitiesForDay(
|
||||
_selectedDay ?? _focusedDay,
|
||||
scheduledActivities,
|
||||
);
|
||||
|
||||
// Sort by time
|
||||
selectedActivities.sort((a, b) => a.date!.compareTo(b.date!));
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
// Calendar Strip
|
||||
Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: isDarkMode ? theme.cardColor : Colors.grey[100],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: TableCalendar(
|
||||
firstDay: DateTime.now().subtract(const Duration(days: 365)),
|
||||
lastDay: DateTime.now().add(const Duration(days: 365)),
|
||||
focusedDay: _focusedDay,
|
||||
calendarFormat: _calendarFormat,
|
||||
headerStyle: HeaderStyle(
|
||||
formatButtonVisible: false,
|
||||
titleCentered: true,
|
||||
titleTextStyle: theme.textTheme.titleLarge!.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
leftChevronIcon: const Icon(Icons.chevron_left),
|
||||
rightChevronIcon: const Icon(Icons.chevron_right),
|
||||
),
|
||||
calendarStyle: CalendarStyle(
|
||||
todayDecoration: BoxDecoration(
|
||||
color: Colors.blue.withValues(alpha: 0.3),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
selectedDecoration: const BoxDecoration(
|
||||
color: Colors.blue,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
markerDecoration: const BoxDecoration(
|
||||
color: Colors.purple,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
selectedDayPredicate: (day) {
|
||||
return isSameDay(_selectedDay, day);
|
||||
},
|
||||
onDaySelected: (selectedDay, focusedDay) {
|
||||
setState(() {
|
||||
_selectedDay = selectedDay;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
},
|
||||
onPageChanged: (focusedDay) {
|
||||
_focusedDay = focusedDay;
|
||||
},
|
||||
eventLoader: (day) {
|
||||
return _getActivitiesForDay(day, scheduledActivities);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Timeline View
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Timeline
|
||||
if (selectedActivities.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 32),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Aucune activité prévue ce jour',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
...selectedActivities.map((activity) {
|
||||
return _buildTimelineItem(activity, theme);
|
||||
}),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Unscheduled Activities Section
|
||||
Text(
|
||||
'Activités à ajouter',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
if (unscheduledActivities.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Text(
|
||||
'Toutes les activités sont planifiées !',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
...unscheduledActivities.map((activity) {
|
||||
return _buildUnscheduledActivityCard(activity, theme);
|
||||
}),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTimelineItem(Activity activity, ThemeData theme) {
|
||||
final timeFormat = DateFormat('HH:mm'); // 10:00
|
||||
final endTimeFormat = DateFormat('HH:mm'); // 11:30 (simulated duration)
|
||||
|
||||
// Simulate duration (1h30)
|
||||
final endTime = activity.date!.add(const Duration(hours: 1, minutes: 30));
|
||||
|
||||
return IntrinsicHeight(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Time Column
|
||||
SizedBox(
|
||||
width: 50,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${activity.date!.hour}h',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Timeline Line
|
||||
// Expanded(child: Container()), // Placeholder for line if needed
|
||||
|
||||
// Activity Card
|
||||
Expanded(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(bottom: 24),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: _getCategoryColor(
|
||||
activity.category,
|
||||
).withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border(
|
||||
left: BorderSide(
|
||||
color: _getCategoryColor(activity.category),
|
||||
width: 4,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
activity.name,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${timeFormat.format(activity.date!)} - ${endTimeFormat.format(endTime)}',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: _getCategoryColor(activity.category),
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUnscheduledActivityCard(Activity activity, ThemeData theme) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.cardColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.05),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.all(16),
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: _getCategoryColor(activity.category).withValues(alpha: 0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
_getCategoryIcon(activity.category),
|
||||
color: _getCategoryColor(activity.category),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
activity.name,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
activity.category,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.grid_view), // Drag handle icon
|
||||
onPressed: () {
|
||||
if (_selectedDay != null) {
|
||||
_selectTimeAndSchedule(activity, _selectedDay!);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Color _getCategoryColor(String category) {
|
||||
// Simple mapping based on category name
|
||||
// You might want to use the enum if possible, but category is String in Activity model
|
||||
if (category.toLowerCase().contains('musée') ||
|
||||
category.toLowerCase().contains('museum')) {
|
||||
return Colors.blue;
|
||||
}
|
||||
if (category.toLowerCase().contains('restaurant') ||
|
||||
category.toLowerCase().contains('food')) {
|
||||
return Colors.orange;
|
||||
}
|
||||
if (category.toLowerCase().contains('nature') ||
|
||||
category.toLowerCase().contains('park')) {
|
||||
return Colors.green;
|
||||
}
|
||||
if (category.toLowerCase().contains('photo') ||
|
||||
category.toLowerCase().contains('attraction')) {
|
||||
return Colors.purple;
|
||||
}
|
||||
if (category.toLowerCase().contains('détente') ||
|
||||
category.toLowerCase().contains('relax')) {
|
||||
return Colors.pink;
|
||||
}
|
||||
return Colors.teal;
|
||||
}
|
||||
|
||||
IconData _getCategoryIcon(String category) {
|
||||
if (category.toLowerCase().contains('musée')) return Icons.museum;
|
||||
if (category.toLowerCase().contains('restaurant')) return Icons.restaurant;
|
||||
if (category.toLowerCase().contains('nature')) return Icons.nature;
|
||||
if (category.toLowerCase().contains('photo')) return Icons.camera_alt;
|
||||
if (category.toLowerCase().contains('détente')) {
|
||||
return Icons.icecream; // Gelato icon :)
|
||||
}
|
||||
return Icons.place;
|
||||
}
|
||||
|
||||
void _showParticipantsDialog(BuildContext context) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Participants'),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
child: FutureBuilder<List<User>>(
|
||||
future: UserRepository().getUsersByIds([
|
||||
...widget.trip.participants,
|
||||
widget.trip.createdBy,
|
||||
]),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return const Center(child: Text('Erreur de chargement'));
|
||||
}
|
||||
|
||||
final users = snapshot.data ?? [];
|
||||
if (users.isEmpty) {
|
||||
return const Center(child: Text('Aucun participant trouvé'));
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final user = users[index];
|
||||
final isCreator = user.id == widget.trip.createdBy;
|
||||
|
||||
return ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundImage: user.profilePictureUrl != null
|
||||
? NetworkImage(user.profilePictureUrl!)
|
||||
: null,
|
||||
child: user.profilePictureUrl == null
|
||||
? Text(
|
||||
'${user.prenom.isNotEmpty ? user.prenom[0] : ''}${user.nom.isNotEmpty ? user.nom[0] : ''}'
|
||||
.toUpperCase(),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
title: Text(user.fullName),
|
||||
subtitle: isCreator ? const Text('Organisateur') : null,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Fermer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
59
lib/components/home/calendar/calendar_page.dart_snippet
Normal file
59
lib/components/home/calendar/calendar_page.dart_snippet
Normal file
@@ -0,0 +1,59 @@
|
||||
void _showParticipantsDialog(BuildContext context) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Participants'),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
child: FutureBuilder<List<User>>(
|
||||
future: UserRepository().getUsersByIds([
|
||||
...widget.trip.participants,
|
||||
widget.trip.createdBy,
|
||||
]),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return const Center(child: Text('Erreur de chargement'));
|
||||
}
|
||||
|
||||
final users = snapshot.data ?? [];
|
||||
if (users.isEmpty) {
|
||||
return const Center(child: Text('Aucun participant trouvé'));
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final user = users[index];
|
||||
final isCreator = user.id == widget.trip.createdBy;
|
||||
|
||||
return ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundImage: user.photoUrl != null
|
||||
? NetworkImage(user.photoUrl!)
|
||||
: null,
|
||||
child: user.photoUrl == null
|
||||
? Text(user.initials)
|
||||
: null,
|
||||
),
|
||||
title: Text(user.fullName),
|
||||
subtitle: isCreator ? const Text('Organisateur') : null,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Fermer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,7 @@ import '../../blocs/trip/trip_bloc.dart';
|
||||
import '../../blocs/trip/trip_state.dart';
|
||||
import '../../blocs/trip/trip_event.dart';
|
||||
import '../../models/trip.dart';
|
||||
import '../../services/error_service.dart';
|
||||
|
||||
/// Home content widget for the main application dashboard.
|
||||
///
|
||||
@@ -79,26 +80,16 @@ class _HomeContentState extends State<HomeContent>
|
||||
return BlocConsumer<TripBloc, TripState>(
|
||||
listener: (context, tripState) {
|
||||
if (tripState is TripOperationSuccess) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(tripState.message),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
ErrorService().showSnackbar(
|
||||
message: tripState.message,
|
||||
isError: false,
|
||||
);
|
||||
} else if (tripState is TripError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(tripState.message),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: tripState.message);
|
||||
} else if (tripState is TripCreated) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Voyage en cours de création...'),
|
||||
backgroundColor: Colors.blue,
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
ErrorService().showSnackbar(
|
||||
message: 'Voyage en cours de création...',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -134,17 +125,7 @@ class _HomeContentState extends State<HomeContent>
|
||||
: Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Vos voyages',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.white70
|
||||
: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
if (tripState is TripLoading || tripState is TripCreated)
|
||||
_buildLoadingState()
|
||||
@@ -165,6 +146,7 @@ class _HomeContentState extends State<HomeContent>
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
heroTag: 'home_fab',
|
||||
onPressed: () async {
|
||||
final tripBloc = context.read<TripBloc>();
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -41,12 +41,9 @@ class _TripCardState extends State<TripCard> {
|
||||
});
|
||||
|
||||
try {
|
||||
// D'abord vérifier si une image existe déjà dans le Storage
|
||||
String? imageUrl = await _placeImageService.getExistingImageUrl(
|
||||
widget.trip.location,
|
||||
);
|
||||
|
||||
// Si aucune image n'existe, en télécharger une nouvelle
|
||||
imageUrl ??= await _placeImageService.getPlaceImageUrl(
|
||||
widget.trip.location,
|
||||
);
|
||||
@@ -57,7 +54,6 @@ class _TripCardState extends State<TripCard> {
|
||||
_isLoadingImage = false;
|
||||
});
|
||||
|
||||
// Mettre à jour le voyage dans la base de données avec l'imageUrl
|
||||
_updateTripWithImage(imageUrl);
|
||||
} else {
|
||||
setState(() {
|
||||
@@ -76,18 +72,13 @@ class _TripCardState extends State<TripCard> {
|
||||
Future<void> _updateTripWithImage(String imageUrl) async {
|
||||
try {
|
||||
if (widget.trip.id != null) {
|
||||
// Créer une copie du voyage avec la nouvelle imageUrl
|
||||
final updatedTrip = widget.trip.copyWith(
|
||||
imageUrl: imageUrl,
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
|
||||
// Mettre à jour dans la base de données
|
||||
await _tripRepository.updateTrip(widget.trip.id!, updatedTrip);
|
||||
}
|
||||
} catch (e) {
|
||||
// En cas d'erreur, on continue sans échec - l'image reste affichée localement
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
Widget _buildImageWidget() {
|
||||
|
||||
@@ -57,7 +57,10 @@ class _LoadingContentState extends State<LoadingContent>
|
||||
widget.onComplete!();
|
||||
}
|
||||
} catch (e) {
|
||||
print('Erreur lors de la tâche en arrière-plan: $e');
|
||||
debugPrint('Erreur lors de la tâche en arrière-plan: $e');
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
@@ -5,6 +6,11 @@ import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import '../../firebase_options.dart';
|
||||
import '../../services/error_service.dart';
|
||||
import '../../services/map_navigation_service.dart';
|
||||
import '../../services/logger_service.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
class MapContent extends StatefulWidget {
|
||||
final String? initialSearchQuery;
|
||||
@@ -17,23 +23,56 @@ class MapContent extends StatefulWidget {
|
||||
class _MapContentState extends State<MapContent> {
|
||||
GoogleMapController? _mapController;
|
||||
LatLng _initialPosition = const LatLng(48.8566, 2.3522);
|
||||
LatLng? _currentMapCenter;
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
bool _isLoadingLocation = false;
|
||||
bool _isSearching = false;
|
||||
Position? _currentPosition;
|
||||
|
||||
|
||||
final Set<Marker> _markers = {};
|
||||
final Set<Circle> _circles = {};
|
||||
|
||||
|
||||
List<PlaceSuggestion> _suggestions = [];
|
||||
|
||||
static final String _apiKey = dotenv.env['GOOGLE_MAPS_API_KEY'] ?? '';
|
||||
|
||||
static String get _apiKey {
|
||||
return DefaultFirebaseOptions.currentPlatform.apiKey;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Si une recherche initiale est fournie, la pré-remplir et lancer la recherche
|
||||
if (widget.initialSearchQuery != null && widget.initialSearchQuery!.isNotEmpty) {
|
||||
|
||||
final mapService = context.read<MapNavigationService>();
|
||||
|
||||
// Écouter les nouvelles demandes
|
||||
mapService.requestStream.listen((request) {
|
||||
LoggerService.info(
|
||||
'MapContent: Received navigation request: ${request.name}',
|
||||
);
|
||||
_handleNavigationRequest(request);
|
||||
});
|
||||
|
||||
// Vérifier s'il y a une demande de navigation en attente
|
||||
if (mapService.lastRequest != null) {
|
||||
LoggerService.info(
|
||||
'MapContent: Found pending navigation request: ${mapService.lastRequest!.name}',
|
||||
);
|
||||
// Handle synchronously for initial build
|
||||
final request = mapService.lastRequest!;
|
||||
final position = LatLng(request.latitude, request.longitude);
|
||||
_initialPosition = position;
|
||||
_markers.add(
|
||||
Marker(
|
||||
markerId: MarkerId(
|
||||
'nav_request_${request.timestamp.millisecondsSinceEpoch}',
|
||||
),
|
||||
position: position,
|
||||
infoWindow: InfoWindow(title: request.name ?? 'Lieu sélectionné'),
|
||||
),
|
||||
);
|
||||
// Ne pas lancer _getCurrentLocation() ici pour ne pas écraser la position
|
||||
} else if (widget.initialSearchQuery != null &&
|
||||
widget.initialSearchQuery!.isNotEmpty) {
|
||||
_searchController.text = widget.initialSearchQuery!;
|
||||
// Lancer la recherche automatiquement après un court délai pour laisser l'interface se charger
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
@@ -45,6 +84,54 @@ class _MapContentState extends State<MapContent> {
|
||||
}
|
||||
}
|
||||
|
||||
void _handleNavigationRequest(MapLocationRequest request) {
|
||||
if (!mounted) return;
|
||||
|
||||
LoggerService.info(
|
||||
'MapContent: Handling navigation request to ${request.latitude}, ${request.longitude}',
|
||||
);
|
||||
final position = LatLng(request.latitude, request.longitude);
|
||||
|
||||
setState(() {
|
||||
// Garder le marqueur de position utilisateur
|
||||
_markers.removeWhere((m) => m.markerId.value != 'user_location');
|
||||
|
||||
// Ajouter le marqueur pour le lieu demandé
|
||||
_markers.add(
|
||||
Marker(
|
||||
markerId: MarkerId(
|
||||
'nav_request_${request.timestamp.millisecondsSinceEpoch}',
|
||||
),
|
||||
position: position,
|
||||
infoWindow: InfoWindow(title: request.name ?? 'Lieu sélectionné'),
|
||||
),
|
||||
);
|
||||
_isSearching = false;
|
||||
});
|
||||
|
||||
// Animer la caméra si le contrôleur est prêt
|
||||
if (_mapController != null) {
|
||||
LoggerService.info(
|
||||
'MapContent: Waiting for map to be visible before animating',
|
||||
);
|
||||
// Attendre un peu que l'onglet change et que la carte soit visible
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
if (mounted && _mapController != null) {
|
||||
LoggerService.info('MapContent: Animating camera to position');
|
||||
_mapController!.animateCamera(
|
||||
CameraUpdate.newLatLngZoom(position, 15),
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
LoggerService.info(
|
||||
'MapContent: MapController not ready, setting initial position',
|
||||
);
|
||||
// Si le contrôleur n'est pas encore prêt, définir la position initiale
|
||||
_initialPosition = position;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.dispose();
|
||||
@@ -65,17 +152,19 @@ class _MapContentState extends State<MapContent> {
|
||||
'https://maps.googleapis.com/maps/api/place/autocomplete/json'
|
||||
'?input=${Uri.encodeComponent(query)}'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr'
|
||||
'&language=fr',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final predictions = data['predictions'] as List;
|
||||
|
||||
|
||||
if (predictions.isNotEmpty) {
|
||||
// Prendre automatiquement la première suggestion
|
||||
final firstPrediction = predictions.first;
|
||||
@@ -83,7 +172,7 @@ class _MapContentState extends State<MapContent> {
|
||||
placeId: firstPrediction['place_id'],
|
||||
description: firstPrediction['description'],
|
||||
);
|
||||
|
||||
|
||||
// Effectuer la sélection automatique
|
||||
await _selectPlaceForInitialSearch(suggestion);
|
||||
} else {
|
||||
@@ -117,9 +206,11 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final location = data['result']['geometry']['location'];
|
||||
final lat = location['lat'];
|
||||
@@ -132,7 +223,7 @@ class _MapContentState extends State<MapContent> {
|
||||
setState(() {
|
||||
// Garder le marqueur de position utilisateur s'il existe
|
||||
_markers.removeWhere((m) => m.markerId.value != 'user_location');
|
||||
|
||||
|
||||
// Ajouter le nouveau marqueur de lieu
|
||||
_markers.add(
|
||||
Marker(
|
||||
@@ -223,45 +314,47 @@ class _MapContentState extends State<MapContent> {
|
||||
}
|
||||
}
|
||||
|
||||
// Créer une icône personnalisée à partir de l'icône Material
|
||||
Future<BitmapDescriptor> _createCustomMarkerIcon() async {
|
||||
// Créer une icône personnalisée
|
||||
Future<BitmapDescriptor> _createMarkerIcon(
|
||||
IconData iconData,
|
||||
Color color, {
|
||||
double size = 60.0,
|
||||
}) async {
|
||||
final pictureRecorder = ui.PictureRecorder();
|
||||
final canvas = Canvas(pictureRecorder);
|
||||
const size = 120.0;
|
||||
|
||||
// Dessiner l'icône person_pin_circle en bleu
|
||||
final iconPainter = TextPainter(
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
final iconPainter = TextPainter(textDirection: TextDirection.ltr);
|
||||
iconPainter.text = TextSpan(
|
||||
text: String.fromCharCode(Icons.person_pin_circle.codePoint),
|
||||
text: String.fromCharCode(iconData.codePoint),
|
||||
style: TextStyle(
|
||||
fontSize: 100,
|
||||
fontFamily: Icons.person_pin_circle.fontFamily,
|
||||
color: Colors.blue[700],
|
||||
fontSize: size,
|
||||
fontFamily: iconData.fontFamily,
|
||||
package: iconData.fontPackage,
|
||||
color: color,
|
||||
shadows: [
|
||||
Shadow(
|
||||
offset: const Offset(1, 1),
|
||||
blurRadius: 2,
|
||||
color: Colors.black.withValues(alpha: 0.3),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
iconPainter.layout();
|
||||
iconPainter.paint(
|
||||
canvas,
|
||||
Offset(
|
||||
(size - iconPainter.width) / 2,
|
||||
0,
|
||||
),
|
||||
);
|
||||
iconPainter.paint(canvas, Offset((size - iconPainter.width) / 2, 0));
|
||||
|
||||
final picture = pictureRecorder.endRecording();
|
||||
final image = await picture.toImage(size.toInt(), size.toInt());
|
||||
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
|
||||
return BitmapDescriptor.fromBytes(bytes!.buffer.asUint8List());
|
||||
return BitmapDescriptor.bytes(bytes!.buffer.asUint8List());
|
||||
}
|
||||
|
||||
// Ajouter le marqueur avec l'icône personnalisée
|
||||
Future<void> _addUserLocationMarker(LatLng position) async {
|
||||
_markers.clear();
|
||||
_circles.clear();
|
||||
|
||||
|
||||
// Ajouter un cercle de précision
|
||||
_circles.add(
|
||||
Circle(
|
||||
@@ -274,8 +367,12 @@ class _MapContentState extends State<MapContent> {
|
||||
),
|
||||
);
|
||||
|
||||
// Créer l'icône personnalisée
|
||||
final icon = await _createCustomMarkerIcon();
|
||||
// Créer l'icône personnalisée (plus petite: 60 au lieu de 80)
|
||||
final icon = await _createMarkerIcon(
|
||||
Icons.person_pin_circle,
|
||||
Colors.blue[700]!,
|
||||
size: 60.0,
|
||||
);
|
||||
|
||||
// Ajouter le marqueur avec l'icône
|
||||
setState(() {
|
||||
@@ -284,10 +381,11 @@ class _MapContentState extends State<MapContent> {
|
||||
markerId: const MarkerId('user_location'),
|
||||
position: position,
|
||||
icon: icon,
|
||||
anchor: const Offset(0.5, 0.85), // Ancrer au bas de l'icône (le point du pin)
|
||||
anchor: const Offset(0.5, 0.85), // Ancrer au bas de l'icône
|
||||
infoWindow: InfoWindow(
|
||||
title: 'Ma position',
|
||||
snippet: 'Lat: ${position.latitude.toStringAsFixed(4)}, Lng: ${position.longitude.toStringAsFixed(4)}',
|
||||
snippet:
|
||||
'Lat: ${position.latitude.toStringAsFixed(4)}, Lng: ${position.longitude.toStringAsFixed(4)}',
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -307,38 +405,69 @@ class _MapContentState extends State<MapContent> {
|
||||
});
|
||||
|
||||
try {
|
||||
final apiKey = _apiKey;
|
||||
LoggerService.info('MapContent: Searching places with query "$query"');
|
||||
if (apiKey.isEmpty) {
|
||||
LoggerService.error('MapContent: API Key is empty!');
|
||||
} else {
|
||||
// Log first few chars to verify correct key is loaded without leaking full key
|
||||
LoggerService.info(
|
||||
'MapContent: Using API Key starting with ${apiKey.substring(0, 5)}...',
|
||||
);
|
||||
}
|
||||
|
||||
final url = Uri.parse(
|
||||
'https://maps.googleapis.com/maps/api/place/autocomplete/json'
|
||||
'?input=${Uri.encodeComponent(query)}'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr'
|
||||
'&key=$apiKey'
|
||||
'&language=fr',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
LoggerService.info(
|
||||
'MapContent: Response status code: ${response.statusCode}',
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final status = data['status'];
|
||||
|
||||
LoggerService.info('MapContent: API Status: $status');
|
||||
|
||||
if (status == 'OK') {
|
||||
final predictions = data['predictions'] as List;
|
||||
|
||||
LoggerService.info(
|
||||
'MapContent: Found ${predictions.length} predictions',
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_suggestions = predictions
|
||||
.map((p) => PlaceSuggestion(
|
||||
placeId: p['place_id'],
|
||||
description: p['description'],
|
||||
))
|
||||
.map(
|
||||
(p) => PlaceSuggestion(
|
||||
placeId: p['place_id'],
|
||||
description: p['description'],
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
_isSearching = false;
|
||||
});
|
||||
} else {
|
||||
LoggerService.error(
|
||||
'MapContent: API Error: $status - ${data['error_message'] ?? "No error message"}',
|
||||
);
|
||||
setState(() {
|
||||
_suggestions = [];
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
LoggerService.error('MapContent: HTTP Error ${response.statusCode}');
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error('MapContent: Exception during search: $e');
|
||||
_showError('Erreur lors de la recherche de lieux: $e');
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
@@ -346,6 +475,128 @@ class _MapContentState extends State<MapContent> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _performTextSearch(String query) async {
|
||||
if (query.isEmpty) return;
|
||||
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
_suggestions = []; // Hide suggestions
|
||||
});
|
||||
|
||||
try {
|
||||
final apiKey = _apiKey;
|
||||
// Utiliser le centre actuel de la carte ou la position initiale
|
||||
final center = _currentMapCenter ?? _initialPosition;
|
||||
|
||||
final url = Uri.parse(
|
||||
'https://maps.googleapis.com/maps/api/place/textsearch/json'
|
||||
'?query=${Uri.encodeComponent(query)}'
|
||||
'&location=${center.latitude},${center.longitude}'
|
||||
'&radius=5000' // Rechercher dans un rayon de 5km autour du centre
|
||||
'&key=$apiKey'
|
||||
'&language=fr',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final results = data['results'] as List;
|
||||
final List<Marker> newMarkers = [];
|
||||
|
||||
// Garder le marqueur de position utilisateur
|
||||
final userMarker = _markers
|
||||
.where((m) => m.markerId.value == 'user_location')
|
||||
.toList();
|
||||
|
||||
double minLat = center.latitude;
|
||||
double maxLat = center.latitude;
|
||||
double minLng = center.longitude;
|
||||
double maxLng = center.longitude;
|
||||
|
||||
// Créer le marqueur rouge standard personnalisé
|
||||
final markerIcon = await _createMarkerIcon(
|
||||
Icons.location_on,
|
||||
Colors.red,
|
||||
size: 50.0,
|
||||
);
|
||||
|
||||
for (final place in results) {
|
||||
final geometry = place['geometry']['location'];
|
||||
final lat = geometry['lat'];
|
||||
final lng = geometry['lng'];
|
||||
final name = place['name'];
|
||||
final placeId = place['place_id'];
|
||||
|
||||
final position = LatLng(lat, lng);
|
||||
|
||||
// Mettre à jour les bornes
|
||||
if (lat < minLat) minLat = lat;
|
||||
if (lat > maxLat) maxLat = lat;
|
||||
if (lng < minLng) minLng = lng;
|
||||
if (lng > maxLng) maxLng = lng;
|
||||
|
||||
newMarkers.add(
|
||||
Marker(
|
||||
markerId: MarkerId(placeId),
|
||||
position: position,
|
||||
icon: markerIcon,
|
||||
anchor: const Offset(0.5, 0.85), // Standard anchor for pins
|
||||
infoWindow: InfoWindow(
|
||||
title: name,
|
||||
snippet: place['formatted_address'] ?? 'Lieu trouvé',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_markers.clear();
|
||||
if (userMarker.isNotEmpty) {
|
||||
_markers.add(userMarker.first);
|
||||
}
|
||||
_markers.addAll(newMarkers);
|
||||
_isSearching = false;
|
||||
});
|
||||
|
||||
// Ajuster la caméra pour montrer tous les résultats
|
||||
if (newMarkers.isNotEmpty) {
|
||||
_mapController?.animateCamera(
|
||||
CameraUpdate.newLatLngBounds(
|
||||
LatLngBounds(
|
||||
southwest: LatLng(minLat, minLng),
|
||||
northeast: LatLng(maxLat, maxLng),
|
||||
),
|
||||
50.0, // padding
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
FocusScope.of(context).unfocus();
|
||||
} else {
|
||||
_showError('Aucun résultat trouvé pour "$query"');
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
_showError('Erreur lors de la recherche: ${response.statusCode}');
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
_showError('Erreur lors de la recherche: $e');
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _selectPlace(PlaceSuggestion suggestion) async {
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
@@ -363,27 +614,39 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final location = data['result']['geometry']['location'];
|
||||
final result = data['result'];
|
||||
final location = result['geometry']['location'];
|
||||
final lat = location['lat'];
|
||||
final lng = location['lng'];
|
||||
final name = data['result']['name'];
|
||||
final name = result['name'];
|
||||
|
||||
final newPosition = LatLng(lat, lng);
|
||||
|
||||
// Utiliser le marqueur rouge standard personnalisé
|
||||
final markerIcon = await _createMarkerIcon(
|
||||
Icons.location_on,
|
||||
Colors.red,
|
||||
size: 50.0,
|
||||
);
|
||||
|
||||
// Ajouter un marqueur pour le lieu recherché (ne pas supprimer le marqueur de position)
|
||||
setState(() {
|
||||
// Garder le marqueur de position utilisateur
|
||||
_markers.removeWhere((m) => m.markerId.value != 'user_location');
|
||||
|
||||
|
||||
// Ajouter le nouveau marqueur de lieu
|
||||
_markers.add(
|
||||
Marker(
|
||||
markerId: MarkerId(suggestion.placeId),
|
||||
position: newPosition,
|
||||
icon: markerIcon,
|
||||
anchor: const Offset(0.5, 0.85),
|
||||
infoWindow: InfoWindow(title: name),
|
||||
),
|
||||
);
|
||||
@@ -394,7 +657,9 @@ class _MapContentState extends State<MapContent> {
|
||||
CameraUpdate.newLatLngZoom(newPosition, 15),
|
||||
);
|
||||
|
||||
FocusScope.of(context).unfocus();
|
||||
if (mounted) {
|
||||
FocusScope.of(context).unfocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -407,13 +672,7 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
void _showError(String message) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(message),
|
||||
backgroundColor: Colors.red,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,6 +696,9 @@ class _MapContentState extends State<MapContent> {
|
||||
onMapCreated: (GoogleMapController controller) {
|
||||
_mapController = controller;
|
||||
},
|
||||
onCameraMove: (CameraPosition position) {
|
||||
_currentMapCenter = position.target;
|
||||
},
|
||||
markers: _markers,
|
||||
circles: _circles,
|
||||
myLocationEnabled: false,
|
||||
@@ -545,7 +807,10 @@ class _MapContentState extends State<MapContent> {
|
||||
: Icon(Icons.search, color: Colors.grey[700]),
|
||||
suffixIcon: _searchController.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: Icon(Icons.clear, color: Colors.grey[700]),
|
||||
icon: Icon(
|
||||
Icons.clear,
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
setState(() {
|
||||
@@ -565,9 +830,14 @@ class _MapContentState extends State<MapContent> {
|
||||
vertical: 14,
|
||||
),
|
||||
),
|
||||
textInputAction: TextInputAction.search,
|
||||
onSubmitted: (value) {
|
||||
_performTextSearch(value);
|
||||
},
|
||||
onChanged: (value) {
|
||||
// Ne pas rechercher si c'est juste le remplissage initial
|
||||
if (widget.initialSearchQuery != null && value == widget.initialSearchQuery) {
|
||||
if (widget.initialSearchQuery != null &&
|
||||
value == widget.initialSearchQuery) {
|
||||
return;
|
||||
}
|
||||
_searchPlaces(value);
|
||||
@@ -601,10 +871,8 @@ class _MapContentState extends State<MapContent> {
|
||||
shrinkWrap: true,
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: _suggestions.length,
|
||||
separatorBuilder: (context, index) => Divider(
|
||||
height: 1,
|
||||
color: Colors.grey[300],
|
||||
),
|
||||
separatorBuilder: (context, index) =>
|
||||
Divider(height: 1, color: Colors.grey[300]),
|
||||
itemBuilder: (context, index) {
|
||||
final suggestion = _suggestions[index];
|
||||
return InkWell(
|
||||
@@ -652,6 +920,7 @@ class _MapContentState extends State<MapContent> {
|
||||
),
|
||||
|
||||
floatingActionButton: FloatingActionButton(
|
||||
heroTag: 'map_fab',
|
||||
onPressed: _getCurrentLocation,
|
||||
tooltip: 'Ma position',
|
||||
child: const Icon(Icons.my_location),
|
||||
@@ -664,8 +933,5 @@ class PlaceSuggestion {
|
||||
final String placeId;
|
||||
final String description;
|
||||
|
||||
PlaceSuggestion({
|
||||
required this.placeId,
|
||||
required this.description,
|
||||
});
|
||||
}
|
||||
PlaceSuggestion({required this.placeId, required this.description});
|
||||
}
|
||||
|
||||
@@ -11,6 +11,13 @@ class PoliciesContent extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _launchCustomPrivacyPolicy() async {
|
||||
final Uri url = Uri.parse('https://xeewy.be/travelmate/policies');
|
||||
if (!await launchUrl(url)) {
|
||||
throw Exception('Could not launch $url');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onBackPressed(BuildContext context) async {
|
||||
if (Navigator.canPop(context)) {
|
||||
Navigator.pop(context);
|
||||
@@ -44,108 +51,8 @@ class PoliciesContent extends StatelessWidget {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Section Collecte d'informations
|
||||
Text(
|
||||
'Collecte d\'informations',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Nous collectons des informations que vous nous fournissez directement, comme votre nom, adresse e-mail et préférences de voyage.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
// Keep only the buttons
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Section Utilisation des données
|
||||
Text(
|
||||
'Utilisation des données',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Vos données sont utilisées pour améliorer votre expérience utilisateur et vous proposer des recommandations personnalisées.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Section Protection des données
|
||||
Text(
|
||||
'Protection des données',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Nous mettons en place des mesures de sécurité appropriées pour protéger vos informations personnelles.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Section Partage des données
|
||||
Text(
|
||||
'Partage des données',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Nous ne partageons pas vos informations personnelles avec des tiers sans votre consentement explicite.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Section Droits de l'utilisateur
|
||||
Text(
|
||||
'Vos droits',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Vous avez le droit d\'accéder, de corriger ou de supprimer vos données personnelles à tout moment. Veuillez nous contacter pour toute demande.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Section Contact
|
||||
Text(
|
||||
'Nous contacter',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Pour toute question concernant cette politique de confidentialité, veuillez nous contacter à support@travelmate.com',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: isDark ? Colors.grey[300] : Colors.grey[800],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Bouton Google Privacy Policy
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
@@ -163,6 +70,24 @@ class PoliciesContent extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// Bouton Nos politiques de confidentialité
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _launchCustomPrivacyPolicy,
|
||||
icon: const Icon(Icons.policy),
|
||||
label: const Text('Nos politiques de confidentialités'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: theme.primaryColor,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:travel_mate/components/widgets/user_state_widget.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
@@ -9,6 +10,7 @@ import '../../../blocs/user/user_bloc.dart';
|
||||
import '../../../blocs/user/user_state.dart' as user_state;
|
||||
import '../../../blocs/user/user_event.dart' as user_event;
|
||||
import '../../../services/auth_service.dart';
|
||||
import '../../../services/logger_service.dart';
|
||||
|
||||
class ProfileContent extends StatelessWidget {
|
||||
ProfileContent({super.key});
|
||||
@@ -19,7 +21,8 @@ class ProfileContent extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return UserStateWrapper(
|
||||
builder: (context, user) {
|
||||
final isEmailAuth = user.authMethod == 'email' || user.authMethod == null;
|
||||
final isEmailAuth =
|
||||
user.authMethod == 'email' || user.authMethod == null;
|
||||
|
||||
return SingleChildScrollView(
|
||||
child: Column(
|
||||
@@ -40,10 +43,12 @@ class ProfileContent extends StatelessWidget {
|
||||
color: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: 8,
|
||||
offset: Offset(0, 2),
|
||||
)
|
||||
),
|
||||
],
|
||||
),
|
||||
child: user.profilePictureUrl != null && user.profilePictureUrl!.isNotEmpty
|
||||
child:
|
||||
user.profilePictureUrl != null &&
|
||||
user.profilePictureUrl!.isNotEmpty
|
||||
? CircleAvatar(
|
||||
radius: 50,
|
||||
backgroundImage: NetworkImage(
|
||||
@@ -57,7 +62,9 @@ class ProfileContent extends StatelessWidget {
|
||||
)
|
||||
: CircleAvatar(
|
||||
radius: 50,
|
||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
child: Text(
|
||||
user.prenom.isNotEmpty
|
||||
? user.prenom[0].toUpperCase()
|
||||
@@ -88,10 +95,7 @@ class ProfileContent extends StatelessWidget {
|
||||
// Email
|
||||
Text(
|
||||
user.email,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[600]),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
|
||||
@@ -99,7 +103,10 @@ class ProfileContent extends StatelessWidget {
|
||||
|
||||
// Badge de méthode de connexion
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: _getAuthMethodColor(user.authMethod, context),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -120,7 +127,10 @@ class ProfileContent extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: _getAuthMethodTextColor(user.authMethod, context),
|
||||
color: _getAuthMethodTextColor(
|
||||
user.authMethod,
|
||||
context,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -140,7 +150,9 @@ class ProfileContent extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black87,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -314,17 +326,13 @@ class ProfileContent extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDestructive
|
||||
? Colors.red
|
||||
color: isDestructive
|
||||
? Colors.red
|
||||
: (isDarkMode ? Colors.white : Colors.black87),
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.arrow_forward_ios,
|
||||
size: 16,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -355,7 +363,7 @@ class ProfileContent extends StatelessWidget {
|
||||
|
||||
Color _getAuthMethodColor(String? authMethod, BuildContext context) {
|
||||
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
|
||||
switch (authMethod) {
|
||||
case 'apple':
|
||||
return isDarkMode ? Colors.white : Colors.black87;
|
||||
@@ -368,7 +376,7 @@ class ProfileContent extends StatelessWidget {
|
||||
|
||||
Color _getAuthMethodTextColor(String? authMethod, BuildContext context) {
|
||||
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
|
||||
switch (authMethod) {
|
||||
case 'apple':
|
||||
return isDarkMode ? Colors.black87 : Colors.white;
|
||||
@@ -401,7 +409,9 @@ class ProfileContent extends StatelessWidget {
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 50,
|
||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
child: Text(
|
||||
prenomController.text.isNotEmpty
|
||||
? prenomController.text[0].toUpperCase()
|
||||
@@ -422,7 +432,11 @@ class ProfileContent extends StatelessWidget {
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(Icons.camera_alt, color: Colors.white, size: 20),
|
||||
icon: Icon(
|
||||
Icons.camera_alt,
|
||||
color: Colors.white,
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () {
|
||||
_showPhotoPickerDialog(dialogContext);
|
||||
},
|
||||
@@ -490,11 +504,9 @@ class ProfileContent extends StatelessWidget {
|
||||
);
|
||||
|
||||
Navigator.of(dialogContext).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Profil mis à jour !'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
_errorService.showSnackbar(
|
||||
message: 'Profil mis à jour !',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -511,60 +523,66 @@ class ProfileContent extends StatelessWidget {
|
||||
void _showPhotoPickerDialog(BuildContext context) {
|
||||
// Récupérer les références AVANT que le modal ne se ferme
|
||||
final userBloc = context.read<UserBloc>();
|
||||
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (BuildContext sheetContext) {
|
||||
return Container(
|
||||
child: Wrap(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: Icon(Icons.photo_library),
|
||||
title: Text('Galerie'),
|
||||
onTap: () {
|
||||
Navigator.pop(sheetContext);
|
||||
_pickImageFromGallery(context, userBloc);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.camera_alt),
|
||||
title: Text('Caméra'),
|
||||
onTap: () {
|
||||
Navigator.pop(sheetContext);
|
||||
_pickImageFromCamera(context, userBloc);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.close),
|
||||
title: Text('Annuler'),
|
||||
onTap: () => Navigator.pop(sheetContext),
|
||||
),
|
||||
],
|
||||
),
|
||||
return Wrap(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: Icon(Icons.photo_library),
|
||||
title: Text('Galerie'),
|
||||
onTap: () {
|
||||
Navigator.pop(sheetContext);
|
||||
_pickImageFromGallery(context, userBloc);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.camera_alt),
|
||||
title: Text('Caméra'),
|
||||
onTap: () {
|
||||
Navigator.pop(sheetContext);
|
||||
_pickImageFromCamera(context, userBloc);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.close),
|
||||
title: Text('Annuler'),
|
||||
onTap: () => Navigator.pop(sheetContext),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickImageFromGallery(BuildContext context, UserBloc userBloc) async {
|
||||
Future<void> _pickImageFromGallery(
|
||||
BuildContext context,
|
||||
UserBloc userBloc,
|
||||
) async {
|
||||
try {
|
||||
final ImagePicker picker = ImagePicker();
|
||||
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
|
||||
|
||||
if (image != null) {
|
||||
if (image != null && context.mounted) {
|
||||
await _uploadProfilePicture(context, image.path, userBloc);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la sélection de l\'image');
|
||||
_errorService.showError(
|
||||
message: 'Erreur lors de la sélection de l\'image',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickImageFromCamera(BuildContext context, UserBloc userBloc) async {
|
||||
Future<void> _pickImageFromCamera(
|
||||
BuildContext context,
|
||||
UserBloc userBloc,
|
||||
) async {
|
||||
try {
|
||||
final ImagePicker picker = ImagePicker();
|
||||
final XFile? image = await picker.pickImage(source: ImageSource.camera);
|
||||
|
||||
if (image != null) {
|
||||
if (image != null && context.mounted) {
|
||||
await _uploadProfilePicture(context, image.path, userBloc);
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -572,17 +590,23 @@ class ProfileContent extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _uploadProfilePicture(BuildContext context, String imagePath, UserBloc userBloc) async {
|
||||
Future<void> _uploadProfilePicture(
|
||||
BuildContext context,
|
||||
String imagePath,
|
||||
UserBloc userBloc,
|
||||
) async {
|
||||
try {
|
||||
final File imageFile = File(imagePath);
|
||||
|
||||
|
||||
// Vérifier que le fichier existe
|
||||
if (!await imageFile.exists()) {
|
||||
_errorService.showError(message: 'Le fichier image n\'existe pas');
|
||||
return;
|
||||
}
|
||||
|
||||
print('DEBUG: Taille du fichier: ${imageFile.lengthSync()} bytes');
|
||||
LoggerService.info(
|
||||
'DEBUG: Taille du fichier: ${imageFile.lengthSync()} bytes',
|
||||
);
|
||||
|
||||
final userState = userBloc.state;
|
||||
if (userState is! user_state.UserLoaded) {
|
||||
@@ -591,30 +615,35 @@ class ProfileContent extends StatelessWidget {
|
||||
}
|
||||
|
||||
final user = userState.user;
|
||||
|
||||
|
||||
// Créer un nom unique pour la photo
|
||||
final String fileName = 'profile_${user.id}_${DateTime.now().millisecondsSinceEpoch}.jpg';
|
||||
final String fileName =
|
||||
'profile_${user.id}_${DateTime.now().millisecondsSinceEpoch}.jpg';
|
||||
final Reference storageRef = FirebaseStorage.instance
|
||||
.ref()
|
||||
.child('profile_pictures')
|
||||
.child(fileName);
|
||||
|
||||
print('DEBUG: Chemin Storage: ${storageRef.fullPath}');
|
||||
print('DEBUG: Upload en cours pour $fileName');
|
||||
LoggerService.info('DEBUG: Chemin Storage: ${storageRef.fullPath}');
|
||||
LoggerService.info('DEBUG: Upload en cours pour $fileName');
|
||||
|
||||
// Uploader l'image avec gestion d'erreur détaillée
|
||||
try {
|
||||
final uploadTask = storageRef.putFile(imageFile);
|
||||
|
||||
|
||||
// Écouter la progression
|
||||
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
|
||||
print('DEBUG: Progression: ${snapshot.bytesTransferred}/${snapshot.totalBytes}');
|
||||
LoggerService.info(
|
||||
'DEBUG: Progression: ${snapshot.bytesTransferred}/${snapshot.totalBytes}',
|
||||
);
|
||||
});
|
||||
|
||||
final snapshot = await uploadTask;
|
||||
print('DEBUG: Upload terminé. État: ${snapshot.state}');
|
||||
LoggerService.info('DEBUG: Upload terminé. État: ${snapshot.state}');
|
||||
} on FirebaseException catch (e) {
|
||||
print('DEBUG: FirebaseException lors de l\'upload: ${e.code} - ${e.message}');
|
||||
LoggerService.error(
|
||||
'DEBUG: FirebaseException lors de l\'upload: ${e.code} - ${e.message}',
|
||||
);
|
||||
if (context.mounted) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur Firebase: ${e.code}\n${e.message}',
|
||||
@@ -623,36 +652,30 @@ class ProfileContent extends StatelessWidget {
|
||||
return;
|
||||
}
|
||||
|
||||
print('DEBUG: Upload terminé, récupération de l\'URL');
|
||||
LoggerService.info('DEBUG: Upload terminé, récupération de l\'URL');
|
||||
|
||||
// Récupérer l'URL
|
||||
final String downloadUrl = await storageRef.getDownloadURL();
|
||||
|
||||
print('DEBUG: URL obtenue: $downloadUrl');
|
||||
LoggerService.info('DEBUG: URL obtenue: $downloadUrl');
|
||||
|
||||
// Mettre à jour le profil avec l'URL en utilisant la référence sauvegardée du BLoC
|
||||
print('DEBUG: Envoi de UserUpdated event au BLoC');
|
||||
userBloc.add(
|
||||
user_event.UserUpdated({
|
||||
'profilePictureUrl': downloadUrl,
|
||||
}),
|
||||
);
|
||||
LoggerService.info('DEBUG: Envoi de UserUpdated event au BLoC');
|
||||
userBloc.add(user_event.UserUpdated({'profilePictureUrl': downloadUrl}));
|
||||
|
||||
// Attendre un peu que Firestore se mette à jour
|
||||
await Future.delayed(Duration(milliseconds: 500));
|
||||
|
||||
if (context.mounted) {
|
||||
print('DEBUG: Affichage du succès');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Photo de profil mise à jour !'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
LoggerService.info('DEBUG: Affichage du succès');
|
||||
_errorService.showSnackbar(
|
||||
message: 'Photo de profil mise à jour !',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
print('DEBUG: Erreur lors de l\'upload: $e');
|
||||
print('DEBUG: Stack trace: $stackTrace');
|
||||
LoggerService.error('DEBUG: Erreur lors de l\'upload: $e');
|
||||
LoggerService.error('DEBUG: Stack trace: $stackTrace');
|
||||
_errorService.logError(
|
||||
'ProfileContent - _uploadProfilePicture',
|
||||
'Erreur lors de l\'upload de la photo: $e\n$stackTrace',
|
||||
@@ -711,22 +734,16 @@ class ProfileContent extends StatelessWidget {
|
||||
if (currentPasswordController.text.isEmpty ||
|
||||
newPasswordController.text.isEmpty ||
|
||||
confirmPasswordController.text.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Tous les champs sont requis'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
_errorService.showError(
|
||||
message: 'Tous les champs sont requis',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPasswordController.text !=
|
||||
confirmPasswordController.text) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Les mots de passe ne correspondent pas'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
_errorService.showError(
|
||||
message: 'Les mots de passe ne correspondent pas',
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -738,13 +755,13 @@ class ProfileContent extends StatelessWidget {
|
||||
email: user.email,
|
||||
);
|
||||
|
||||
Navigator.of(dialogContext).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Mot de passe changé !'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
_errorService.showSnackbar(
|
||||
message: 'Mot de passe changé !',
|
||||
isError: false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur: Mot de passe actuel incorrect',
|
||||
@@ -763,7 +780,7 @@ class ProfileContent extends StatelessWidget {
|
||||
BuildContext context,
|
||||
user_state.UserModel user,
|
||||
) {
|
||||
final passwordController = TextEditingController();
|
||||
final confirmationController = TextEditingController();
|
||||
final authService = AuthService();
|
||||
|
||||
showDialog(
|
||||
@@ -775,15 +792,15 @@ class ProfileContent extends StatelessWidget {
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Êtes-vous sûr de vouloir supprimer votre compte ? Cette action est irréversible.',
|
||||
'Êtes-vous sûr de vouloir supprimer votre compte ? Cette action est irréversible.\n\nPour confirmer, veuillez écrire "CONFIRMER" ci-dessous.',
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: passwordController,
|
||||
obscureText: true,
|
||||
controller: confirmationController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Confirmez votre mot de passe',
|
||||
labelText: 'Écrivez CONFIRMER',
|
||||
border: OutlineInputBorder(),
|
||||
hintText: 'CONFIRMER',
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -795,23 +812,48 @@ class ProfileContent extends StatelessWidget {
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
try {
|
||||
await authService.deleteAccount(
|
||||
password: passwordController.text,
|
||||
email: user.email,
|
||||
);
|
||||
|
||||
Navigator.of(dialogContext).pop();
|
||||
context.read<UserBloc>().add(user_event.UserLoggedOut());
|
||||
Navigator.pushNamedAndRemoveUntil(
|
||||
context,
|
||||
'/login',
|
||||
(route) => false,
|
||||
);
|
||||
} catch (e) {
|
||||
if (confirmationController.text != 'CONFIRMER') {
|
||||
_errorService.showError(
|
||||
message: 'Erreur: Mot de passe incorrect',
|
||||
message: 'Veuillez écrire CONFIRMER pour valider',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await authService.deleteAccount();
|
||||
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
context.read<UserBloc>().add(user_event.UserLoggedOut());
|
||||
Navigator.pushNamedAndRemoveUntil(
|
||||
context,
|
||||
'/login',
|
||||
(route) => false,
|
||||
);
|
||||
}
|
||||
} on FirebaseAuthException catch (e) {
|
||||
if (e.code == 'requires-recent-login') {
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
_errorService.showSnackbar(
|
||||
message:
|
||||
'Par sécurité, veuillez vous reconnecter avant de supprimer votre compte',
|
||||
isError: true, // It's a warning/error
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (context.mounted) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur lors de la suppression: ${e.message}',
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur inattendue: ${e.toString()}',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
style: TextButton.styleFrom(foregroundColor: Colors.red),
|
||||
|
||||
@@ -3,9 +3,33 @@ import 'package:travel_mate/components/settings/policies/policies_content.dart';
|
||||
import 'theme/settings_theme_content.dart';
|
||||
import 'profile/profile_content.dart';
|
||||
|
||||
class SettingsContent extends StatelessWidget {
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
|
||||
class SettingsContent extends StatefulWidget {
|
||||
const SettingsContent({super.key});
|
||||
|
||||
@override
|
||||
State<SettingsContent> createState() => _SettingsContentState();
|
||||
}
|
||||
|
||||
class _SettingsContentState extends State<SettingsContent> {
|
||||
String _version = '...';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadVersion();
|
||||
}
|
||||
|
||||
Future<void> _loadVersion() async {
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_version = packageInfo.version;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> changePage(BuildContext context, Widget page) async {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => page));
|
||||
}
|
||||
@@ -46,20 +70,6 @@ class SettingsContent extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
|
||||
ListTile(
|
||||
leading: const Icon(Icons.notifications),
|
||||
title: const Text('Notifications'),
|
||||
trailing: const Icon(Icons.arrow_forward_ios),
|
||||
onTap: () {},
|
||||
),
|
||||
|
||||
ListTile(
|
||||
leading: const Icon(Icons.language),
|
||||
title: const Text('Langue'),
|
||||
trailing: const Icon(Icons.arrow_forward_ios),
|
||||
onTap: () {},
|
||||
),
|
||||
|
||||
ListTile(
|
||||
leading: const Icon(Icons.privacy_tip),
|
||||
title: const Text('Confidentialité'),
|
||||
@@ -84,7 +94,7 @@ class SettingsContent extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'1.0.0',
|
||||
_version,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
|
||||
),
|
||||
],
|
||||
|
||||
57
lib/components/signup/password_requirements.dart
Normal file
57
lib/components/signup/password_requirements.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class PasswordRequirements extends StatelessWidget {
|
||||
final String password;
|
||||
|
||||
const PasswordRequirements({super.key, required this.password});
|
||||
|
||||
bool get _hasMinLength => password.length >= 8;
|
||||
bool get _hasUppercase => password.contains(RegExp(r'[A-Z]'));
|
||||
bool get _hasLowercase => password.contains(RegExp(r'[a-z]'));
|
||||
bool get _hasDigit => password.contains(RegExp(r'[0-9]'));
|
||||
bool get _hasSpecialChar =>
|
||||
password.contains(RegExp(r'[!@#\$%^&*(),.?":{}|<>]'));
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 10),
|
||||
const Text(
|
||||
'Votre mot de passe doit contenir :',
|
||||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_buildRequirement(_hasMinLength, 'Au moins 8 caractères'),
|
||||
_buildRequirement(_hasUppercase, 'Une majuscule'),
|
||||
_buildRequirement(_hasLowercase, 'Une minuscule'),
|
||||
_buildRequirement(_hasDigit, 'Un chiffre'),
|
||||
_buildRequirement(_hasSpecialChar, 'Un caractère spécial'),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRequirement(bool isMet, String text) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isMet ? Icons.check_circle : Icons.circle_outlined,
|
||||
color: isMet ? Colors.green : Colors.grey,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: isMet ? Colors.green : Colors.grey,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
140
lib/components/whats_new_dialog.dart
Normal file
140
lib/components/whats_new_dialog.dart
Normal file
@@ -0,0 +1,140 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../services/whats_new_service.dart';
|
||||
|
||||
class WhatsNewDialog extends StatelessWidget {
|
||||
final VoidCallback onDismiss;
|
||||
final List<WhatsNewItem> features;
|
||||
|
||||
const WhatsNewDialog({
|
||||
super.key,
|
||||
required this.onDismiss,
|
||||
required this.features,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.auto_awesome,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Quoi de neuf ?',
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Features List
|
||||
Flexible(
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
itemCount: features.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 16),
|
||||
itemBuilder: (context, index) {
|
||||
final feature = features[index];
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
feature.icon,
|
||||
color: theme.colorScheme.primary,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
feature.title,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
feature.description,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Button
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
child: ElevatedButton(
|
||||
onPressed: () {
|
||||
// Marquer comme vu via le service
|
||||
WhatsNewService().markCurrentVersionAsSeen();
|
||||
onDismiss();
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.primary,
|
||||
foregroundColor: theme.colorScheme.onPrimary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Text(
|
||||
'C\'est parti !',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class WhatsNewItem {
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String description;
|
||||
|
||||
const WhatsNewItem({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.description,
|
||||
});
|
||||
}
|
||||
@@ -27,18 +27,6 @@ class DefaultFirebaseOptions {
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
return ios;
|
||||
case TargetPlatform.macOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for macos - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.windows:
|
||||
return windows;
|
||||
case TargetPlatform.linux:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for linux - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
@@ -63,15 +51,4 @@ class DefaultFirebaseOptions {
|
||||
iosClientId: '521527250907-3i1qe2656eojs8k9hjdi573j09i9p41m.apps.googleusercontent.com',
|
||||
iosBundleId: 'com.example.travelMate',
|
||||
);
|
||||
|
||||
static const FirebaseOptions windows = FirebaseOptions(
|
||||
apiKey: 'AIzaSyC4t-WOvp22zns9b9t58urznsNAhSHRAag',
|
||||
appId: '1:521527250907:web:53ff98bcdb8c218f7da1fe',
|
||||
messagingSenderId: '521527250907',
|
||||
projectId: 'travelmate-a47f5',
|
||||
authDomain: 'travelmate-a47f5.firebaseapp.com',
|
||||
storageBucket: 'travelmate-a47f5.firebasestorage.app',
|
||||
measurementId: 'G-J246Y7J61M',
|
||||
);
|
||||
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:travel_mate/blocs/balance/balance_bloc.dart';
|
||||
import 'package:travel_mate/blocs/expense/expense_bloc.dart';
|
||||
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
|
||||
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
|
||||
import 'package:travel_mate/blocs/message/message_bloc.dart';
|
||||
import 'package:travel_mate/blocs/activity/activity_bloc.dart';
|
||||
import 'package:travel_mate/firebase_options.dart';
|
||||
@@ -11,6 +14,10 @@ import 'package:travel_mate/services/error_service.dart';
|
||||
import 'package:travel_mate/services/activity_places_service.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:travel_mate/services/expense_service.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:travel_mate/services/notification_service.dart';
|
||||
import 'package:travel_mate/services/map_navigation_service.dart';
|
||||
import 'package:travel_mate/services/analytics_service.dart';
|
||||
import 'blocs/auth/auth_bloc.dart';
|
||||
import 'blocs/auth/auth_event.dart';
|
||||
import 'blocs/theme/theme_bloc.dart';
|
||||
@@ -34,14 +41,33 @@ import 'pages/home.dart';
|
||||
import 'pages/signup.dart';
|
||||
import 'pages/resetpswd.dart';
|
||||
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
|
||||
/// Entry point of the Travel Mate application.
|
||||
///
|
||||
/// This function initializes Flutter widgets, loads environment variables,
|
||||
/// initializes Firebase, and starts the application.
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
]);
|
||||
await dotenv.load(fileName: ".env");
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
await initializeDateFormatting('fr_FR', null);
|
||||
|
||||
// Set the background messaging handler early on, as a named top-level function
|
||||
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
|
||||
|
||||
await NotificationService().initialize();
|
||||
|
||||
// Requirements for Google Maps on Android (Hybrid Composition)
|
||||
final GoogleMapsFlutterPlatform mapsImplementation =
|
||||
GoogleMapsFlutterPlatform.instance;
|
||||
if (mapsImplementation is GoogleMapsFlutterAndroid) {
|
||||
mapsImplementation.useAndroidViewSurface = true;
|
||||
}
|
||||
|
||||
runApp(const MyApp());
|
||||
}
|
||||
@@ -117,6 +143,14 @@ class MyApp extends StatelessWidget {
|
||||
expenseRepository: context.read<ExpenseRepository>(),
|
||||
),
|
||||
),
|
||||
// Map navigation service
|
||||
RepositoryProvider<MapNavigationService>(
|
||||
create: (context) => MapNavigationService(),
|
||||
),
|
||||
// Analysis service
|
||||
RepositoryProvider<AnalyticsService>(
|
||||
create: (context) => AnalyticsService(),
|
||||
),
|
||||
],
|
||||
child: MultiBlocProvider(
|
||||
providers: [
|
||||
@@ -177,6 +211,9 @@ class MyApp extends StatelessWidget {
|
||||
title: 'Travel Mate',
|
||||
navigatorKey: ErrorService.navigatorKey,
|
||||
themeMode: themeState.themeMode,
|
||||
navigatorObservers: [
|
||||
context.read<AnalyticsService>().getAnalyticsObserver(),
|
||||
],
|
||||
// Light theme configuration
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
|
||||
@@ -20,6 +20,8 @@ class Activity {
|
||||
final Map<String, int> votes; // userId -> vote (1 pour pour, -1 pour contre)
|
||||
final DateTime createdAt;
|
||||
final DateTime updatedAt;
|
||||
final DateTime? date; // Date prévue pour l'activité
|
||||
final String? createdBy; // ID de l'utilisateur qui a créé l'activité
|
||||
|
||||
Activity({
|
||||
required this.id,
|
||||
@@ -40,11 +42,13 @@ class Activity {
|
||||
this.votes = const {},
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
this.date,
|
||||
this.createdBy,
|
||||
});
|
||||
|
||||
/// Calcule le score total des votes
|
||||
int get totalVotes {
|
||||
return votes.values.fold(0, (sum, vote) => sum + vote);
|
||||
return votes.values.fold(0, (total, vote) => total + vote);
|
||||
}
|
||||
|
||||
/// Calcule le nombre de votes positifs
|
||||
@@ -104,6 +108,9 @@ class Activity {
|
||||
Map<String, int>? votes,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
DateTime? date,
|
||||
bool clearDate = false,
|
||||
String? createdBy,
|
||||
}) {
|
||||
return Activity(
|
||||
id: id ?? this.id,
|
||||
@@ -124,6 +131,8 @@ class Activity {
|
||||
votes: votes ?? this.votes,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
date: clearDate ? null : (date ?? this.date),
|
||||
createdBy: createdBy ?? this.createdBy,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,6 +157,8 @@ class Activity {
|
||||
'votes': votes,
|
||||
'createdAt': Timestamp.fromDate(createdAt),
|
||||
'updatedAt': Timestamp.fromDate(updatedAt),
|
||||
'date': date != null ? Timestamp.fromDate(date!) : null,
|
||||
'createdBy': createdBy,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -172,6 +183,8 @@ class Activity {
|
||||
votes: Map<String, int>.from(map['votes'] ?? {}),
|
||||
createdAt: (map['createdAt'] as Timestamp).toDate(),
|
||||
updatedAt: (map['updatedAt'] as Timestamp).toDate(),
|
||||
date: map['date'] != null ? (map['date'] as Timestamp).toDate() : null,
|
||||
createdBy: map['createdBy'],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,107 +4,117 @@ import 'package:flutter/material.dart';
|
||||
import 'expense_split.dart';
|
||||
|
||||
/// Enumeration of supported currencies for expenses.
|
||||
///
|
||||
///
|
||||
/// Each currency includes both a display symbol and standard currency code.
|
||||
enum ExpenseCurrency {
|
||||
/// Euro currency
|
||||
eur('€', 'EUR'),
|
||||
/// US Dollar currency
|
||||
|
||||
/// US Dollar currency
|
||||
usd('\$', 'USD'),
|
||||
|
||||
/// British Pound currency
|
||||
gbp('£', 'GBP');
|
||||
|
||||
const ExpenseCurrency(this.symbol, this.code);
|
||||
|
||||
|
||||
/// Currency symbol for display (e.g., €, $, £)
|
||||
final String symbol;
|
||||
|
||||
|
||||
/// Standard currency code (e.g., EUR, USD, GBP)
|
||||
final String code;
|
||||
}
|
||||
|
||||
/// Enumeration of expense categories with display names and icons.
|
||||
///
|
||||
///
|
||||
/// Provides predefined categories for organizing travel expenses.
|
||||
enum ExpenseCategory {
|
||||
/// Restaurant and food expenses
|
||||
restaurant('Restaurant', Icons.restaurant),
|
||||
|
||||
/// Transportation expenses
|
||||
transport('Transport', Icons.directions_car),
|
||||
|
||||
/// Accommodation and lodging expenses
|
||||
accommodation('Accommodation', Icons.hotel),
|
||||
|
||||
/// Entertainment and activity expenses
|
||||
entertainment('Entertainment', Icons.local_activity),
|
||||
|
||||
/// Shopping expenses
|
||||
shopping('Shopping', Icons.shopping_bag),
|
||||
|
||||
/// Other miscellaneous expenses
|
||||
other('Other', Icons.category);
|
||||
other('Other', Icons.category),
|
||||
|
||||
/// Reimbursement for settling debts
|
||||
reimbursement('Remboursement', Icons.monetization_on);
|
||||
|
||||
const ExpenseCategory(this.displayName, this.icon);
|
||||
|
||||
|
||||
/// Human-readable display name for the category
|
||||
final String displayName;
|
||||
|
||||
|
||||
/// Icon representing the category
|
||||
final IconData icon;
|
||||
}
|
||||
|
||||
/// Model representing a travel expense.
|
||||
///
|
||||
///
|
||||
/// This class encapsulates all information about an expense including
|
||||
/// amount, currency, category, who paid, how it's split among participants,
|
||||
/// and receipt information. It extends [Equatable] for value comparison.
|
||||
class Expense extends Equatable {
|
||||
/// Unique identifier for the expense
|
||||
final String id;
|
||||
|
||||
|
||||
/// ID of the group this expense belongs to
|
||||
final String groupId;
|
||||
|
||||
|
||||
/// Description of the expense
|
||||
final String description;
|
||||
|
||||
|
||||
/// Amount of the expense in the original currency
|
||||
final double amount;
|
||||
|
||||
|
||||
/// Currency of the expense
|
||||
final ExpenseCurrency currency;
|
||||
|
||||
|
||||
/// Amount converted to EUR for standardized calculations
|
||||
final double amountInEur;
|
||||
|
||||
|
||||
/// Category of the expense
|
||||
final ExpenseCategory category;
|
||||
|
||||
|
||||
/// ID of the user who paid for this expense
|
||||
final String paidById;
|
||||
|
||||
|
||||
/// Name of the user who paid for this expense
|
||||
final String paidByName;
|
||||
|
||||
|
||||
/// Date when the expense occurred
|
||||
final DateTime date;
|
||||
|
||||
|
||||
/// Timestamp when the expense was created
|
||||
final DateTime createdAt;
|
||||
|
||||
|
||||
/// Timestamp when the expense was last edited (null if never edited)
|
||||
final DateTime? editedAt;
|
||||
|
||||
|
||||
/// Whether this expense has been edited after creation
|
||||
final bool isEdited;
|
||||
|
||||
|
||||
/// Whether this expense has been archived
|
||||
final bool isArchived;
|
||||
|
||||
|
||||
/// URL to the receipt image (optional)
|
||||
final String? receiptUrl;
|
||||
|
||||
|
||||
/// List of expense splits showing how the cost is divided
|
||||
final List<ExpenseSplit> splits;
|
||||
|
||||
/// Creates a new [Expense] instance.
|
||||
///
|
||||
///
|
||||
/// All parameters except [editedAt] and [receiptUrl] are required.
|
||||
const Expense({
|
||||
required this.id,
|
||||
@@ -144,13 +154,17 @@ class Expense extends Equatable {
|
||||
paidByName: map['paidByName'] ?? '',
|
||||
date: _parseDateTime(map['date']),
|
||||
createdAt: _parseDateTime(map['createdAt']),
|
||||
editedAt: map['editedAt'] != null ? _parseDateTime(map['editedAt']) : null,
|
||||
editedAt: map['editedAt'] != null
|
||||
? _parseDateTime(map['editedAt'])
|
||||
: null,
|
||||
isEdited: map['isEdited'] ?? false,
|
||||
isArchived: map['isArchived'] ?? false,
|
||||
receiptUrl: map['receiptUrl'],
|
||||
splits: (map['splits'] as List?)
|
||||
?.map((s) => ExpenseSplit.fromMap(s))
|
||||
.toList() ?? [],
|
||||
splits:
|
||||
(map['splits'] as List?)
|
||||
?.map((s) => ExpenseSplit.fromMap(s))
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -243,25 +257,36 @@ class Expense extends Equatable {
|
||||
|
||||
// Marquer comme archivé
|
||||
Expense copyWithArchived() {
|
||||
return copyWith(
|
||||
isArchived: true,
|
||||
);
|
||||
return copyWith(isArchived: true);
|
||||
}
|
||||
|
||||
// Ajouter/mettre à jour l'URL du reçu
|
||||
Expense copyWithReceipt(String receiptUrl) {
|
||||
return copyWith(
|
||||
receiptUrl: receiptUrl,
|
||||
);
|
||||
return copyWith(receiptUrl: receiptUrl);
|
||||
}
|
||||
|
||||
// Mettre à jour les splits
|
||||
Expense copyWithSplits(List<ExpenseSplit> newSplits) {
|
||||
return copyWith(
|
||||
splits: newSplits,
|
||||
);
|
||||
return copyWith(splits: newSplits);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
groupId,
|
||||
description,
|
||||
amount,
|
||||
currency,
|
||||
amountInEur,
|
||||
category,
|
||||
paidById,
|
||||
paidByName,
|
||||
date,
|
||||
createdAt,
|
||||
editedAt,
|
||||
isEdited,
|
||||
isArchived,
|
||||
receiptUrl,
|
||||
splits,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,54 +1,59 @@
|
||||
import 'group_member.dart';
|
||||
|
||||
/// Model representing a travel group.
|
||||
///
|
||||
///
|
||||
/// A group is a collection of travelers who are part of a specific trip.
|
||||
/// It contains information about group members, creation details, and
|
||||
/// provides methods for serialization with Firestore.
|
||||
class Group {
|
||||
/// Unique identifier for the group
|
||||
final String id;
|
||||
|
||||
final String id;
|
||||
|
||||
/// Display name of the group
|
||||
final String name;
|
||||
|
||||
|
||||
/// ID of the trip this group belongs to
|
||||
final String tripId;
|
||||
|
||||
|
||||
/// ID of the user who created this group
|
||||
final String createdBy;
|
||||
|
||||
|
||||
/// Timestamp when the group was created
|
||||
final DateTime createdAt;
|
||||
|
||||
|
||||
/// Timestamp when the group was last updated
|
||||
final DateTime updatedAt;
|
||||
|
||||
|
||||
/// List of members in this group
|
||||
final List<GroupMember> members;
|
||||
|
||||
/// List of member IDs for efficient querying and security rules
|
||||
final List<String> memberIds;
|
||||
|
||||
/// Creates a new [Group] instance.
|
||||
///
|
||||
///
|
||||
/// [id], [name], [tripId], and [createdBy] are required.
|
||||
/// [createdAt] and [updatedAt] default to current time if not provided.
|
||||
/// [members] defaults to empty list if not provided.
|
||||
Group({
|
||||
required this.id,
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.tripId,
|
||||
required this.createdBy,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
List<GroupMember>? members,
|
||||
}) : createdAt = createdAt ?? DateTime.now(),
|
||||
updatedAt = updatedAt ?? DateTime.now(),
|
||||
members = members ?? [];
|
||||
List<String>? memberIds,
|
||||
}) : createdAt = createdAt ?? DateTime.now(),
|
||||
updatedAt = updatedAt ?? DateTime.now(),
|
||||
members = members ?? [],
|
||||
memberIds = memberIds ?? [];
|
||||
|
||||
/// Creates a [Group] instance from a Firestore document map.
|
||||
///
|
||||
///
|
||||
/// [map] - The document data from Firestore
|
||||
/// [id] - The document ID from Firestore
|
||||
///
|
||||
///
|
||||
/// Returns a new [Group] instance with data from the map.
|
||||
factory Group.fromMap(Map<String, dynamic> map, String id) {
|
||||
return Group(
|
||||
@@ -59,6 +64,7 @@ class Group {
|
||||
createdAt: DateTime.fromMillisecondsSinceEpoch(map['createdAt'] ?? 0),
|
||||
updatedAt: DateTime.fromMillisecondsSinceEpoch(map['updatedAt'] ?? 0),
|
||||
members: [],
|
||||
memberIds: List<String>.from(map['memberIds'] ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,6 +75,7 @@ class Group {
|
||||
'createdBy': createdBy,
|
||||
'createdAt': createdAt.millisecondsSinceEpoch,
|
||||
'updatedAt': updatedAt.millisecondsSinceEpoch,
|
||||
'memberIds': memberIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,6 +87,7 @@ class Group {
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
List<GroupMember>? members,
|
||||
List<String>? memberIds,
|
||||
}) {
|
||||
return Group(
|
||||
id: id ?? this.id,
|
||||
@@ -89,6 +97,7 @@ class Group {
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
members: members ?? this.members,
|
||||
memberIds: memberIds ?? this.memberIds,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,22 @@ class GroupBalance extends Equatable {
|
||||
factory GroupBalance.fromMap(Map<String, dynamic> map) {
|
||||
return GroupBalance(
|
||||
groupId: map['groupId'] ?? '',
|
||||
userBalances: (map['userBalances'] as List?)
|
||||
?.map((userBalance) => UserBalance.fromMap(userBalance as Map<String, dynamic>))
|
||||
.toList() ?? [],
|
||||
settlements: (map['settlements'] as List?)
|
||||
?.map((settlement) => Settlement.fromMap(settlement as Map<String, dynamic>))
|
||||
.toList() ?? [],
|
||||
userBalances:
|
||||
(map['userBalances'] as List?)
|
||||
?.map(
|
||||
(userBalance) =>
|
||||
UserBalance.fromMap(userBalance as Map<String, dynamic>),
|
||||
)
|
||||
.toList() ??
|
||||
[],
|
||||
settlements:
|
||||
(map['settlements'] as List?)
|
||||
?.map(
|
||||
(settlement) =>
|
||||
Settlement.fromMap(settlement as Map<String, dynamic>),
|
||||
)
|
||||
.toList() ??
|
||||
[],
|
||||
totalExpenses: (map['totalExpenses'] as num?)?.toDouble() ?? 0.0,
|
||||
calculatedAt: _parseDateTime(map['calculatedAt']),
|
||||
);
|
||||
@@ -37,8 +47,12 @@ class GroupBalance extends Equatable {
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'groupId': groupId,
|
||||
'userBalances': userBalances.map((userBalance) => userBalance.toMap()).toList(),
|
||||
'settlements': settlements.map((settlement) => settlement.toMap()).toList(),
|
||||
'userBalances': userBalances
|
||||
.map((userBalance) => userBalance.toMap())
|
||||
.toList(),
|
||||
'settlements': settlements
|
||||
.map((settlement) => settlement.toMap())
|
||||
.toList(),
|
||||
'totalExpenses': totalExpenses,
|
||||
'calculatedAt': Timestamp.fromDate(calculatedAt),
|
||||
};
|
||||
@@ -71,16 +85,20 @@ class GroupBalance extends Equatable {
|
||||
}
|
||||
|
||||
// Méthodes utilitaires pour la logique métier
|
||||
bool get hasUnbalancedUsers => userBalances.any((balance) => !balance.isBalanced);
|
||||
|
||||
bool get hasUnbalancedUsers =>
|
||||
userBalances.any((balance) => !balance.isBalanced);
|
||||
|
||||
bool get hasSettlements => settlements.isNotEmpty;
|
||||
|
||||
double get totalSettlementAmount => settlements.fold(0.0, (sum, settlement) => sum + settlement.amount);
|
||||
|
||||
List<UserBalance> get creditors => userBalances.where((b) => b.shouldReceive).toList();
|
||||
|
||||
List<UserBalance> get debtors => userBalances.where((b) => b.shouldPay).toList();
|
||||
|
||||
|
||||
double get totalSettlementAmount =>
|
||||
settlements.fold(0.0, (total, settlement) => total + settlement.amount);
|
||||
|
||||
List<UserBalance> get creditors =>
|
||||
userBalances.where((b) => b.shouldReceive).toList();
|
||||
|
||||
List<UserBalance> get debtors =>
|
||||
userBalances.where((b) => b.shouldPay).toList();
|
||||
|
||||
int get participantCount => userBalances.length;
|
||||
|
||||
@override
|
||||
@@ -90,4 +108,4 @@ class GroupBalance extends Equatable {
|
||||
String toString() {
|
||||
return 'GroupBalance(groupId: $groupId, totalExpenses: $totalExpenses, participantCount: $participantCount, calculatedAt: $calculatedAt)';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class GroupMember {
|
||||
final String userId;
|
||||
final String firstName;
|
||||
final String lastName;
|
||||
final String pseudo; // Pseudo du membre (par défaut = prénom)
|
||||
final String role; // 'admin' ou 'member'
|
||||
final DateTime joinedAt;
|
||||
@@ -9,17 +10,20 @@ class GroupMember {
|
||||
GroupMember({
|
||||
required this.userId,
|
||||
required this.firstName,
|
||||
String? lastName,
|
||||
String? pseudo,
|
||||
this.role = 'member',
|
||||
DateTime? joinedAt,
|
||||
this.profilePictureUrl,
|
||||
}) : pseudo = pseudo ?? firstName, // Par défaut, pseudo = prénom
|
||||
}) : lastName = lastName ?? '',
|
||||
pseudo = pseudo ?? firstName,
|
||||
joinedAt = joinedAt ?? DateTime.now();
|
||||
|
||||
factory GroupMember.fromMap(Map<String, dynamic> map, String userId) {
|
||||
return GroupMember(
|
||||
userId: userId,
|
||||
firstName: map['firstName'] ?? '',
|
||||
lastName: map['lastName'] ?? '',
|
||||
pseudo: map['pseudo'] ?? map['firstName'] ?? '',
|
||||
role: map['role'] ?? 'member',
|
||||
joinedAt: DateTime.fromMillisecondsSinceEpoch(map['joinedAt'] ?? 0),
|
||||
@@ -30,6 +34,7 @@ class GroupMember {
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'firstName': firstName,
|
||||
'lastName': lastName,
|
||||
'pseudo': pseudo,
|
||||
'role': role,
|
||||
'joinedAt': joinedAt.millisecondsSinceEpoch,
|
||||
@@ -40,6 +45,7 @@ class GroupMember {
|
||||
GroupMember copyWith({
|
||||
String? userId,
|
||||
String? firstName,
|
||||
String? lastName,
|
||||
String? pseudo,
|
||||
String? role,
|
||||
DateTime? joinedAt,
|
||||
@@ -48,6 +54,7 @@ class GroupMember {
|
||||
return GroupMember(
|
||||
userId: userId ?? this.userId,
|
||||
firstName: firstName ?? this.firstName,
|
||||
lastName: lastName ?? this.lastName,
|
||||
pseudo: pseudo ?? this.pseudo,
|
||||
role: role ?? this.role,
|
||||
joinedAt: joinedAt ?? this.joinedAt,
|
||||
|
||||
@@ -10,6 +10,7 @@ class Message {
|
||||
final Map<String, String> reactions; // userId -> emoji
|
||||
final DateTime? editedAt;
|
||||
final bool isEdited;
|
||||
final bool isDeleted;
|
||||
|
||||
Message({
|
||||
this.id = '',
|
||||
@@ -21,6 +22,7 @@ class Message {
|
||||
this.reactions = const {},
|
||||
this.editedAt,
|
||||
this.isEdited = false,
|
||||
this.isDeleted = false,
|
||||
});
|
||||
|
||||
factory Message.fromFirestore(DocumentSnapshot doc) {
|
||||
@@ -39,6 +41,7 @@ class Message {
|
||||
reactions: reactionsData?.map((key, value) => MapEntry(key, value.toString())) ?? {},
|
||||
editedAt: editedAtTimestamp?.toDate(),
|
||||
isEdited: data['isEdited'] ?? false,
|
||||
isDeleted: data['isDeleted'] ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,6 +55,7 @@ class Message {
|
||||
'reactions': reactions,
|
||||
'editedAt': editedAt != null ? Timestamp.fromDate(editedAt!) : null,
|
||||
'isEdited': isEdited,
|
||||
'isDeleted': isDeleted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,6 +69,7 @@ class Message {
|
||||
Map<String, String>? reactions,
|
||||
DateTime? editedAt,
|
||||
bool? isEdited,
|
||||
bool? isDeleted,
|
||||
}) {
|
||||
return Message(
|
||||
id: id ?? this.id,
|
||||
@@ -76,6 +81,7 @@ class Message {
|
||||
reactions: reactions ?? this.reactions,
|
||||
editedAt: editedAt ?? this.editedAt,
|
||||
isEdited: isEdited ?? this.isEdited,
|
||||
isDeleted: isDeleted ?? this.isDeleted,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,11 @@ import '../blocs/user/user_bloc.dart';
|
||||
import '../blocs/user/user_event.dart';
|
||||
import '../blocs/auth/auth_bloc.dart';
|
||||
import '../blocs/auth/auth_event.dart';
|
||||
import '../services/error_service.dart';
|
||||
import '../services/notification_service.dart';
|
||||
import '../services/map_navigation_service.dart';
|
||||
import '../services/whats_new_service.dart';
|
||||
import '../components/whats_new_dialog.dart';
|
||||
|
||||
class HomePage extends StatefulWidget {
|
||||
const HomePage({super.key});
|
||||
@@ -36,6 +41,63 @@ class _HomePageState extends State<HomePage> {
|
||||
super.initState();
|
||||
// Initialiser les données utilisateur
|
||||
context.read<UserBloc>().add(UserInitialized());
|
||||
|
||||
// Setup notifications listener and check for initial message
|
||||
final notificationService = NotificationService();
|
||||
notificationService.startListening();
|
||||
|
||||
// Check for initial message after a slight delay to ensure the widget tree is fully built
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
notificationService.handleInitialMessage();
|
||||
});
|
||||
|
||||
// Écouter les demandes de navigation vers la carte
|
||||
context.read<MapNavigationService>().requestStream.listen((request) {
|
||||
if (_currentIndex != 2) {
|
||||
setState(() {
|
||||
_currentIndex = 2;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Vérifier les nouveautés
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
await _checkAndShowWhatsNew();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _checkAndShowWhatsNew() async {
|
||||
final service = WhatsNewService();
|
||||
if (await service.shouldShowWhatsNew()) {
|
||||
if (!mounted) return;
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) => WhatsNewDialog(
|
||||
onDismiss: () => Navigator.pop(context),
|
||||
features: const [
|
||||
WhatsNewItem(
|
||||
icon: Icons.map_outlined,
|
||||
title: 'Recherche globale',
|
||||
description:
|
||||
'Recherchez des restaurants, musées et plus encore directement depuis la carte.',
|
||||
),
|
||||
WhatsNewItem(
|
||||
icon: Icons.search,
|
||||
title: 'Autocomplétion améliorée',
|
||||
description:
|
||||
'Découvrez des suggestions intelligentes lors de la recherche de lieux et d\'activités.',
|
||||
),
|
||||
WhatsNewItem(
|
||||
icon: Icons.warning_amber_rounded,
|
||||
title: 'Alertes de distance',
|
||||
description:
|
||||
'Soyez averti si une activité est trop éloignée de votre lieu de séjour.',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildPage(int index) {
|
||||
@@ -119,12 +181,7 @@ class _HomePageState extends State<HomePage> {
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur lors de la déconnexion: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
ErrorService().showError(message: 'Erreur lors de la déconnexion: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,38 +189,51 @@ class _HomePageState extends State<HomePage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(titles[_currentIndex]),
|
||||
),
|
||||
appBar: AppBar(title: Text(titles[_currentIndex])),
|
||||
drawer: Drawer(
|
||||
child: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
DrawerHeader(
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.black
|
||||
: Colors.white,
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.black
|
||||
: Colors.white,
|
||||
),
|
||||
child: Text(
|
||||
"Travel Mate",
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
fontSize: 24,
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildDrawerItem(icon: Icons.home, title: "Mes voyages", index: 0),
|
||||
_buildDrawerItem(icon: Icons.settings, title: "Paramètres", index: 1),
|
||||
_buildDrawerItem(
|
||||
icon: Icons.settings,
|
||||
title: "Paramètres",
|
||||
index: 1,
|
||||
),
|
||||
_buildDrawerItem(icon: Icons.map, title: "Carte", index: 2),
|
||||
_buildDrawerItem(icon: Icons.group, title: "Chat de groupe", index: 3),
|
||||
_buildDrawerItem(icon: Icons.account_balance_wallet, title: "Comptes", index: 4),
|
||||
_buildDrawerItem(
|
||||
icon: Icons.group,
|
||||
title: "Chat de groupe",
|
||||
index: 3,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
icon: Icons.account_balance_wallet,
|
||||
title: "Comptes",
|
||||
index: 4,
|
||||
),
|
||||
const Divider(),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.logout, color: Colors.red),
|
||||
title: const Text("Déconnexion", style: TextStyle(color: Colors.red)),
|
||||
title: const Text(
|
||||
"Déconnexion",
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
onTap: _handleLogout, // Utiliser la nouvelle méthode
|
||||
),
|
||||
],
|
||||
@@ -191,7 +261,9 @@ class _HomePageState extends State<HomePage> {
|
||||
leading: Icon(icon),
|
||||
title: Text(title),
|
||||
selected: _currentIndex == index,
|
||||
selectedTileColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
|
||||
selectedTileColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary.withValues(alpha: 0.1),
|
||||
onTap: () => _onNavigationTap(index),
|
||||
);
|
||||
}
|
||||
@@ -201,4 +273,4 @@ class _HomePageState extends State<HomePage> {
|
||||
_pageCache.clear();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../blocs/auth/auth_bloc.dart';
|
||||
import '../blocs/auth/auth_event.dart';
|
||||
import '../blocs/auth/auth_state.dart';
|
||||
import 'package:sign_in_button/sign_in_button.dart';
|
||||
import '../services/error_service.dart';
|
||||
|
||||
/// Login page widget for user authentication.
|
||||
///
|
||||
@@ -87,14 +88,13 @@ class _LoginPageState extends State<LoginPage> {
|
||||
body: BlocConsumer<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthAuthenticated) {
|
||||
Navigator.pushReplacementNamed(context, '/home');
|
||||
} else if (state is AuthError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(state.message),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
Navigator.pushNamedAndRemoveUntil(
|
||||
context,
|
||||
'/home',
|
||||
(route) => false,
|
||||
);
|
||||
} else if (state is AuthError) {
|
||||
ErrorService().showError(message: state.message);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
|
||||
@@ -1,8 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../blocs/auth/auth_bloc.dart';
|
||||
import '../blocs/auth/auth_event.dart';
|
||||
import '../blocs/auth/auth_state.dart';
|
||||
import '../services/error_service.dart';
|
||||
|
||||
class ForgotPasswordPage extends StatelessWidget {
|
||||
class ForgotPasswordPage extends StatefulWidget {
|
||||
const ForgotPasswordPage({super.key});
|
||||
|
||||
@override
|
||||
State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
|
||||
}
|
||||
|
||||
class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
|
||||
final _emailController = TextEditingController();
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? _validateEmail(String? value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Email requis';
|
||||
}
|
||||
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
||||
if (!emailRegex.hasMatch(value.trim())) {
|
||||
return 'Email invalide';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
context.read<AuthBloc>().add(
|
||||
AuthPasswordResetRequested(email: _emailController.text.trim()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -16,87 +54,152 @@ class ForgotPasswordPage extends StatelessWidget {
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
),
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Center(
|
||||
child: Column(
|
||||
children: [
|
||||
const Text(
|
||||
"Travel Mate",
|
||||
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
const Text(
|
||||
"Vous avez oublié votre mot de passe ? \n Ne vous inquiétez pas vous pouvez le réinitaliser !",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
const Text(
|
||||
"Quel est votre email ? \n Si celui-ci existe dans note base de donées, nous vous enverrons un mail avec un mot de passe unique.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
const TextField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'example@travelmate.com',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(12)),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
// Logique de connexion
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(50),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Text('Envoyer', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
Container(
|
||||
width: double.infinity,
|
||||
height: 1,
|
||||
color: Colors.grey.shade300,
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("Pas encore inscrit ? "),
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
// Go to sign up page
|
||||
Navigator.pushNamed(context, '/signup');
|
||||
},
|
||||
child: const Text(
|
||||
'Inscrivez-vous !',
|
||||
body: BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthPasswordResetSent) {
|
||||
ErrorService().showSnackbar(
|
||||
message: 'Email de réinitialisation envoyé !',
|
||||
isError: false,
|
||||
);
|
||||
Navigator.pop(context);
|
||||
} else if (state is AuthError) {
|
||||
ErrorService().showError(message: state.message);
|
||||
}
|
||||
},
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
children: [
|
||||
const Text(
|
||||
"Travel Mate",
|
||||
style: TextStyle(
|
||||
color: Color.fromARGB(255, 37, 109, 167),
|
||||
decoration: TextDecoration.underline,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
const Text(
|
||||
"Vous avez oublié votre mot de passe ? \n Ne vous inquiétez pas vous pouvez le réinitaliser !",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
const Text(
|
||||
"Quel est votre email ? \n Si celui-ci existe dans note base de donées, nous vous enverrons un mail avec un mot de passe unique.",
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
validator: _validateEmail,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
hintText: 'example@travelmate.com',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(12)),
|
||||
),
|
||||
prefixIcon: Icon(Icons.email_outlined),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) {
|
||||
final isLoading = state is AuthLoading;
|
||||
|
||||
return ElevatedButton(
|
||||
onPressed: isLoading ? null : _submit,
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(50),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
backgroundColor:
|
||||
Theme.of(context).brightness ==
|
||||
Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
foregroundColor:
|
||||
Theme.of(context).brightness ==
|
||||
Brightness.dark
|
||||
? Colors.black
|
||||
: Colors.white,
|
||||
),
|
||||
child: isLoading
|
||||
? SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color:
|
||||
Theme.of(context).brightness ==
|
||||
Brightness.dark
|
||||
? Colors.black
|
||||
: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Text(
|
||||
'Envoyer',
|
||||
style: TextStyle(fontSize: 18),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
Container(
|
||||
width: double.infinity,
|
||||
height: 1,
|
||||
color: Colors.grey.shade300,
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("Pas encore inscrit ? "),
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
// Go to sign up page
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/signup',
|
||||
);
|
||||
},
|
||||
child: const Text(
|
||||
'Inscrivez-vous !',
|
||||
style: TextStyle(
|
||||
color: Color.fromARGB(255, 37, 109, 167),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:sign_in_button/sign_in_button.dart';
|
||||
import 'package:travel_mate/components/loading/laoding_content.dart';
|
||||
import 'package:travel_mate/components/signup/password_requirements.dart';
|
||||
import 'package:travel_mate/components/signup/sign_up_platform_content.dart';
|
||||
import 'package:travel_mate/services/auth_service.dart';
|
||||
import '../blocs/auth/auth_bloc.dart';
|
||||
@@ -66,6 +67,18 @@ class _SignUpPageState extends State<SignUpPage> {
|
||||
if (value.length < 8) {
|
||||
return 'Le mot de passe doit contenir au moins 8 caractères';
|
||||
}
|
||||
if (!value.contains(RegExp(r'[A-Z]'))) {
|
||||
return 'Le mot de passe doit contenir une majuscule';
|
||||
}
|
||||
if (!value.contains(RegExp(r'[a-z]'))) {
|
||||
return 'Le mot de passe doit contenir une minuscule';
|
||||
}
|
||||
if (!value.contains(RegExp(r'[0-9]'))) {
|
||||
return 'Le mot de passe doit contenir un chiffre';
|
||||
}
|
||||
if (!value.contains(RegExp(r'[!@#\$%^&*(),.?":{}|<>]'))) {
|
||||
return 'Le mot de passe doit contenir un caractère spécial';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -115,11 +128,13 @@ class _SignUpPageState extends State<SignUpPage> {
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
Navigator.pushReplacementNamed(context, '/home');
|
||||
} else if (state is AuthError) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur lors de la création du compte',
|
||||
Navigator.pushNamedAndRemoveUntil(
|
||||
context,
|
||||
'/home',
|
||||
(route) => false,
|
||||
);
|
||||
} else if (state is AuthError) {
|
||||
_errorService.showError(message: state.message);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
@@ -211,6 +226,7 @@ class _SignUpPageState extends State<SignUpPage> {
|
||||
controller: _passwordController,
|
||||
validator: _validatePassword,
|
||||
obscureText: _obscurePassword,
|
||||
onChanged: (value) => setState(() {}),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Mot de passe',
|
||||
border: const OutlineInputBorder(
|
||||
@@ -231,6 +247,7 @@ class _SignUpPageState extends State<SignUpPage> {
|
||||
),
|
||||
),
|
||||
),
|
||||
PasswordRequirements(password: _passwordController.text),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Champ Confirmation mot de passe
|
||||
|
||||
@@ -7,7 +7,8 @@ class AccountRepository {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final _errorService = ErrorService();
|
||||
|
||||
CollectionReference get _accountCollection => _firestore.collection('accounts');
|
||||
CollectionReference get _accountCollection =>
|
||||
_firestore.collection('accounts');
|
||||
|
||||
CollectionReference _membersCollection(String accountId) {
|
||||
return _accountCollection.doc(accountId).collection('members');
|
||||
@@ -32,8 +33,13 @@ class AccountRepository {
|
||||
|
||||
return accountRef.id;
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la création du compte: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la création du compte: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de créer le compte');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +47,6 @@ class AccountRepository {
|
||||
return _accountCollection
|
||||
.snapshots()
|
||||
.asyncMap((snapshot) async {
|
||||
|
||||
List<Account> userAccounts = [];
|
||||
|
||||
for (var accountDoc in snapshot.docs) {
|
||||
@@ -54,14 +59,24 @@ class AccountRepository {
|
||||
.get();
|
||||
if (memberDoc.exists) {
|
||||
final accountData = accountDoc.data() as Map<String, dynamic>;
|
||||
final account = Account.fromMap(accountData, accountId); // ✅ Ajout de l'ID
|
||||
final account = Account.fromMap(
|
||||
accountData,
|
||||
accountId,
|
||||
); // ✅ Ajout de l'ID
|
||||
final members = await getAccountMembers(accountId);
|
||||
userAccounts.add(account.copyWith(members: members));
|
||||
} else {
|
||||
_errorService.logInfo('account_repository.dart', 'Utilisateur NON membre de $accountId');
|
||||
_errorService.logInfo(
|
||||
'account_repository.dart',
|
||||
'Utilisateur NON membre de $accountId',
|
||||
);
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur processing account doc: $e',
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
return userAccounts;
|
||||
@@ -70,14 +85,19 @@ class AccountRepository {
|
||||
if (prev.length != next.length) return false;
|
||||
final prevIds = prev.map((a) => a.id).toSet();
|
||||
final nextIds = next.map((a) => a.id).toSet();
|
||||
|
||||
final identical = prevIds.difference(nextIds).isEmpty &&
|
||||
nextIds.difference(prevIds).isEmpty;
|
||||
|
||||
|
||||
final identical =
|
||||
prevIds.difference(nextIds).isEmpty &&
|
||||
nextIds.difference(prevIds).isEmpty;
|
||||
|
||||
return identical;
|
||||
})
|
||||
.handleError((error, stackTrace) {
|
||||
_errorService.logError(error, stackTrace);
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur stream accounts: $error',
|
||||
stackTrace,
|
||||
);
|
||||
return <Account>[];
|
||||
});
|
||||
}
|
||||
@@ -85,16 +105,16 @@ class AccountRepository {
|
||||
Future<List<GroupMember>> getAccountMembers(String accountId) async {
|
||||
try {
|
||||
final snapshot = await _membersCollection(accountId).get();
|
||||
return snapshot.docs
|
||||
.map((doc) {
|
||||
return GroupMember.fromMap(
|
||||
doc.data() as Map<String, dynamic>,
|
||||
doc.id,
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération des membres: $e');
|
||||
return snapshot.docs.map((doc) {
|
||||
return GroupMember.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
}).toList();
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la récupération des membres: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer les membres');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,8 +125,13 @@ class AccountRepository {
|
||||
return Account.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération du compte: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la récupération du compte: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer le compte');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,14 +142,19 @@ class AccountRepository {
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
|
||||
if (querySnapshot.docs.isNotEmpty) {
|
||||
final doc = querySnapshot.docs.first;
|
||||
return Account.fromMap(doc.data(), doc.id);
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération du compte: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la récupération du compte: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer le compte');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,10 +162,17 @@ class AccountRepository {
|
||||
try {
|
||||
// Mettre à jour la date de modification
|
||||
final updatedAccount = account.copyWith(updatedAt: DateTime.now());
|
||||
await _firestore.collection('accounts').doc(accountId).update(updatedAccount.toMap());
|
||||
} catch (e) {
|
||||
_errorService.logError('account_repository.dart', 'Erreur lors de la mise à jour du compte: $e');
|
||||
throw Exception('Erreur lors de la mise à jour du compte: $e');
|
||||
await _firestore
|
||||
.collection('accounts')
|
||||
.doc(accountId)
|
||||
.update(updatedAccount.toMap());
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la mise à jour du compte: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de mettre à jour le compte');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,24 +193,28 @@ class AccountRepository {
|
||||
for (var memberDoc in membersSnapshot.docs) {
|
||||
await _membersCollection(docId).doc(memberDoc.id).delete();
|
||||
}
|
||||
|
||||
|
||||
// Supprimer le compte
|
||||
await _accountCollection.doc(docId).delete();
|
||||
} catch (e) {
|
||||
_errorService.logError('account_repository.dart', 'Erreur lors de la suppression du compte: $e');
|
||||
throw Exception('Erreur lors de la suppression du compte: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la suppression du compte: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer le compte');
|
||||
}
|
||||
}
|
||||
|
||||
Stream<List<GroupMember>> watchGroupMembers(String accountId) {
|
||||
return _membersCollection(accountId).snapshots().map(
|
||||
(snapshot) => snapshot.docs
|
||||
.map((doc) => GroupMember.fromMap(
|
||||
doc.data() as Map<String, dynamic>,
|
||||
doc.id,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
(snapshot) => snapshot.docs
|
||||
.map(
|
||||
(doc) =>
|
||||
GroupMember.fromMap(doc.data() as Map<String, dynamic>, doc.id),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Stream<Account?> watchAccount(String accountId) {
|
||||
@@ -198,4 +239,35 @@ class AccountRepository {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addMemberToAccount(String accountId, GroupMember member) async {
|
||||
try {
|
||||
await _membersCollection(
|
||||
accountId,
|
||||
).doc(member.userId).set(member.toMap());
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de l\'ajout du membre: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible d\'ajouter le membre');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> removeMemberFromAccount(
|
||||
String accountId,
|
||||
String memberId,
|
||||
) async {
|
||||
try {
|
||||
await _membersCollection(accountId).doc(memberId).delete();
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'account_repository.dart',
|
||||
'Erreur lors de la suppression du membre: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer le membre');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,18 +16,32 @@ class ActivityRepository {
|
||||
/// Ajoute une nouvelle activité
|
||||
Future<String?> addActivity(Activity activity) async {
|
||||
try {
|
||||
print('ActivityRepository: Ajout d\'une activité: ${activity.name}');
|
||||
|
||||
final docRef = await _firestore.collection(_collection).add(activity.toMap());
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Ajout d\'une activité: ${activity.name}',
|
||||
);
|
||||
|
||||
final docRef = await _firestore
|
||||
.collection(_collection)
|
||||
.add(activity.toMap());
|
||||
|
||||
// Mettre à jour l'activité avec l'ID généré
|
||||
await docRef.update({'id': docRef.id});
|
||||
|
||||
print('ActivityRepository: Activité ajoutée avec ID: ${docRef.id}');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'ActivityRepository',
|
||||
'Activité ajoutée avec ID: ${docRef.id}',
|
||||
);
|
||||
return docRef.id;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur lors de l\'ajout: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur ajout activité: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur lors de l\'ajout: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur ajout activité: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -35,8 +49,11 @@ class ActivityRepository {
|
||||
/// Récupère toutes les activités d'un voyage
|
||||
Future<List<Activity>> getActivitiesByTrip(String tripId) async {
|
||||
try {
|
||||
print('ActivityRepository: Récupération des activités pour le voyage: $tripId');
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Récupération des activités pour le voyage: $tripId',
|
||||
);
|
||||
|
||||
// Modifié pour éviter l'erreur d'index composite
|
||||
// On récupère d'abord par tripId, puis on trie en mémoire
|
||||
final querySnapshot = await _firestore
|
||||
@@ -51,28 +68,51 @@ class ActivityRepository {
|
||||
// Tri en mémoire par date de mise à jour (plus récent en premier)
|
||||
activities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
|
||||
print('ActivityRepository: ${activities.length} activités trouvées');
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'${activities.length} activités trouvées',
|
||||
);
|
||||
return activities;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur lors de la récupération: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur récupération activités: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur lors de la récupération: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur récupération activités: $e',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupère une activité par son ID (alias pour getActivityById pour compatibilité)
|
||||
Future<Activity?> getActivity(String tripId, String activityId) async {
|
||||
return getActivityById(activityId);
|
||||
}
|
||||
|
||||
/// Récupère une activité par son ID
|
||||
Future<Activity?> getActivityById(String activityId) async {
|
||||
try {
|
||||
final doc = await _firestore.collection(_collection).doc(activityId).get();
|
||||
|
||||
final doc = await _firestore
|
||||
.collection(_collection)
|
||||
.doc(activityId)
|
||||
.get();
|
||||
|
||||
if (doc.exists) {
|
||||
return Activity.fromSnapshot(doc);
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur récupération activité: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur récupération activité: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur récupération activité: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur récupération activité: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -80,18 +120,30 @@ class ActivityRepository {
|
||||
/// Met à jour une activité
|
||||
Future<bool> updateActivity(Activity activity) async {
|
||||
try {
|
||||
print('ActivityRepository: Mise à jour de l\'activité: ${activity.id}');
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Mise à jour de l\'activité: ${activity.id}',
|
||||
);
|
||||
|
||||
await _firestore
|
||||
.collection(_collection)
|
||||
.doc(activity.id)
|
||||
.update(activity.copyWith(updatedAt: DateTime.now()).toMap());
|
||||
|
||||
print('ActivityRepository: Activité mise à jour avec succès');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'ActivityRepository',
|
||||
'Activité mise à jour avec succès',
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur lors de la mise à jour: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur mise à jour activité: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur lors de la mise à jour: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur mise à jour activité: $e',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -99,50 +151,75 @@ class ActivityRepository {
|
||||
/// Supprime une activité
|
||||
Future<bool> deleteActivity(String activityId) async {
|
||||
try {
|
||||
print('ActivityRepository: Suppression de l\'activité: $activityId');
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Suppression de l\'activité: $activityId',
|
||||
);
|
||||
|
||||
await _firestore.collection(_collection).doc(activityId).delete();
|
||||
|
||||
print('ActivityRepository: Activité supprimée avec succès');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'ActivityRepository',
|
||||
'Activité supprimée avec succès',
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur lors de la suppression: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur suppression activité: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur lors de la suppression: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur suppression activité: $e',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Vote pour une activité
|
||||
Future<bool> voteForActivity(String activityId, String userId, int vote) async {
|
||||
Future<bool> voteForActivity(
|
||||
String activityId,
|
||||
String userId,
|
||||
int vote,
|
||||
) async {
|
||||
try {
|
||||
// Validation des paramètres
|
||||
if (activityId.isEmpty) {
|
||||
print('ActivityRepository: ID d\'activité vide');
|
||||
_errorService.logError('activity_repository', 'ID d\'activité vide pour le vote');
|
||||
_errorService.logError('ActivityRepository', 'ID d\'activité vide');
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'ID d\'activité vide pour le vote',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (userId.isEmpty) {
|
||||
print('ActivityRepository: ID d\'utilisateur vide');
|
||||
_errorService.logError('activity_repository', 'ID d\'utilisateur vide pour le vote');
|
||||
_errorService.logError('ActivityRepository', 'ID d\'utilisateur vide');
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'ID d\'utilisateur vide pour le vote',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
print('ActivityRepository: Vote pour l\'activité $activityId: $vote');
|
||||
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Vote pour l\'activité $activityId: $vote',
|
||||
);
|
||||
|
||||
// vote: 1 pour positif, -1 pour négatif, 0 pour supprimer le vote
|
||||
final activityRef = _firestore.collection(_collection).doc(activityId);
|
||||
|
||||
|
||||
await _firestore.runTransaction((transaction) async {
|
||||
final snapshot = await transaction.get(activityRef);
|
||||
|
||||
|
||||
if (!snapshot.exists) {
|
||||
throw Exception('Activité non trouvée');
|
||||
}
|
||||
|
||||
|
||||
final activity = Activity.fromSnapshot(snapshot);
|
||||
final newVotes = Map<String, int>.from(activity.votes);
|
||||
|
||||
|
||||
if (vote == 0) {
|
||||
// Supprimer le vote
|
||||
newVotes.remove(userId);
|
||||
@@ -150,17 +227,20 @@ class ActivityRepository {
|
||||
// Ajouter ou modifier le vote
|
||||
newVotes[userId] = vote;
|
||||
}
|
||||
|
||||
|
||||
transaction.update(activityRef, {
|
||||
'votes': newVotes,
|
||||
'updatedAt': Timestamp.fromDate(DateTime.now()),
|
||||
});
|
||||
});
|
||||
|
||||
print('ActivityRepository: Vote enregistré avec succès');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'ActivityRepository',
|
||||
'Vote enregistré avec succès',
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur lors du vote: $e');
|
||||
_errorService.logError('ActivityRepository', 'Erreur lors du vote: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur vote: $e');
|
||||
return false;
|
||||
}
|
||||
@@ -174,18 +254,24 @@ class ActivityRepository {
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.snapshots()
|
||||
.map((snapshot) {
|
||||
final activities = snapshot.docs
|
||||
.map((doc) => Activity.fromSnapshot(doc))
|
||||
.toList();
|
||||
|
||||
// Tri en mémoire par date de mise à jour (plus récent en premier)
|
||||
activities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
|
||||
return activities;
|
||||
});
|
||||
final activities = snapshot.docs
|
||||
.map((doc) => Activity.fromSnapshot(doc))
|
||||
.toList();
|
||||
|
||||
// Tri en mémoire par date de mise à jour (plus récent en premier)
|
||||
activities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
|
||||
return activities;
|
||||
});
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur stream activités: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur stream activités: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur stream activités: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur stream activités: $e',
|
||||
);
|
||||
return Stream.value([]);
|
||||
}
|
||||
}
|
||||
@@ -193,34 +279,46 @@ class ActivityRepository {
|
||||
/// Ajoute plusieurs activités en lot
|
||||
Future<List<String>> addActivitiesBatch(List<Activity> activities) async {
|
||||
try {
|
||||
print('ActivityRepository: Ajout en lot de ${activities.length} activités');
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Ajout en lot de ${activities.length} activités',
|
||||
);
|
||||
|
||||
final batch = _firestore.batch();
|
||||
final addedIds = <String>[];
|
||||
|
||||
|
||||
for (final activity in activities) {
|
||||
final docRef = _firestore.collection(_collection).doc();
|
||||
final activityWithId = activity.copyWith(id: docRef.id);
|
||||
batch.set(docRef, activityWithId.toMap());
|
||||
addedIds.add(docRef.id);
|
||||
}
|
||||
|
||||
|
||||
await batch.commit();
|
||||
|
||||
print('ActivityRepository: ${addedIds.length} activités ajoutées en lot');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'ActivityRepository',
|
||||
'${addedIds.length} activités ajoutées en lot',
|
||||
);
|
||||
return addedIds;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur ajout en lot: $e');
|
||||
_errorService.logError('ActivityRepository', 'Erreur ajout en lot: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur ajout en lot: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Recherche des activités par catégorie
|
||||
Future<List<Activity>> getActivitiesByCategory(String tripId, String category) async {
|
||||
Future<List<Activity>> getActivitiesByCategory(
|
||||
String tripId,
|
||||
String category,
|
||||
) async {
|
||||
try {
|
||||
print('ActivityRepository: Recherche par catégorie: $category pour le voyage: $tripId');
|
||||
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Recherche par catégorie: $category pour le voyage: $tripId',
|
||||
);
|
||||
|
||||
// Récupérer toutes les activités du voyage puis filtrer en mémoire
|
||||
final querySnapshot = await _firestore
|
||||
.collection(_collection)
|
||||
@@ -237,32 +335,44 @@ class ActivityRepository {
|
||||
|
||||
return activities;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur recherche par catégorie: $e');
|
||||
_errorService.logError('activity_repository', 'Erreur recherche par catégorie: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur recherche par catégorie: $e',
|
||||
);
|
||||
_errorService.logError(
|
||||
'activity_repository',
|
||||
'Erreur recherche par catégorie: $e',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupère les activités les mieux notées d'un voyage
|
||||
Future<List<Activity>> getTopRatedActivities(String tripId, {int limit = 10}) async {
|
||||
Future<List<Activity>> getTopRatedActivities(
|
||||
String tripId, {
|
||||
int limit = 10,
|
||||
}) async {
|
||||
try {
|
||||
final activities = await getActivitiesByTrip(tripId);
|
||||
|
||||
|
||||
// Trier par nombre de votes positifs puis par note Google
|
||||
activities.sort((a, b) {
|
||||
final aScore = a.totalVotes;
|
||||
final bScore = b.totalVotes;
|
||||
|
||||
|
||||
if (aScore != bScore) {
|
||||
return bScore.compareTo(aScore);
|
||||
}
|
||||
|
||||
|
||||
return (b.rating ?? 0).compareTo(a.rating ?? 0);
|
||||
});
|
||||
|
||||
|
||||
return activities.take(limit).toList();
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur activités top rated: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur activités top rated: $e',
|
||||
);
|
||||
_errorService.logError('activity_repository', 'Erreur top rated: $e');
|
||||
return [];
|
||||
}
|
||||
@@ -281,11 +391,14 @@ class ActivityRepository {
|
||||
if (querySnapshot.docs.isNotEmpty) {
|
||||
return Activity.fromSnapshot(querySnapshot.docs.first);
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur recherche activité existante: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur recherche activité existante: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import '../models/user.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/error_service.dart';
|
||||
import '../services/notification_service.dart';
|
||||
|
||||
/// Repository for authentication operations and user data management.
|
||||
///
|
||||
@@ -57,11 +58,12 @@ class AuthRepository {
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
await _saveFCMToken(firebaseUser.user!.uid);
|
||||
return await getUserFromFirestore(firebaseUser.user!.uid);
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Utilisateur ou mot de passe incorrect');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('AuthRepository', 'SignIn error: $e', stackTrace);
|
||||
throw Exception('Utilisateur ou mot de passe incorrect');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Creates a new user account with email and password.
|
||||
@@ -102,11 +104,14 @@ class AuthRepository {
|
||||
);
|
||||
|
||||
await _firestore.collection('users').doc(user.id).set(user.toMap());
|
||||
if (user.id != null) {
|
||||
await _saveFCMToken(user.id!);
|
||||
}
|
||||
return user;
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la création du compte');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError('AuthRepository', 'SignUp error: $e', stackTrace);
|
||||
throw Exception('Erreur lors de la création du compte');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Signs in a user using Google authentication.
|
||||
@@ -122,11 +127,16 @@ class AuthRepository {
|
||||
String firstname,
|
||||
) async {
|
||||
try {
|
||||
final firebaseUser = await _authService.signInWithGoogle();
|
||||
firebase_auth.User? firebaseUser = _authService.currentUser;
|
||||
|
||||
if (firebaseUser.user != null) {
|
||||
if (firebaseUser == null) {
|
||||
final userCredential = await _authService.signInWithGoogle();
|
||||
firebaseUser = userCredential.user;
|
||||
}
|
||||
|
||||
if (firebaseUser != null) {
|
||||
// Check if user already exists in Firestore
|
||||
final existingUser = await getUserFromFirestore(firebaseUser.user!.uid);
|
||||
final existingUser = await getUserFromFirestore(firebaseUser.uid);
|
||||
|
||||
if (existingUser != null) {
|
||||
return existingUser;
|
||||
@@ -134,23 +144,30 @@ class AuthRepository {
|
||||
|
||||
// Create new user document for first-time Google sign-in
|
||||
final user = User(
|
||||
id: firebaseUser.user!.uid,
|
||||
email: firebaseUser.user!.email ?? '',
|
||||
id: firebaseUser.uid,
|
||||
email: firebaseUser.email ?? '',
|
||||
nom: name,
|
||||
prenom: firstname,
|
||||
phoneNumber: phoneNumber,
|
||||
profilePictureUrl: firebaseUser.user!.photoURL ?? 'Unknown',
|
||||
profilePictureUrl: firebaseUser.photoURL ?? 'Unknown',
|
||||
platform: 'google',
|
||||
);
|
||||
|
||||
await _firestore.collection('users').doc(user.id).set(user.toMap());
|
||||
if (user.id != null) {
|
||||
await _saveFCMToken(user.id!);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la connexion Google');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AuthRepository',
|
||||
'Google SignUp error: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Erreur lors de la connexion Google');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<User?> signInWithGoogle() async {
|
||||
@@ -158,14 +175,21 @@ class AuthRepository {
|
||||
final firebaseUser = await _authService.signInWithGoogle();
|
||||
final user = await getUserFromFirestore(firebaseUser.user!.uid);
|
||||
if (user != null) {
|
||||
if (user.id != null) {
|
||||
await _saveFCMToken(user.id!);
|
||||
}
|
||||
return user;
|
||||
} else {
|
||||
throw Exception('Utilisateur non trouvé');
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la connexion Google');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AuthRepository',
|
||||
'Google SignIn error: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Erreur lors de la connexion Google');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Signs in a user using Apple authentication.
|
||||
@@ -181,33 +205,45 @@ class AuthRepository {
|
||||
String firstname,
|
||||
) async {
|
||||
try {
|
||||
final firebaseUser = await _authService.signInWithApple();
|
||||
firebase_auth.User? firebaseUser = _authService.currentUser;
|
||||
|
||||
if (firebaseUser.user != null) {
|
||||
final existingUser = await getUserFromFirestore(firebaseUser.user!.uid);
|
||||
if (firebaseUser == null) {
|
||||
final userCredential = await _authService.signInWithApple();
|
||||
firebaseUser = userCredential.user;
|
||||
}
|
||||
|
||||
if (firebaseUser != null) {
|
||||
final existingUser = await getUserFromFirestore(firebaseUser.uid);
|
||||
|
||||
if (existingUser != null) {
|
||||
return existingUser;
|
||||
}
|
||||
|
||||
final user = User(
|
||||
id: firebaseUser.user!.uid,
|
||||
email: firebaseUser.user!.email ?? '',
|
||||
id: firebaseUser.uid,
|
||||
email: firebaseUser.email ?? '',
|
||||
nom: name,
|
||||
prenom: firstname,
|
||||
phoneNumber: phoneNumber,
|
||||
profilePictureUrl: firebaseUser.user!.photoURL ?? 'Unknown',
|
||||
profilePictureUrl: firebaseUser.photoURL ?? 'Unknown',
|
||||
platform: 'apple',
|
||||
);
|
||||
|
||||
await _firestore.collection('users').doc(user.id).set(user.toMap());
|
||||
if (user.id != null) {
|
||||
await _saveFCMToken(user.id!);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la connexion Apple');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AuthRepository',
|
||||
'Apple SignUp error: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Erreur lors de la connexion Apple');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<User?> signInWithApple() async {
|
||||
@@ -215,14 +251,21 @@ class AuthRepository {
|
||||
final firebaseUser = await _authService.signInWithApple();
|
||||
final user = await getUserFromFirestore(firebaseUser.user!.uid);
|
||||
if (user != null) {
|
||||
if (user.id != null) {
|
||||
await _saveFCMToken(user.id!);
|
||||
}
|
||||
return user;
|
||||
} else {
|
||||
throw Exception('Utilisateur non trouvé');
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(message: 'Erreur lors de la connexion Apple');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'AuthRepository',
|
||||
'Apple SignIn error: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Erreur lors de la connexion Apple');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Signs out the current user.
|
||||
@@ -248,7 +291,7 @@ class AuthRepository {
|
||||
///
|
||||
/// [uid] - The Firebase user ID to look up
|
||||
///
|
||||
/// Returns the [User] model if found, null otherwise.
|
||||
/// Returns the [User] model if successful, null otherwise.
|
||||
Future<User?> getUserFromFirestore(String uid) async {
|
||||
try {
|
||||
final doc = await _firestore.collection('users').doc(uid).get();
|
||||
@@ -261,4 +304,23 @@ class AuthRepository {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper method to save the FCM token for the authenticated user.
|
||||
Future<void> _saveFCMToken(String userId) async {
|
||||
try {
|
||||
final token = await NotificationService().getFCMToken();
|
||||
if (token != null) {
|
||||
await _firestore.collection('users').doc(userId).set({
|
||||
'fcmToken': token,
|
||||
}, SetOptions(merge: true));
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
// Non-blocking error
|
||||
_errorService.logError(
|
||||
'AuthRepository',
|
||||
'Error saving FCM token: $e',
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,9 +37,13 @@ class BalanceRepository {
|
||||
totalExpenses: totalExpenses,
|
||||
calculatedAt: DateTime.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceRepository', 'Erreur calcul balance: $e');
|
||||
rethrow;
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'BalanceRepository',
|
||||
'Erreur calcul balance: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de calculer la balance');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,9 +54,13 @@ class BalanceRepository {
|
||||
.first;
|
||||
|
||||
return _calculateUserBalances(expenses);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceRepository', 'Erreur calcul user balances: $e');
|
||||
rethrow;
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'BalanceRepository',
|
||||
'Erreur calcul user balances: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de calculer les balances utilisateurs');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,19 +73,17 @@ class BalanceRepository {
|
||||
if (expense.isArchived) continue;
|
||||
|
||||
// Ajouter le payeur
|
||||
userBalanceMap.putIfAbsent(expense.paidById, () => {
|
||||
'name': expense.paidByName,
|
||||
'paid': 0.0,
|
||||
'owed': 0.0,
|
||||
});
|
||||
userBalanceMap.putIfAbsent(
|
||||
expense.paidById,
|
||||
() => {'name': expense.paidByName, 'paid': 0.0, 'owed': 0.0},
|
||||
);
|
||||
|
||||
// Ajouter les participants
|
||||
for (final split in expense.splits) {
|
||||
userBalanceMap.putIfAbsent(split.userId, () => {
|
||||
'name': split.userName,
|
||||
'paid': 0.0,
|
||||
'owed': 0.0,
|
||||
});
|
||||
userBalanceMap.putIfAbsent(
|
||||
split.userId,
|
||||
() => {'name': split.userName, 'paid': 0.0, 'owed': 0.0},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +106,7 @@ class BalanceRepository {
|
||||
final data = entry.value;
|
||||
final paid = data['paid'] as double;
|
||||
final owed = data['owed'] as double;
|
||||
|
||||
|
||||
return UserBalance(
|
||||
userId: userId,
|
||||
userName: data['name'] as String,
|
||||
@@ -114,7 +120,7 @@ class BalanceRepository {
|
||||
// Algorithme d'optimisation des règlements
|
||||
List<Settlement> _calculateOptimalSettlements(List<UserBalance> balances) {
|
||||
final settlements = <Settlement>[];
|
||||
|
||||
|
||||
// Séparer les créditeurs et débiteurs
|
||||
final creditors = balances.where((b) => b.shouldReceive).toList();
|
||||
final debtors = balances.where((b) => b.shouldPay).toList();
|
||||
@@ -125,10 +131,10 @@ class BalanceRepository {
|
||||
|
||||
// Créer des copies mutables des montants
|
||||
final creditorsRemaining = Map.fromEntries(
|
||||
creditors.map((c) => MapEntry(c.userId, c.balance))
|
||||
creditors.map((c) => MapEntry(c.userId, c.balance)),
|
||||
);
|
||||
final debtorsRemaining = Map.fromEntries(
|
||||
debtors.map((d) => MapEntry(d.userId, -d.balance))
|
||||
debtors.map((d) => MapEntry(d.userId, -d.balance)),
|
||||
);
|
||||
|
||||
// Algorithme glouton pour minimiser le nombre de transactions
|
||||
@@ -139,15 +145,20 @@ class BalanceRepository {
|
||||
|
||||
if (creditAmount <= 0.01 || debtAmount <= 0.01) continue;
|
||||
|
||||
final settlementAmount = [creditAmount, debtAmount].reduce((a, b) => a < b ? a : b);
|
||||
final settlementAmount = [
|
||||
creditAmount,
|
||||
debtAmount,
|
||||
].reduce((a, b) => a < b ? a : b);
|
||||
|
||||
settlements.add(Settlement(
|
||||
fromUserId: debtor.userId,
|
||||
fromUserName: debtor.userName,
|
||||
toUserId: creditor.userId,
|
||||
toUserName: creditor.userName,
|
||||
amount: settlementAmount,
|
||||
));
|
||||
settlements.add(
|
||||
Settlement(
|
||||
fromUserId: debtor.userId,
|
||||
fromUserName: debtor.userName,
|
||||
toUserId: creditor.userId,
|
||||
toUserName: creditor.userName,
|
||||
amount: settlementAmount,
|
||||
),
|
||||
);
|
||||
|
||||
creditorsRemaining[creditor.userId] = creditAmount - settlementAmount;
|
||||
debtorsRemaining[debtor.userId] = debtAmount - settlementAmount;
|
||||
@@ -156,4 +167,4 @@ class BalanceRepository {
|
||||
|
||||
return settlements;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
import '../models/group.dart';
|
||||
import '../models/group_member.dart';
|
||||
|
||||
class GroupRepository {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
final _errorService = ErrorService();
|
||||
|
||||
CollectionReference get _groupsCollection => _firestore.collection('groups');
|
||||
@@ -20,8 +22,10 @@ class GroupRepository {
|
||||
try {
|
||||
return await _firestore.runTransaction<String>((transaction) async {
|
||||
final groupRef = _groupsCollection.doc();
|
||||
|
||||
final groupData = group.toMap();
|
||||
|
||||
// Ajouter les IDs des membres à la liste memberIds
|
||||
final memberIds = members.map((m) => m.userId).toList();
|
||||
final groupData = group.copyWith(memberIds: memberIds).toMap();
|
||||
transaction.set(groupRef, groupData);
|
||||
|
||||
for (var member in members) {
|
||||
@@ -31,60 +35,32 @@ class GroupRepository {
|
||||
|
||||
return groupRef.id;
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la création du groupe: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur création groupe: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de créer le groupe');
|
||||
}
|
||||
}
|
||||
|
||||
Stream<List<Group>> getGroupsByUserId(String userId) {
|
||||
Stream<List<Group>> getGroupsByUserId(String userId) {
|
||||
return _groupsCollection
|
||||
.where('memberIds', arrayContains: userId)
|
||||
.snapshots()
|
||||
.asyncMap((snapshot) async {
|
||||
|
||||
List<Group> userGroups = [];
|
||||
|
||||
for (var groupDoc in snapshot.docs) {
|
||||
try {
|
||||
final groupId = groupDoc.id;
|
||||
|
||||
// Vérifier si l'utilisateur est membre
|
||||
final memberDoc = await groupDoc.reference
|
||||
.collection('members')
|
||||
.doc(userId)
|
||||
.get();
|
||||
|
||||
if (memberDoc.exists) {
|
||||
final groupData = groupDoc.data() as Map<String, dynamic>;
|
||||
final group = Group.fromMap(groupData, groupId);
|
||||
|
||||
final members = await getGroupMembers(groupId);
|
||||
userGroups.add(group.copyWith(members: members));
|
||||
} else {
|
||||
_errorService.logInfo('group_repository.dart','Utilisateur NON membre de $groupId');
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(e.toString(), stackTrace);
|
||||
}
|
||||
}
|
||||
return userGroups;
|
||||
})
|
||||
.distinct((prev, next) {
|
||||
// Comparer les listes pour éviter les doublons
|
||||
if (prev.length != next.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Vérifier si les IDs sont identiques
|
||||
final prevIds = prev.map((g) => g.id).toSet();
|
||||
final nextIds = next.map((g) => g.id).toSet();
|
||||
|
||||
final identical = prevIds.difference(nextIds).isEmpty &&
|
||||
nextIds.difference(prevIds).isEmpty;
|
||||
|
||||
return identical;
|
||||
.map((snapshot) {
|
||||
return snapshot.docs.map((doc) {
|
||||
final groupData = doc.data() as Map<String, dynamic>;
|
||||
return Group.fromMap(groupData, doc.id);
|
||||
}).toList();
|
||||
})
|
||||
.handleError((error, stackTrace) {
|
||||
_errorService.logError(error, stackTrace);
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur stream groups: $error',
|
||||
stackTrace,
|
||||
);
|
||||
return <Group>[];
|
||||
});
|
||||
}
|
||||
@@ -92,120 +68,260 @@ class GroupRepository {
|
||||
Future<Group?> getGroupById(String groupId) async {
|
||||
try {
|
||||
final doc = await _groupsCollection.doc(groupId).get();
|
||||
|
||||
|
||||
if (!doc.exists) return null;
|
||||
|
||||
|
||||
final group = Group.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
final members = await getGroupMembers(groupId);
|
||||
|
||||
|
||||
return group.copyWith(members: members);
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération du groupe: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur get group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer le groupe');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Group?> getGroupByTripId(String tripId) async {
|
||||
try {
|
||||
final querySnapshot = await _groupsCollection
|
||||
final userId = _auth.currentUser?.uid;
|
||||
if (userId == null) return null;
|
||||
|
||||
// Tentative 1: Requête optimisée avec memberIds
|
||||
var querySnapshot = await _groupsCollection
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.where('memberIds', arrayContains: userId)
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
// Tentative 2: Fallback pour le créateur (si memberIds est manquant - anciennes données)
|
||||
if (querySnapshot.docs.isEmpty) {
|
||||
querySnapshot = await _groupsCollection
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.where('createdBy', isEqualTo: userId)
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
// Si on trouve le groupe via le fallback, on lance une migration
|
||||
if (querySnapshot.docs.isNotEmpty) {
|
||||
_migrateGroupData(querySnapshot.docs.first.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (querySnapshot.docs.isEmpty) return null;
|
||||
|
||||
final doc = querySnapshot.docs.first;
|
||||
final group = Group.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
final members = await getGroupMembers(doc.id);
|
||||
|
||||
|
||||
return group.copyWith(members: members);
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération du groupe: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur get group by trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer le groupe du voyage');
|
||||
}
|
||||
}
|
||||
|
||||
/// Méthode utilitaire pour migrer les anciennes données
|
||||
Future<void> _migrateGroupData(String groupId) async {
|
||||
try {
|
||||
final members = await getGroupMembers(groupId);
|
||||
final memberIds = members.map((m) => m.userId).toList();
|
||||
|
||||
if (memberIds.isNotEmpty) {
|
||||
await _groupsCollection.doc(groupId).update({'memberIds': memberIds});
|
||||
_errorService.logSuccess(
|
||||
'GroupRepository',
|
||||
'Migration réussie pour le groupe $groupId',
|
||||
);
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur de migration pour le groupe $groupId: $e',
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<GroupMember>> getGroupMembers(String groupId) async {
|
||||
try {
|
||||
final snapshot = await _membersCollection(groupId).get();
|
||||
return snapshot.docs
|
||||
.map((doc) {
|
||||
return GroupMember.fromMap(
|
||||
doc.data() as Map<String, dynamic>,
|
||||
doc.id,
|
||||
);
|
||||
})
|
||||
.toList();
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération des membres: $e');
|
||||
final snapshot = await _membersCollection(groupId).get();
|
||||
return snapshot.docs.map((doc) {
|
||||
return GroupMember.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
}).toList();
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur get members: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer les membres');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addMember(String groupId, GroupMember member) async {
|
||||
try {
|
||||
// 1. Récupérer le groupe pour avoir le tripId
|
||||
final group = await getGroupById(groupId);
|
||||
if (group == null) throw Exception('Groupe introuvable');
|
||||
|
||||
// 2. Ajouter le membre dans la sous-collection members du groupe
|
||||
await _membersCollection(groupId).doc(member.userId).set(member.toMap());
|
||||
|
||||
|
||||
// 3. Mettre à jour la liste memberIds du groupe
|
||||
await _groupsCollection.doc(groupId).update({
|
||||
'updatedAt': DateTime.now().millisecondsSinceEpoch,
|
||||
'memberIds': FieldValue.arrayUnion([member.userId]),
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de l\'ajout du membre: $e');
|
||||
|
||||
// 4. Mettre à jour la liste participants du voyage
|
||||
await _firestore.collection('trips').doc(group.tripId).update({
|
||||
'participants': FieldValue.arrayUnion([member.userId]),
|
||||
});
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur add member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible d\'ajouter le membre');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> removeMember(String groupId, String userId) async {
|
||||
try {
|
||||
// 1. Récupérer le groupe pour avoir le tripId
|
||||
final group = await getGroupById(groupId);
|
||||
if (group == null) throw Exception('Groupe introuvable');
|
||||
|
||||
// 2. Supprimer le membre de la sous-collection members du groupe
|
||||
await _membersCollection(groupId).doc(userId).delete();
|
||||
|
||||
|
||||
// 3. Mettre à jour la liste memberIds du groupe
|
||||
await _groupsCollection.doc(groupId).update({
|
||||
'updatedAt': DateTime.now().millisecondsSinceEpoch,
|
||||
'memberIds': FieldValue.arrayRemove([userId]),
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la suppression du membre: $e');
|
||||
|
||||
// 4. Mettre à jour la liste participants du voyage
|
||||
await _firestore.collection('trips').doc(group.tripId).update({
|
||||
'participants': FieldValue.arrayRemove([userId]),
|
||||
});
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur remove member: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer le membre');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateGroup(String groupId, Group group) async {
|
||||
try {
|
||||
await _groupsCollection.doc(groupId).update(
|
||||
group.toMap()..['updatedAt'] = DateTime.now().millisecondsSinceEpoch,
|
||||
await _groupsCollection
|
||||
.doc(groupId)
|
||||
.update(
|
||||
group.toMap()
|
||||
..['updatedAt'] = DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la mise à jour du groupe: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur update group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de mettre à jour le groupe');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteGroup(String tripId) async {
|
||||
try {
|
||||
final querySnapshot = await _groupsCollection
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.limit(1)
|
||||
.get();
|
||||
try {
|
||||
final userId = _auth.currentUser?.uid;
|
||||
if (userId == null) throw Exception('Utilisateur non connecté');
|
||||
|
||||
if (querySnapshot.docs.isEmpty) {
|
||||
throw Exception('Aucun groupe trouvé pour ce voyage');
|
||||
final querySnapshot = await _groupsCollection
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.where('createdBy', isEqualTo: userId)
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (querySnapshot.docs.isEmpty) {
|
||||
throw Exception('Aucun groupe trouvé pour ce voyage');
|
||||
}
|
||||
|
||||
final groupDoc = querySnapshot.docs.first;
|
||||
final groupId = groupDoc.id;
|
||||
|
||||
final membersSnapshot = await _membersCollection(groupId).get();
|
||||
for (var doc in membersSnapshot.docs) {
|
||||
await doc.reference.delete();
|
||||
}
|
||||
|
||||
await _groupsCollection.doc(groupId).delete();
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur delete group: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer le groupe');
|
||||
}
|
||||
|
||||
final groupDoc = querySnapshot.docs.first;
|
||||
final groupId = groupDoc.id;
|
||||
|
||||
final membersSnapshot = await _membersCollection(groupId).get();
|
||||
for (var doc in membersSnapshot.docs) {
|
||||
await doc.reference.delete();
|
||||
}
|
||||
|
||||
await _groupsCollection.doc(groupId).delete();
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la suppression du groupe: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Stream<List<GroupMember>> watchGroupMembers(String groupId) {
|
||||
return _membersCollection(groupId).snapshots().map(
|
||||
(snapshot) => snapshot.docs
|
||||
.map((doc) => GroupMember.fromMap(
|
||||
doc.data() as Map<String, dynamic>,
|
||||
doc.id,
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
(snapshot) => snapshot.docs
|
||||
.map(
|
||||
(doc) =>
|
||||
GroupMember.fromMap(doc.data() as Map<String, dynamic>, doc.id),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateMemberDetails({
|
||||
required String userId,
|
||||
String? firstName,
|
||||
String? lastName,
|
||||
String? profilePictureUrl,
|
||||
}) async {
|
||||
try {
|
||||
// 1. Trouver tous les groupes où l'utilisateur est membre
|
||||
final groupsSnapshot = await _groupsCollection
|
||||
.where('memberIds', arrayContains: userId)
|
||||
.get();
|
||||
|
||||
// 2. Mettre à jour les infos du membre dans chaque groupe
|
||||
for (final groupDoc in groupsSnapshot.docs) {
|
||||
final memberRef = _membersCollection(groupDoc.id).doc(userId);
|
||||
|
||||
final updates = <String, dynamic>{};
|
||||
if (firstName != null) updates['firstName'] = firstName;
|
||||
if (lastName != null) updates['lastName'] = lastName;
|
||||
if (profilePictureUrl != null) {
|
||||
updates['profilePictureUrl'] = profilePictureUrl;
|
||||
}
|
||||
|
||||
if (updates.isNotEmpty) {
|
||||
await memberRef.update(updates);
|
||||
}
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur update member details: $e',
|
||||
stackTrace,
|
||||
);
|
||||
// On ne throw pas d'exception ici pour ne pas bloquer l'update user principal
|
||||
// C'est une opération "best effort"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ class MessageRepository {
|
||||
});
|
||||
}
|
||||
|
||||
// Supprimer un message
|
||||
// Supprimer un message (marquer comme supprimé)
|
||||
Future<void> deleteMessage({
|
||||
required String groupId,
|
||||
required String messageId,
|
||||
@@ -52,7 +52,10 @@ class MessageRepository {
|
||||
.doc(groupId)
|
||||
.collection('messages')
|
||||
.doc(messageId)
|
||||
.delete();
|
||||
.update({
|
||||
'isDeleted': true,
|
||||
'text': '',
|
||||
});
|
||||
}
|
||||
|
||||
// Modifier un message
|
||||
|
||||
@@ -1,33 +1,45 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import '../models/trip.dart';
|
||||
import '../services/error_service.dart';
|
||||
|
||||
class TripRepository {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final _errorService = ErrorService();
|
||||
|
||||
CollectionReference get _tripsCollection => _firestore.collection('trips');
|
||||
|
||||
// Récupérer tous les voyages d'un utilisateur
|
||||
Stream<List<Trip>> getTripsByUserId(String userId) {
|
||||
Stream<List<Trip>> getTripsByUserId(String userId) {
|
||||
try {
|
||||
return _tripsCollection
|
||||
.where('participants', arrayContains: userId)
|
||||
.snapshots()
|
||||
.map((snapshot) {
|
||||
final trips = snapshot.docs
|
||||
.map((doc) {
|
||||
try {
|
||||
final data = doc.data() as Map<String, dynamic>;
|
||||
return Trip.fromMap(data, doc.id);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.whereType<Trip>()
|
||||
.toList();
|
||||
return trips;
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération des voyages: $e');
|
||||
.map((snapshot) {
|
||||
final trips = snapshot.docs
|
||||
.map((doc) {
|
||||
try {
|
||||
final data = doc.data() as Map<String, dynamic>;
|
||||
return Trip.fromMap(data, doc.id);
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur parsing trip ${doc.id}: $e',
|
||||
stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.whereType<Trip>()
|
||||
.toList();
|
||||
return trips;
|
||||
});
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur stream trips: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer les voyages');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +50,13 @@ class TripRepository {
|
||||
// Ne pas modifier les timestamps ici, ils sont déjà au bon format
|
||||
final docRef = await _tripsCollection.add(tripData);
|
||||
return docRef.id;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la création du voyage: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur création trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de créer le voyage');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,14 +64,19 @@ class TripRepository {
|
||||
Future<Trip?> getTripById(String tripId) async {
|
||||
try {
|
||||
final doc = await _tripsCollection.doc(tripId).get();
|
||||
|
||||
|
||||
if (!doc.exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return Trip.fromMap(doc.data() as Map<String, dynamic>, doc.id);
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la récupération du voyage: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur get trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer le voyage');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,10 +86,15 @@ class TripRepository {
|
||||
final tripData = trip.toMap();
|
||||
// Mettre à jour le timestamp de modification
|
||||
tripData['updatedAt'] = Timestamp.now();
|
||||
|
||||
|
||||
await _tripsCollection.doc(tripId).update(tripData);
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la mise à jour du voyage: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur update trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de mettre à jour le voyage');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,8 +102,13 @@ class TripRepository {
|
||||
Future<void> deleteTrip(String tripId) async {
|
||||
try {
|
||||
await _tripsCollection.doc(tripId).delete();
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la suppression du voyage: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'TripRepository',
|
||||
'Erreur delete trip: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer le voyage');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,35 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import '../models/user.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../services/error_service.dart';
|
||||
|
||||
/// Repository for user data operations in Firestore.
|
||||
///
|
||||
///
|
||||
/// This repository provides methods for CRUD operations on user data,
|
||||
/// including retrieving users by ID or email, updating user information,
|
||||
/// and managing user profiles in the Firestore database.
|
||||
class UserRepository {
|
||||
/// Firestore instance for database operations.
|
||||
final FirebaseFirestore _firestore;
|
||||
|
||||
|
||||
/// Authentication service for user-related operations.
|
||||
final AuthService _authService;
|
||||
|
||||
final _errorService = ErrorService();
|
||||
|
||||
/// Creates a new [UserRepository] with optional dependencies.
|
||||
///
|
||||
///
|
||||
/// If [firestore] or [authService] are not provided, default instances will be used.
|
||||
UserRepository({
|
||||
FirebaseFirestore? firestore,
|
||||
AuthService? authService,
|
||||
}) : _firestore = firestore ?? FirebaseFirestore.instance,
|
||||
_authService = authService ?? AuthService();
|
||||
UserRepository({FirebaseFirestore? firestore, AuthService? authService})
|
||||
: _firestore = firestore ?? FirebaseFirestore.instance,
|
||||
_authService = authService ?? AuthService();
|
||||
|
||||
/// Retrieves a user by their unique ID.
|
||||
///
|
||||
///
|
||||
/// Fetches the user document from Firestore and converts it to a [User] model.
|
||||
///
|
||||
///
|
||||
/// [uid] - The unique user identifier
|
||||
///
|
||||
///
|
||||
/// Returns the [User] model if found, null otherwise.
|
||||
/// Throws an exception if the operation fails.
|
||||
Future<User?> getUserById(String uid) async {
|
||||
@@ -39,18 +40,23 @@ class UserRepository {
|
||||
return User.fromMap({...data, 'id': uid});
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
throw Exception('Error retrieving user: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Error retrieving user: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de récupérer l\'utilisateur');
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves a user by their email address.
|
||||
///
|
||||
///
|
||||
/// Searches the users collection for a matching email address.
|
||||
/// Email comparison is case-insensitive after trimming whitespace.
|
||||
///
|
||||
///
|
||||
/// [email] - The email address to search for
|
||||
///
|
||||
///
|
||||
/// Returns the first [User] found with the matching email, null if not found.
|
||||
/// Throws an exception if the operation fails.
|
||||
Future<User?> getUserByEmail(String email) async {
|
||||
@@ -67,28 +73,38 @@ class UserRepository {
|
||||
return User.fromMap({...data, 'id': doc.id});
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
throw Exception('Error searching for user: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Error searching for user: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de trouver l\'utilisateur');
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates an existing user in Firestore.
|
||||
///
|
||||
///
|
||||
/// Updates the user document with the provided user data.
|
||||
///
|
||||
///
|
||||
/// [user] - The user object containing updated information
|
||||
///
|
||||
///
|
||||
/// Returns true if the update was successful, false otherwise.
|
||||
Future<bool> updateUser(User user) async {
|
||||
try {
|
||||
await _firestore.collection('users').doc(user.id).update(user.toMap());
|
||||
|
||||
|
||||
// Mettre à jour le displayName dans Firebase Auth
|
||||
await _authService.updateDisplayName(displayName: user.fullName);
|
||||
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la mise à jour: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Erreur lors de la mise à jour: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de mettre à jour l\'utilisateur');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,8 +114,13 @@ class UserRepository {
|
||||
await _firestore.collection('users').doc(uid).delete();
|
||||
// Note: Vous devrez également supprimer le compte Firebase Auth
|
||||
return true;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la suppression: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Erreur lors de la suppression: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de supprimer l\'utilisateur');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,15 +134,59 @@ class UserRepository {
|
||||
if (currentUser?.email == null) {
|
||||
throw Exception('Utilisateur non connecté ou email non disponible');
|
||||
}
|
||||
|
||||
|
||||
await _authService.resetPasswordFromCurrentPassword(
|
||||
email: currentUser!.email!,
|
||||
currentPassword: currentPassword,
|
||||
newPassword: newPassword,
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors du changement de mot de passe: $e');
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Erreur lors du changement de mot de passe: $e',
|
||||
stackTrace,
|
||||
);
|
||||
throw Exception('Impossible de changer le mot de passe');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Récupérer plusieurs utilisateurs par leurs IDs
|
||||
Future<List<User>> getUsersByIds(List<String> uids) async {
|
||||
if (uids.isEmpty) return [];
|
||||
|
||||
try {
|
||||
// Firestore 'in' query supports up to 10 values.
|
||||
// If we have more, we need to split into chunks.
|
||||
List<User> users = [];
|
||||
|
||||
// Remove duplicates
|
||||
final uniqueIds = uids.toSet().toList();
|
||||
|
||||
// Split into chunks of 10
|
||||
for (var i = 0; i < uniqueIds.length; i += 10) {
|
||||
final end = (i + 10 < uniqueIds.length) ? i + 10 : uniqueIds.length;
|
||||
final chunk = uniqueIds.sublist(i, end);
|
||||
|
||||
final querySnapshot = await _firestore
|
||||
.collection('users')
|
||||
.where(FieldPath.documentId, whereIn: chunk)
|
||||
.get();
|
||||
|
||||
for (var doc in querySnapshot.docs) {
|
||||
final data = doc.data();
|
||||
users.add(User.fromMap({...data, 'id': doc.id}));
|
||||
}
|
||||
}
|
||||
|
||||
return users;
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'UserRepository',
|
||||
'Error retrieving users by IDs: $e',
|
||||
stackTrace,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import '../firebase_options.dart'; // Add this import
|
||||
import '../models/activity.dart';
|
||||
import '../services/error_service.dart';
|
||||
import '../services/logger_service.dart';
|
||||
|
||||
/// Service pour rechercher des activités touristiques via Google Places API
|
||||
class ActivityPlacesService {
|
||||
@@ -12,7 +14,17 @@ class ActivityPlacesService {
|
||||
ActivityPlacesService._internal();
|
||||
|
||||
final ErrorService _errorService = ErrorService();
|
||||
static final String _apiKey = dotenv.env['GOOGLE_MAPS_API_KEY'] ?? '';
|
||||
|
||||
static String get _apiKey {
|
||||
try {
|
||||
return DefaultFirebaseOptions.currentPlatform.apiKey;
|
||||
} catch (e) {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Impossible de récupérer la clé API Firebase: $e',
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/// Recherche des activités près d'une destination
|
||||
Future<List<Activity>> searchActivities({
|
||||
@@ -23,81 +35,75 @@ class ActivityPlacesService {
|
||||
int maxResults = 20,
|
||||
int offset = 0,
|
||||
}) async {
|
||||
try {
|
||||
print(
|
||||
'ActivityPlacesService: Recherche d\'activités pour: $destination (max: $maxResults, offset: $offset)',
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Recherche d\'activités pour: $destination (max: $maxResults, offset: $offset)',
|
||||
);
|
||||
|
||||
// 1. Géocoder la destination
|
||||
final coordinates = await _geocodeDestination(destination);
|
||||
|
||||
// 2. Rechercher les activités par catégorie ou toutes les catégories
|
||||
List<Activity> allActivities = [];
|
||||
|
||||
if (category != null) {
|
||||
final activities = await _searchByCategory(
|
||||
coordinates['lat']!,
|
||||
coordinates['lng']!,
|
||||
category,
|
||||
tripId,
|
||||
radius,
|
||||
);
|
||||
allActivities.addAll(activities);
|
||||
} else {
|
||||
// Rechercher dans toutes les catégories principales
|
||||
final mainCategories = [
|
||||
ActivityCategory.attraction,
|
||||
ActivityCategory.museum,
|
||||
ActivityCategory.restaurant,
|
||||
ActivityCategory.culture,
|
||||
ActivityCategory.nature,
|
||||
];
|
||||
|
||||
// 1. Géocoder la destination
|
||||
final coordinates = await _geocodeDestination(destination);
|
||||
|
||||
// 2. Rechercher les activités par catégorie ou toutes les catégories
|
||||
List<Activity> allActivities = [];
|
||||
|
||||
if (category != null) {
|
||||
for (final cat in mainCategories) {
|
||||
final activities = await _searchByCategory(
|
||||
coordinates['lat']!,
|
||||
coordinates['lng']!,
|
||||
category,
|
||||
cat,
|
||||
tripId,
|
||||
radius,
|
||||
);
|
||||
allActivities.addAll(activities);
|
||||
} else {
|
||||
// Rechercher dans toutes les catégories principales
|
||||
final mainCategories = [
|
||||
ActivityCategory.attraction,
|
||||
ActivityCategory.museum,
|
||||
ActivityCategory.restaurant,
|
||||
ActivityCategory.culture,
|
||||
ActivityCategory.nature,
|
||||
];
|
||||
|
||||
for (final cat in mainCategories) {
|
||||
final activities = await _searchByCategory(
|
||||
coordinates['lat']!,
|
||||
coordinates['lng']!,
|
||||
cat,
|
||||
tripId,
|
||||
radius,
|
||||
);
|
||||
allActivities.addAll(activities);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Supprimer les doublons et trier par note
|
||||
final uniqueActivities = _removeDuplicates(allActivities);
|
||||
uniqueActivities.sort((a, b) => (b.rating ?? 0).compareTo(a.rating ?? 0));
|
||||
// 3. Supprimer les doublons et trier par note
|
||||
final uniqueActivities = _removeDuplicates(allActivities);
|
||||
uniqueActivities.sort((a, b) => (b.rating ?? 0).compareTo(a.rating ?? 0));
|
||||
|
||||
print(
|
||||
'ActivityPlacesService: ${uniqueActivities.length} activités trouvées au total',
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: ${uniqueActivities.length} activités trouvées au total',
|
||||
);
|
||||
|
||||
// 4. Appliquer la pagination
|
||||
final startIndex = offset;
|
||||
final endIndex = (startIndex + maxResults).clamp(
|
||||
0,
|
||||
uniqueActivities.length,
|
||||
);
|
||||
|
||||
if (startIndex >= uniqueActivities.length) {
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Offset $startIndex dépasse le nombre total (${uniqueActivities.length})',
|
||||
);
|
||||
|
||||
// 4. Appliquer la pagination
|
||||
final startIndex = offset;
|
||||
final endIndex = (startIndex + maxResults).clamp(
|
||||
0,
|
||||
uniqueActivities.length,
|
||||
);
|
||||
|
||||
if (startIndex >= uniqueActivities.length) {
|
||||
print(
|
||||
'ActivityPlacesService: Offset $startIndex dépasse le nombre total (${uniqueActivities.length})',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
final paginatedResults = uniqueActivities.sublist(startIndex, endIndex);
|
||||
print(
|
||||
'ActivityPlacesService: Retour de ${paginatedResults.length} activités (offset: $offset, max: $maxResults)',
|
||||
);
|
||||
|
||||
return paginatedResults;
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur lors de la recherche: $e');
|
||||
_errorService.logError('activity_places_service', e);
|
||||
return [];
|
||||
}
|
||||
|
||||
final paginatedResults = uniqueActivities.sublist(startIndex, endIndex);
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Retour de ${paginatedResults.length} activités (offset: $offset, max: $maxResults)',
|
||||
);
|
||||
|
||||
return paginatedResults;
|
||||
}
|
||||
|
||||
/// Géocode une destination pour obtenir les coordonnées
|
||||
@@ -105,24 +111,36 @@ class ActivityPlacesService {
|
||||
try {
|
||||
// Vérifier que la clé API est configurée
|
||||
if (_apiKey.isEmpty) {
|
||||
print('ActivityPlacesService: Clé API Google Maps manquante');
|
||||
throw Exception('Clé API Google Maps non configurée');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Clé API Google Maps manquante',
|
||||
);
|
||||
throw Exception(
|
||||
'Clé API Google Maps non configurée dans DefaultFirebaseOptions. Platform: ${Platform.isAndroid
|
||||
? 'Android'
|
||||
: Platform.isIOS
|
||||
? 'iOS'
|
||||
: 'Autre'}',
|
||||
);
|
||||
}
|
||||
|
||||
final encodedDestination = Uri.encodeComponent(destination);
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/geocode/json?address=$encodedDestination&key=$_apiKey';
|
||||
'https://maps.googleapis.com/maps/api/geocode/json?address=$encodedDestination&key=$_apiKey&language=fr';
|
||||
|
||||
print('ActivityPlacesService: Géocodage de "$destination"');
|
||||
print('ActivityPlacesService: URL = $url');
|
||||
LoggerService.info('ActivityPlacesService: Géocodage de "$destination"');
|
||||
LoggerService.info('ActivityPlacesService: URL = $url');
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
print('ActivityPlacesService: Status code = ${response.statusCode}');
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Status code = ${response.statusCode}',
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
print('ActivityPlacesService: Réponse géocodage = ${data['status']}');
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Réponse géocodage = ${data['status']}',
|
||||
);
|
||||
|
||||
if (data['status'] == 'OK' && data['results'].isNotEmpty) {
|
||||
final location = data['results'][0]['geometry']['location'];
|
||||
@@ -130,10 +148,12 @@ class ActivityPlacesService {
|
||||
'lat': location['lat'].toDouble(),
|
||||
'lng': location['lng'].toDouble(),
|
||||
};
|
||||
print('ActivityPlacesService: Coordonnées trouvées = $coordinates');
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Coordonnées trouvées = $coordinates',
|
||||
);
|
||||
return coordinates;
|
||||
} else {
|
||||
print(
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur API = ${data['error_message'] ?? data['status']}',
|
||||
);
|
||||
if (data['status'] == 'REQUEST_DENIED') {
|
||||
@@ -154,7 +174,7 @@ class ActivityPlacesService {
|
||||
throw Exception('Erreur HTTP ${response.statusCode}');
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur géocodage: $e');
|
||||
LoggerService.error('ActivityPlacesService: Erreur géocodage: $e');
|
||||
rethrow; // Rethrow pour permettre la gestion d'erreur en amont
|
||||
}
|
||||
}
|
||||
@@ -167,45 +187,52 @@ class ActivityPlacesService {
|
||||
String tripId,
|
||||
int radius,
|
||||
) async {
|
||||
try {
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=${category.googlePlaceType}'
|
||||
'&key=$_apiKey';
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=${category.googlePlaceType}'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
|
||||
for (final place in data['results']) {
|
||||
try {
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
for (final place in data['results']) {
|
||||
try {
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
|
||||
return activities;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche par catégorie: $e');
|
||||
return [];
|
||||
return activities;
|
||||
} else if (data['status'] == 'ZERO_RESULTS') {
|
||||
return [];
|
||||
} else {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur API Places: ${data['status']} - ${data['error_message']}',
|
||||
);
|
||||
throw Exception(
|
||||
'API Places Error: ${data['status']} - ${data['error_message']}',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
throw Exception('Erreur HTTP ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +287,7 @@ class ActivityPlacesService {
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error('ActivityPlacesService: Erreur conversion place: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -272,7 +299,8 @@ class ActivityPlacesService {
|
||||
'https://maps.googleapis.com/maps/api/place/details/json'
|
||||
'?place_id=$placeId'
|
||||
'&fields=formatted_address,formatted_phone_number,website,opening_hours,editorial_summary'
|
||||
'&key=$_apiKey';
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
@@ -285,7 +313,9 @@ class ActivityPlacesService {
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur récupération détails: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur récupération détails: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -325,57 +355,62 @@ class ActivityPlacesService {
|
||||
required String tripId,
|
||||
int radius = 5000,
|
||||
}) async {
|
||||
try {
|
||||
print(
|
||||
'ActivityPlacesService: Recherche textuelle: $query à $destination',
|
||||
);
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Recherche textuelle: $query à $destination',
|
||||
);
|
||||
|
||||
// Géocoder la destination
|
||||
final coordinates = await _geocodeDestination(destination);
|
||||
// Géocoder la destination
|
||||
final coordinates = await _geocodeDestination(destination);
|
||||
|
||||
final encodedQuery = Uri.encodeComponent(query);
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/place/textsearch/json'
|
||||
'?query=$encodedQuery in $destination'
|
||||
'&location=${coordinates['lat']},${coordinates['lng']}'
|
||||
'&radius=$radius'
|
||||
'&key=$_apiKey';
|
||||
final encodedQuery = Uri.encodeComponent(query);
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/place/textsearch/json'
|
||||
'?query=$encodedQuery'
|
||||
'&location=${coordinates['lat']},${coordinates['lng']}'
|
||||
'&radius=$radius'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
|
||||
for (final place in data['results']) {
|
||||
try {
|
||||
// Déterminer la catégorie basée sur les types du lieu
|
||||
final types = List<String>.from(place['types'] ?? []);
|
||||
final category = _determineCategoryFromTypes(types);
|
||||
for (final place in data['results']) {
|
||||
try {
|
||||
// Déterminer la catégorie basée sur les types du lieu
|
||||
final types = List<String>.from(place['types'] ?? []);
|
||||
final category = _determineCategoryFromTypes(types);
|
||||
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
|
||||
return activities;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche textuelle: $e');
|
||||
return [];
|
||||
return activities;
|
||||
} else if (data['status'] == 'ZERO_RESULTS') {
|
||||
return [];
|
||||
} else {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur API Places Text Search: ${data['status']}',
|
||||
);
|
||||
throw Exception('API Error: ${data['status']}');
|
||||
}
|
||||
} else {
|
||||
throw Exception('Erreur HTTP ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,11 +458,11 @@ class ActivityPlacesService {
|
||||
if (latitude != null && longitude != null) {
|
||||
lat = latitude;
|
||||
lng = longitude;
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Utilisation des coordonnées pré-géolocalisées: $lat, $lng',
|
||||
);
|
||||
} else if (destination != null) {
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Géolocalisation de la destination: $destination',
|
||||
);
|
||||
final coordinates = await _geocodeDestination(destination);
|
||||
@@ -437,7 +472,7 @@ class ActivityPlacesService {
|
||||
throw Exception('Destination ou coordonnées requises');
|
||||
}
|
||||
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Recherche paginée aux coordonnées: $lat, $lng (page: ${nextPageToken ?? "première"})',
|
||||
);
|
||||
|
||||
@@ -464,7 +499,9 @@ class ActivityPlacesService {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche paginée: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur recherche paginée: $e',
|
||||
);
|
||||
_errorService.logError('activity_places_service', e);
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
@@ -484,65 +521,63 @@ class ActivityPlacesService {
|
||||
int pageSize,
|
||||
String? nextPageToken,
|
||||
) async {
|
||||
try {
|
||||
String url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=${category.googlePlaceType}'
|
||||
'&key=$_apiKey';
|
||||
String url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=${category.googlePlaceType}'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
if (nextPageToken != null) {
|
||||
url += '&pagetoken=$nextPageToken';
|
||||
}
|
||||
if (nextPageToken != null) {
|
||||
url += '&pagetoken=$nextPageToken';
|
||||
}
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
final results = data['results'] as List? ?? [];
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
final results = data['results'] as List? ?? [];
|
||||
|
||||
// Limiter à pageSize résultats
|
||||
final limitedResults = results.take(pageSize).toList();
|
||||
// Limiter à pageSize résultats
|
||||
final limitedResults = results.take(pageSize).toList();
|
||||
|
||||
for (final place in limitedResults) {
|
||||
try {
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
for (final place in limitedResults) {
|
||||
try {
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
'activities': activities,
|
||||
'nextPageToken': data['next_page_token'],
|
||||
'hasMoreData': data['next_page_token'] != null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche catégorie paginée: $e');
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
return {
|
||||
'activities': activities,
|
||||
'nextPageToken': data['next_page_token'],
|
||||
'hasMoreData': data['next_page_token'] != null,
|
||||
};
|
||||
} else if (data['status'] == 'ZERO_RESULTS') {
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} else {
|
||||
throw Exception('API Error: ${data['status']}');
|
||||
}
|
||||
} else {
|
||||
throw Exception('Erreur HTTP ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,72 +590,136 @@ class ActivityPlacesService {
|
||||
int pageSize,
|
||||
String? nextPageToken,
|
||||
) async {
|
||||
try {
|
||||
// Pour toutes les catégories, on utilise une recherche plus générale
|
||||
String url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=tourist_attraction'
|
||||
'&key=$_apiKey';
|
||||
// Pour toutes les catégories, on utilise une recherche plus générale
|
||||
String url =
|
||||
'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
|
||||
'?location=$lat,$lng'
|
||||
'&radius=$radius'
|
||||
'&type=tourist_attraction'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
if (nextPageToken != null) {
|
||||
url += '&pagetoken=$nextPageToken';
|
||||
if (nextPageToken != null) {
|
||||
url += '&pagetoken=$nextPageToken';
|
||||
}
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
final results = data['results'] as List? ?? [];
|
||||
|
||||
// Limiter à pageSize résultats
|
||||
final limitedResults = results.take(pageSize).toList();
|
||||
|
||||
for (final place in limitedResults) {
|
||||
try {
|
||||
// Déterminer la catégorie basée sur les types du lieu
|
||||
final types = List<String>.from(place['types'] ?? []);
|
||||
final category = _determineCategoryFromTypes(types);
|
||||
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
'activities': activities,
|
||||
'nextPageToken': data['next_page_token'],
|
||||
'hasMoreData': data['next_page_token'] != null,
|
||||
};
|
||||
} else if (data['status'] == 'ZERO_RESULTS') {
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} else {
|
||||
throw Exception('API Error: ${data['status']}');
|
||||
}
|
||||
} else {
|
||||
throw Exception('Erreur HTTP ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupère des suggestions d'autocomplétion
|
||||
Future<List<Map<String, String>>> fetchSuggestions({
|
||||
required String query,
|
||||
double? lat,
|
||||
double? lng,
|
||||
}) async {
|
||||
if (query.isEmpty) return [];
|
||||
|
||||
try {
|
||||
String url =
|
||||
'https://maps.googleapis.com/maps/api/place/autocomplete/json'
|
||||
'?input=${Uri.encodeComponent(query)}'
|
||||
'&key=$_apiKey'
|
||||
'&language=fr';
|
||||
|
||||
if (lat != null && lng != null) {
|
||||
url += '&location=$lat,$lng&radius=50000'; // 50km bias
|
||||
}
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
if (data['status'] == 'OK') {
|
||||
final List<Activity> activities = [];
|
||||
final results = data['results'] as List? ?? [];
|
||||
|
||||
// Limiter à pageSize résultats
|
||||
final limitedResults = results.take(pageSize).toList();
|
||||
|
||||
for (final place in limitedResults) {
|
||||
try {
|
||||
// Déterminer la catégorie basée sur les types du lieu
|
||||
final types = List<String>.from(place['types'] ?? []);
|
||||
final category = _determineCategoryFromTypes(types);
|
||||
|
||||
final activity = await _convertPlaceToActivity(
|
||||
place,
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
if (activity != null) {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
'activities': activities,
|
||||
'nextPageToken': data['next_page_token'],
|
||||
'hasMoreData': data['next_page_token'] != null,
|
||||
};
|
||||
return (data['predictions'] as List).map<Map<String, String>>((p) {
|
||||
return {
|
||||
'description': p['description'] as String,
|
||||
'placeId': p['place_id'] as String,
|
||||
};
|
||||
}).toList();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
return [];
|
||||
} catch (e) {
|
||||
print(
|
||||
'ActivityPlacesService: Erreur recherche toutes catégories paginée: $e',
|
||||
LoggerService.error('ActivityPlacesService: Erreur autocomplete: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupère une activité via son Place ID
|
||||
Future<Activity?> getActivityByPlaceId({
|
||||
required String placeId,
|
||||
required String tripId,
|
||||
}) async {
|
||||
try {
|
||||
final details = await _getPlaceDetails(placeId);
|
||||
if (details == null) return null;
|
||||
|
||||
// Créer une map simulant la structure "place" attendue par _convertPlaceToActivity
|
||||
// Note: _getPlaceDetails retourne "result", qui est déjà ce qu'on veut,
|
||||
// mais _convertPlaceToActivity attend le format "search result" qui a geometry au premier niveau.
|
||||
// Heureusement _getPlaceDetails retourne une structure compatible pour geometry/photos etc.
|
||||
|
||||
// On doit s'assurer d'avoir les types pour déterminer la catégorie
|
||||
final types = List<String>.from(details['types'] ?? []);
|
||||
final category = _determineCategoryFromTypes(types);
|
||||
|
||||
return await _convertPlaceToActivity(
|
||||
details, // details a la structure nécessaire (geometry, name, etc)
|
||||
tripId,
|
||||
category,
|
||||
);
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} catch (e) {
|
||||
LoggerService.error('ActivityPlacesService: Erreur get details: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
54
lib/services/analytics_service.dart
Normal file
54
lib/services/analytics_service.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'package:firebase_analytics/firebase_analytics.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Service wrapper for Google Analytics
|
||||
class AnalyticsService {
|
||||
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
|
||||
|
||||
FirebaseAnalyticsObserver getAnalyticsObserver() =>
|
||||
FirebaseAnalyticsObserver(analytics: _analytics);
|
||||
|
||||
Future<void> logEvent({
|
||||
required String name,
|
||||
Map<String, Object>? parameters,
|
||||
}) async {
|
||||
try {
|
||||
await _analytics.logEvent(name: name, parameters: parameters);
|
||||
} catch (e) {
|
||||
debugPrint('Error logging analytics event: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUserProperty({
|
||||
required String name,
|
||||
required String? value,
|
||||
}) async {
|
||||
try {
|
||||
await _analytics.setUserProperty(name: name, value: value);
|
||||
} catch (e) {
|
||||
debugPrint('Error setting user property: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setUserId(String? id) async {
|
||||
try {
|
||||
await _analytics.setUserId(id: id);
|
||||
} catch (e) {
|
||||
debugPrint('Error setting user ID: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logScreenView({
|
||||
required String screenName,
|
||||
String? screenClass,
|
||||
}) async {
|
||||
try {
|
||||
await _analytics.logScreenView(
|
||||
screenName: screenName,
|
||||
screenClass: screenClass,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Error logging screen view: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,20 +83,30 @@ class AuthService {
|
||||
///
|
||||
/// [password] - The user's current password for re-authentication
|
||||
/// [email] - The user's email address for re-authentication
|
||||
Future<void> deleteAccount({
|
||||
required String password,
|
||||
required String email,
|
||||
}) async {
|
||||
// Re-authenticate the user for security
|
||||
AuthCredential credential = EmailAuthProvider.credential(
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
await currentUser!.reauthenticateWithCredential(credential);
|
||||
|
||||
// Delete the user account permanently
|
||||
await currentUser!.delete();
|
||||
await firebaseAuth.signOut();
|
||||
Future<void> deleteAccount() async {
|
||||
try {
|
||||
await currentUser!.delete();
|
||||
await firebaseAuth.signOut();
|
||||
} on FirebaseAuthException catch (e) {
|
||||
if (e.code == 'requires-recent-login') {
|
||||
_errorService.logError(
|
||||
'Delete account requires recent login',
|
||||
StackTrace.current,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
_errorService.logError(
|
||||
'Error deleting account: ${e.code} - ${e.message}',
|
||||
StackTrace.current,
|
||||
);
|
||||
rethrow;
|
||||
} catch (e) {
|
||||
_errorService.logError(
|
||||
'Unknown error deleting account: $e',
|
||||
StackTrace.current,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the user's password after re-authentication.
|
||||
@@ -161,18 +171,35 @@ class AuthService {
|
||||
}
|
||||
} on GoogleSignInException catch (e) {
|
||||
_errorService.logError('Google Sign-In error: $e', StackTrace.current);
|
||||
_errorService.showError(
|
||||
message: 'La connexion avec Google a échoué. Veuillez réessayer.',
|
||||
);
|
||||
rethrow;
|
||||
} on FirebaseAuthException catch (e) {
|
||||
_errorService.logError(
|
||||
'Firebase error during Google Sign-In initialization: $e',
|
||||
StackTrace.current,
|
||||
);
|
||||
if (e.code == 'account-exists-with-different-credential') {
|
||||
_errorService.showError(
|
||||
message:
|
||||
'Un compte existe déjà avec cette adresse email. Veuillez vous connecter avec la méthode utilisée précédemment.',
|
||||
);
|
||||
} else {
|
||||
_errorService.showError(
|
||||
message:
|
||||
'Une erreur est survenue lors de la connexion avec Google. Veuillez réessayer plus tard.',
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
} catch (e) {
|
||||
_errorService.logError(
|
||||
'Unknown error during Google Sign-In initialization: $e',
|
||||
StackTrace.current,
|
||||
);
|
||||
_errorService.showError(
|
||||
message: 'Une erreur inattendue est survenue. Veuillez réessayer.',
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@@ -198,20 +225,20 @@ class AuthService {
|
||||
}
|
||||
|
||||
// Request Apple ID credential with platform-specific configuration
|
||||
final AuthorizationCredentialAppleID credential =
|
||||
await SignInWithApple.getAppleIDCredential(
|
||||
scopes: [
|
||||
AppleIDAuthorizationScopes.email,
|
||||
AppleIDAuthorizationScopes.fullName,
|
||||
],
|
||||
// Configuration for Android/Web
|
||||
webAuthenticationOptions: WebAuthenticationOptions(
|
||||
clientId: 'be.devdayronvl.TravelMate',
|
||||
redirectUri: Uri.parse(
|
||||
'https://your-project-id.firebaseapp.com/__/auth/handler',
|
||||
),
|
||||
),
|
||||
);
|
||||
final AuthorizationCredentialAppleID
|
||||
credential = await SignInWithApple.getAppleIDCredential(
|
||||
scopes: [
|
||||
AppleIDAuthorizationScopes.email,
|
||||
AppleIDAuthorizationScopes.fullName,
|
||||
],
|
||||
// Configuration for Android/Web
|
||||
webAuthenticationOptions: WebAuthenticationOptions(
|
||||
clientId: 'be.devdayronvl.TravelMate.service',
|
||||
redirectUri: Uri.parse(
|
||||
'https://us-central1-travelmate-a47f5.cloudfunctions.net/callbacks_signInWithApple',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Create OAuth credential for Firebase
|
||||
final OAuthCredential oauthCredential = OAuthProvider("apple.com")
|
||||
@@ -237,24 +264,49 @@ class AuthService {
|
||||
return userCredential;
|
||||
} on SignInWithAppleException catch (e) {
|
||||
_errorService.logError('Apple Sign-In error: $e', StackTrace.current);
|
||||
_errorService.showError(
|
||||
message: 'La connexion avec Apple a échoué. Veuillez réessayer.',
|
||||
);
|
||||
throw FirebaseAuthException(
|
||||
code: 'ERROR_APPLE_SIGNIN_FAILED',
|
||||
message: 'Apple Sign-In failed: ${e.toString()}',
|
||||
message: 'Apple Sign-In failed',
|
||||
);
|
||||
} on FirebaseAuthException catch (e) {
|
||||
_errorService.logError(
|
||||
'Firebase error during Apple Sign-In: $e',
|
||||
StackTrace.current,
|
||||
);
|
||||
if (e.code == 'account-exists-with-different-credential') {
|
||||
_errorService.showError(
|
||||
message:
|
||||
'Un compte existe déjà avec cette adresse email. Veuillez vous connecter avec la méthode utilisée précédemment.',
|
||||
);
|
||||
} else if (e.code == 'invalid-credential') {
|
||||
_errorService.showError(
|
||||
message: 'Les informations de connexion sont invalides.',
|
||||
);
|
||||
} else if (e.code == 'user-disabled') {
|
||||
_errorService.showError(
|
||||
message: 'Ce compte utilisateur a été désactivé.',
|
||||
);
|
||||
} else {
|
||||
_errorService.showError(
|
||||
message:
|
||||
'Une erreur est survenue lors de la connexion avec Apple. Veuillez réessayer plus tard.',
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
} catch (e) {
|
||||
_errorService.logError(
|
||||
'Unknown error during Apple Sign-In: $e',
|
||||
StackTrace.current,
|
||||
);
|
||||
_errorService.showError(
|
||||
message: 'Une erreur inattendue est survenue. Veuillez réessayer.',
|
||||
);
|
||||
throw FirebaseAuthException(
|
||||
code: 'ERROR_APPLE_SIGNIN_UNKNOWN',
|
||||
message: 'Unknown error during Apple Sign-In: $e',
|
||||
message: 'Unknown error during Apple Sign-In',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
/// - [Settlement] for individual payment recommendations
|
||||
/// - [UserBalance] for per-user balance information
|
||||
library;
|
||||
|
||||
import '../models/group_balance.dart';
|
||||
import '../models/expense.dart';
|
||||
import '../models/group_statistics.dart';
|
||||
@@ -59,7 +60,10 @@ class BalanceService {
|
||||
try {
|
||||
return await _balanceRepository.calculateGroupBalance(groupId);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceService', 'Erreur calcul balance groupe: $e');
|
||||
_errorService.logError(
|
||||
'BalanceService',
|
||||
'Erreur calcul balance groupe: $e',
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@@ -80,7 +84,9 @@ class BalanceService {
|
||||
|
||||
/// Stream de la balance en temps réel
|
||||
Stream<GroupBalance> getGroupBalanceStream(String groupId) {
|
||||
return _expenseRepository.getExpensesStream(groupId).asyncMap((expenses) async {
|
||||
return _expenseRepository.getExpensesStream(groupId).asyncMap((
|
||||
expenses,
|
||||
) async {
|
||||
try {
|
||||
final userBalances = calculateUserBalances(expenses);
|
||||
final settlements = optimizeSettlements(userBalances);
|
||||
@@ -145,7 +151,7 @@ class BalanceService {
|
||||
/// Optimiser les règlements (algorithme avancé)
|
||||
List<Settlement> optimizeSettlements(List<UserBalance> balances) {
|
||||
final settlements = <Settlement>[];
|
||||
|
||||
|
||||
// Filtrer les utilisateurs avec une balance significative (> 0.01€)
|
||||
final creditors = balances
|
||||
.where((b) => b.shouldReceive && b.balance > 0.01)
|
||||
@@ -164,10 +170,10 @@ class BalanceService {
|
||||
|
||||
// Utiliser des copies mutables pour les calculs
|
||||
final creditorsRemaining = Map<String, double>.fromEntries(
|
||||
creditors.map((c) => MapEntry(c.userId, c.balance))
|
||||
creditors.map((c) => MapEntry(c.userId, c.balance)),
|
||||
);
|
||||
final debtorsRemaining = Map<String, double>.fromEntries(
|
||||
debtors.map((d) => MapEntry(d.userId, -d.balance))
|
||||
debtors.map((d) => MapEntry(d.userId, -d.balance)),
|
||||
);
|
||||
|
||||
// Algorithme glouton optimisé
|
||||
@@ -185,16 +191,19 @@ class BalanceService {
|
||||
);
|
||||
|
||||
if (settlementAmount > 0.01) {
|
||||
settlements.add(Settlement(
|
||||
fromUserId: debtor.userId,
|
||||
fromUserName: debtor.userName,
|
||||
toUserId: creditor.userId,
|
||||
toUserName: creditor.userName,
|
||||
amount: settlementAmount,
|
||||
));
|
||||
settlements.add(
|
||||
Settlement(
|
||||
fromUserId: debtor.userId,
|
||||
fromUserName: debtor.userName,
|
||||
toUserId: creditor.userId,
|
||||
toUserName: creditor.userName,
|
||||
amount: settlementAmount,
|
||||
),
|
||||
);
|
||||
|
||||
// Mettre à jour les montants restants
|
||||
creditorsRemaining[creditor.userId] = creditRemaining - settlementAmount;
|
||||
creditorsRemaining[creditor.userId] =
|
||||
creditRemaining - settlementAmount;
|
||||
debtorsRemaining[debtor.userId] = debtRemaining - settlementAmount;
|
||||
}
|
||||
}
|
||||
@@ -204,7 +213,10 @@ class BalanceService {
|
||||
}
|
||||
|
||||
/// Calculer le montant optimal pour un règlement
|
||||
double _calculateOptimalSettlementAmount(double creditAmount, double debtAmount) {
|
||||
double _calculateOptimalSettlementAmount(
|
||||
double creditAmount,
|
||||
double debtAmount,
|
||||
) {
|
||||
final amount = [creditAmount, debtAmount].reduce((a, b) => a < b ? a : b);
|
||||
// Arrondir à 2 décimales
|
||||
return (amount * 100).round() / 100;
|
||||
@@ -213,36 +225,50 @@ class BalanceService {
|
||||
/// Valider les règlements calculés
|
||||
List<Settlement> _validateSettlements(List<Settlement> settlements) {
|
||||
// Supprimer les règlements trop petits
|
||||
final validSettlements = settlements
|
||||
.where((s) => s.amount > 0.01)
|
||||
.toList();
|
||||
final validSettlements = settlements.where((s) => s.amount > 0.01).toList();
|
||||
|
||||
// Log pour debug en cas de problème
|
||||
final totalSettlements = validSettlements.fold(0.0, (sum, s) => sum + s.amount);
|
||||
_errorService.logInfo('BalanceService',
|
||||
'Règlements calculés: ${validSettlements.length}, Total: ${totalSettlements.toStringAsFixed(2)}€');
|
||||
final totalSettlements = validSettlements.fold(
|
||||
0.0,
|
||||
(sum, s) => sum + s.amount,
|
||||
);
|
||||
_errorService.logInfo(
|
||||
'BalanceService',
|
||||
'Règlements calculés: ${validSettlements.length}, Total: ${totalSettlements.toStringAsFixed(2)}€',
|
||||
);
|
||||
|
||||
return validSettlements;
|
||||
}
|
||||
|
||||
/// Calculer la dette entre deux utilisateurs spécifiques
|
||||
double calculateDebtBetweenUsers(String groupId, String userId1, String userId2) {
|
||||
double calculateDebtBetweenUsers(
|
||||
String groupId,
|
||||
String userId1,
|
||||
String userId2,
|
||||
) {
|
||||
// Cette méthode pourrait être utile pour des fonctionnalités avancées
|
||||
// comme "Combien me doit X ?" ou "Combien je dois à Y ?"
|
||||
return 0.0; // TODO: Implémenter si nécessaire
|
||||
|
||||
// On peut utiliser optimizeSettlements pour avoir la réponse précise
|
||||
// Cependant, cela nécessite d'avoir les dépenses.
|
||||
// Comme cette méthode est synchrone et ne prend pas les dépenses en entrée,
|
||||
// elle est difficile à implémenter correctement sans changer sa signature.
|
||||
// Pour l'instant, on retourne 0.0 car elle n'est pas utilisée.
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/// Analyser les tendances de dépenses par catégorie
|
||||
Map<String, double> analyzeCategorySpending(List<Expense> expenses) {
|
||||
final categoryTotals = <String, double>{};
|
||||
|
||||
|
||||
for (final expense in expenses) {
|
||||
if (expense.isArchived) continue;
|
||||
|
||||
|
||||
final categoryName = expense.category.displayName;
|
||||
categoryTotals[categoryName] = (categoryTotals[categoryName] ?? 0) + expense.amountInEur;
|
||||
categoryTotals[categoryName] =
|
||||
(categoryTotals[categoryName] ?? 0) + expense.amountInEur;
|
||||
}
|
||||
|
||||
|
||||
return categoryTotals;
|
||||
}
|
||||
|
||||
@@ -253,9 +279,12 @@ class BalanceService {
|
||||
}
|
||||
|
||||
final nonArchivedExpenses = expenses.where((e) => !e.isArchived).toList();
|
||||
final totalAmount = nonArchivedExpenses.fold(0.0, (sum, e) => sum + e.amountInEur);
|
||||
final totalAmount = nonArchivedExpenses.fold(
|
||||
0.0,
|
||||
(sum, e) => sum + e.amountInEur,
|
||||
);
|
||||
final averageAmount = totalAmount / nonArchivedExpenses.length;
|
||||
|
||||
|
||||
final categorySpending = analyzeCategorySpending(nonArchivedExpenses);
|
||||
final topCategory = categorySpending.entries
|
||||
.reduce((a, b) => a.value > b.value ? a : b)
|
||||
@@ -279,11 +308,14 @@ class BalanceService {
|
||||
try {
|
||||
// Ici vous pourriez enregistrer le règlement en base
|
||||
// ou créer une transaction de règlement
|
||||
|
||||
|
||||
// Pour l'instant, on pourrait juste recalculer
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
_errorService.logSuccess('BalanceService', 'Règlement marqué comme effectué');
|
||||
|
||||
_errorService.logSuccess(
|
||||
'BalanceService',
|
||||
'Règlement marqué comme effectué',
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceService', 'Erreur mark settlement: $e');
|
||||
rethrow;
|
||||
@@ -312,4 +344,4 @@ class _UserBalanceCalculator {
|
||||
balance: _totalPaid - _totalOwed,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,33 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../components/error/error_content.dart';
|
||||
import 'logger_service.dart';
|
||||
|
||||
/// Service for handling application errors and user notifications.
|
||||
///
|
||||
///
|
||||
/// This singleton service provides centralized error handling capabilities
|
||||
/// including displaying error dialogs, snackbars, and logging errors for
|
||||
/// debugging purposes. It uses a global navigator key to show notifications
|
||||
/// from anywhere in the application.
|
||||
class ErrorService {
|
||||
static final ErrorService _instance = ErrorService._internal();
|
||||
|
||||
|
||||
/// Factory constructor that returns the singleton instance.
|
||||
factory ErrorService() => _instance;
|
||||
|
||||
|
||||
/// Private constructor for singleton pattern.
|
||||
ErrorService._internal();
|
||||
|
||||
/// Global navigator key for accessing context from anywhere in the app.
|
||||
///
|
||||
///
|
||||
/// This key should be assigned to the MaterialApp's navigatorKey property
|
||||
/// to enable error notifications from any part of the application.
|
||||
static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
/// Displays an error message in a dialog.
|
||||
///
|
||||
///
|
||||
/// Shows a modal dialog with the error message and optional retry functionality.
|
||||
/// The dialog appearance can be customized with different icons and colors.
|
||||
///
|
||||
///
|
||||
/// [message] - The error message to display
|
||||
/// [title] - The dialog title (defaults to 'Error')
|
||||
/// [onRetry] - Optional callback for retry functionality
|
||||
@@ -53,10 +54,10 @@ class ErrorService {
|
||||
}
|
||||
|
||||
/// Displays an error or success message in a snackbar.
|
||||
///
|
||||
///
|
||||
/// Shows a floating snackbar at the bottom of the screen with the message.
|
||||
/// The appearance changes based on whether it's an error or success message.
|
||||
///
|
||||
///
|
||||
/// [message] - The message to display
|
||||
/// [onRetry] - Optional callback for retry functionality
|
||||
/// [isError] - Whether this is an error (true) or success (false) message
|
||||
@@ -89,36 +90,35 @@ class ErrorService {
|
||||
}
|
||||
|
||||
/// Logs error messages to the console during development.
|
||||
///
|
||||
///
|
||||
/// Formats and displays error information including source, error message,
|
||||
/// and optional stack trace in a visually distinct format.
|
||||
///
|
||||
///
|
||||
/// [source] - The source or location where the error occurred
|
||||
/// [error] - The error object or message
|
||||
/// [stackTrace] - Optional stack trace for debugging
|
||||
void logError(String source, dynamic error, [StackTrace? stackTrace]) {
|
||||
print('═══════════════════════════════════');
|
||||
print('❌ ERROR in $source');
|
||||
print('Message: $error');
|
||||
if (stackTrace != null) {
|
||||
print('StackTrace: $stackTrace');
|
||||
}
|
||||
print('═══════════════════════════════════');
|
||||
LoggerService.error(
|
||||
'❌ ERROR in $source\nMessage: $error',
|
||||
name: source,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Logs informational messages to the console during development.
|
||||
///
|
||||
///
|
||||
/// [source] - The source or location of the information
|
||||
/// [message] - The informational message
|
||||
void logInfo(String source, String message) {
|
||||
print('ℹ️ [$source] $message');
|
||||
LoggerService.info('ℹ️ $message', name: source);
|
||||
}
|
||||
|
||||
/// Logs success messages to the console during development.
|
||||
///
|
||||
///
|
||||
/// [source] - The source or location of the success
|
||||
/// [message] - The success message
|
||||
void logSuccess(String source, String message) {
|
||||
print('✅ [$source] $message');
|
||||
LoggerService.info('✅ $message', name: source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
30
lib/services/logger_service.dart
Normal file
30
lib/services/logger_service.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'dart:developer' as developer;
|
||||
|
||||
class LoggerService {
|
||||
static void log(String message, {String name = 'App'}) {
|
||||
developer.log(message, name: name);
|
||||
}
|
||||
|
||||
static void error(
|
||||
String message, {
|
||||
String name = 'App',
|
||||
Object? error,
|
||||
StackTrace? stackTrace,
|
||||
}) {
|
||||
developer.log(
|
||||
message,
|
||||
name: name,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
level: 1000,
|
||||
);
|
||||
}
|
||||
|
||||
static void info(String message, {String name = 'App'}) {
|
||||
developer.log(message, name: name, level: 800);
|
||||
}
|
||||
|
||||
static void warning(String message, {String name = 'App'}) {
|
||||
developer.log(message, name: name, level: 900);
|
||||
}
|
||||
}
|
||||
36
lib/services/map_navigation_service.dart
Normal file
36
lib/services/map_navigation_service.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'dart:async';
|
||||
|
||||
class MapLocationRequest {
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
final String? name;
|
||||
final DateTime timestamp;
|
||||
|
||||
MapLocationRequest({
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
this.name,
|
||||
}) : timestamp = DateTime.now();
|
||||
}
|
||||
|
||||
class MapNavigationService {
|
||||
final _requestController = StreamController<MapLocationRequest>.broadcast();
|
||||
MapLocationRequest? _lastRequest;
|
||||
|
||||
Stream<MapLocationRequest> get requestStream => _requestController.stream;
|
||||
MapLocationRequest? get lastRequest => _lastRequest;
|
||||
|
||||
void navigateToLocation(double lat, double lng, {String? name}) {
|
||||
final request = MapLocationRequest(
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
name: name,
|
||||
);
|
||||
_lastRequest = request;
|
||||
_requestController.add(request);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_requestController.close();
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@ class MessageService {
|
||||
MessageService({
|
||||
required MessageRepository messageRepository,
|
||||
ErrorService? errorService,
|
||||
}) : _messageRepository = messageRepository,
|
||||
_errorService = errorService ?? ErrorService();
|
||||
}) : _messageRepository = messageRepository,
|
||||
_errorService = errorService ?? ErrorService();
|
||||
|
||||
// Envoyer un message
|
||||
Future<void> sendMessage({
|
||||
@@ -30,12 +30,13 @@ class MessageService {
|
||||
senderId: senderId,
|
||||
senderName: senderName,
|
||||
);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de l\'envoi du message: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible d\'envoyer le message');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,12 +44,13 @@ class MessageService {
|
||||
Stream<List<Message>> getMessagesStream(String groupId) {
|
||||
try {
|
||||
return _messageRepository.getMessagesStream(groupId);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de la récupération des messages: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible de récupérer les messages');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,12 +64,13 @@ class MessageService {
|
||||
groupId: groupId,
|
||||
messageId: messageId,
|
||||
);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de la suppression du message: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible de supprimer le message');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,12 +90,13 @@ class MessageService {
|
||||
messageId: messageId,
|
||||
newText: newText.trim(),
|
||||
);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de la modification du message: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible de modifier le message');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,12 +114,13 @@ class MessageService {
|
||||
userId: userId,
|
||||
reaction: reaction,
|
||||
);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de l\'ajout de la réaction: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible d\'ajouter la réaction');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,12 +136,13 @@ class MessageService {
|
||||
messageId: messageId,
|
||||
userId: userId,
|
||||
);
|
||||
} catch (e) {
|
||||
} catch (e, stackTrace) {
|
||||
_errorService.logError(
|
||||
'message_service.dart',
|
||||
'Erreur lors de la suppression de la réaction: $e',
|
||||
stackTrace,
|
||||
);
|
||||
rethrow;
|
||||
throw Exception('Impossible de supprimer la réaction');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
256
lib/services/notification_service.dart
Normal file
256
lib/services/notification_service.dart
Normal file
@@ -0,0 +1,256 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:travel_mate/services/logger_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
import 'package:travel_mate/repositories/group_repository.dart';
|
||||
import 'package:travel_mate/repositories/account_repository.dart';
|
||||
import 'package:travel_mate/components/group/chat_group_content.dart';
|
||||
import 'package:travel_mate/components/account/group_expenses_page.dart';
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
await Firebase.initializeApp();
|
||||
LoggerService.info('Handling a background message: ${message.messageId}');
|
||||
}
|
||||
|
||||
class NotificationService {
|
||||
static final NotificationService _instance = NotificationService._internal();
|
||||
factory NotificationService() => _instance;
|
||||
NotificationService._internal();
|
||||
|
||||
late final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
|
||||
late final FlutterLocalNotificationsPlugin _localNotifications =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
|
||||
bool _isInitialized = false;
|
||||
|
||||
Future<void> initialize() async {
|
||||
if (_isInitialized) return;
|
||||
|
||||
// Request permissions
|
||||
await _requestPermissions();
|
||||
|
||||
// Initialize local notifications
|
||||
const androidSettings = AndroidInitializationSettings(
|
||||
'@mipmap/ic_launcher',
|
||||
);
|
||||
const iosSettings = DarwinInitializationSettings();
|
||||
const initSettings = InitializationSettings(
|
||||
android: androidSettings,
|
||||
iOS: iosSettings,
|
||||
);
|
||||
|
||||
await _localNotifications.initialize(
|
||||
initSettings,
|
||||
onDidReceiveNotificationResponse: (details) {
|
||||
// Handle notification tap
|
||||
LoggerService.info('Notification tapped: ${details.payload}');
|
||||
if (details.payload != null) {
|
||||
try {
|
||||
final data = json.decode(details.payload!) as Map<String, dynamic>;
|
||||
_handleNotificationTap(data);
|
||||
} catch (e) {
|
||||
LoggerService.error('Error parsing notification payload', error: e);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Handle foreground messages
|
||||
FirebaseMessaging.onMessage.listen(_handleForegroundMessage);
|
||||
|
||||
// Handle token refresh
|
||||
FirebaseMessaging.instance.onTokenRefresh.listen(_onTokenRefresh);
|
||||
|
||||
// Setup interacted message (Deep Linking)
|
||||
// We don't call this here anymore, it will be called from HomePage
|
||||
// await setupInteractedMessage();
|
||||
|
||||
_isInitialized = true;
|
||||
LoggerService.info('NotificationService initialized');
|
||||
|
||||
// Print current token for debugging
|
||||
final token = await getFCMToken();
|
||||
LoggerService.info('Current FCM Token: $token');
|
||||
}
|
||||
|
||||
/// Sets up the background message listener.
|
||||
/// Should be called when the app is ready to handle navigation.
|
||||
void startListening() {
|
||||
// Handle any interaction when the app is in the background via a
|
||||
// Stream listener
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
|
||||
_handleNotificationTap(message.data);
|
||||
});
|
||||
}
|
||||
|
||||
/// Checks for an initial message (app opened from terminated state)
|
||||
/// and handles it if present.
|
||||
Future<void> handleInitialMessage() async {
|
||||
// Get any messages which caused the application to open from
|
||||
// a terminated state.
|
||||
RemoteMessage? initialMessage = await _firebaseMessaging
|
||||
.getInitialMessage();
|
||||
|
||||
if (initialMessage != null) {
|
||||
LoggerService.info('Found initial message: ${initialMessage.data}');
|
||||
_handleNotificationTap(initialMessage.data);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleNotificationTap(Map<String, dynamic> data) async {
|
||||
LoggerService.info('Handling notification tap with data: $data');
|
||||
// DEBUG: Show snackbar to verify payload
|
||||
// ErrorService().showSnackbar(message: 'Debug: Payload $data', isError: false);
|
||||
|
||||
final type = data['type'];
|
||||
|
||||
try {
|
||||
if (type == 'message') {
|
||||
final groupId = data['groupId'];
|
||||
if (groupId != null) {
|
||||
final groupRepository = GroupRepository();
|
||||
final group = await groupRepository.getGroupById(groupId);
|
||||
if (group != null) {
|
||||
ErrorService.navigatorKey.currentState?.push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => ChatGroupContent(group: group),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
LoggerService.error('Group not found: $groupId');
|
||||
// ErrorService().showError(message: 'Groupe introuvable: $groupId');
|
||||
}
|
||||
} else {
|
||||
LoggerService.error('Missing groupId in payload');
|
||||
// ErrorService().showError(message: 'Payload invalide: groupId manquant');
|
||||
}
|
||||
} else if (type == 'expense') {
|
||||
final tripId = data['tripId'];
|
||||
if (tripId != null) {
|
||||
final accountRepository = AccountRepository();
|
||||
final groupRepository = GroupRepository();
|
||||
|
||||
final account = await accountRepository.getAccountByTripId(tripId);
|
||||
final group = await groupRepository.getGroupByTripId(tripId);
|
||||
|
||||
if (account != null && group != null) {
|
||||
ErrorService.navigatorKey.currentState?.push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
GroupExpensesPage(account: account, group: group),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
LoggerService.error('Account or Group not found for trip: $tripId');
|
||||
// ErrorService().showError(message: 'Compte ou Groupe introuvable');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LoggerService.info('Unknown notification type: $type');
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error('Error handling notification tap: $e');
|
||||
ErrorService().showError(message: 'Erreur navigation: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onTokenRefresh(String newToken) async {
|
||||
LoggerService.info('FCM Token refreshed: $newToken');
|
||||
// We need the user ID to save the token.
|
||||
// Since this service is a singleton, we might not have direct access to the user ID here
|
||||
// without injecting the repository or bloc.
|
||||
// For now, we rely on the AuthBloc to update the token on login/start.
|
||||
// Ideally, we should save it here if we have the user ID.
|
||||
}
|
||||
|
||||
Future<void> _requestPermissions() async {
|
||||
NotificationSettings settings = await _firebaseMessaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
LoggerService.info(
|
||||
'User granted permission: ${settings.authorizationStatus}',
|
||||
);
|
||||
}
|
||||
|
||||
Future<String?> getFCMToken() async {
|
||||
try {
|
||||
if (Platform.isIOS) {
|
||||
String? apnsToken = await _firebaseMessaging.getAPNSToken();
|
||||
int retries = 0;
|
||||
while (apnsToken == null && retries < 10) {
|
||||
LoggerService.info(
|
||||
'Waiting for APNS token... (Attempt ${retries + 1}/10)',
|
||||
);
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
apnsToken = await _firebaseMessaging.getAPNSToken();
|
||||
retries++;
|
||||
}
|
||||
if (apnsToken == null) {
|
||||
LoggerService.error('APNS token not available after retries');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final token = await _firebaseMessaging.getToken();
|
||||
LoggerService.info('NotificationService - FCM Token: $token');
|
||||
return token;
|
||||
} catch (e) {
|
||||
LoggerService.error('Error getting FCM token: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveTokenToFirestore(String userId) async {
|
||||
try {
|
||||
final token = await getFCMToken();
|
||||
if (token != null) {
|
||||
await FirebaseFirestore.instance.collection('users').doc(userId).set({
|
||||
'fcmToken': token,
|
||||
}, SetOptions(merge: true));
|
||||
LoggerService.info('FCM Token saved to Firestore for user: $userId');
|
||||
}
|
||||
} catch (e) {
|
||||
LoggerService.error('Error saving FCM token to Firestore: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleForegroundMessage(RemoteMessage message) async {
|
||||
LoggerService.info('Got a message whilst in the foreground!');
|
||||
LoggerService.info('Message data: ${message.data}');
|
||||
|
||||
if (message.notification != null) {
|
||||
LoggerService.info(
|
||||
'Message also contained a notification: ${message.notification}',
|
||||
);
|
||||
|
||||
// Show local notification
|
||||
const androidDetails = AndroidNotificationDetails(
|
||||
'high_importance_channel',
|
||||
'High Importance Notifications',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
);
|
||||
const iosDetails = DarwinNotificationDetails();
|
||||
const details = NotificationDetails(
|
||||
android: androidDetails,
|
||||
iOS: iosDetails,
|
||||
);
|
||||
|
||||
await _localNotifications.show(
|
||||
message.hashCode,
|
||||
message.notification?.title,
|
||||
message.notification?.body,
|
||||
details,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user