Compare commits
10 Commits
41402e1b2c
...
bf796a661c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf796a661c | ||
|
|
272fce2e59 | ||
|
|
fd710b8cb8 | ||
|
|
cad9d42128 | ||
|
|
9198493dd5 | ||
|
|
f7eeb7c6f1 | ||
|
|
258f10b42b | ||
|
|
79cf3f4655 | ||
|
|
c322bc079a | ||
|
|
9101a94691 |
55
.github/workflows/deploy-playstore.yml
vendored
Normal file
55
.github/workflows/deploy-playstore.yml
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
name: Deploy to Play Store
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- release # L'action se déclenche uniquement sur la branche 'release'
|
||||
|
||||
jobs:
|
||||
build_and_deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
# 1. Récupérer le code
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# 2. Installer Java (requis pour Android build)
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
# 3. Installer Flutter
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: 'stable'
|
||||
|
||||
# 4. Gérer les dépendances
|
||||
- run: flutter pub get
|
||||
|
||||
# 5. Créer le Keystore depuis le secret (Décodage)
|
||||
- name: Decode Keystore
|
||||
run: |
|
||||
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
|
||||
|
||||
# 6. Créer le fichier key.properties pour que Gradle trouve la clé
|
||||
- name: Create key.properties
|
||||
run: |
|
||||
echo "storePassword=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}" > android/key.properties
|
||||
echo "keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}" >> android/key.properties
|
||||
echo "keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}" >> android/key.properties
|
||||
echo "storeFile=upload-keystore.jks" >> android/key.properties
|
||||
|
||||
# 7. Construire l'AppBundle (.aab)
|
||||
- name: Build AppBundle
|
||||
run: flutter build appbundle --release
|
||||
|
||||
# 8. Uploader sur le Play Store (Track: alpha = Test fermé)
|
||||
- name: Upload to Play Store
|
||||
uses: r0adkll/upload-google-play@v1
|
||||
with:
|
||||
serviceAccountJsonPlainText: ${{ secrets.PLAY_STORE_CONFIG_JSON }}
|
||||
packageName: be.devdayronvl.travel_mate
|
||||
releaseFiles: build/app/outputs/bundle/release/app-release.aab
|
||||
track: alpha # 'alpha' correspond souvent au Test Fermé. Sinon 'internal' ou 'beta'.
|
||||
status: completed
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -44,7 +44,9 @@ app.*.map.json
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
.vscode
|
||||
.VSCodeCounter
|
||||
.VSCodeCounter/*
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
firestore.rules
|
||||
storage.rules
|
||||
|
||||
@@ -9,7 +9,7 @@ plugins {
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.travel_mate"
|
||||
namespace = "be.davdayronvl.travel_mate"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
@@ -24,7 +24,7 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.example.travel_mate"
|
||||
applicationId = "be.davdayronvl.travel_mate"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = flutter.minSdkVersion
|
||||
@@ -32,12 +32,18 @@ android {
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
signingConfigs {
|
||||
release {
|
||||
keyAlias = keystoreProperties['keyAlias']
|
||||
keyPassword = keystoreProperties['keyPassword']
|
||||
storeFile = keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
|
||||
storePassword = keystoreProperties['storePassword']
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
signingConfig = signingConfigs.release
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<!-- Permissions pour écrire dans le stockage -->
|
||||
<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
|
||||
|
||||
@@ -40,6 +40,8 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
on<_AccountsUpdated>(_onAccountsUpdated);
|
||||
on<CreateAccount>(_onCreateAccount);
|
||||
on<CreateAccountWithMembers>(_onCreateAccountWithMembers);
|
||||
on<AddMemberToAccount>(_onAddMemberToAccount);
|
||||
on<RemoveMemberFromAccount>(_onRemoveMemberFromAccount);
|
||||
}
|
||||
|
||||
Future<void> _onLoadAccountsByUserId(
|
||||
@@ -109,6 +111,34 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {
|
||||
}
|
||||
}
|
||||
|
||||
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(e.toString(), stackTrace);
|
||||
emit(AccountError('Erreur lors de l\'ajout du membre: ${e.toString()}'));
|
||||
}
|
||||
}
|
||||
|
||||
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(e.toString(), stackTrace);
|
||||
emit(AccountError('Erreur lors de la suppression du membre: ${e.toString()}'));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_accountsSubscription?.cancel();
|
||||
|
||||
@@ -86,3 +86,31 @@ 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];
|
||||
}
|
||||
@@ -21,9 +21,10 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
_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
|
||||
@@ -51,12 +53,14 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
|
||||
final activities = await _repository.getActivitiesByTrip(event.tripId);
|
||||
|
||||
emit(ActivityLoaded(
|
||||
activities: activities,
|
||||
filteredActivities: activities,
|
||||
));
|
||||
emit(
|
||||
ActivityLoaded(activities: activities, filteredActivities: activities),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur chargement activités: $e');
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur chargement activités: $e',
|
||||
);
|
||||
emit(const ActivityError('Impossible de charger les activités'));
|
||||
}
|
||||
}
|
||||
@@ -76,16 +80,44 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
}
|
||||
|
||||
// Sinon, on charge normalement
|
||||
emit(ActivityLoaded(
|
||||
activities: activities,
|
||||
filteredActivities: activities,
|
||||
));
|
||||
emit(
|
||||
ActivityLoaded(activities: activities, filteredActivities: activities),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur chargement activités: $e');
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur chargement activités: $e',
|
||||
);
|
||||
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) {
|
||||
_errorService.logError('activity_bloc', 'Erreur mise à jour date: $e');
|
||||
emit(const ActivityError('Impossible de mettre à jour la date'));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles searching activities using Google Places API
|
||||
Future<void> _onSearchActivities(
|
||||
SearchActivities event,
|
||||
@@ -104,7 +136,9 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
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
|
||||
);
|
||||
|
||||
@@ -121,11 +155,13 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, finalResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
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'));
|
||||
@@ -168,13 +204,18 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, finalResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
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');
|
||||
_errorService.logError(
|
||||
'activity_bloc',
|
||||
'Erreur recherche activités avec coordonnées: $e',
|
||||
);
|
||||
emit(const ActivityError('Impossible de rechercher les activités'));
|
||||
}
|
||||
}
|
||||
@@ -196,10 +237,9 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Mettre en cache les résultats
|
||||
ActivityCacheService().setCachedActivities(event.tripId, searchResults);
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
searchResults: searchResults,
|
||||
query: event.query,
|
||||
));
|
||||
emit(
|
||||
ActivitySearchResults(searchResults: searchResults, query: event.query),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur recherche textuelle: $e');
|
||||
emit(const ActivityError('Impossible de rechercher les activités'));
|
||||
@@ -230,16 +270,23 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
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(
|
||||
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 {
|
||||
@@ -281,19 +328,23 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
.where((activity) => activity.id != event.googleActivityId)
|
||||
.toList();
|
||||
|
||||
emit(ActivitySearchResults(
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
));
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Sinon, émettre l'état d'ajout réussi
|
||||
emit(ActivityAdded(
|
||||
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 {
|
||||
@@ -314,11 +365,13 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Filter out existing activities
|
||||
final filteredActivities = <Activity>[];
|
||||
|
||||
emit(ActivityBatchAdding(
|
||||
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];
|
||||
@@ -337,11 +390,13 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
}
|
||||
|
||||
// Update progress
|
||||
emit(ActivityBatchAdding(
|
||||
emit(
|
||||
ActivityBatchAdding(
|
||||
activitiesToAdd: event.activities,
|
||||
progress: i + 1,
|
||||
total: event.activities.length,
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (filteredActivities.isEmpty) {
|
||||
@@ -352,10 +407,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
final addedIds = await _repository.addActivitiesBatch(filteredActivities);
|
||||
|
||||
if (addedIds.isNotEmpty) {
|
||||
emit(ActivityOperationSuccess(
|
||||
emit(
|
||||
ActivityOperationSuccess(
|
||||
'${addedIds.length} activité(s) ajoutée(s) avec succès',
|
||||
operationType: 'batch_add',
|
||||
));
|
||||
),
|
||||
);
|
||||
// Reload activities
|
||||
add(LoadActivities(event.activities.first.tripId));
|
||||
} else {
|
||||
@@ -376,10 +433,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
// Show voting state
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
emit(ActivityVoting(
|
||||
emit(
|
||||
ActivityVoting(
|
||||
activityId: event.activityId,
|
||||
activities: currentState.activities,
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final success = await _repository.voteForActivity(
|
||||
@@ -389,11 +448,13 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
);
|
||||
|
||||
if (success) {
|
||||
emit(ActivityVoteRecorded(
|
||||
emit(
|
||||
ActivityVoteRecorded(
|
||||
activityId: event.activityId,
|
||||
vote: event.vote,
|
||||
userId: event.userId,
|
||||
));
|
||||
),
|
||||
);
|
||||
|
||||
// Reload activities to reflect the new vote
|
||||
if (state is ActivityLoaded) {
|
||||
@@ -402,7 +463,8 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
currentState.activities.first.tripId,
|
||||
);
|
||||
|
||||
emit(currentState.copyWith(
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
activities: activities,
|
||||
filteredActivities: _applyFilters(
|
||||
activities,
|
||||
@@ -411,7 +473,8 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
currentState.showVotedOnly,
|
||||
event.userId,
|
||||
),
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
emit(const ActivityError('Impossible d\'enregistrer le vote'));
|
||||
@@ -431,10 +494,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
final success = await _repository.deleteActivity(event.activityId);
|
||||
|
||||
if (success) {
|
||||
emit(ActivityDeleted(
|
||||
emit(
|
||||
ActivityDeleted(
|
||||
activityId: event.activityId,
|
||||
message: 'Activité supprimée avec succès',
|
||||
));
|
||||
),
|
||||
);
|
||||
|
||||
// Reload if we're on the activity list
|
||||
if (state is ActivityLoaded) {
|
||||
@@ -468,12 +533,14 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
'', // UserId would be needed for showVotedOnly filter
|
||||
);
|
||||
|
||||
emit(currentState.copyWith(
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
filteredActivities: filteredActivities,
|
||||
activeFilter: event.category,
|
||||
minRating: event.minRating,
|
||||
showVotedOnly: event.showVotedOnly ?? false,
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,19 +570,23 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
try {
|
||||
if (state is ActivityLoaded) {
|
||||
final currentState = state as ActivityLoaded;
|
||||
emit(ActivityUpdating(
|
||||
emit(
|
||||
ActivityUpdating(
|
||||
activityId: event.activity.id,
|
||||
activities: currentState.activities,
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final success = await _repository.updateActivity(event.activity);
|
||||
|
||||
if (success) {
|
||||
emit(const ActivityOperationSuccess(
|
||||
emit(
|
||||
const ActivityOperationSuccess(
|
||||
'Activité mise à jour avec succès',
|
||||
operationType: 'update',
|
||||
));
|
||||
),
|
||||
);
|
||||
|
||||
// Reload activities
|
||||
add(LoadActivities(event.activity.tripId));
|
||||
@@ -536,11 +607,13 @@ 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(
|
||||
add(
|
||||
VoteForActivity(
|
||||
activityId: event.activityId,
|
||||
userId: event.userId,
|
||||
vote: 1,
|
||||
));
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('activity_bloc', 'Erreur favori: $e');
|
||||
emit(const ActivityError('Impossible de modifier les favoris'));
|
||||
@@ -558,7 +631,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) {
|
||||
@@ -587,11 +678,13 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
.toList();
|
||||
|
||||
// Émettre le nouvel état avec l'activité retirée
|
||||
emit(ActivitySearchResults(
|
||||
emit(
|
||||
ActivitySearchResults(
|
||||
searchResults: updatedResults,
|
||||
query: currentState.query,
|
||||
isLoading: false,
|
||||
));
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,10 +693,12 @@ class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
|
||||
RestoreCachedSearchResults event,
|
||||
Emitter<ActivityState> emit,
|
||||
) async {
|
||||
emit(ActivitySearchResults(
|
||||
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];
|
||||
|
||||
@@ -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
|
||||
@@ -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];
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
/// ));
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../repositories/balance_repository.dart';
|
||||
import '../../repositories/expense_repository.dart';
|
||||
@@ -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);
|
||||
@@ -83,18 +89,22 @@ 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);
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
emit(GroupBalancesLoaded(
|
||||
balances: userBalances,
|
||||
settlements: settlements,
|
||||
));
|
||||
emit(
|
||||
GroupBalancesLoaded(balances: userBalances, settlements: settlements),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceBloc', 'Error loading balance: $e');
|
||||
emit(BalanceError(e.toString()));
|
||||
@@ -121,15 +131,18 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
|
||||
}
|
||||
|
||||
// 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);
|
||||
final settlements = await _balanceService.calculateOptimalSettlements(
|
||||
event.groupId,
|
||||
);
|
||||
|
||||
emit(GroupBalancesLoaded(
|
||||
balances: userBalances,
|
||||
settlements: settlements,
|
||||
));
|
||||
emit(
|
||||
GroupBalancesLoaded(balances: userBalances, settlements: settlements),
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.logError('BalanceBloc', 'Error refreshing balance: $e');
|
||||
emit(BalanceError(e.toString()));
|
||||
|
||||
@@ -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);
|
||||
@@ -56,7 +57,9 @@ 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();
|
||||
|
||||
@@ -64,7 +67,8 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
|
||||
.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');
|
||||
@@ -105,7 +109,10 @@ 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');
|
||||
@@ -127,7 +134,10 @@ 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');
|
||||
|
||||
@@ -28,8 +28,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 {
|
||||
@@ -132,33 +133,13 @@ class _AccountContentState extends State<AccountContent> {
|
||||
/// 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));
|
||||
},
|
||||
@@ -167,11 +148,21 @@ class _AccountContentState extends State<AccountContent> {
|
||||
},
|
||||
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é')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -196,7 +187,7 @@ class _AccountContentState extends State<AccountContent> {
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text('Loading accounts...'),
|
||||
Text('Chargement des comptes...'),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -204,7 +195,7 @@ class _AccountContentState extends State<AccountContent> {
|
||||
|
||||
if (accountState is AccountError) {
|
||||
return ErrorContent(
|
||||
message: 'Account loading error...',
|
||||
message: 'Erreur de chargement des comptes...',
|
||||
onRetry: () {
|
||||
context.read<AccountBloc>().add(LoadAccountsByUserId(userId));
|
||||
},
|
||||
@@ -222,13 +213,13 @@ 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'),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -258,7 +249,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,
|
||||
),
|
||||
@@ -289,17 +280,6 @@ 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),
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
/// - Group
|
||||
/// - ExpenseBloc
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -76,8 +77,10 @@ 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;
|
||||
|
||||
@@ -103,27 +106,40 @@ 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();
|
||||
@@ -221,17 +237,14 @@ 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 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();
|
||||
}).toList();
|
||||
|
||||
if (selectedSplits.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -248,11 +261,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,29 +283,29 @@ 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
|
||||
content: Text(
|
||||
widget.expenseToEdit == null
|
||||
? 'Dépense ajoutée'
|
||||
: 'Dépense modifiée'),
|
||||
: 'Dépense modifiée',
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
@@ -296,10 +313,7 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
@@ -314,77 +328,124 @@ 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
|
||||
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'),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
: '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(
|
||||
),
|
||||
const Divider(height: 1),
|
||||
|
||||
// Form Content
|
||||
Expanded(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
// Description
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Description',
|
||||
hintText: 'Ex: Restaurant, Essence...',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.description),
|
||||
prefixIcon: const Icon(Icons.description_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'Veuillez entrer une description';
|
||||
return 'Requis';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Montant et devise
|
||||
// Montant et Devise
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextFormField(
|
||||
controller: _amountController,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Montant',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.euro),
|
||||
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,
|
||||
),
|
||||
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';
|
||||
if (double.tryParse(value) == null ||
|
||||
double.parse(value) <= 0) {
|
||||
return 'Invalide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<ExpenseCurrency>(
|
||||
initialValue: _selectedCurrency,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Devise',
|
||||
border: OutlineInputBorder(),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 16,
|
||||
),
|
||||
),
|
||||
items: ExpenseCurrency.values.map((currency) {
|
||||
return DropdownMenuItem(
|
||||
@@ -406,21 +467,21 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
// Catégorie
|
||||
DropdownButtonFormField<ExpenseCategory>(
|
||||
initialValue: _selectedCategory,
|
||||
decoration: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Catégorie',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.category),
|
||||
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: Row(
|
||||
children: [
|
||||
Icon(category.icon, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text(category.displayName),
|
||||
],
|
||||
),
|
||||
child: Text(category.displayName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
@@ -432,35 +493,52 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
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),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(const Duration(days: 365)),
|
||||
lastDate: DateTime.now().add(
|
||||
const Duration(days: 365),
|
||||
),
|
||||
);
|
||||
if (date != null) {
|
||||
setState(() => _selectedDate = date);
|
||||
}
|
||||
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: const InputDecoration(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Payé par',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person),
|
||||
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(
|
||||
@@ -469,19 +547,20 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => _paidById = value);
|
||||
}
|
||||
if (value != null) setState(() => _paidById = value);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Division
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
// 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(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
@@ -493,7 +572,15 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(_splitEqually ? 'Égale' : 'Personnalisée'),
|
||||
Text(
|
||||
'Égale',
|
||||
style: TextStyle(
|
||||
color: isDark
|
||||
? Colors.grey[400]
|
||||
: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Switch(
|
||||
value: _splitEqually,
|
||||
onChanged: (value) {
|
||||
@@ -502,30 +589,56 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
if (value) _calculateSplits();
|
||||
});
|
||||
},
|
||||
activeThumbColor: theme.colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(),
|
||||
...widget.group.members.map((member) {
|
||||
final isSelected = _splits.containsKey(member.userId) &&
|
||||
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,
|
||||
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,
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
onChanged: (value) {
|
||||
final amount = double.tryParse(value) ?? 0;
|
||||
setState(() => _splits[member.userId] = amount);
|
||||
final amount =
|
||||
double.tryParse(value) ?? 0;
|
||||
setState(
|
||||
() =>
|
||||
_splits[member.userId] = amount,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
Checkbox(
|
||||
value: isSelected,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
@@ -537,62 +650,104 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
|
||||
}
|
||||
});
|
||||
},
|
||||
activeColor: theme.colorScheme.primary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
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,
|
||||
// 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),
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
side: BorderSide(color: Colors.grey[300]!),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Boutons
|
||||
Row(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Annuler'),
|
||||
const Icon(Icons.receipt_long, color: Colors.green),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Reçu joint'),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => setState(() {
|
||||
_receiptImage = null;
|
||||
_receiptRemoved = true;
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
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(
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 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),
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(widget.expenseToEdit == null ? 'Ajouter' : 'Modifier'),
|
||||
: Text(
|
||||
widget.expenseToEdit == null
|
||||
? 'Ajouter'
|
||||
: 'Enregistrer',
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,31 +50,64 @@ 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),
|
||||
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(12),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
// Icone circulaire
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: isDark ? Colors.blue[900] : Colors.blue[100],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
color: _getCategoryColor(
|
||||
expense.category,
|
||||
).withValues(alpha: 0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
expense.category.icon,
|
||||
color: Colors.blue,
|
||||
color: _getCategoryColor(expense.category),
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
|
||||
// Détails
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -81,44 +116,58 @@ class ExpensesTab extends StatelessWidget {
|
||||
expense.description,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'Payé par ${expense.paidByName}',
|
||||
isPayer
|
||||
? 'Payé par vous'
|
||||
: 'Payé par ${expense.paidByName}',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
fontSize: 13,
|
||||
color: isDark
|
||||
? Colors.grey[400]
|
||||
: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
dateFormat.format(expense.date),
|
||||
' • ${dateFormat.format(expense.date)}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[500] : Colors.grey[500],
|
||||
fontSize: 13,
|
||||
color: isDark
|
||||
? Colors.grey[500]
|
||||
: Colors.grey[500],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Montant
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
'${expense.amount.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: const TextStyle(
|
||||
'$prefix${amountToDisplay.toStringAsFixed(2)} ${expense.currency.symbol}',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.green,
|
||||
color: amountColor,
|
||||
),
|
||||
),
|
||||
if (expense.currency != ExpenseCurrency.eur)
|
||||
Text(
|
||||
'${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
'Total ${expense.amountInEur.toStringAsFixed(2)} €',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? Colors.grey[400] : Colors.grey[600],
|
||||
fontSize: 11,
|
||||
color: isDark ? Colors.grey[500] : Colors.grey[400],
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -127,16 +176,31 @@ class ExpensesTab extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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,8 @@ 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';
|
||||
|
||||
class GroupExpensesPage extends StatefulWidget {
|
||||
final Account account;
|
||||
@@ -31,13 +32,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();
|
||||
}
|
||||
|
||||
@@ -57,33 +59,35 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
|
||||
@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,
|
||||
title: const Text(
|
||||
'Dépenses du voyage',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
centerTitle: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
bottom: TabBar(
|
||||
controller: _tabController,
|
||||
indicatorColor: Colors.white,
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: Colors.white70,
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(Icons.balance),
|
||||
text: 'Balances',
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.receipt_long),
|
||||
text: 'Dépenses',
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.payment),
|
||||
text: 'Règlements',
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.filter_list),
|
||||
onPressed: () {
|
||||
_showFilterDialog();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: MultiBlocListener(
|
||||
listeners: [
|
||||
BlocListener<ExpenseBloc, ExpenseState>(
|
||||
@@ -103,14 +107,93 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
} 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: Column(
|
||||
children: [
|
||||
// Summary Card
|
||||
BlocBuilder<BalanceBloc, BalanceState>(
|
||||
builder: (context, state) {
|
||||
if (state is GroupBalancesLoaded) {
|
||||
return _buildSummaryCard(state.balances, isDarkMode);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
|
||||
// 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'),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Tab View
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
// Onglet Balances
|
||||
// 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) {
|
||||
@@ -118,41 +201,13 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
} 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}');
|
||||
return _buildErrorState('Erreur: ${state.message}');
|
||||
}
|
||||
return _buildEmptyState('Aucune balance disponible');
|
||||
},
|
||||
),
|
||||
|
||||
// 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');
|
||||
},
|
||||
],
|
||||
),
|
||||
|
||||
// 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');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -160,8 +215,109 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
floatingActionButton: FloatingActionButton(
|
||||
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 +327,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 +342,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 +362,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 +375,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,
|
||||
),
|
||||
],
|
||||
@@ -247,10 +389,8 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
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(
|
||||
@@ -261,4 +401,96 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _showFilterDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
return AlertDialog(
|
||||
title: const Text('Filtrer les dépenses'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
DropdownButtonFormField<ExpenseCategory>(
|
||||
// ignore: deprecated_member_use
|
||||
value: _selectedCategory,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Catégorie',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
const DropdownMenuItem<ExpenseCategory>(
|
||||
value: null,
|
||||
child: Text('Toutes'),
|
||||
),
|
||||
...ExpenseCategory.values.map((category) {
|
||||
return DropdownMenuItem(
|
||||
value: category,
|
||||
child: Text(category.displayName),
|
||||
);
|
||||
}),
|
||||
],
|
||||
onChanged: (value) {
|
||||
setState(() => _selectedCategory = value);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<String>(
|
||||
// ignore: deprecated_member_use
|
||||
value: _selectedPayerId,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Payé par',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
const DropdownMenuItem<String>(
|
||||
value: null,
|
||||
child: Text('Tous'),
|
||||
),
|
||||
...widget.group.members.map((member) {
|
||||
return DropdownMenuItem(
|
||||
value: member.userId,
|
||||
child: Text(member.firstName),
|
||||
);
|
||||
}),
|
||||
],
|
||||
onChanged: (value) {
|
||||
setState(() => _selectedPayerId = value);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_selectedCategory = null;
|
||||
_selectedPayerId = null;
|
||||
});
|
||||
// Also update parent state
|
||||
this.setState(() {
|
||||
_selectedCategory = null;
|
||||
_selectedPayerId = null;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Réinitialiser'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
// Update parent state
|
||||
this.setState(() {});
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Appliquer'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,10 @@ import '../../blocs/activity/activity_state.dart';
|
||||
import '../../models/trip.dart';
|
||||
import '../../models/activity.dart';
|
||||
import '../../services/activity_cache_service.dart';
|
||||
import '../activities/add_activity_bottom_sheet.dart';
|
||||
|
||||
import '../loading/laoding_content.dart';
|
||||
import '../../blocs/user/user_bloc.dart';
|
||||
import '../../blocs/user/user_state.dart';
|
||||
|
||||
class ActivitiesPage extends StatefulWidget {
|
||||
final Trip trip;
|
||||
@@ -23,9 +25,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
late TabController _tabController;
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
final ActivityCacheService _cacheService = ActivityCacheService();
|
||||
String _selectedCategory = 'Toutes les catégories';
|
||||
String _selectedPrice = 'Prix';
|
||||
String _selectedRating = 'Note';
|
||||
|
||||
// Cache pour éviter de recharger les données
|
||||
bool _activitiesLoaded = false;
|
||||
@@ -35,8 +34,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
List<Activity> _tripActivities = [];
|
||||
List<Activity> _approvedActivities = [];
|
||||
bool _isLoadingTripActivities = false;
|
||||
int _totalGoogleActivitiesRequested =
|
||||
0; // Compteur pour les recherches progressives
|
||||
|
||||
bool _autoReloadInProgress =
|
||||
false; // Protection contre les rechargements en boucle
|
||||
int _lastAutoReloadTriggerCount =
|
||||
@@ -83,7 +81,9 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
// Si on va sur l'onglet suggestions Google et qu'aucune recherche n'a été faite
|
||||
if (_tabController.index == 2 && !_googleSearchPerformed) {
|
||||
// Vérifier si on a des activités en cache
|
||||
final cachedActivities = _cacheService.getCachedActivities(widget.trip.id!);
|
||||
final cachedActivities = _cacheService.getCachedActivities(
|
||||
widget.trip.id!,
|
||||
);
|
||||
if (cachedActivities != null && cachedActivities.isNotEmpty) {
|
||||
// Restaurer les activités en cache dans le BLoC
|
||||
context.read<ActivityBloc>().add(
|
||||
@@ -174,10 +174,26 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
// Stocker les activités localement
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
setState(() {
|
||||
_tripActivities = state.activities;
|
||||
_approvedActivities = state.activities
|
||||
.where((a) => a.totalVotes > 0)
|
||||
final allActivities = state.filteredActivities;
|
||||
|
||||
_approvedActivities = allActivities
|
||||
.where(
|
||||
(a) => a.isApprovedByAllParticipants([
|
||||
...widget.trip.participants,
|
||||
widget.trip.createdBy,
|
||||
]),
|
||||
)
|
||||
.toList();
|
||||
|
||||
_tripActivities = allActivities
|
||||
.where(
|
||||
(a) => !a.isApprovedByAllParticipants([
|
||||
...widget.trip.participants,
|
||||
widget.trip.createdBy,
|
||||
]),
|
||||
)
|
||||
.toList();
|
||||
|
||||
_isLoadingTripActivities = false;
|
||||
});
|
||||
|
||||
@@ -189,6 +205,37 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
}
|
||||
|
||||
if (state is ActivitySearchResults) {
|
||||
// Gérer l'ajout d'activité depuis les résultats de recherche
|
||||
if (state.newlyAddedActivity != null) {
|
||||
// Fermer le dialog de loading s'il est ouvert
|
||||
if (Navigator.of(context).canPop()) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
setState(() {
|
||||
_tripActivities.add(state.newlyAddedActivity!);
|
||||
});
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${state.newlyAddedActivity!.name} ajoutée au voyage !',
|
||||
),
|
||||
duration: const Duration(seconds: 2),
|
||||
backgroundColor: Colors.green,
|
||||
action: SnackBarAction(
|
||||
label: 'Voir',
|
||||
textColor: Colors.white,
|
||||
onPressed: () {
|
||||
_tabController.animateTo(0);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Déclencher l'auto-reload uniquement pour la recherche initiale (6 résultats)
|
||||
// et pas pour les rechargements automatiques
|
||||
if (state.searchResults.length <= 6 && !_autoReloadInProgress) {
|
||||
@@ -220,21 +267,13 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
elevation: 0,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: _showAddActivityBottomSheet,
|
||||
),
|
||||
],
|
||||
actions: [],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// Barre de recherche
|
||||
_buildSearchBar(theme),
|
||||
|
||||
// Filtres
|
||||
_buildFilters(theme),
|
||||
|
||||
// Onglets de catégories
|
||||
_buildCategoryTabs(theme),
|
||||
|
||||
@@ -260,7 +299,9 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(
|
||||
alpha: 0.3,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: TextField(
|
||||
@@ -268,11 +309,11 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Rechercher restaurants, musées...',
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
prefixIcon: Icon(
|
||||
Icons.search,
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
border: InputBorder.none,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
@@ -280,95 +321,32 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
onChanged: (value) {
|
||||
// TODO: Implémenter la recherche
|
||||
onSubmitted: (value) {
|
||||
if (value.isNotEmpty) {
|
||||
_performSearch(value);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFilters(ThemeData theme) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildFilterButton(
|
||||
theme,
|
||||
_selectedCategory,
|
||||
Icons.category,
|
||||
() => _showCategoryFilter(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
_buildFilterButton(
|
||||
theme,
|
||||
_selectedPrice,
|
||||
Icons.euro,
|
||||
() => _showPriceFilter(),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
_buildFilterButton(
|
||||
theme,
|
||||
_selectedRating,
|
||||
Icons.star,
|
||||
() => _showRatingFilter(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFilterButton(
|
||||
ThemeData theme,
|
||||
String text,
|
||||
IconData icon,
|
||||
VoidCallback onPressed,
|
||||
) {
|
||||
return GestureDetector(
|
||||
onTap: onPressed,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: theme.colorScheme.outline.withOpacity(0.5)),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
color: theme.colorScheme.surface,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 16,
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
text,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryTabs(ThemeData theme) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(
|
||||
alpha: 0.3,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: theme.colorScheme.onSurface.withOpacity(0.7),
|
||||
unselectedLabelColor: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.7,
|
||||
),
|
||||
indicator: BoxDecoration(
|
||||
color: theme.colorScheme.primary,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
@@ -376,246 +354,15 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
indicatorSize: TabBarIndicatorSize.tab,
|
||||
dividerColor: Colors.transparent,
|
||||
tabs: const [
|
||||
Tab(text: 'Activités du voyage'),
|
||||
Tab(text: 'Activités approuvées'),
|
||||
Tab(text: 'Suggestions Google'),
|
||||
Tab(text: 'Voyage'),
|
||||
Tab(text: 'Approuvées'),
|
||||
Tab(text: 'Suggestion'),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showCategoryFilter() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => _buildCategoryFilterSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
void _showPriceFilter() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => _buildPriceFilterSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
void _showRatingFilter() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => _buildRatingFilterSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryFilterSheet() {
|
||||
final theme = Theme.of(context);
|
||||
final categories = [
|
||||
'Toutes les catégories',
|
||||
...ActivityCategory.values.map((e) => e.displayName),
|
||||
];
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight:
|
||||
MediaQuery.of(context).size.height * 0.7, // Limite à 70% de l'écran
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Catégories',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: categories
|
||||
.map(
|
||||
(category) => ListTile(
|
||||
title: Text(category),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_selectedCategory = category;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
_applyFilters();
|
||||
},
|
||||
trailing: _selectedCategory == category
|
||||
? Icon(
|
||||
Icons.check,
|
||||
color: theme.colorScheme.primary,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPriceFilterSheet() {
|
||||
final theme = Theme.of(context);
|
||||
final prices = [
|
||||
'Prix',
|
||||
'Gratuit',
|
||||
'Bon marché',
|
||||
'Modéré',
|
||||
'Cher',
|
||||
'Très cher',
|
||||
];
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.7,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Niveau de prix',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: prices
|
||||
.map(
|
||||
(price) => ListTile(
|
||||
title: Text(price),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_selectedPrice = price;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
_applyFilters();
|
||||
},
|
||||
trailing: _selectedPrice == price
|
||||
? Icon(
|
||||
Icons.check,
|
||||
color: theme.colorScheme.primary,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRatingFilterSheet() {
|
||||
final theme = Theme.of(context);
|
||||
final ratings = [
|
||||
'Note',
|
||||
'4+ étoiles',
|
||||
'3+ étoiles',
|
||||
'2+ étoiles',
|
||||
'1+ étoiles',
|
||||
];
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.7,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Note minimale',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: ratings
|
||||
.map(
|
||||
(rating) => ListTile(
|
||||
title: Text(rating),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_selectedRating = rating;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
_applyFilters();
|
||||
},
|
||||
trailing: _selectedRating == rating
|
||||
? Icon(
|
||||
Icons.check,
|
||||
color: theme.colorScheme.primary,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _applyFilters() {
|
||||
String? category = _selectedCategory == 'Toutes les catégories'
|
||||
? null
|
||||
: _selectedCategory;
|
||||
double? minRating = _getMinRatingFromString(_selectedRating);
|
||||
|
||||
context.read<ActivityBloc>().add(
|
||||
FilterActivities(category: category, minRating: minRating),
|
||||
);
|
||||
}
|
||||
|
||||
double? _getMinRatingFromString(String rating) {
|
||||
switch (rating) {
|
||||
case '4+ étoiles':
|
||||
return 4.0;
|
||||
case '3+ étoiles':
|
||||
return 3.0;
|
||||
case '2+ étoiles':
|
||||
return 2.0;
|
||||
case '1+ étoiles':
|
||||
return 1.0;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _showAddActivityBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom,
|
||||
),
|
||||
child: AddActivityBottomSheet(trip: widget.trip),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTripActivitiesTab() {
|
||||
// Utiliser les données locales au lieu du BLoC
|
||||
if (_isLoadingTripActivities) {
|
||||
@@ -814,7 +561,9 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
Text(
|
||||
'Recherche powered by Google Places',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -845,7 +594,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
Text(
|
||||
subtitle,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.7),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
@@ -977,7 +726,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withOpacity(0.1),
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
@@ -1015,7 +764,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.withOpacity(0.1),
|
||||
color: Colors.amber.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
@@ -1043,7 +792,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
Text(
|
||||
activity.description,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.8),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.8),
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -1056,14 +805,18 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
Icon(
|
||||
Icons.location_on,
|
||||
size: 16,
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.6,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
activity.address!,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.6,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -1084,10 +837,10 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.orange.withOpacity(0.1),
|
||||
color: Colors.orange.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Colors.orange.withOpacity(0.3),
|
||||
color: Colors.orange.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
@@ -1140,7 +893,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green.withOpacity(0.1),
|
||||
color: Colors.green.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
@@ -1170,7 +923,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withOpacity(0.1),
|
||||
color: Colors.red.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
@@ -1247,9 +1000,41 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
}
|
||||
|
||||
void _voteForActivity(String activityId, int vote) {
|
||||
// TODO: Récupérer l'ID utilisateur actuel
|
||||
// Pour l'instant, on utilise un ID temporaire
|
||||
final userId = 'current_user_id';
|
||||
// Récupérer l'ID utilisateur actuel depuis le UserBloc
|
||||
final userState = context.read<UserBloc>().state;
|
||||
final userId = userState is UserLoaded
|
||||
? userState.user.id
|
||||
: widget.trip.createdBy;
|
||||
|
||||
// Vérifier si l'activité existe dans la liste locale pour vérifier le vote
|
||||
// (car l'objet activity passé peut venir d'une liste filtrée ou autre)
|
||||
final currentActivity = _tripActivities.firstWhere(
|
||||
(a) => a.id == activityId,
|
||||
orElse: () => _approvedActivities.firstWhere(
|
||||
(a) => a.id == activityId,
|
||||
orElse: () => Activity(
|
||||
id: '',
|
||||
tripId: '',
|
||||
name: '',
|
||||
description: '',
|
||||
category: '',
|
||||
createdAt: DateTime.now(),
|
||||
updatedAt: DateTime.now(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Si l'activité a été trouvée et que l'utilisateur a déjà voté
|
||||
if (currentActivity.id.isNotEmpty && currentActivity.hasUserVoted(userId)) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Vous avez déjà voté pour cette activité'),
|
||||
backgroundColor: Colors.orange,
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
context.read<ActivityBloc>().add(
|
||||
VoteForActivity(activityId: activityId, userId: userId, vote: vote),
|
||||
@@ -1285,12 +1070,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
loadingText: 'Ajout de ${activity.name}...',
|
||||
onBackgroundTask: () async {
|
||||
// Ajouter l'activité au voyage
|
||||
context.read<ActivityBloc>().add(
|
||||
AddActivityAndRemoveFromSearch(
|
||||
activity: newActivity,
|
||||
googleActivityId: activity.id,
|
||||
),
|
||||
);
|
||||
context.read<ActivityBloc>().add(AddActivity(newActivity));
|
||||
// Attendre que l'ajout soit complété
|
||||
await Future.delayed(const Duration(milliseconds: 1000));
|
||||
},
|
||||
@@ -1345,7 +1125,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
6; // Activités actuelles + ce qui manque + buffer de 6
|
||||
|
||||
// Mettre à jour le compteur et recharger avec le nouveau total
|
||||
_totalGoogleActivitiesRequested = newTotalToRequest;
|
||||
|
||||
_loadMoreGoogleActivitiesWithTotal(newTotalToRequest);
|
||||
|
||||
// Libérer le verrou après un délai
|
||||
@@ -1358,7 +1138,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
}
|
||||
|
||||
void _searchGoogleActivities() {
|
||||
_totalGoogleActivitiesRequested = 6; // Reset du compteur
|
||||
_autoReloadInProgress = false; // Reset des protections
|
||||
_lastAutoReloadTriggerCount = 0;
|
||||
|
||||
@@ -1389,7 +1168,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
}
|
||||
|
||||
void _resetAndSearchGoogleActivities() {
|
||||
_totalGoogleActivitiesRequested = 6; // Reset du compteur
|
||||
_autoReloadInProgress = false; // Reset des protections
|
||||
_lastAutoReloadTriggerCount = 0;
|
||||
|
||||
@@ -1426,8 +1204,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
final currentCount = currentState.searchResults.length;
|
||||
final newTotal = currentCount + 6;
|
||||
|
||||
_totalGoogleActivitiesRequested = newTotal;
|
||||
|
||||
// Utiliser les coordonnées pré-géolocalisées du voyage si disponibles
|
||||
if (widget.trip.hasCoordinates) {
|
||||
context.read<ActivityBloc>().add(
|
||||
@@ -1514,4 +1290,19 @@ class _ActivitiesPageState extends State<ActivitiesPage>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _performSearch(String query) {
|
||||
// Basculer vers l'onglet suggestions
|
||||
_tabController.animateTo(2);
|
||||
|
||||
// Déclencher la recherche textuelle
|
||||
context.read<ActivityBloc>().add(
|
||||
SearchActivitiesByText(
|
||||
tripId: widget.trip.id!,
|
||||
destination: widget.trip.location,
|
||||
query: query,
|
||||
),
|
||||
);
|
||||
_googleSearchPerformed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,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),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
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';
|
||||
|
||||
/// Chat group content widget for group messaging functionality.
|
||||
///
|
||||
@@ -28,10 +31,7 @@ class ChatGroupContent extends StatefulWidget {
|
||||
///
|
||||
/// 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();
|
||||
@@ -47,17 +47,36 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
/// 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();
|
||||
}
|
||||
|
||||
@@ -132,10 +151,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
/// [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),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,7 +199,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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -235,7 +254,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 +263,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 +286,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,
|
||||
@@ -299,7 +326,9 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
? '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,
|
||||
@@ -316,9 +345,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
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 +374,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,7 +392,12 @@ 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;
|
||||
|
||||
@@ -381,15 +409,65 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
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.firstWhere(
|
||||
(m) => m.userId == message.senderId,
|
||||
orElse: () => null as dynamic,
|
||||
)
|
||||
as dynamic;
|
||||
|
||||
// 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(
|
||||
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) ...[
|
||||
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),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 10,
|
||||
),
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: MediaQuery.of(context).size.width * 0.7,
|
||||
maxWidth: MediaQuery.of(context).size.width * 0.65,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: bubbleColor,
|
||||
@@ -401,11 +479,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
||||
crossAxisAlignment: isMe
|
||||
? CrossAxisAlignment.end
|
||||
: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (!isMe) ...[
|
||||
Text(
|
||||
message.senderName,
|
||||
displayName,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
@@ -415,8 +495,18 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
Text(
|
||||
message.text,
|
||||
style: TextStyle(fontSize: 15, color: textColor),
|
||||
message.isDeleted
|
||||
? 'a supprimé un message'
|
||||
: message.text,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
color: message.isDeleted
|
||||
? textColor.withValues(alpha: 0.5)
|
||||
: textColor,
|
||||
fontStyle: message.isDeleted
|
||||
? FontStyle.italic
|
||||
: FontStyle.normal,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
@@ -454,6 +544,9 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -497,7 +590,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 +602,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 +642,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 +746,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 +808,85 @@ 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
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Pseudo modifié en "$newPseudo"'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur lors de la modification du pseudo: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,17 +127,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 +144,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';
|
||||
}
|
||||
|
||||
|
||||
333
lib/components/home/calendar/calendar_page.dart
Normal file
333
lib/components/home/calendar/calendar_page.dart
Normal file
@@ -0,0 +1,333 @@
|
||||
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';
|
||||
|
||||
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;
|
||||
CalendarFormat _calendarFormat = CalendarFormat.month;
|
||||
|
||||
@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);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Calendrier du voyage'),
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
elevation: 0,
|
||||
),
|
||||
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, though ideally we should be in loaded state
|
||||
// This might happen if we navigate back and forth
|
||||
}
|
||||
|
||||
// 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,
|
||||
);
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
TableCalendar(
|
||||
firstDay: DateTime.now().subtract(const Duration(days: 365)),
|
||||
lastDay: DateTime.now().add(const Duration(days: 365)),
|
||||
focusedDay: _focusedDay,
|
||||
calendarFormat: _calendarFormat,
|
||||
selectedDayPredicate: (day) {
|
||||
return isSameDay(_selectedDay, day);
|
||||
},
|
||||
onDaySelected: (selectedDay, focusedDay) {
|
||||
setState(() {
|
||||
_selectedDay = selectedDay;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
},
|
||||
onFormatChanged: (format) {
|
||||
setState(() {
|
||||
_calendarFormat = format;
|
||||
});
|
||||
},
|
||||
onPageChanged: (focusedDay) {
|
||||
_focusedDay = focusedDay;
|
||||
},
|
||||
eventLoader: (day) {
|
||||
return _getActivitiesForDay(day, scheduledActivities);
|
||||
},
|
||||
calendarBuilders: CalendarBuilders(
|
||||
markerBuilder: (context, day, events) {
|
||||
if (events.isEmpty) return null;
|
||||
return Positioned(
|
||||
bottom: 1,
|
||||
child: Container(
|
||||
width: 7,
|
||||
height: 7,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
calendarStyle: CalendarStyle(
|
||||
todayDecoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.5),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
selectedDecoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
// Scheduled Activities for Selected Day
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
'Activités du ${DateFormat('dd/MM/yyyy').format(_selectedDay!)}',
|
||||
style: theme.textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: selectedActivities.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
'Aucune activité prévue',
|
||||
style: theme.textTheme.bodyMedium
|
||||
?.copyWith(
|
||||
color: theme.colorScheme.onSurface
|
||||
.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
itemCount: selectedActivities.length,
|
||||
itemBuilder: (context, index) {
|
||||
final activity =
|
||||
selectedActivities[index];
|
||||
return ListTile(
|
||||
title: Text(activity.name),
|
||||
subtitle: Text(
|
||||
'${activity.category} - ${DateFormat('HH:mm').format(activity.date!)}',
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () {
|
||||
context.read<ActivityBloc>().add(
|
||||
UpdateActivityDate(
|
||||
tripId: widget.trip.id!,
|
||||
activityId: activity.id,
|
||||
date: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const VerticalDivider(),
|
||||
// Unscheduled Activities
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
'À planifier',
|
||||
style: theme.textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: unscheduledActivities.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
'Tout est planifié !',
|
||||
style: theme.textTheme.bodyMedium
|
||||
?.copyWith(
|
||||
color: theme.colorScheme.onSurface
|
||||
.withValues(alpha: 0.6),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
itemCount: unscheduledActivities.length,
|
||||
itemBuilder: (context, index) {
|
||||
final activity =
|
||||
unscheduledActivities[index];
|
||||
return Draggable<Activity>(
|
||||
data: activity,
|
||||
feedback: Material(
|
||||
elevation: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
color: theme.cardColor,
|
||||
child: Text(activity.name),
|
||||
),
|
||||
),
|
||||
child: ListTile(
|
||||
title: Text(
|
||||
activity.name,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () {
|
||||
if (_selectedDay != null) {
|
||||
_selectTimeAndSchedule(
|
||||
activity,
|
||||
_selectedDay!,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
// Zone de drop pour le calendrier
|
||||
DragTarget<Activity>(
|
||||
onWillAcceptWithDetails: (details) => true,
|
||||
onAcceptWithDetails: (details) {
|
||||
if (_selectedDay != null) {
|
||||
_selectTimeAndSchedule(
|
||||
details.data,
|
||||
_selectedDay!,
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, candidateData, rejectedData) {
|
||||
return Container(
|
||||
height: 50,
|
||||
color: candidateData.isNotEmpty
|
||||
? theme.colorScheme.primary.withValues(
|
||||
alpha: 0.1,
|
||||
)
|
||||
: null,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Glisser ici pour planifier',
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,12 @@ import '../../models/group.dart';
|
||||
import '../../models/group_member.dart';
|
||||
import '../../services/user_service.dart';
|
||||
import '../../repositories/group_repository.dart';
|
||||
import '../../repositories/account_repository.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import '../../services/place_image_service.dart';
|
||||
import '../../services/trip_geocoding_service.dart';
|
||||
import '../../services/logger_service.dart';
|
||||
|
||||
/// Create trip content widget for trip creation and editing functionality.
|
||||
///
|
||||
@@ -45,10 +47,7 @@ class CreateTripContent extends StatefulWidget {
|
||||
/// Args:
|
||||
/// [tripToEdit]: Optional trip to edit. If provided, the form will
|
||||
/// be populated with existing trip data for editing
|
||||
const CreateTripContent({
|
||||
super.key,
|
||||
this.tripToEdit,
|
||||
});
|
||||
const CreateTripContent({super.key, this.tripToEdit});
|
||||
|
||||
@override
|
||||
State<CreateTripContent> createState() => _CreateTripContentState();
|
||||
@@ -71,6 +70,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
/// Services for user and group operations
|
||||
final _userService = UserService();
|
||||
final _groupRepository = GroupRepository();
|
||||
final _accountRepository = AccountRepository();
|
||||
final _placeImageService = PlaceImageService();
|
||||
final _tripGeocodingService = TripGeocodingService();
|
||||
|
||||
@@ -149,7 +149,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
'?input=${Uri.encodeComponent(query)}'
|
||||
'&types=(cities)'
|
||||
'&language=fr'
|
||||
'&key=$_apiKey'
|
||||
'&key=$_apiKey',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
@@ -205,7 +205,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
|
||||
_suggestionsOverlay = OverlayEntry(
|
||||
builder: (context) => Positioned(
|
||||
width: MediaQuery.of(context).size.width - 32, // Largeur du champ avec padding
|
||||
width:
|
||||
MediaQuery.of(context).size.width -
|
||||
32, // Largeur du champ avec padding
|
||||
child: CompositedTransformFollower(
|
||||
link: _layerLink,
|
||||
showWhenUnlinked: false,
|
||||
@@ -263,19 +265,25 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
|
||||
/// Charge l'image du lieu depuis Google Places API
|
||||
Future<void> _loadPlaceImage(String location) async {
|
||||
print('CreateTripContent: Chargement de l\'image pour: $location');
|
||||
LoggerService.info(
|
||||
'CreateTripContent: Chargement de l\'image pour: $location',
|
||||
);
|
||||
|
||||
try {
|
||||
final imageUrl = await _placeImageService.getPlaceImageUrl(location);
|
||||
print('CreateTripContent: Image URL reçue: $imageUrl');
|
||||
LoggerService.info('CreateTripContent: Image URL reçue: $imageUrl');
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_selectedImageUrl = imageUrl;
|
||||
});
|
||||
print('CreateTripContent: État mis à jour avec imageUrl: $_selectedImageUrl');
|
||||
LoggerService.info(
|
||||
'CreateTripContent: État mis à jour avec imageUrl: $_selectedImageUrl',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
print('CreateTripContent: Erreur lors du chargement de l\'image: $e');
|
||||
LoggerService.error(
|
||||
'CreateTripContent: Erreur lors du chargement de l\'image: $e',
|
||||
);
|
||||
if (mounted) {
|
||||
_errorService.logError(
|
||||
'create_trip_content.dart',
|
||||
@@ -347,42 +355,36 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
decoration: InputDecoration(
|
||||
hintText: label,
|
||||
hintStyle: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.5),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
),
|
||||
prefixIcon: Icon(
|
||||
icon,
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.5),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
),
|
||||
suffixIcon: suffixIcon,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: isDarkMode
|
||||
? Colors.white.withOpacity(0.2)
|
||||
: Colors.black.withOpacity(0.2),
|
||||
? Colors.white.withValues(alpha: 0.2)
|
||||
: Colors.black.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: isDarkMode
|
||||
? Colors.white.withOpacity(0.2)
|
||||
: Colors.black.withOpacity(0.2),
|
||||
? Colors.white.withValues(alpha: 0.2)
|
||||
: Colors.black.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: Colors.teal,
|
||||
width: 2,
|
||||
),
|
||||
borderSide: BorderSide(color: Colors.teal, width: 2),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(
|
||||
color: Colors.red,
|
||||
width: 2,
|
||||
),
|
||||
borderSide: const BorderSide(color: Colors.red, width: 2),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: theme.cardColor,
|
||||
@@ -412,15 +414,15 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isDarkMode
|
||||
? Colors.white.withOpacity(0.2)
|
||||
: Colors.black.withOpacity(0.2),
|
||||
? Colors.white.withValues(alpha: 0.2)
|
||||
: Colors.black.withValues(alpha: 0.2),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.calendar_today,
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.5),
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
@@ -431,7 +433,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: date != null
|
||||
? theme.colorScheme.onSurface
|
||||
: theme.colorScheme.onSurface.withOpacity(0.5),
|
||||
: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -452,7 +454,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
_createGroupAndAccountForTrip(_createdTripId!);
|
||||
} else if (tripState is TripOperationSuccess) {
|
||||
if (mounted) {
|
||||
_errorService.showSnackbar(message: tripState.message, isError: false);
|
||||
_errorService.showSnackbar(
|
||||
message: tripState.message,
|
||||
isError: false,
|
||||
);
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
@@ -463,7 +468,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
}
|
||||
} else if (tripState is TripError) {
|
||||
if (mounted) {
|
||||
_errorService.showSnackbar(message: tripState.message, isError: true);
|
||||
_errorService.showSnackbar(
|
||||
message: tripState.message,
|
||||
isError: true,
|
||||
);
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
@@ -476,7 +484,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
return Scaffold(
|
||||
backgroundColor: theme.scaffoldBackgroundColor,
|
||||
appBar: AppBar(
|
||||
title: Text(isEditing ? 'Modifier le voyage' : 'Créer un voyage'),
|
||||
title: Text(
|
||||
isEditing ? 'Modifier le voyage' : 'Créer un voyage',
|
||||
),
|
||||
backgroundColor: theme.appBarTheme.backgroundColor,
|
||||
foregroundColor: theme.appBarTheme.foregroundColor,
|
||||
),
|
||||
@@ -504,7 +514,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: Icon(Icons.arrow_back, color: theme.colorScheme.onSurface),
|
||||
icon: Icon(
|
||||
Icons.arrow_back,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
@@ -517,7 +530,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(isDarkMode ? 0.3 : 0.1),
|
||||
color: Colors.black.withValues(
|
||||
alpha: isDarkMode ? 0.3 : 0.1,
|
||||
),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 5),
|
||||
),
|
||||
@@ -542,7 +557,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
Text(
|
||||
'Donne un nom à ton voyage',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.7,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
@@ -586,7 +603,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
@@ -611,10 +630,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Dates
|
||||
Row(
|
||||
Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
@@ -631,10 +649,8 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
const SizedBox(height: 20),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
@@ -651,7 +667,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
@@ -669,11 +684,14 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
controller: _budgetController,
|
||||
label: 'Ex : 500',
|
||||
icon: Icons.euro,
|
||||
keyboardType: TextInputType.numberWithOptions(decimal: true),
|
||||
keyboardType: TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Inviter des amis
|
||||
// Inviter des amis - seulement en mode création
|
||||
if (!isEditing) ...[
|
||||
Text(
|
||||
'Invite tes amis',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
@@ -702,7 +720,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
),
|
||||
child: IconButton(
|
||||
onPressed: _addParticipant,
|
||||
icon: const Icon(Icons.add, color: Colors.white),
|
||||
icon: const Icon(
|
||||
Icons.add,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -721,7 +742,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withOpacity(0.1),
|
||||
color: Colors.teal.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Row(
|
||||
@@ -729,7 +750,8 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
children: [
|
||||
Text(
|
||||
email,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
style: theme.textTheme.bodySmall
|
||||
?.copyWith(
|
||||
color: Colors.teal,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
@@ -750,6 +772,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
],
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
@@ -758,7 +781,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
width: double.infinity,
|
||||
height: 56,
|
||||
child: ElevatedButton(
|
||||
onPressed: _isLoading ? null : () => _saveTrip(userState.user),
|
||||
onPressed: _isLoading
|
||||
? null
|
||||
: () => _saveTrip(userState.user),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.teal,
|
||||
foregroundColor: Colors.white,
|
||||
@@ -773,12 +798,17 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
isEditing ? 'Modifier le voyage' : 'Créer le voyage',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
isEditing
|
||||
? 'Modifier le voyage'
|
||||
: 'Créer le voyage',
|
||||
style: theme.textTheme.titleMedium
|
||||
?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
@@ -846,15 +876,18 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
||||
if (!emailRegex.hasMatch(email)) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Email invalide')));
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Email invalide')));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_participants.contains(email)) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text('Ce participant est déjà ajouté')));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Ce participant est déjà ajouté')),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -871,13 +904,15 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
});
|
||||
}
|
||||
|
||||
// Mettre à jour le groupe avec les nouveaux membres
|
||||
Future<void> _updateGroupMembers(
|
||||
// Mettre à jour le groupe ET le compte avec les nouveaux membres
|
||||
Future<void> _updateGroupAndAccountMembers(
|
||||
String tripId,
|
||||
user_state.UserModel currentUser,
|
||||
List<Map<String, dynamic>> participantsData,
|
||||
) async {
|
||||
final groupBloc = context.read<GroupBloc>();
|
||||
final accountBloc = context.read<AccountBloc>();
|
||||
|
||||
try {
|
||||
final group = await _groupRepository.getGroupByTripId(tripId);
|
||||
|
||||
@@ -889,33 +924,58 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Récupérer le compte associé au voyage
|
||||
final account = await _accountRepository.getAccountByTripId(tripId);
|
||||
|
||||
final newMembers = await _createMembers();
|
||||
|
||||
final currentMembers = await _groupRepository.getGroupMembers(group.id);
|
||||
final currentMemberIds = currentMembers.map((m) => m.userId).toSet();
|
||||
final newMemberIds = newMembers.map((m) => m.userId).toSet();
|
||||
|
||||
final membersToAdd = newMembers.where((m) => !currentMemberIds.contains(m.userId)).toList();
|
||||
final membersToAdd = newMembers
|
||||
.where((m) => !currentMemberIds.contains(m.userId))
|
||||
.toList();
|
||||
|
||||
final membersToRemove = currentMembers
|
||||
.where((m) => !newMemberIds.contains(m.userId) && m.role != 'admin')
|
||||
.toList();
|
||||
|
||||
// Ajouter les nouveaux membres au groupe ET au compte
|
||||
for (final member in membersToAdd) {
|
||||
if (mounted) {
|
||||
groupBloc.add(AddMemberToGroup(group.id, member));
|
||||
if (account != null) {
|
||||
accountBloc.add(AddMemberToAccount(account.id, member));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Supprimer les membres supprimés du groupe ET du compte
|
||||
for (final member in membersToRemove) {
|
||||
if (mounted) {
|
||||
groupBloc.add(RemoveMemberFromGroup(group.id, member.userId));
|
||||
if (account != null) {
|
||||
accountBloc.add(RemoveMemberFromAccount(account.id, member.userId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Groupe et compte mis à jour avec succès !'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError(
|
||||
'create_trip_content.dart',
|
||||
'Erreur lors de la mise à jour du groupe: $e',
|
||||
'Erreur lors de la mise à jour du groupe et du compte: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -931,17 +991,21 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
GroupMember(
|
||||
userId: currentUser.id,
|
||||
firstName: currentUser.prenom,
|
||||
lastName: currentUser.nom,
|
||||
pseudo: currentUser.prenom,
|
||||
role: 'admin',
|
||||
profilePictureUrl: currentUser.profilePictureUrl,
|
||||
),
|
||||
...participantsData.map((p) => GroupMember(
|
||||
...participantsData.map(
|
||||
(p) => GroupMember(
|
||||
userId: p['id'] as String,
|
||||
firstName: p['firstName'] as String,
|
||||
lastName: p['lastName'] as String? ?? '',
|
||||
pseudo: p['firstName'] as String,
|
||||
role: 'member',
|
||||
profilePictureUrl: p['profilePictureUrl'] as String?,
|
||||
)),
|
||||
),
|
||||
),
|
||||
];
|
||||
return groupMembers;
|
||||
}
|
||||
@@ -951,7 +1015,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
final accountBloc = context.read<AccountBloc>();
|
||||
|
||||
try {
|
||||
|
||||
final userState = context.read<UserBloc>().state;
|
||||
if (userState is! user_state.UserLoaded) {
|
||||
throw Exception('Utilisateur non connecté');
|
||||
@@ -971,20 +1034,18 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
throw Exception('Erreur lors de la création des membres du groupe');
|
||||
}
|
||||
|
||||
groupBloc.add(CreateGroupWithMembers(
|
||||
group: group,
|
||||
members: groupMembers,
|
||||
));
|
||||
groupBloc.add(
|
||||
CreateGroupWithMembers(group: group, members: groupMembers),
|
||||
);
|
||||
final account = Account(
|
||||
id: '',
|
||||
tripId: tripId,
|
||||
name: _titleController.text.trim(),
|
||||
);
|
||||
|
||||
accountBloc.add(CreateAccountWithMembers(
|
||||
account: account,
|
||||
members: groupMembers,
|
||||
));
|
||||
accountBloc.add(
|
||||
CreateAccountWithMembers(account: account, members: groupMembers),
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -998,7 +1059,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
});
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
_errorService.logError(
|
||||
'create_trip_content.dart',
|
||||
@@ -1007,10 +1067,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
|
||||
);
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
@@ -1019,8 +1076,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Future<void> _saveTrip(user_state.UserModel currentUser) async {
|
||||
if (!_formKey.currentState!.validate()) {
|
||||
return;
|
||||
@@ -1043,7 +1098,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
|
||||
try {
|
||||
final participantsData = await _getParticipantsData(_participants);
|
||||
List<String> participantIds = participantsData.map((p) => p['id'] as String).toList();
|
||||
List<String> participantIds = participantsData
|
||||
.map((p) => p['id'] as String)
|
||||
.toList();
|
||||
|
||||
if (!participantIds.contains(currentUser.id)) {
|
||||
participantIds.insert(0, currentUser.id);
|
||||
@@ -1067,17 +1124,16 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
// Géolocaliser le voyage avant de le sauvegarder
|
||||
Trip tripWithCoordinates;
|
||||
try {
|
||||
print('🌍 [CreateTrip] Géolocalisation en cours pour: ${trip.location}');
|
||||
tripWithCoordinates = await _tripGeocodingService.geocodeTrip(trip);
|
||||
print('✅ [CreateTrip] Géolocalisation réussie: ${tripWithCoordinates.latitude}, ${tripWithCoordinates.longitude}');
|
||||
} catch (e) {
|
||||
print('⚠️ [CreateTrip] Erreur de géolocalisation: $e');
|
||||
// Continuer sans coordonnées en cas d'erreur
|
||||
tripWithCoordinates = trip;
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Voyage créé sans géolocalisation (pas d\'impact sur les fonctionnalités)'),
|
||||
content: Text(
|
||||
'Voyage créé sans géolocalisation (pas d\'impact sur les fonctionnalités)',
|
||||
),
|
||||
backgroundColor: Colors.orange,
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
@@ -1089,15 +1145,22 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
// Mode mise à jour
|
||||
tripBloc.add(TripUpdateRequested(trip: tripWithCoordinates));
|
||||
|
||||
// Vérifier que l'ID du voyage existe avant de mettre à jour le groupe
|
||||
if (widget.tripToEdit != null && widget.tripToEdit!.id != null && widget.tripToEdit!.id!.isNotEmpty) {
|
||||
await _updateGroupMembers(
|
||||
// Mettre à jour le groupe ET les comptes avec les nouveaux participants
|
||||
if (widget.tripToEdit != null &&
|
||||
widget.tripToEdit!.id != null &&
|
||||
widget.tripToEdit!.id!.isNotEmpty) {
|
||||
LoggerService.info(
|
||||
'🔄 [CreateTrip] Mise à jour du groupe et du compte pour le voyage ID: ${widget.tripToEdit!.id}',
|
||||
);
|
||||
LoggerService.info(
|
||||
'👥 Participants: ${participantsData.map((p) => p['id']).toList()}',
|
||||
);
|
||||
await _updateGroupAndAccountMembers(
|
||||
widget.tripToEdit!.id!,
|
||||
currentUser,
|
||||
participantsData,
|
||||
);
|
||||
}
|
||||
|
||||
} else {
|
||||
// Mode création - Le groupe sera créé dans le listener TripCreated
|
||||
tripBloc.add(TripCreateRequested(trip: tripWithCoordinates));
|
||||
@@ -1105,10 +1168,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
|
||||
);
|
||||
|
||||
setState(() {
|
||||
@@ -1118,7 +1178,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _getParticipantsData(List<String> emails) async {
|
||||
Future<List<Map<String, dynamic>>> _getParticipantsData(
|
||||
List<String> emails,
|
||||
) async {
|
||||
List<Map<String, dynamic>> participantsData = [];
|
||||
|
||||
for (String email in emails) {
|
||||
@@ -1127,11 +1189,13 @@ class _CreateTripContentState extends State<CreateTripContent> {
|
||||
if (userId != null) {
|
||||
final userDoc = await _userService.getUserById(userId);
|
||||
final firstName = userDoc?.prenom ?? 'Utilisateur';
|
||||
final lastName = userDoc?.nom ?? '';
|
||||
final profilePictureUrl = userDoc?.profilePictureUrl;
|
||||
|
||||
participantsData.add({
|
||||
'id': userId,
|
||||
'firstName': firstName,
|
||||
'lastName': lastName,
|
||||
'profilePictureUrl': profilePictureUrl,
|
||||
});
|
||||
} else {
|
||||
@@ -1160,8 +1224,5 @@ class PlaceSuggestion {
|
||||
final String placeId;
|
||||
final String description;
|
||||
|
||||
PlaceSuggestion({
|
||||
required this.placeId,
|
||||
required this.description,
|
||||
});
|
||||
PlaceSuggestion({required this.placeId, required this.description});
|
||||
}
|
||||
@@ -134,17 +134,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()
|
||||
|
||||
@@ -11,7 +11,11 @@ import 'package:travel_mate/components/map/map_content.dart';
|
||||
import 'package:travel_mate/services/error_service.dart';
|
||||
import 'package:travel_mate/services/activity_cache_service.dart';
|
||||
import 'package:travel_mate/repositories/group_repository.dart';
|
||||
import 'package:travel_mate/repositories/user_repository.dart';
|
||||
import 'package:travel_mate/repositories/account_repository.dart';
|
||||
import 'package:travel_mate/models/group_member.dart';
|
||||
import 'package:travel_mate/components/activities/activities_page.dart';
|
||||
import 'package:travel_mate/components/home/calendar/calendar_page.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class ShowTripDetailsContent extends StatefulWidget {
|
||||
@@ -26,6 +30,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
final ErrorService _errorService = ErrorService();
|
||||
final ActivityCacheService _cacheService = ActivityCacheService();
|
||||
final GroupRepository _groupRepository = GroupRepository();
|
||||
final UserRepository _userRepository = UserRepository();
|
||||
final AccountRepository _accountRepository = AccountRepository();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -94,7 +100,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
backgroundColor: theme.dialogBackgroundColor,
|
||||
backgroundColor:
|
||||
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
|
||||
title: Text(
|
||||
'Ouvrir la carte',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
@@ -199,7 +206,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
}
|
||||
|
||||
// Fallback vers l'URL web
|
||||
final webUrl = 'https://www.google.com/maps/search/?api=1&query=$location';
|
||||
final webUrl =
|
||||
'https://www.google.com/maps/search/?api=1&query=$location';
|
||||
final webUri = Uri.parse(webUrl);
|
||||
if (await canLaunchUrl(webUri)) {
|
||||
await launchUrl(webUri, mode: LaunchMode.externalApplication);
|
||||
@@ -207,7 +215,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
}
|
||||
|
||||
_errorService.showError(
|
||||
message: 'Impossible d\'ouvrir Google Maps. Vérifiez que l\'application est installée.',
|
||||
message:
|
||||
'Impossible d\'ouvrir Google Maps. Vérifiez que l\'application est installée.',
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
@@ -238,12 +247,11 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
}
|
||||
|
||||
_errorService.showError(
|
||||
message: 'Impossible d\'ouvrir Waze. Vérifiez que l\'application est installée.',
|
||||
message:
|
||||
'Impossible d\'ouvrir Waze. Vérifiez que l\'application est installée.',
|
||||
);
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur lors de l\'ouverture de Waze',
|
||||
);
|
||||
_errorService.showError(message: 'Erreur lors de l\'ouverture de Waze');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,7 +261,9 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: isDarkMode ? theme.scaffoldBackgroundColor : Colors.grey[50],
|
||||
backgroundColor: isDarkMode
|
||||
? theme.scaffoldBackgroundColor
|
||||
: Colors.grey[50],
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
@@ -287,7 +297,7 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha:0.1),
|
||||
color: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 5),
|
||||
),
|
||||
@@ -295,11 +305,14 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: widget.trip.imageUrl != null && widget.trip.imageUrl!.isNotEmpty
|
||||
child:
|
||||
widget.trip.imageUrl != null &&
|
||||
widget.trip.imageUrl!.isNotEmpty
|
||||
? Image.network(
|
||||
widget.trip.imageUrl!,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) => _buildPlaceholderImage(),
|
||||
errorBuilder: (context, error, stackTrace) =>
|
||||
_buildPlaceholderImage(),
|
||||
)
|
||||
: _buildPlaceholderImage(),
|
||||
),
|
||||
@@ -313,21 +326,24 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
children: [
|
||||
// Section "Départ dans X jours"
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.cardColor,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isDarkMode
|
||||
? Colors.white.withValues(alpha:0.1)
|
||||
: Colors.black.withValues(alpha:0.1),
|
||||
? Colors.white.withValues(alpha: 0.1)
|
||||
: Colors.black.withValues(alpha: 0.1),
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: isDarkMode
|
||||
? Colors.black.withValues(alpha:0.3)
|
||||
: Colors.black.withValues(alpha:0.1),
|
||||
? Colors.black.withValues(alpha: 0.3)
|
||||
: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: isDarkMode ? 8 : 5,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
@@ -338,7 +354,7 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha:0.1),
|
||||
color: Colors.teal.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
@@ -354,11 +370,15 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
Text(
|
||||
'Départ dans',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha:0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.6,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
daysUntilTrip > 0 ? '$daysUntilTrip Jours' : 'Voyage terminé',
|
||||
daysUntilTrip > 0
|
||||
? '$daysUntilTrip Jours'
|
||||
: 'Voyage terminé',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurface,
|
||||
@@ -367,7 +387,9 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
Text(
|
||||
widget.trip.formattedDates,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha:0.6),
|
||||
color: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.6,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -406,7 +428,13 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
icon: Icons.calendar_today,
|
||||
title: 'Calendrier',
|
||||
color: Colors.blue,
|
||||
onTap: () => _showComingSoon('Calendrier'),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
CalendarPage(trip: widget.trip),
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildActionButton(
|
||||
icon: Icons.local_activity,
|
||||
@@ -428,6 +456,9 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
_buildNextActivitiesSection(),
|
||||
_buildExpensesCard(),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -444,18 +475,11 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.location_city,
|
||||
size: 48,
|
||||
color: Colors.grey,
|
||||
),
|
||||
Icon(Icons.location_city, size: 48, color: Colors.grey),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Aucune image',
|
||||
style: TextStyle(
|
||||
color: Colors.grey,
|
||||
fontSize: 14,
|
||||
),
|
||||
style: TextStyle(color: Colors.grey, fontSize: 14),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -482,15 +506,15 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isDarkMode
|
||||
? Colors.white.withValues(alpha:0.1)
|
||||
: Colors.black.withValues(alpha:0.1),
|
||||
? Colors.white.withValues(alpha: 0.1)
|
||||
: Colors.black.withValues(alpha: 0.1),
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: isDarkMode
|
||||
? Colors.black.withValues(alpha:0.3)
|
||||
: Colors.black.withValues(alpha:0.1),
|
||||
? Colors.black.withValues(alpha: 0.3)
|
||||
: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: isDarkMode ? 8 : 5,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
@@ -505,11 +529,7 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
color: color.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: color,
|
||||
size: 24,
|
||||
),
|
||||
child: Icon(icon, color: color, size: 24),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
@@ -593,7 +613,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: theme.dialogBackgroundColor,
|
||||
backgroundColor:
|
||||
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
|
||||
title: Text(
|
||||
'Confirmer la suppression',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
@@ -622,10 +643,7 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(context, true);
|
||||
},
|
||||
child: const Text(
|
||||
'Supprimer',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
child: const Text('Supprimer', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -641,6 +659,21 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
|
||||
return FutureBuilder(
|
||||
future: _groupRepository.getGroupByTripId(widget.trip.id!),
|
||||
builder: (context, groupSnapshot) {
|
||||
if (groupSnapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (groupSnapshot.hasError ||
|
||||
!groupSnapshot.hasData ||
|
||||
groupSnapshot.data == null) {
|
||||
return const Center(child: Text('Aucun participant'));
|
||||
}
|
||||
|
||||
final groupId = groupSnapshot.data!.id;
|
||||
|
||||
return StreamBuilder<List<GroupMember>>(
|
||||
stream: _groupRepository.watchGroupMembers(groupId),
|
||||
builder: (context, snapshot) {
|
||||
// En attente
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
@@ -657,13 +690,7 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
);
|
||||
}
|
||||
|
||||
// Pas de groupe trouvé
|
||||
if (!snapshot.hasData || snapshot.data == null) {
|
||||
return const Center(child: Text('Aucun participant'));
|
||||
}
|
||||
|
||||
final group = snapshot.data!;
|
||||
final members = group.members;
|
||||
final members = snapshot.data ?? [];
|
||||
|
||||
if (members.isEmpty) {
|
||||
return const Center(child: Text('Aucun participant'));
|
||||
@@ -673,21 +700,25 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
...List.generate(
|
||||
members.length,
|
||||
(index) {
|
||||
...List.generate(members.length, (index) {
|
||||
final member = members[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 12),
|
||||
child: _buildParticipantAvatar(member),
|
||||
);
|
||||
},
|
||||
}),
|
||||
// Bouton "+" pour ajouter un participant
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 12),
|
||||
child: _buildAddParticipantButton(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Construire un avatar pour un participant
|
||||
@@ -695,7 +726,9 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
final theme = Theme.of(context);
|
||||
final initials = member.pseudo.isNotEmpty
|
||||
? member.pseudo[0].toUpperCase()
|
||||
: (member.firstName.isNotEmpty ? member.firstName[0].toUpperCase() : '?');
|
||||
: (member.firstName.isNotEmpty
|
||||
? member.firstName[0].toUpperCase()
|
||||
: '?');
|
||||
|
||||
final name = member.pseudo.isNotEmpty ? member.pseudo : member.firstName;
|
||||
|
||||
@@ -719,11 +752,14 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
child: CircleAvatar(
|
||||
radius: 28,
|
||||
backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.2),
|
||||
backgroundImage: (member.profilePictureUrl != null &&
|
||||
backgroundImage:
|
||||
(member.profilePictureUrl != null &&
|
||||
member.profilePictureUrl!.isNotEmpty)
|
||||
? NetworkImage(member.profilePictureUrl!)
|
||||
: null,
|
||||
child: (member.profilePictureUrl == null || member.profilePictureUrl!.isEmpty)
|
||||
child:
|
||||
(member.profilePictureUrl == null ||
|
||||
member.profilePictureUrl!.isEmpty)
|
||||
? Text(
|
||||
initials,
|
||||
style: TextStyle(
|
||||
@@ -738,6 +774,191 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Construire le bouton pour ajouter un participant
|
||||
Widget _buildAddParticipantButton() {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Tooltip(
|
||||
message: 'Ajouter un participant',
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.3),
|
||||
width: 2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: GestureDetector(
|
||||
onTap: _showAddParticipantDialog,
|
||||
child: CircleAvatar(
|
||||
radius: 28,
|
||||
backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.1),
|
||||
child: Icon(Icons.add, color: theme.colorScheme.primary, size: 28),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher le dialogue pour ajouter un participant
|
||||
void _showAddParticipantDialog() {
|
||||
final theme = Theme.of(context);
|
||||
final TextEditingController emailController = TextEditingController();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
backgroundColor:
|
||||
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
|
||||
title: Text(
|
||||
'Ajouter un participant',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Entrez l\'email du participant à ajouter :',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'participant@example.com',
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
|
||||
),
|
||||
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: () {
|
||||
if (emailController.text.isNotEmpty) {
|
||||
_addParticipantByEmail(emailController.text);
|
||||
Navigator.pop(context);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Veuillez entrer un email valide'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: Text(
|
||||
'Ajouter',
|
||||
style: TextStyle(color: theme.colorScheme.primary),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Ajouter un participant par email
|
||||
Future<void> _addParticipantByEmail(String email) async {
|
||||
try {
|
||||
// Chercher l'utilisateur par email
|
||||
final user = await _userRepository.getUserByEmail(email);
|
||||
|
||||
if (user == null) {
|
||||
_errorService.showError(
|
||||
message: 'Utilisateur non trouvé avec cet email',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.id == null) {
|
||||
_errorService.showError(message: 'ID utilisateur invalide');
|
||||
return;
|
||||
}
|
||||
|
||||
// Ajouter l'utilisateur au groupe
|
||||
if (widget.trip.id != null) {
|
||||
final group = await _groupRepository.getGroupByTripId(widget.trip.id!);
|
||||
if (group != null) {
|
||||
// Créer un GroupMember à partir du User
|
||||
final newMember = GroupMember(
|
||||
userId: user.id!,
|
||||
firstName: user.prenom,
|
||||
lastName: user.nom,
|
||||
pseudo: user.prenom,
|
||||
profilePictureUrl: user.profilePictureUrl,
|
||||
);
|
||||
|
||||
// Ajouter le membre au groupe
|
||||
await _groupRepository.addMember(group.id, newMember);
|
||||
|
||||
// Ajouter le membre au compte
|
||||
final account = await _accountRepository.getAccountByTripId(
|
||||
widget.trip.id!,
|
||||
);
|
||||
if (account != null) {
|
||||
await _accountRepository.addMemberToAccount(account.id, newMember);
|
||||
}
|
||||
|
||||
// Mettre à jour la liste des participants du voyage
|
||||
final newParticipants = [...widget.trip.participants, user.id!];
|
||||
final updatedTrip = widget.trip.copyWith(
|
||||
participants: newParticipants,
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
context.read<TripBloc>().add(
|
||||
TripUpdateRequested(trip: updatedTrip),
|
||||
);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('${user.prenom} a été ajouté au voyage'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
|
||||
// Rafraîchir la page
|
||||
setState(() {});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur lors de l\'ajout du participant: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _navigateToActivities() {
|
||||
Navigator.push(
|
||||
context,
|
||||
@@ -746,4 +967,175 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNextActivitiesSection() {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Prochaines activités',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => _navigateToActivities(),
|
||||
child: Text(
|
||||
'Tout voir',
|
||||
style: TextStyle(
|
||||
color: Colors.teal,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_buildActivityCard(
|
||||
title: 'Visite du Colisée',
|
||||
date: '11 août, 10:00',
|
||||
icon: Icons.museum,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildActivityCard(
|
||||
title: 'Dîner à Trastevere',
|
||||
date: '11 août, 20:30',
|
||||
icon: Icons.restaurant,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActivityCard({
|
||||
required String title,
|
||||
required String date,
|
||||
required IconData icon,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
final isDarkMode = theme.brightness == Brightness.dark;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.cardColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: isDarkMode
|
||||
? Colors.white.withValues(alpha: 0.1)
|
||||
: Colors.black.withValues(alpha: 0.05),
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.05),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.teal.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(icon, color: Colors.teal, size: 24),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
date,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.chevron_right,
|
||||
color: theme.colorScheme.onSurface.withValues(alpha: 0.4),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildExpensesCard() {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(top: 24),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFDF4E3), // Light beige background
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.orange,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.warning_amber_rounded,
|
||||
color: Colors.white,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Dépenses',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: const Color(0xFF5D4037), // Brown text
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Vous devez 25€ à Clara',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF8D6E63), // Lighter brown
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => _showComingSoon('Régler les dépenses'),
|
||||
child: Text(
|
||||
'Régler',
|
||||
style: TextStyle(
|
||||
color: const Color(0xFF5D4037),
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ class _MapContentState extends State<MapContent> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Si une recherche initiale est fournie, la pré-remplir et lancer la recherche
|
||||
if (widget.initialSearchQuery != null && widget.initialSearchQuery!.isNotEmpty) {
|
||||
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), () {
|
||||
@@ -65,11 +66,13 @@ 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);
|
||||
|
||||
@@ -117,6 +120,8 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
@@ -230,9 +235,7 @@ class _MapContentState extends State<MapContent> {
|
||||
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),
|
||||
style: TextStyle(
|
||||
@@ -242,19 +245,13 @@ class _MapContentState extends State<MapContent> {
|
||||
),
|
||||
);
|
||||
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
|
||||
@@ -284,10 +281,14 @@ 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 (le point du pin)
|
||||
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)}',
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -311,11 +312,13 @@ 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);
|
||||
|
||||
@@ -324,10 +327,12 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
setState(() {
|
||||
_suggestions = predictions
|
||||
.map((p) => PlaceSuggestion(
|
||||
.map(
|
||||
(p) => PlaceSuggestion(
|
||||
placeId: p['place_id'],
|
||||
description: p['description'],
|
||||
))
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
_isSearching = false;
|
||||
});
|
||||
@@ -363,6 +368,8 @@ class _MapContentState extends State<MapContent> {
|
||||
|
||||
final response = await http.get(url);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
|
||||
@@ -394,9 +401,11 @@ class _MapContentState extends State<MapContent> {
|
||||
CameraUpdate.newLatLngZoom(newPosition, 15),
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
FocusScope.of(context).unfocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_showError('Erreur lors de la sélection du lieu: $e');
|
||||
setState(() {
|
||||
@@ -545,7 +554,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(() {
|
||||
@@ -567,7 +579,8 @@ class _MapContentState extends State<MapContent> {
|
||||
),
|
||||
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 +614,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(
|
||||
@@ -664,8 +675,5 @@ class PlaceSuggestion {
|
||||
final String placeId;
|
||||
final String description;
|
||||
|
||||
PlaceSuggestion({
|
||||
required this.placeId,
|
||||
required this.description,
|
||||
});
|
||||
PlaceSuggestion({required this.placeId, required this.description});
|
||||
}
|
||||
@@ -9,6 +9,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 +20,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 +42,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 +61,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 +94,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 +102,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 +126,10 @@ class ProfileContent extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: _getAuthMethodTextColor(user.authMethod, context),
|
||||
color: _getAuthMethodTextColor(
|
||||
user.authMethod,
|
||||
context,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -320,11 +329,7 @@ class ProfileContent extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.arrow_forward_ios,
|
||||
size: 16,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -401,7 +406,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 +429,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);
|
||||
},
|
||||
@@ -515,8 +526,7 @@ class ProfileContent extends StatelessWidget {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (BuildContext sheetContext) {
|
||||
return Container(
|
||||
child: Wrap(
|
||||
return Wrap(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: Icon(Icons.photo_library),
|
||||
@@ -540,31 +550,38 @@ class ProfileContent extends StatelessWidget {
|
||||
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,7 +589,11 @@ 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);
|
||||
|
||||
@@ -582,7 +603,9 @@ class ProfileContent extends StatelessWidget {
|
||||
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) {
|
||||
@@ -593,14 +616,15 @@ 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 {
|
||||
@@ -608,13 +632,17 @@ class ProfileContent extends StatelessWidget {
|
||||
|
||||
// É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,26 +651,22 @@ 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');
|
||||
LoggerService.info('DEBUG: Affichage du succès');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Photo de profil mise à jour !'),
|
||||
@@ -651,8 +675,8 @@ class ProfileContent extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
} 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',
|
||||
@@ -738,6 +762,7 @@ class ProfileContent extends StatelessWidget {
|
||||
email: user.email,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
@@ -745,6 +770,7 @@ class ProfileContent extends StatelessWidget {
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur: Mot de passe actuel incorrect',
|
||||
@@ -801,6 +827,7 @@ class ProfileContent extends StatelessWidget {
|
||||
email: user.email,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
Navigator.of(dialogContext).pop();
|
||||
context.read<UserBloc>().add(user_event.UserLoggedOut());
|
||||
Navigator.pushNamedAndRemoveUntil(
|
||||
@@ -808,6 +835,7 @@ class ProfileContent extends StatelessWidget {
|
||||
'/login',
|
||||
(route) => false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.showError(
|
||||
message: 'Erreur: Mot de passe incorrect',
|
||||
|
||||
@@ -20,6 +20,7 @@ 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é
|
||||
|
||||
Activity({
|
||||
required this.id,
|
||||
@@ -40,11 +41,12 @@ class Activity {
|
||||
this.votes = const {},
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
this.date,
|
||||
});
|
||||
|
||||
/// 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 +106,8 @@ class Activity {
|
||||
Map<String, int>? votes,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
DateTime? date,
|
||||
bool clearDate = false,
|
||||
}) {
|
||||
return Activity(
|
||||
id: id ?? this.id,
|
||||
@@ -124,6 +128,7 @@ class Activity {
|
||||
votes: votes ?? this.votes,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
date: clearDate ? null : (date ?? this.date),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,6 +153,7 @@ class Activity {
|
||||
'votes': votes,
|
||||
'createdAt': Timestamp.fromDate(createdAt),
|
||||
'updatedAt': Timestamp.fromDate(updatedAt),
|
||||
'date': date != null ? Timestamp.fromDate(date!) : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -172,6 +178,7 @@ 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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,10 @@ import 'expense_split.dart';
|
||||
enum ExpenseCurrency {
|
||||
/// Euro currency
|
||||
eur('€', 'EUR'),
|
||||
|
||||
/// US Dollar currency
|
||||
usd('\$', 'USD'),
|
||||
|
||||
/// British Pound currency
|
||||
gbp('£', 'GBP');
|
||||
|
||||
@@ -29,14 +31,19 @@ enum ExpenseCurrency {
|
||||
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);
|
||||
|
||||
@@ -144,13 +151,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?)
|
||||
splits:
|
||||
(map['splits'] as List?)
|
||||
?.map((s) => ExpenseSplit.fromMap(s))
|
||||
.toList() ?? [],
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -243,25 +254,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,
|
||||
];
|
||||
}
|
||||
@@ -27,6 +27,9 @@ class Group {
|
||||
/// 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.
|
||||
@@ -40,9 +43,11 @@ class Group {
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
List<GroupMember>? members,
|
||||
List<String>? memberIds,
|
||||
}) : createdAt = createdAt ?? DateTime.now(),
|
||||
updatedAt = updatedAt ?? DateTime.now(),
|
||||
members = members ?? [];
|
||||
members = members ?? [],
|
||||
memberIds = memberIds ?? [];
|
||||
|
||||
/// Creates a [Group] instance from a Firestore document map.
|
||||
///
|
||||
@@ -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,15 +85,19 @@ 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);
|
||||
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 creditors =>
|
||||
userBalances.where((b) => b.shouldReceive).toList();
|
||||
|
||||
List<UserBalance> get debtors => userBalances.where((b) => b.shouldPay).toList();
|
||||
List<UserBalance> get debtors =>
|
||||
userBalances.where((b) => b.shouldPay).toList();
|
||||
|
||||
int get participantCount => userBalances.length;
|
||||
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -198,4 +198,22 @@ class AccountRepository {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> addMemberToAccount(String accountId, GroupMember member) async {
|
||||
try {
|
||||
await _membersCollection(accountId).doc(member.userId).set(member.toMap());
|
||||
} catch (e) {
|
||||
_errorService.logError('account_repository.dart', 'Erreur lors de l\'ajout du membre: $e');
|
||||
throw Exception('Erreur lors de l\'ajout du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> removeMemberFromAccount(String accountId, String memberId) async {
|
||||
try {
|
||||
await _membersCollection(accountId).doc(memberId).delete();
|
||||
} catch (e) {
|
||||
_errorService.logError('account_repository.dart', 'Erreur lors de la suppression du membre: $e');
|
||||
throw Exception('Erreur lors de la suppression du membre: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}');
|
||||
_errorService.logInfo(
|
||||
'ActivityRepository',
|
||||
'Ajout d\'une activité: ${activity.name}',
|
||||
);
|
||||
|
||||
final docRef = await _firestore.collection(_collection).add(activity.toMap());
|
||||
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,7 +49,10 @@ 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
|
||||
@@ -51,19 +68,36 @@ 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);
|
||||
@@ -71,8 +105,14 @@ class ActivityRepository {
|
||||
|
||||
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,36 +151,61 @@ 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);
|
||||
@@ -157,10 +234,13 @@ class ActivityRepository {
|
||||
});
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -184,8 +264,14 @@ class ActivityRepository {
|
||||
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,7 +279,10 @@ 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>[];
|
||||
@@ -207,19 +296,28 @@ class ActivityRepository {
|
||||
|
||||
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
|
||||
@@ -237,14 +335,23 @@ 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);
|
||||
|
||||
@@ -262,7 +369,10 @@ class ActivityRepository {
|
||||
|
||||
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 [];
|
||||
}
|
||||
@@ -284,7 +394,10 @@ class ActivityRepository {
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
print('ActivityRepository: Erreur recherche activité existante: $e');
|
||||
_errorService.logError(
|
||||
'ActivityRepository',
|
||||
'Erreur recherche activité existante: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
@@ -21,7 +23,9 @@ class GroupRepository {
|
||||
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) {
|
||||
@@ -38,50 +42,13 @@ class GroupRepository {
|
||||
|
||||
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);
|
||||
@@ -106,11 +73,30 @@ class GroupRepository {
|
||||
|
||||
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;
|
||||
@@ -123,17 +109,33 @@ class GroupRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
_errorService.logError(
|
||||
'GroupRepository',
|
||||
'Erreur de migration pour le groupe $groupId: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
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');
|
||||
}
|
||||
@@ -141,10 +143,22 @@ class GroupRepository {
|
||||
|
||||
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]),
|
||||
});
|
||||
|
||||
// 4. Mettre à jour la liste participants du voyage
|
||||
await _firestore.collection('trips').doc(group.tripId).update({
|
||||
'participants': FieldValue.arrayUnion([member.userId]),
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de l\'ajout du membre: $e');
|
||||
@@ -153,10 +167,22 @@ class GroupRepository {
|
||||
|
||||
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]),
|
||||
});
|
||||
|
||||
// 4. Mettre à jour la liste participants du voyage
|
||||
await _firestore.collection('trips').doc(group.tripId).update({
|
||||
'participants': FieldValue.arrayRemove([userId]),
|
||||
});
|
||||
} catch (e) {
|
||||
throw Exception('Erreur lors de la suppression du membre: $e');
|
||||
@@ -165,8 +191,11 @@ class GroupRepository {
|
||||
|
||||
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');
|
||||
@@ -175,8 +204,12 @@ class GroupRepository {
|
||||
|
||||
Future<void> deleteGroup(String tripId) async {
|
||||
try {
|
||||
final userId = _auth.currentUser?.uid;
|
||||
if (userId == null) throw Exception('Utilisateur non connecté');
|
||||
|
||||
final querySnapshot = await _groupsCollection
|
||||
.where('tripId', isEqualTo: tripId)
|
||||
.where('createdBy', isEqualTo: userId)
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
@@ -196,15 +229,15 @@ class GroupRepository {
|
||||
} 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,
|
||||
))
|
||||
.map(
|
||||
(doc) =>
|
||||
GroupMember.fromMap(doc.data() as Map<String, dynamic>, doc.id),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
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 {
|
||||
@@ -24,7 +25,7 @@ class ActivityPlacesService {
|
||||
int offset = 0,
|
||||
}) async {
|
||||
try {
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Recherche d\'activités pour: $destination (max: $maxResults, offset: $offset)',
|
||||
);
|
||||
|
||||
@@ -69,7 +70,7 @@ class ActivityPlacesService {
|
||||
final uniqueActivities = _removeDuplicates(allActivities);
|
||||
uniqueActivities.sort((a, b) => (b.rating ?? 0).compareTo(a.rating ?? 0));
|
||||
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: ${uniqueActivities.length} activités trouvées au total',
|
||||
);
|
||||
|
||||
@@ -81,20 +82,22 @@ class ActivityPlacesService {
|
||||
);
|
||||
|
||||
if (startIndex >= uniqueActivities.length) {
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Offset $startIndex dépasse le nombre total (${uniqueActivities.length})',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
final paginatedResults = uniqueActivities.sublist(startIndex, endIndex);
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Retour de ${paginatedResults.length} activités (offset: $offset, max: $maxResults)',
|
||||
);
|
||||
|
||||
return paginatedResults;
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur lors de la recherche: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur lors de la recherche: $e',
|
||||
);
|
||||
_errorService.logError('activity_places_service', e);
|
||||
return [];
|
||||
}
|
||||
@@ -105,7 +108,9 @@ class ActivityPlacesService {
|
||||
try {
|
||||
// Vérifier que la clé API est configurée
|
||||
if (_apiKey.isEmpty) {
|
||||
print('ActivityPlacesService: Clé API Google Maps manquante');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Clé API Google Maps manquante',
|
||||
);
|
||||
throw Exception('Clé API Google Maps non configurée');
|
||||
}
|
||||
|
||||
@@ -113,16 +118,20 @@ class ActivityPlacesService {
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/geocode/json?address=$encodedDestination&key=$_apiKey';
|
||||
|
||||
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 +139,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 +165,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
|
||||
}
|
||||
}
|
||||
@@ -194,7 +205,9 @@ class ActivityPlacesService {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,7 +217,9 @@ class ActivityPlacesService {
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche par catégorie: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur recherche par catégorie: $e',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -260,7 +275,7 @@ class ActivityPlacesService {
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error('ActivityPlacesService: Erreur conversion place: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -285,7 +300,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;
|
||||
}
|
||||
}
|
||||
@@ -326,7 +343,7 @@ class ActivityPlacesService {
|
||||
int radius = 5000,
|
||||
}) async {
|
||||
try {
|
||||
print(
|
||||
LoggerService.info(
|
||||
'ActivityPlacesService: Recherche textuelle: $query à $destination',
|
||||
);
|
||||
|
||||
@@ -364,7 +381,9 @@ class ActivityPlacesService {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,7 +393,9 @@ class ActivityPlacesService {
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche textuelle: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur recherche textuelle: $e',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -423,11 +444,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 +458,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 +485,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>[],
|
||||
@@ -519,7 +542,9 @@ class ActivityPlacesService {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -537,7 +562,9 @@ class ActivityPlacesService {
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur recherche catégorie paginée: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur recherche catégorie paginée: $e',
|
||||
);
|
||||
return {
|
||||
'activities': <Activity>[],
|
||||
'nextPageToken': null,
|
||||
@@ -595,7 +622,9 @@ class ActivityPlacesService {
|
||||
activities.add(activity);
|
||||
}
|
||||
} catch (e) {
|
||||
print('ActivityPlacesService: Erreur conversion place: $e');
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur conversion place: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -613,7 +642,7 @@ class ActivityPlacesService {
|
||||
'hasMoreData': false,
|
||||
};
|
||||
} catch (e) {
|
||||
print(
|
||||
LoggerService.error(
|
||||
'ActivityPlacesService: Erreur recherche toutes catégories paginée: $e',
|
||||
);
|
||||
return {
|
||||
|
||||
@@ -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);
|
||||
@@ -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(
|
||||
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,23 +225,36 @@ 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
|
||||
@@ -240,7 +265,8 @@ class BalanceService {
|
||||
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,7 +279,10 @@ 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);
|
||||
@@ -283,7 +312,10 @@ class BalanceService {
|
||||
// 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;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../components/error/error_content.dart';
|
||||
import 'logger_service.dart';
|
||||
|
||||
/// Service for handling application errors and user notifications.
|
||||
///
|
||||
@@ -97,13 +98,12 @@ class ErrorService {
|
||||
/// [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.
|
||||
@@ -111,7 +111,7 @@ class ErrorService {
|
||||
/// [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.
|
||||
@@ -119,6 +119,6 @@ class ErrorService {
|
||||
/// [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);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ class PlaceImageService {
|
||||
|
||||
/// Récupère l'URL de l'image d'un lieu depuis Google Places API
|
||||
Future<String?> getPlaceImageUrl(String location) async {
|
||||
|
||||
try {
|
||||
// ÉTAPE 1: Vérifier d'abord si une image existe déjà dans le Storage
|
||||
final existingUrl = await _checkExistingImage(location);
|
||||
@@ -19,9 +18,11 @@ class PlaceImageService {
|
||||
return existingUrl;
|
||||
}
|
||||
|
||||
|
||||
if (_apiKey.isEmpty) {
|
||||
_errorService.logError('PlaceImageService', 'Google Maps API key manquante');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Google Maps API key manquante',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -29,17 +30,14 @@ class PlaceImageService {
|
||||
final searchTerms = _generateSearchTerms(location);
|
||||
|
||||
for (final searchTerm in searchTerms) {
|
||||
|
||||
// 1. Rechercher le lieu
|
||||
final placeId = await _getPlaceIdForTerm(searchTerm);
|
||||
if (placeId == null) continue;
|
||||
|
||||
|
||||
// 2. Récupérer les détails du lieu avec les photos
|
||||
final photoReference = await _getPhotoReference(placeId);
|
||||
if (photoReference == null) continue;
|
||||
|
||||
|
||||
// 3. Télécharger et sauvegarder l'image (seulement si pas d'image existante)
|
||||
final imageUrl = await _downloadAndSaveImage(photoReference, location);
|
||||
if (imageUrl != null) {
|
||||
@@ -48,9 +46,11 @@ class PlaceImageService {
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la récupération de l\'image: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la récupération de l\'image: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,10 @@ class PlaceImageService {
|
||||
/// Recherche un place ID pour un terme spécifique
|
||||
Future<String?> _getPlaceIdForTerm(String searchTerm) async {
|
||||
// Essayer d'abord avec les attractions touristiques
|
||||
String? placeId = await _searchPlaceWithType(searchTerm, 'tourist_attraction');
|
||||
String? placeId = await _searchPlaceWithType(
|
||||
searchTerm,
|
||||
'tourist_attraction',
|
||||
);
|
||||
if (placeId != null) return placeId;
|
||||
|
||||
// Puis avec les points d'intérêt
|
||||
@@ -146,7 +149,7 @@ class PlaceImageService {
|
||||
'?query=${Uri.encodeComponent('$location attractions monuments')}'
|
||||
'&type=$type'
|
||||
'&fields=place_id,name,types,rating'
|
||||
'&key=$_apiKey'
|
||||
'&key=$_apiKey',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
@@ -180,7 +183,7 @@ class PlaceImageService {
|
||||
'?input=${Uri.encodeComponent(location)}'
|
||||
'&inputtype=textquery'
|
||||
'&fields=place_id'
|
||||
'&key=$_apiKey'
|
||||
'&key=$_apiKey',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
@@ -205,7 +208,7 @@ class PlaceImageService {
|
||||
'https://maps.googleapis.com/maps/api/place/details/json'
|
||||
'?place_id=$placeId'
|
||||
'&fields=photos'
|
||||
'&key=$_apiKey'
|
||||
'&key=$_apiKey',
|
||||
);
|
||||
|
||||
final response = await http.get(url);
|
||||
@@ -217,7 +220,6 @@ class PlaceImageService {
|
||||
data['result'] != null &&
|
||||
data['result']['photos'] != null &&
|
||||
data['result']['photos'].isNotEmpty) {
|
||||
|
||||
final photos = data['result']['photos'] as List;
|
||||
|
||||
// Trier les photos pour obtenir les meilleures
|
||||
@@ -230,7 +232,10 @@ class PlaceImageService {
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la récupération de la référence photo: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la récupération de la référence photo: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -275,23 +280,27 @@ class PlaceImageService {
|
||||
}
|
||||
|
||||
/// Télécharge l'image et la sauvegarde dans Firebase Storage
|
||||
Future<String?> _downloadAndSaveImage(String photoReference, String location) async {
|
||||
Future<String?> _downloadAndSaveImage(
|
||||
String photoReference,
|
||||
String location,
|
||||
) async {
|
||||
try {
|
||||
// URL pour télécharger l'image en haute qualité et format horizontal
|
||||
final imageUrl = 'https://maps.googleapis.com/maps/api/place/photo'
|
||||
final imageUrl =
|
||||
'https://maps.googleapis.com/maps/api/place/photo'
|
||||
'?maxwidth=1200' // Augmenté pour une meilleure qualité
|
||||
'&maxheight=800' // Ratio horizontal ~1.5:1
|
||||
'&photo_reference=$photoReference'
|
||||
'&key=$_apiKey';
|
||||
|
||||
|
||||
// Télécharger l'image
|
||||
final response = await http.get(Uri.parse(imageUrl));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
// Créer un nom de fichier unique basé sur la localisation normalisée
|
||||
final normalizedLocation = _normalizeLocationName(location);
|
||||
final fileName = '${normalizedLocation}_${DateTime.now().millisecondsSinceEpoch}.jpg';
|
||||
final fileName =
|
||||
'${normalizedLocation}_${DateTime.now().millisecondsSinceEpoch}.jpg';
|
||||
|
||||
// Référence vers Firebase Storage
|
||||
final storageRef = _storage.ref().child('trip_images/$fileName');
|
||||
@@ -313,11 +322,13 @@ class PlaceImageService {
|
||||
// Récupérer l'URL de téléchargement
|
||||
final downloadUrl = await uploadTask.ref.getDownloadURL();
|
||||
return downloadUrl;
|
||||
} else {
|
||||
}
|
||||
} else {}
|
||||
return null;
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors du téléchargement/sauvegarde: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors du téléchargement/sauvegarde: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -332,36 +343,43 @@ class PlaceImageService {
|
||||
for (final item in listResult.items) {
|
||||
try {
|
||||
final metadata = await item.getMetadata();
|
||||
final storedNormalizedLocation = metadata.customMetadata?['normalizedLocation'];
|
||||
final storedNormalizedLocation =
|
||||
metadata.customMetadata?['normalizedLocation'];
|
||||
final storedLocation = metadata.customMetadata?['location'];
|
||||
|
||||
// Méthode 1: Vérifier avec la location normalisée (nouvelles images)
|
||||
if (storedNormalizedLocation != null && storedNormalizedLocation == normalizedLocation) {
|
||||
if (storedNormalizedLocation != null &&
|
||||
storedNormalizedLocation == normalizedLocation) {
|
||||
final url = await item.getDownloadURL();
|
||||
return url;
|
||||
}
|
||||
|
||||
// Méthode 2: Vérifier avec la location originale normalisée (anciennes images)
|
||||
if (storedLocation != null) {
|
||||
final storedLocationNormalized = _normalizeLocationName(storedLocation);
|
||||
final storedLocationNormalized = _normalizeLocationName(
|
||||
storedLocation,
|
||||
);
|
||||
if (storedLocationNormalized == normalizedLocation) {
|
||||
final url = await item.getDownloadURL();
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
// Méthode 3: Essayer de deviner depuis le nom du fichier (fallback)
|
||||
final fileName = item.name;
|
||||
if (fileName.toLowerCase().contains(normalizedLocation.toLowerCase())) {
|
||||
if (fileName.toLowerCase().contains(
|
||||
normalizedLocation.toLowerCase(),
|
||||
)) {
|
||||
try {
|
||||
final url = await item.getDownloadURL();
|
||||
return url;
|
||||
} catch (urlError) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la récupération de l\'URL: $urlError');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la récupération de l\'URL: $urlError',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,7 +402,6 @@ class PlaceImageService {
|
||||
Future<void> cleanupUnusedImages(List<String> usedImageUrls) async {
|
||||
try {
|
||||
final listResult = await _storage.ref('trip_images').listAll();
|
||||
int deletedCount = 0;
|
||||
|
||||
for (final item in listResult.items) {
|
||||
try {
|
||||
@@ -392,15 +409,19 @@ class PlaceImageService {
|
||||
|
||||
if (!usedImageUrls.contains(url)) {
|
||||
await item.delete();
|
||||
deletedCount++;
|
||||
}
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors du nettoyage: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors du nettoyage: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors du nettoyage: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors du nettoyage: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,7 +438,8 @@ class PlaceImageService {
|
||||
|
||||
try {
|
||||
final metadata = await item.getMetadata();
|
||||
final storedNormalizedLocation = metadata.customMetadata?['normalizedLocation'];
|
||||
final storedNormalizedLocation =
|
||||
metadata.customMetadata?['normalizedLocation'];
|
||||
final storedLocation = metadata.customMetadata?['location'];
|
||||
|
||||
if (storedNormalizedLocation != null) {
|
||||
@@ -448,13 +470,11 @@ class PlaceImageService {
|
||||
}
|
||||
|
||||
// Supprimer les doublons (garder le plus récent)
|
||||
int deletedCount = 0;
|
||||
|
||||
for (final entry in locationGroups.entries) {
|
||||
final location = entry.key;
|
||||
final images = entry.value;
|
||||
|
||||
if (images.length > 1) {
|
||||
|
||||
// Trier par timestamp (garder le plus récent)
|
||||
images.sort((a, b) {
|
||||
final aTimestamp = _extractTimestampFromName(a.name);
|
||||
@@ -466,17 +486,20 @@ class PlaceImageService {
|
||||
for (int i = 1; i < images.length; i++) {
|
||||
try {
|
||||
await images[i].delete();
|
||||
deletedCount++;
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la suppression du doublon: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la suppression du doublon: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors du nettoyage des doublons: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors du nettoyage des doublons: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,7 +522,10 @@ class PlaceImageService {
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la recherche d\'image existante: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la recherche d\'image existante: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -510,7 +536,10 @@ class PlaceImageService {
|
||||
final ref = _storage.refFromURL(imageUrl);
|
||||
await ref.delete();
|
||||
} catch (e) {
|
||||
_errorService.logError('PlaceImageService', 'Erreur lors de la suppression de l\'image: $e');
|
||||
_errorService.logError(
|
||||
'PlaceImageService',
|
||||
'Erreur lors de la suppression de l\'image: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@
|
||||
/// await storageService.deleteFile(fileUrl);
|
||||
/// ```
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:firebase_storage/firebase_storage.dart';
|
||||
@@ -45,10 +46,8 @@ class StorageService {
|
||||
/// Args:
|
||||
/// [storage]: Optional Firebase Storage instance (auto-created if null)
|
||||
/// [errorService]: Optional error service instance (auto-created if null)
|
||||
StorageService({
|
||||
FirebaseStorage? storage,
|
||||
ErrorService? errorService,
|
||||
}) : _storage = storage ?? FirebaseStorage.instance,
|
||||
StorageService({FirebaseStorage? storage, ErrorService? errorService})
|
||||
: _storage = storage ?? FirebaseStorage.instance,
|
||||
_errorService = errorService ?? ErrorService();
|
||||
|
||||
/// Uploads a receipt image for an expense with automatic compression.
|
||||
@@ -62,7 +61,7 @@ class StorageService {
|
||||
/// [imageFile]: The image file to upload
|
||||
///
|
||||
/// Returns:
|
||||
/// A Future<String> containing the download URL of the uploaded image
|
||||
/// A `Future<String>` containing the download URL of the uploaded image
|
||||
///
|
||||
/// Throws:
|
||||
/// Exception if file validation fails or upload encounters an error
|
||||
@@ -95,8 +94,12 @@ class StorageService {
|
||||
|
||||
// Progress monitoring (optional)
|
||||
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
|
||||
final progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
|
||||
_errorService.logInfo('StorageService', 'Upload progress: ${progress.toStringAsFixed(1)}%');
|
||||
final progress =
|
||||
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
|
||||
_errorService.logInfo(
|
||||
'StorageService',
|
||||
'Upload progress: ${progress.toStringAsFixed(1)}%',
|
||||
);
|
||||
});
|
||||
|
||||
// Wait for completion
|
||||
@@ -105,9 +108,11 @@ class StorageService {
|
||||
// Get download URL
|
||||
final downloadUrl = await snapshot.ref.getDownloadURL();
|
||||
|
||||
_errorService.logSuccess('StorageService', 'Image uploaded successfully: $fileName');
|
||||
_errorService.logSuccess(
|
||||
'StorageService',
|
||||
'Image uploaded successfully: $fileName',
|
||||
);
|
||||
return downloadUrl;
|
||||
|
||||
} catch (e) {
|
||||
_errorService.logError('StorageService', 'Error uploading image: $e');
|
||||
rethrow;
|
||||
@@ -146,7 +151,7 @@ class StorageService {
|
||||
/// [imageFile]: The image file to compress
|
||||
///
|
||||
/// Returns:
|
||||
/// A Future<Uint8List> containing the compressed image bytes
|
||||
/// A `Future<Uint8List>` containing the compressed image bytes
|
||||
///
|
||||
/// Throws:
|
||||
/// Exception if the image cannot be decoded or processed
|
||||
@@ -176,8 +181,10 @@ class StorageService {
|
||||
// Encode as JPEG with compression
|
||||
final compressedBytes = img.encodeJpg(image, quality: 85);
|
||||
|
||||
_errorService.logInfo('StorageService',
|
||||
'Image compressed: ${bytes.length} → ${compressedBytes.length} bytes');
|
||||
_errorService.logInfo(
|
||||
'StorageService',
|
||||
'Image compressed: ${bytes.length} → ${compressedBytes.length} bytes',
|
||||
);
|
||||
|
||||
return Uint8List.fromList(compressedBytes);
|
||||
} catch (e) {
|
||||
@@ -244,12 +251,14 @@ class StorageService {
|
||||
/// [imageFiles]: List of image files to upload
|
||||
///
|
||||
/// Returns:
|
||||
/// A Future<List<String>> containing download URLs of uploaded images
|
||||
/// A `Future<List<String>>` containing download URLs of uploaded images
|
||||
Future<List<String>> uploadMultipleImages(
|
||||
String groupId,
|
||||
List<File> imageFiles,
|
||||
) async {
|
||||
final uploadTasks = imageFiles.map((file) => uploadReceiptImage(groupId, file));
|
||||
final uploadTasks = imageFiles.map(
|
||||
(file) => uploadReceiptImage(groupId, file),
|
||||
);
|
||||
return await Future.wait(uploadTasks);
|
||||
}
|
||||
|
||||
@@ -259,7 +268,10 @@ class StorageService {
|
||||
final ref = _storage.refFromURL(imageUrl);
|
||||
return await ref.getMetadata();
|
||||
} catch (e) {
|
||||
_errorService.logError('StorageService', 'Erreur récupération metadata: $e');
|
||||
_errorService.logError(
|
||||
'StorageService',
|
||||
'Erreur récupération metadata: $e',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -281,7 +293,10 @@ class StorageService {
|
||||
// Supprimer les fichiers de plus de 30 jours sans dépense associée
|
||||
if (daysSinceUpload > 30) {
|
||||
await ref.delete();
|
||||
_errorService.logInfo('StorageService', 'Image orpheline supprimée: ${ref.name}');
|
||||
_errorService.logInfo(
|
||||
'StorageService',
|
||||
'Image orpheline supprimée: ${ref.name}',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,7 +319,10 @@ class StorageService {
|
||||
|
||||
return totalSize;
|
||||
} catch (e) {
|
||||
_errorService.logError('StorageService', 'Erreur calcul taille storage: $e');
|
||||
_errorService.logError(
|
||||
'StorageService',
|
||||
'Erreur calcul taille storage: $e',
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,12 @@ import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import '../models/trip.dart';
|
||||
import 'error_service.dart';
|
||||
import 'logger_service.dart';
|
||||
|
||||
/// Service pour géocoder les destinations des voyages
|
||||
class TripGeocodingService {
|
||||
static final TripGeocodingService _instance = TripGeocodingService._internal();
|
||||
static final TripGeocodingService _instance =
|
||||
TripGeocodingService._internal();
|
||||
factory TripGeocodingService() => _instance;
|
||||
TripGeocodingService._internal();
|
||||
|
||||
@@ -16,23 +18,27 @@ class TripGeocodingService {
|
||||
/// Géocode la destination d'un voyage et retourne un Trip mis à jour
|
||||
Future<Trip> geocodeTrip(Trip trip) async {
|
||||
try {
|
||||
print('🌍 [TripGeocoding] Géocodage de "${trip.location}"');
|
||||
LoggerService.info('🌍 [TripGeocoding] Géocodage de "${trip.location}"');
|
||||
|
||||
// Vérifier si on a déjà des coordonnées récentes
|
||||
if (trip.hasRecentCoordinates) {
|
||||
print('✅ [TripGeocoding] Coordonnées récentes trouvées, pas de géocodage nécessaire');
|
||||
LoggerService.info(
|
||||
'✅ [TripGeocoding] Coordonnées récentes trouvées, pas de géocodage nécessaire',
|
||||
);
|
||||
return trip;
|
||||
}
|
||||
|
||||
if (_apiKey.isEmpty) {
|
||||
print('❌ [TripGeocoding] Clé API Google Maps manquante');
|
||||
LoggerService.error('❌ [TripGeocoding] Clé API Google Maps manquante');
|
||||
throw Exception('Clé API Google Maps non configurée');
|
||||
}
|
||||
|
||||
final coordinates = await _geocodeDestination(trip.location);
|
||||
|
||||
if (coordinates != null) {
|
||||
print('✅ [TripGeocoding] Coordonnées trouvées: ${coordinates['lat']}, ${coordinates['lng']}');
|
||||
LoggerService.info(
|
||||
'✅ [TripGeocoding] Coordonnées trouvées: ${coordinates['lat']}, ${coordinates['lng']}',
|
||||
);
|
||||
|
||||
return trip.copyWith(
|
||||
latitude: coordinates['lat'],
|
||||
@@ -40,11 +46,13 @@ class TripGeocodingService {
|
||||
lastGeocodingUpdate: DateTime.now(),
|
||||
);
|
||||
} else {
|
||||
print('⚠️ [TripGeocoding] Impossible de géocoder "${trip.location}"');
|
||||
LoggerService.warning(
|
||||
'⚠️ [TripGeocoding] Impossible de géocoder "${trip.location}"',
|
||||
);
|
||||
return trip;
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ [TripGeocoding] Erreur lors du géocodage: $e');
|
||||
LoggerService.error('❌ [TripGeocoding] Erreur lors du géocodage: $e');
|
||||
_errorService.logError('trip_geocoding_service', e);
|
||||
return trip; // Retourner le voyage original en cas d'erreur
|
||||
}
|
||||
@@ -53,18 +61,23 @@ class TripGeocodingService {
|
||||
/// Géocode une destination et retourne les coordonnées
|
||||
Future<Map<String, double>?> _geocodeDestination(String destination) async {
|
||||
try {
|
||||
final url = 'https://maps.googleapis.com/maps/api/geocode/json'
|
||||
final url =
|
||||
'https://maps.googleapis.com/maps/api/geocode/json'
|
||||
'?address=${Uri.encodeComponent(destination)}'
|
||||
'&key=$_apiKey';
|
||||
|
||||
print('🌐 [TripGeocoding] URL = $url');
|
||||
LoggerService.info('🌐 [TripGeocoding] URL = $url');
|
||||
|
||||
final response = await http.get(Uri.parse(url));
|
||||
print('📡 [TripGeocoding] Status code = ${response.statusCode}');
|
||||
LoggerService.info(
|
||||
'📡 [TripGeocoding] Status code = ${response.statusCode}',
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
print('📋 [TripGeocoding] Réponse géocodage = ${data['status']}');
|
||||
LoggerService.info(
|
||||
'📋 [TripGeocoding] Réponse géocodage = ${data['status']}',
|
||||
);
|
||||
|
||||
if (data['status'] == 'OK' && data['results'].isNotEmpty) {
|
||||
final location = data['results'][0]['geometry']['location'];
|
||||
@@ -72,18 +85,24 @@ class TripGeocodingService {
|
||||
'lat': (location['lat'] as num).toDouble(),
|
||||
'lng': (location['lng'] as num).toDouble(),
|
||||
};
|
||||
print('📍 [TripGeocoding] Coordonnées trouvées = $coordinates');
|
||||
LoggerService.info(
|
||||
'📍 [TripGeocoding] Coordonnées trouvées = $coordinates',
|
||||
);
|
||||
return coordinates;
|
||||
} else {
|
||||
print('⚠️ [TripGeocoding] Erreur API = ${data['error_message'] ?? data['status']}');
|
||||
LoggerService.warning(
|
||||
'⚠️ [TripGeocoding] Erreur API = ${data['error_message'] ?? data['status']}',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
print('❌ [TripGeocoding] Erreur HTTP ${response.statusCode}');
|
||||
LoggerService.error(
|
||||
'❌ [TripGeocoding] Erreur HTTP ${response.statusCode}',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ [TripGeocoding] Exception lors du géocodage: $e');
|
||||
LoggerService.error('❌ [TripGeocoding] Exception lors du géocodage: $e');
|
||||
_errorService.logError('trip_geocoding_service', e);
|
||||
return null;
|
||||
}
|
||||
@@ -96,7 +115,9 @@ class TripGeocodingService {
|
||||
|
||||
/// Géocode plusieurs voyages en batch
|
||||
Future<List<Trip>> geocodeTrips(List<Trip> trips) async {
|
||||
print('🔄 [TripGeocoding] Géocodage de ${trips.length} voyages');
|
||||
LoggerService.info(
|
||||
'🔄 [TripGeocoding] Géocodage de ${trips.length} voyages',
|
||||
);
|
||||
|
||||
final List<Trip> geocodedTrips = [];
|
||||
|
||||
@@ -112,7 +133,7 @@ class TripGeocodingService {
|
||||
}
|
||||
}
|
||||
|
||||
print('✅ [TripGeocoding] Géocodage terminé');
|
||||
LoggerService.info('✅ [TripGeocoding] Géocodage terminé');
|
||||
return geocodedTrips;
|
||||
}
|
||||
}
|
||||
20
pubspec.lock
20
pubspec.lock
@@ -617,7 +617,7 @@ packages:
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
image:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: image
|
||||
sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928"
|
||||
@@ -825,7 +825,7 @@ packages:
|
||||
source: hosted
|
||||
version: "3.2.1"
|
||||
path:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: path
|
||||
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
|
||||
@@ -1024,6 +1024,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0"
|
||||
simple_gesture_detector:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: simple_gesture_detector
|
||||
sha256: ba2cd5af24ff20a0b8d609cec3f40e5b0744d2a71804a2616ae086b9c19d19a3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.2.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
@@ -1125,6 +1133,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.4.0"
|
||||
table_calendar:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: table_calendar
|
||||
sha256: "0c0c6219878b363a2d5f40c7afb159d845f253d061dc3c822aa0d5fe0f721982"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.0"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -37,6 +37,7 @@ dependencies:
|
||||
location: ^8.0.1
|
||||
flutter_bloc : ^9.1.1
|
||||
equatable: ^2.0.5
|
||||
table_calendar: ^3.1.0
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
@@ -58,6 +59,8 @@ dependencies:
|
||||
sign_in_with_apple: ^7.0.1
|
||||
sign_in_button: ^4.0.1
|
||||
cached_network_image: ^3.3.1
|
||||
path: ^1.9.1
|
||||
image: ^4.5.4
|
||||
|
||||
dev_dependencies:
|
||||
flutter_launcher_icons: ^0.13.1
|
||||
|
||||
@@ -20,7 +20,7 @@ void main() async {
|
||||
if (stats['tripsWithImages'] > 0) {
|
||||
await tripImageService.cleanupUnusedImages(userId);
|
||||
|
||||
final newStats = await tripImageService.getImageStatistics(userId);
|
||||
await tripImageService.getImageStatistics(userId);
|
||||
} else {}
|
||||
} catch (e) {
|
||||
exit(1);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// ignore_for_file: avoid_print
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_storage/firebase_storage.dart';
|
||||
import 'package:travel_mate/firebase_options.dart';
|
||||
@@ -32,7 +33,7 @@ void main() async {
|
||||
final location = customMeta['location'] ?? 'Inconnue';
|
||||
final normalizedLocation =
|
||||
customMeta['normalizedLocation'] ?? 'Non définie';
|
||||
final source = customMeta['source'] ?? 'Inconnue';
|
||||
|
||||
final uploadedAt = customMeta['uploadedAt'] ?? 'Inconnue';
|
||||
|
||||
// Récupérer l'URL de téléchargement
|
||||
@@ -76,18 +77,17 @@ void main() async {
|
||||
|
||||
int totalDuplicates = 0;
|
||||
for (final entry in locationGroups.entries) {
|
||||
final location = entry.key;
|
||||
final images = entry.value;
|
||||
|
||||
if (images.length > 1) {
|
||||
totalDuplicates += images.length - 1;
|
||||
|
||||
for (int i = 0; i < images.length; i++) {
|
||||
final image = images[i];
|
||||
}
|
||||
for (int i = 0; i < images.length; i++) {}
|
||||
} else {}
|
||||
}
|
||||
|
||||
if (totalDuplicates > 0) {}
|
||||
} catch (e) {}
|
||||
} catch (e) {
|
||||
print('Erreur globale: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// ignore_for_file: avoid_print
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// ignore_for_file: avoid_print
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// ignore_for_file: avoid_print
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:travel_mate/services/place_image_service.dart';
|
||||
|
||||
@@ -23,13 +24,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should prioritize tourist attractions in search terms', () {
|
||||
const testCases = [
|
||||
'Paris',
|
||||
'London',
|
||||
'Rome',
|
||||
'New York',
|
||||
'Tokyo'
|
||||
];
|
||||
const testCases = ['Paris', 'London', 'Rome', 'New York', 'Tokyo'];
|
||||
|
||||
for (String city in testCases) {
|
||||
print('City: $city should have tourist attraction terms');
|
||||
@@ -129,7 +124,9 @@ void main() {
|
||||
print('Photos triées par qualité:');
|
||||
for (var photo in photos) {
|
||||
final ratio = photo['width']! / photo['height']!;
|
||||
print('${photo['width']}x${photo['height']} (ratio: ${ratio.toStringAsFixed(2)})');
|
||||
print(
|
||||
'${photo['width']}x${photo['height']} (ratio: ${ratio.toStringAsFixed(2)})',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user